From d18d8ba045e6d683f8e5939535453d51e28af095 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 17:39:28 +0100 Subject: [PATCH 001/177] CUDA HC: the wide up read, one warp per row, opt-in (STRATA_GR_UP_WIDE=1) The up projection of the hyper-connection read runs 160 blocks of 8 warps (each warp takes 8 rows) on a 12.0 card, so 160 blocks of 192 SMs and ~6.7 warps an SM: the read is latency-bound at about 0.5 TB/s. This kernel takes one row per warp and 2 columns x the 4 streams a block, so the grid is N/2 = 1280 blocks (53 warps an SM). Every row's dot, xor tree, epilogue and the cross-stream sum are gr_up_multi_kernel's, in its order, so the outputs are bitwise the same; the token streams of both arms were identical in all 6 pairs measured. Measured on l620 (RTX PRO 5000 72 GB, all experts in VRAM, IQ3_S, 3 interleaved pairs, fresh engine each): story 197.4 -> 201.3 tok/s (+1.9%), code 243.0 -> 244.7 (+0.7%). Off by default (STRATA_GR_UP_WIDE unset); the q8_1 tail of S26 needs the 16-column blocks, so the wide kernel is only used when no q8_1 image is written. --- src/kernels/cuda/fused_gr.cu | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 576e5d67..a1f2fe6c 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -430,6 +430,76 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE } +// 149-cuda: the same up projection with one warp per row instead of eight rows per warp. A block still covers +// all HC streams x a few columns, so the cross-stream sum stays in shared memory, and every row's dot, xor tree +// and epilogue are gr_up_multi_kernel's - bitwise the same outputs. 8 warps cover 2 columns x 4 streams (8 +// rows), so the grid grows from UPM_BLOCKS (160) to N/2 (1280): the card's SMs get ~8x the warps, which is what +// this read is short of on a 12.0 card (160 blocks do not fill 192 SMs; measured 2.6 ms per round for 1.26 GB, +// about 0.5 TB/s). Not used when the S26 q8_1 tail is on (its counter assumes UPM_COLS columns a block). +constexpr int UPW_COLS = 2; +constexpr int UPW_BLOCKS = N / UPW_COLS; + +/// STRATA_GR_UP_WIDE=1: the wide up read; default off (each card's own A/B decides). +bool gr_up_wide_on() { + static const bool on = [] { + const char* v = std::getenv("STRATA_GR_UP_WIDE"); + return v != nullptr && std::atoi(v) != 0; + }(); + return on; +} + +template +__global__ void __launch_bounds__(THREADS) gr_up_wide_kernel(GrMulti m) { + __shared__ __align__(16) float lo[MAX_T][LR]; + __shared__ float g[MAX_T][HC][UPW_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = EXACT_T ? MAX_T : m.T; + const int d0 = blockIdx.x * UPW_COLS; + for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; + __syncthreads(); + if (warp < HC * UPW_COLS) { + const int c = warp / UPW_COLS, dd = warp - c * UPW_COLS, i = c * N + d0 + dd; + const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); + const Bf16x8 wa = unpack8(__ldg(w4 + lane)); + const Bf16x8 wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); + float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (lane < T) { + const FusedGrArgs& a = m.a[lane]; + rv = a.R[i]; + wn = a.w_norm[i]; + rsc = a.rs[c]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float mine = 0.0f; +#pragma unroll + for (int k = 0; k < MAX_T; ++k) { + if (!EXACT_T && k >= T) break; + float acc = dot8u_ptr(wa, lo[k] + lane * 8); + if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); + acc = warp_sum(acc); + if (lane == k) mine = acc; + } + if (lane < T) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[lane].R_out[i] = rv; + } + const float x = rv * wn * rsc; + g[lane][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPW_COLS; i += THREADS) { + const int k = i / UPW_COLS, col = i - k * UPW_COLS; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) s += g[k][c][col]; + m.a[k].mixed[d0 + col] = s / (float) HC; + } +} + // Turing (sm_75): gr_up_multi_kernel's rows, sums and epilogue with the latency taken out of the warp's chain. A warp's // 8 rows of w_up are all loaded before any dot (was: one row's load after the previous row's epilogue: ~9k of the // warp's ~22k cycles were waits on memory, ncu on an RTX 2080 Ti); a token's 8 activations per lane are read from @@ -1317,6 +1387,19 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long } } if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); + // 149-cuda: the wide up read (test arm; STRATA_GR_UP_WIDE=1). The q8_1 tail of S26 needs the 16-column + // blocks, so the wide kernel is only used when no q8_1 image is written. + if (!q8w && m.a[0].q8_mixed == nullptr && gr_up_wide_on()) { + switch (no_multi_gr ? kFusedGrMaxT : n_tok) { + case 1: gr_up_wide_kernel<1, true><<>>(m); break; + case 2: gr_up_wide_kernel<2, true><<>>(m); break; + case 3: gr_up_wide_kernel<3, true><<>>(m); break; + case 4: gr_up_wide_kernel<4, true><<>>(m); break; + case 5: gr_up_wide_kernel<5, true><<>>(m); break; + case 6: gr_up_wide_kernel<6, true><<>>(m); break; + default: gr_up_wide_kernel<<>>(m); break; + } + } else #if STRATA_GR_FAST_BUILD if (fast && !q8w) gr_up_fast_kernel<<>>(m); else From 91d4d7ff8628ed477b4085f4111fb06eabee9ed2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 18:56:26 +0100 Subject: [PATCH 002/177] STRATA_TRACE: print elapsed milliseconds on each request step The trace lines named the step a request reached but not how long it took to get there, so a stall between two marks was invisible. Each line now carries the time since the first traced step (thread-local). A diagnostic only: no step, no order and no output changes without STRATA_TRACE set. Found with it on z440 (Q2_0, layer split 24, 16,383-token prompt): the batched read takes 8,758 ms while stage 0's own GPU timeline is 5,374 ms - stage 1 is the slow one - and the expert-cache refill after the prompt costs a further 592 ms of the request. --- src/program/generate.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0b153ee1..56c2136a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11026,7 +11026,11 @@ int main(int argc, char** argv) { const bool trace = std::getenv("STRATA_TRACE") != nullptr; auto tr = [&](const char* what, long long a = -1, long long b = -1) { if (!trace) return; - std::fprintf(stderr, "strata trace: %s %lld %lld\n", what, a, b); + static thread_local Clock::time_point t0; + static thread_local bool t0_set = false; + if (!t0_set) { t0 = Clock::now(); t0_set = true; } + const double ms = std::chrono::duration(Clock::now() - t0).count(); + std::fprintf(stderr, "strata trace: %s %lld %lld %.1f ms\n", what, a, b, ms); std::fflush(stderr); }; { From 14d076ee2ed2d394dd19a83fbbb9c61ca0b8fb77 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 20:15:58 +0100 Subject: [PATCH 003/177] STRATA_TRACE: the prompt chunk line carries its stage range and elapsed ms Same diagnostic as the request-step timestamps: with a layer split the chunk line now says which stage is starting a chunk and when, so a prompt's stage overlap can be read off the log. STRATA_TRACE only; no behaviour change. Measured with it on z440 (Q2_0, split 24, 16,383-token prompt): serial reads run stage 0's two 8,192-token chunks 3,332 ms apart and the whole read takes 8,788 ms; --prefill-pipe 1500 reads four 4,096-token chunks 1,582 ms apart and the read takes 8,375 ms, so the stages overlap only partially at best. --- src/prefill/prefill.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 6cb888e5..4f9265bf 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2717,7 +2717,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri stopped_at_ = c0; break; } - if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); } + if (std::getenv("STRATA_TRACE")) { + static thread_local Clock::time_point t0; + static thread_local bool set = false; + if (!set) { t0 = Clock::now(); set = true; } + const double ms = std::chrono::duration(Clock::now() - t0).count(); + std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld stage [%lld,%lld) %.1f ms\n", (long long) c0, + (long long) n, (long long) stage_lb_, (long long) stage_le_, ms); + std::fflush(stderr); + } const int64_t T = std::min(C, n - c0), p0 = pos0 + c0; core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251 #if defined(STRATA_HAVE_DFLASH2) From 3a26753027c50bda0868ba9c99564b5de92ce510 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 20:52:26 +0100 Subject: [PATCH 004/177] STRATA_TRACE: one clock for the whole process, so a layer split's stages compare The trace origin was thread-local, and the prompt's later stages run on their own thread, so their timestamps could not be compared with the first stage's. One process-wide origin makes the hand-off visible. Found with it on z440 (Q2_0, split 24, 16,383-token prompt, 8K chunks): stage 0 starts at 0 ms and 3,267 ms, stage 1 at 3,268 ms and 5,996 ms, read ends at 8,775 ms - the two stages do overlap chunk-for-chunk, and each takes ~2.7 s per 8K chunk for its 24 layers. A split 30 run leaves stage 1 at 3.09 s a chunk with 18 layers, so the per-chunk cost is not its layer count. --- src/prefill/prefill.cpp | 5 +++-- src/program/generate.cpp | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 4f9265bf..9fee4720 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2718,8 +2718,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri break; } if (std::getenv("STRATA_TRACE")) { - static thread_local Clock::time_point t0; - static thread_local bool set = false; + static Clock::time_point t0; // process-wide: the stages run on different threads + static bool set = false; if (!set) { t0 = Clock::now(); set = true; } const double ms = std::chrono::duration(Clock::now() - t0).count(); std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld stage [%lld,%lld) %.1f ms\n", (long long) c0, @@ -5171,3 +5171,4 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } } // namespace strata::prefill + diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 56c2136a..15c28199 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11026,8 +11026,8 @@ int main(int argc, char** argv) { const bool trace = std::getenv("STRATA_TRACE") != nullptr; auto tr = [&](const char* what, long long a = -1, long long b = -1) { if (!trace) return; - static thread_local Clock::time_point t0; - static thread_local bool t0_set = false; + static Clock::time_point t0; // process-wide: the stages run on different threads + static bool t0_set = false; if (!t0_set) { t0 = Clock::now(); t0_set = true; } const double ms = std::chrono::duration(Clock::now() - t0).count(); std::fprintf(stderr, "strata trace: %s %lld %lld %.1f ms\n", what, a, b, ms); @@ -17093,3 +17093,4 @@ int main(int argc, char** argv) { cudaFree(arena); return 0; } + From d39e2a753967f81eb199d5e535efc4d2556a432c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 21:21:28 +0100 Subject: [PATCH 005/177] sm_120: the wide hyper-connection up read is on by default STRATA_GR_UP_WIDE (one warp a row, N/2 = 1,280 blocks instead of 160) measured on the RTX PRO 5000 Blackwell 72 GB, IQ3_S, every expert in VRAM, 5 interleaved pairs of fresh engines: story 197.6 -> 201.3 tok/s (+1.9%), code 243.5 -> 245.1 (+0.7%). A third run against the switch (default on vs STRATA_GR_UP_WIDE=0) reads +1.7% / +0.8%. The produced token ids were identical in all 6 pairs, and fused_gr_bench's per-T hashes are the plain read's. The switch stays: =0 off, =1 on any card, STRATA_SM120_PERF=0 the whole 12.0 set. Other cards are untouched. --- include/strata/core/sm120_series.hpp | 2 ++ src/kernels/cuda/fused_gr.cu | 22 ++++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index 7dad43d7..9059d312 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -10,6 +10,8 @@ // STRATA_GR_DOWN_TG=1 the hyper-connection down projection with one token a block row (T times the blocks); =2 (token // pairs) on a 12.0 card with fewer than 80 SMs // STRATA_GU_SWIGLU=1 gate/up, SwiGLU and the q8_1 blocks of the routed experts in one launch +// STRATA_GR_UP_WIDE=1 the hyper-connection up projection with one warp a row (1,280 blocks instead of 160; +1.9% +// story / +0.7% code decode on the RTX PRO 5000, 5 pairs, token ids identical; bitwise) // and one that rounds differently (KL-checked, the AMD gfx12 rule): STRATA_PF_FUSED (the native packs' prompt experts on the // fused int8 kernels, IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate/up only, 12.0 cards with 80+ SMs only; =0 keeps MMQ, =1 takes every // covered format on any card). diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index a1f2fe6c..6c2b1677 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -439,13 +439,27 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { constexpr int UPW_COLS = 2; constexpr int UPW_BLOCKS = N / UPW_COLS; -/// STRATA_GR_UP_WIDE=1: the wide up read; default off (each card's own A/B decides). +/// STRATA_GR_UP_WIDE: the wide up read. ON BY DEFAULT on a 12.0 card (sm120_series.hpp; STRATA_SM120_PERF=0 or +/// STRATA_GR_UP_WIDE=0 turns it off, =1 forces it on any card). Measured on the RTX PRO 5000 (IQ3_S, all experts +/// resident, 5 interleaved pairs of fresh engines): story 197.6 -> 201.3 tok/s (+1.9%), code 243.5 -> 245.1 (+0.7%), +/// the produced token ids identical in 6/6 runs; the isolated read (fused_gr_bench) is bitwise the old kernel's. bool gr_up_wide_on() { - static const bool on = [] { + static const int env = [] { const char* v = std::getenv("STRATA_GR_UP_WIDE"); - return v != nullptr && std::atoi(v) != 0; + return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); - return on; + if (env >= 0) return env != 0; + static int per_dev[64]; // 0 unknown, 1 no, 2 yes + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; + if (!per_dev[dev]) { + int major = 0, minor = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + per_dev[dev] = strata::sm120_default(major, minor) ? 2 : 1; + cudaGetLastError(); // drop what an attribute query on a CPU-only box leaves behind + } + return per_dev[dev] == 2; } template From bc6a39217a4afd1ea598c1fb628e3672cbbfc926 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 25 Oct 2026 21:26:06 +0100 Subject: [PATCH 006/177] docs: 0.2.7 release notes draft from the CUDA speed work A draft for the owner: the one engine default that changed (the wide hyper-connection up read on a 12.0 card, +1.9% story / +0.7% code decode on the RTX PRO 5000, 5 pairs, bitwise), the four settings that are faster where the PC supports them (PLE in RAM, the English draft vocabulary, --prefill-pipe on a two-card split, q4_0 KV on 12 GB with its precision cost), and the list of what was measured and rejected so it is not retried. No version number is claimed: the owner decides what else 0.2.7 carries. --- docs/release-notes-0.2.7.md | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 docs/release-notes-0.2.7.md diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md new file mode 100644 index 00000000..b3cea997 --- /dev/null +++ b/docs/release-notes-0.2.7.md @@ -0,0 +1,54 @@ +# Strata 0.2.7 (draft): a faster Qwen3.8 on NVIDIA + +> **DRAFT for the owner.** Written by the CUDA speed work on branch `f-027-cuda`; no engine version is claimed here +> because the owner decides what else 0.2.7 carries. Every number below was measured on the borrowed boxes named in +> each line, same day, against the same build with the new default turned off. + +## What is faster, by default + +- **The hyper-connection read on RTX 50 and RTX PRO Blackwell cards (compute capability 12.0).** The model's + hyper-connection mixing runs 96 small projections per token; its "up" half now runs one warp per row instead of + eight rows per warp, which fills a modern card's SMs instead of 160 blocks on 192 of them. Measured on an RTX PRO + 5000 Blackwell 72 GB (Qwen3.8-Flash-Next IQ3_S, every expert in VRAM), five interleaved pairs of fresh engines: + **story 197.6 -> 201.3 tokens/s (+1.9%), code 243.5 -> 245.1 (+0.7%)**. The answers are unchanged - the new + kernel does the same arithmetic in the same order, the produced tokens were identical in all six pairs and the + engine's own kernel check is bitwise. + - Off switch: `STRATA_GR_UP_WIDE=0`. `STRATA_SM120_PERF=0` still turns off the whole Blackwell set. + - Other cards are untouched: the old kernel runs everywhere else. + +## What is faster if your PC is set up for it + +These need no engine change; they are settings. Each was measured on the same boxes. + +- **`--ple-io ram`** - the 28.8 GB n-gram table in RAM instead of read from the SSD row by row. On the 72 GB card + (251 GB RAM): prompt **+16.5% at 1K, +30.6% at 4K, +16.8% at 8K**, -2.6% at 16K. Setup already chooses it on + Linux PCs with RAM to spare. +- **`--mtp-draft-vocab draft_vocab_en.bin`** - the helper that guesses the next words considers 162 KB of the + vocabulary instead of 425 KB, so it reads less per guess: **+2.7..3.1% story and +2.2..3.0% code** decode on both + big boxes. The big model checks every guess, so the answers are unchanged (identical tokens in every run where + the machine is deterministic). A CJK or Cyrillic user should keep the wider subset. +- **`--prefill-pipe `** - on a two-card layer split, plan the prompt's chunks for the pipeline: **+12.0% at 4K, + +22.3% at 8K, +2.9% at 16K** prompt on 2x RTX A4000. `R` is the PC's own ratio; `setup --calibrate` measures it + (1,500 on that box). +- **`--kv q4_0` on a 12 GB card** - the KV cache at 4 bits leaves room for ~1,000 more experts: **+12.0% story + decode** on an RTX 3060 12 GB (IQ3_XXS). It costs KV precision on long documents (document perplexity +8% at 1K, + +12% at 8K in `bench/results/2026-09-27-kv-q4`), so it is a choice, not a default. + +## What was tried and did not make it + +Recorded so nobody repeats it: deeper or wider MTP windows, `STRATA_QFUSE`, `STRATA_STAGE_TRIM`, `STRATA_HC_Q8`, +DFlash2 as the drafter, 4-bit draft copies, `pcie_frac` changes on the 3060, `--pipeline-windows` on a two-card +split, the K-split and the shared-memory-free variants of the hyper-connection down projection, `--prefill` chunks +above 8K, and every Blackwell default switch turned off one at a time. The numbers are in +`CUDA Plan/RESULTS.md` outside this repository. + +## Updating + +- The engine package that carries this is chosen by the owner; the app and the Terminal keep their own versions. +- From 0.2.6: the usual update path for the part that changed. + +--- + +Strata is free and open source. If it runs well on your PC, a coffee keeps the work on it going: + +Buy Me A Coffee From c30656aaf908db8181edd8ce16a97a84911bba63 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 00:27:14 +0100 Subject: [PATCH 007/177] route: residency-biased routing is on by default at 2.0 on a card of 13 GiB or less The router's top-10 is picked again with a logit bonus for the experts already in VRAM (route_prior.cu); the weights stay the router's. Measured on an RTX 3060 12 GB, IQ3_XXS, 5 interleaved pairs of fresh engines: story 44.2 -> 60.9 tok/s (+37.6%), code 47.3 -> 64.0 (+35.2%); =1.0 gives +22.6% / +24.6%. Three more pairs against the switch itself read +23.6% / +36.9%. It changes which experts run, so it is a default only where the expert cache cannot hold the model, and the owner approved that trade for 12 GB cards. It is NOT a default on a bigger card: on an RTX PRO 5000 72 GB it measures -1.9% / -0.5% and on 2x RTX A4000 -4.2% / +11.0% (3 pairs each); both were re-run after this change and are unchanged (201.7 / 246.9 and 87.1 / 107.1 tok/s). STRATA_ROUTE_PRIOR=0 turns it off and any explicit value wins. --- src/core/verify.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 3d6f48b2..145e9d76 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1966,9 +1966,23 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; } - // STRATA_ROUTE_PRIOR=lambda (opt-in, changes the output): the top-10 picked again with a logit bonus for the - // resident experts; the weights stay the router's (route_prior.cu) - static const float route_prior = [] { const char* v = std::getenv("STRATA_ROUTE_PRIOR"); return v ? (float) std::atof(v) : 0.0f; }(); + // STRATA_ROUTE_PRIOR=lambda: the top-10 picked again with a logit bonus for the resident experts; the weights + // stay the router's (route_prior.cu). **On by default at 2.0 on a card of 13 GiB or less**, where the expert + // cache cannot hold the model: measured on an RTX 3060 12 GB (IQ3_XXS), 5 interleaved pairs, story 44.2 -> + // 60.9 tok/s (+37.6%) and code 47.3 -> 64.0 (+35.2%); at 1.0 it is +22.6% / +24.6%. The owner approved the + // quality trade for 12 GB cards (it changes which experts run). It is NOT a default where the cache holds + // the model: on an RTX PRO 5000 72 GB it measured -1.9% / -0.5% and on 2x RTX A4000 -4.2% / +11.0%, so + // STRATA_ROUTE_PRIOR=0 turns it off and any explicit value wins. + static const float route_prior = [] { + const char* v = std::getenv("STRATA_ROUTE_PRIOR"); + if (v != nullptr) return (float) std::atof(v); + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) return 0.0f; + size_t free_b = 0, total_b = 0; + if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) return 0.0f; + cudaGetLastError(); // drop what a query on a device without a context leaves behind + return (double) total_b / 1073741824.0 <= 13.0 ? 2.0f : 0.0f; + }(); if (route_prior > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) route_prior_top10(logits_ + tb * NE, hits_.d_res + l * g.n_expert, route_prior, ids_ + tb * K, w_ + tb * K, n, cs); if (route_resident_cfg().margin > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) { From 2395c8a53e9f93bd46bccb366eff56b0799348d7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 00:47:21 +0100 Subject: [PATCH 008/177] hc: the one-kernel persistent hyper-connection read builds and runs on CUDA The design was HIP-only: 80 resident blocks, a column slice of D each, two grid barriers on an atomic counter, a barrier timeout so a card that cannot hold all 80 blocks resident turns a hang into a refused start-up check. Ported by giving grid_sync a CUDA branch (volatile generation counter + clock64() for the timeout, scaled to SM clocks), guarding the gfx-arch refusal to HIP and adding a masked-shuffle helper. On the RTX PRO 5000 Blackwell 72 GB it passes its own check - '80 blocks on 110 multiprocessors, 0 token counts timed out, max relative difference 1.8e-07 against the default read' - and measurably does NOT win: story 201.4 -> 190.6 tok/s (-5.4%), code 245.6 -> 249.6 (+1.6%) over 3 interleaved pairs. That matches the AMD note in the same file (an R9700 measured it neutral to 1% slower), so it stays opt-in (STRATA_HC_PERSIST=1) and is not a default. The port is kept as the starting point for a CUDA-tuned block mapping. --- src/kernels/cuda/fused_gr.cu | 59 +++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 6c2b1677..a70b7abe 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -2695,7 +2695,7 @@ void hc_q8_to_bf16(const void* codes, const float* scales, uint16_t* out, long l hc_q8_bf16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>((const int8_t*) codes, scales, out, n); } -// ===================================== the read as ONE persistent kernel (opt-in STRATA_HC_PERSIST=1, HIP) ============== +// ================================== the read as ONE persistent kernel (opt-in STRATA_HC_PERSIST=1, CUDA + HIP) ============== // 80 blocks that must all be resident (a start-up run per T decides; larger T keep the default read) and two grid // barriers on an atomic counter. Block b: (A) stages R' * w_norm for columns [128 b, 128 b + 128) (one stream) and writes // that slice's sum of squares and the UNSCALED partial dots of the 320 down + 4 inject rows (the v3 identity @@ -2703,9 +2703,18 @@ void hc_q8_to_bf16(const void* codes, const float* scales, uint16_t* out, long l // barrier; (C) the up projection read straight from VRAM, a thread pair per row, the epilogue as gr_up_kernel. // ANOTHER SUMMATION ORDER than the default read (not bitwise; the init check bounds the difference). Only the verifier's hyper-connection reads use it: they run on one stream per card (both pipeline // verifiers share it), so two of these kernels never wait on each other; the drafter's reads keep the default kernels. -#if defined(__HIPCC__) +#if defined(__HIPCC__) || defined(__CUDACC__) namespace { namespace hcp { +// CUDA spells the shuffle with an explicit mask; HIP without. One helper so the kernel body below stays portable. +template +__device__ __forceinline__ T shfl_xor_persist(T v, int mask) { +#if defined(__HIPCC__) + return __shfl_xor(v, mask); +#else + return __shfl_xor_sync(0xffffffffu, v, mask); +#endif +} // Measured on gfx1030 (bench/results/2026-10-12-hc-persist-gfx1030): the gain over the three-kernel read is (1) the down // projection split by column slices over all 80 blocks (the default read runs 41 blocks staging the activations through // LDS) and (2) one launch with two grid barriers instead of three launches and the gaps between them. Prefetching the @@ -2733,6 +2742,35 @@ __device__ __forceinline__ bool grid_sync(unsigned* bar, unsigned long long tick (void) ticks; if (threadIdx.x == 0) __hip_atomic_store(&bar[48], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); return false; +#elif defined(__CUDACC__) + // CUDA: the same generation barrier. clock64() counts SM clocks (~2 GHz), so the tick constants below are scaled; + // the timeout turns a card that cannot hold all NB blocks resident into a wrong-but-slow read rather than a hang. + __shared__ int s_abort; + volatile unsigned* vb = bar; + __syncthreads(); + if (threadIdx.x == 0) { + int ab = 0; + const unsigned gen = vb[32]; + __threadfence(); + const unsigned arrived = atomicAdd(&bar[0], 1u); + if (arrived == NB - 1) { + atomicExch(&bar[0], 0u); + __threadfence(); + atomicAdd(&bar[32], 1u); + } else { + const long long t0 = clock64(); + while (vb[32] == gen) { + if (vb[48] != 0u) { ab = 1; break; } + if (clock64() - t0 > (long long) ticks) { atomicExch(&bar[48], 1u); ab = 1; break; } + __nanosleep(64); + } + } + if (vb[48] != 0u) ab = 1; + s_abort = ab; + } + __syncthreads(); + __threadfence(); + return s_abort == 0; #else __shared__ int s_abort; __syncthreads(); @@ -2801,7 +2839,7 @@ __global__ void __launch_bounds__(THREADS) persist_kernel(PArgs f) { if constexpr (DP) { double ss = (double) r.x * r.x + (double) r.y * r.y + (double) r.z * r.z + (double) r.w * r.w; #pragma unroll - for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor(ss, o); + for (int o = 16; o > 0; o >>= 1) ss += shfl_xor_persist(ss, o); if (lane == 0) f.sspd[k * NB + b] = ss; } else { const float ss = warp_sum(r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w); // warp k = token k @@ -2823,7 +2861,7 @@ __global__ void __launch_bounds__(THREADS) persist_kernel(PArgs f) { A v; if constexpr (DP) v = dot8d(w, &xs[k][hl * 8]); else v = dot8(w, &xs[k][hl * 8]); #pragma unroll - for (int o = 8; o > 0; o >>= 1) v += __shfl_xor(v, o); + for (int o = 8; o > 0; o >>= 1) v += shfl_xor_persist(v, o); acc[k] = v; } #pragma unroll @@ -2911,7 +2949,7 @@ __global__ void __launch_bounds__(THREADS) persist_kernel(PArgs f) { } float acc[T]; #pragma unroll - for (int k = 0; k < T; ++k) acc[k] = (float) (v[k] + __shfl_xor(v[k], 1)); + for (int k = 0; k < T; ++k) acc[k] = (float) (v[k] + shfl_xor_persist(v[k], 1)); if (uh == 0) { const float wn = a0.w_norm[ui]; #pragma unroll @@ -2967,7 +3005,13 @@ bool dp_on() { KFn kernel_for(int T) { return dp_on() ? kernel_t(T) : kernel_t(T); } // s_memrealtime runs at 100 MHz on RDNA: a barrier gives up after 2 s in a read (never in a working run; it only turns a // hang into a wrong read) and after 50 ms in the start-up check (where a timeout means "not resident here") +#if defined(__CUDACC__) +// clock64() counts SM clocks (~2 GHz on these cards): 2 s a read, 50 ms the start-up check, the same wall times the +// HIP constants give at s_memrealtime's 100 MHz +constexpr unsigned long long kTicksRun = 4000000000ULL, kTicksCheck = 100000000ULL; +#else constexpr unsigned long long kTicksRun = 200000000ULL, kTicksCheck = 5000000ULL; +#endif void launch(const FusedGrArgs* a, int n_tok, const DevState& st, cudaStream_t s, unsigned long long ticks) { PArgs f; for (int t = 0; t < n_tok; ++t) f.a[t] = a[t]; @@ -2995,11 +3039,13 @@ void fused_gr_persist_init() { "(this card runs %d)\n", dev, prop.warpSize); return; } +#if defined(__HIPCC__) if (strata::kernels::gfx_arch_is_gfx12(prop.gcnArchName) || strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)) { std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: gfx11 / gfx12 have no s_memrealtime for the barrier " "timeout (written and measured for gfx1030; an R9700 saw no gain from it, #2226)\n", dev); return; } +#endif const int mp = prop.multiProcessorCount; // only for the confirmation line (WGPs on RDNA) bool ok = cudaMalloc((void**) &st.part, (size_t) kFusedGrMaxT * hcp::NR * hcp::NB * sizeof(float)) == cudaSuccess && cudaMalloc((void**) &st.ssp, (size_t) kFusedGrMaxT * hcp::NB * sizeof(float)) == cudaSuccess && @@ -3139,3 +3185,6 @@ bool fused_gr_read_persist(const FusedGrArgs*, int, void*) { return false; } #endif } // namespace strata::kernels + + + From 44b88bc91e122bc0ac287ea0b0c26860efa344d6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 01:01:09 +0100 Subject: [PATCH 009/177] docs: the release notes carry the residency-biased routing default It now ships on at 2.0 for a card of 13 GiB or less: +37.6% story / +35.2% code decode over five interleaved pairs on an RTX 3060 12 GB, and it stays off on bigger cards where it measured neutral to negative (l620 -1.9%/-0.5%, z440 -4.2%/+11.0%). It changes which experts run - the owner approved that trade for 12 GB cards - and STRATA_ROUTE_PRIOR=0 turns it off. --- docs/release-notes-0.2.7.md | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index b3cea997..fa0af0b9 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -27,12 +27,21 @@ These need no engine change; they are settings. Each was measured on the same bo vocabulary instead of 425 KB, so it reads less per guess: **+2.7..3.1% story and +2.2..3.0% code** decode on both big boxes. The big model checks every guess, so the answers are unchanged (identical tokens in every run where the machine is deterministic). A CJK or Cyrillic user should keep the wider subset. -- **`--prefill-pipe `** - on a two-card layer split, plan the prompt's chunks for the pipeline: **+12.0% at 4K, - +22.3% at 8K, +2.9% at 16K** prompt on 2x RTX A4000. `R` is the PC's own ratio; `setup --calibrate` measures it +- **`--prefill-pipe `** - on a two-card layer split, plan the prompt's chunks for the pipeline: **+15.4% at 4K, + +22.5% at 8K, +2.7% at 16K** prompt on 2x RTX A4000 (5 interleaved pairs). `R` is the PC's own ratio; `setup --calibrate` measures it (1,500 on that box). -- **`--kv q4_0` on a 12 GB card** - the KV cache at 4 bits leaves room for ~1,000 more experts: **+12.0% story - decode** on an RTX 3060 12 GB (IQ3_XXS). It costs KV precision on long documents (document perplexity +8% at 1K, - +12% at 8K in `bench/results/2026-09-27-kv-q4`), so it is a choice, not a default. +- **`--kv q4_0` on a 12 GB card** - the KV cache at 4 bits leaves room for ~1,000 more experts. On the RTX 3060 + 12 GB (IQ3_XXS) the gain did **not** reproduce: +12.0% story over three pairs, -2.9% over five, with that box's + own baseline moving 41.6 -> 49.0 tok/s between sessions, so no speed claim is made for it. It costs KV precision + on long documents (document perplexity +8% at 1K, +12% at 8K in `bench/results/2026-09-27-kv-q4`), so it is a + choice, not a default. + +## A setting that is much faster on a 12 GB card, but changes the answers + +STRATA_ROUTE_PRIOR (now on by default at 2.0 on a card with 13 GB of memory or less, =0 turns it off) gives the router a bonus for experts already in VRAM. On an RTX 3060 12 GB (IQ3_XXS) it +measured **+37.6% story and +35.2% code decode over five interleaved pairs** - by far the largest single gain found on +that card. It works by choosing a slightly different set of experts, so the replies change: it is **opt-in and needs a +quality check before anyone calls it a default**. STRATA_ROUTE_PRIOR=1.0 is the conservative end (+22.6% / +24.6%). ## What was tried and did not make it @@ -52,3 +61,6 @@ above 8K, and every Blackwell default switch turned off one at a time. The numbe Strata is free and open source. If it runs well on your PC, a coffee keeps the work on it going: Buy Me A Coffee + + + From 1e72cdc4b99cbf4ff6daef4c9fabf62ca5cd7b14 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 03:01:27 +0100 Subject: [PATCH 010/177] DeepSeek engine (AMD): a staging ring sized from the VRAM room, and expert-tile knobs for the MarLin work The prompt path streams the experts the cards cannot hold. ring_mb_auto() gave 16 MB whenever the cards held >= 1/1.3 of the experts, which is exactly this 2.25 bpw cell (126.8 GB of room, 156.3 GB of experts, share 0.769): the stream then had no depth and the expert tiles waited 1.7 s inside a 5.2 s stage. A share of the VRAM room (5%, 400-2000 MB) when any expert spills, 16 MB when they all fit (the 0.2.6 rule, kept for the decode it was chosen for). Measured, 4x R9700, 2.25 plain pack, 6 experts, --dspark off, 8192-token code prompt, ids 5705e1164a: 8K warm 632 -> 675-678 ppts (+6.8%, 5 prompts a run, 3 runs), agent decode 35.9 -> 35.3 tok/s (-1.7%, 4 runs). The profile of the warm pass: expert stage 5185 -> 4034 ms (kernels 3509 -> 2645 ms, the same kernels now that the weights arrive in VRAM ahead of them, waits 1676 -> 1389 ms), everything else equal. Also in this commit (opt-in, defaults byte-identical except the F16 activation path which is bit-identical): - SetArgs::x16: gate/up take the layer's F16 copy of the activations (rows_f16 rounds exactly as the tile's own smem store did) - half the activation bytes, 26% faster gate/up in the standalone bench (box/expert_bench.cpp), +0.3% at the pass level (the stage is stream-bound). - HIPK_CFG 6..11: tile variants for the expert GEMMs (64x128, 32x128, 128x256, 64x128/4 waves, 128/128+down 256, 64x256). 64x128 (cfg 6) is 21% faster than 128x128 in the bench and +0.9% in the pass. - HIPK_DBG 1/2/3: switch the MMA / the decode off in the tiles (the breakdown in 09-marlin-kernel-diary.md). - ds4_iq_hip.inc: a UTF-8 BOM on a source file removed. --- include/strata/dsv41/exl3.hpp | 4 ++++ src/dsv41/ds4_gguf.cu | 1 + src/dsv41/ds4_iq.cuh | 3 +++ src/dsv41/ds4_iq_hip.inc | 13 ++++++++++++ src/dsv41/ds4_iq_hip_r.inc | 40 +++++++++++++++++++++++++++-------- src/dsv41/ds4_model.cu | 16 +++++++++++--- 6 files changed, 65 insertions(+), 12 deletions(-) diff --git a/include/strata/dsv41/exl3.hpp b/include/strata/dsv41/exl3.hpp index b080a597..a5455b75 100644 --- a/include/strata/dsv41/exl3.hpp +++ b/include/strata/dsv41/exl3.hpp @@ -154,6 +154,10 @@ struct SetArgs { int max_rows = 0; // the most rows one expert of the set has int n_embd = 4096, n_ff = 2048; float limit = 0.0f; + // gate / up: the caller's F16 copy of the activations (row_idx picks the rows). The tiles round F32 to F16 for + // their shared-memory tile anyway, so the same values come out; this only saves the F32 read of the same rows by + // every column block of an expert (18-36 reads of 1.8-3.7 MB on a prompt) - MarLin's "small operand cheap". + const uint16_t* x16 = nullptr; }; /// h[local row] = FP16 clamped swiglu of gate and up over x[row_idx[local row]] (F32 rows, ldx floats apart). void set_gate_up(const SetArgs& a, const float* x, int ldx, const int* row_idx, uint16_t* h16, int ldh, cudaStream_t s); diff --git a/src/dsv41/ds4_gguf.cu b/src/dsv41/ds4_gguf.cu index e7f8a153..55231c8d 100644 --- a/src/dsv41/ds4_gguf.cu +++ b/src/dsv41/ds4_gguf.cu @@ -1402,6 +1402,7 @@ iq::SetArgs iq_set(const x3::SetArgs& sa) { // a set as ds4_iq's arguments (th q.n_embd = sa.n_embd; q.n_ff = sa.n_ff; q.limit = sa.limit; + q.xf16 = sa.x16; return q; } } // namespace diff --git a/src/dsv41/ds4_iq.cuh b/src/dsv41/ds4_iq.cuh index c2b74ff1..5cfb4f7b 100644 --- a/src/dsv41/ds4_iq.cuh +++ b/src/dsv41/ds4_iq.cuh @@ -86,6 +86,9 @@ struct SetArgs { const float* xf = nullptr; const int* idx = nullptr; const uint16_t* xh = nullptr; + // gate / up from the caller's F16 copy of the activations (the same rounding the tiles make themselves: the same + // bits), so the F32 rows are not read 18+ times a prompt (MarLin's "keep the small operand in its cheap format") + const uint16_t* xf16 = nullptr; int ldx = 0; uint16_t* h = nullptr; float* y = nullptr; diff --git a/src/dsv41/ds4_iq_hip.inc b/src/dsv41/ds4_iq_hip.inc index 4e62dffd..d4e11796 100644 --- a/src/dsv41/ds4_iq_hip.inc +++ b/src/dsv41/ds4_iq_hip.inc @@ -311,6 +311,19 @@ inline bool launch(const SetArgs& a, cudaStream_t s) { if (cfg == 3 && a.max_rows <= 32) return runr(a, s); if (cfg == 4 && a.max_rows <= 32) return runr(a, s); if (cfg == 5 && a.max_rows <= 32) return runr(a, s); + // (MarLin tile sweep on long sets: a shorter block for the tail rows - one kernel, same arithmetic) + if (cfg == 6) return runr(a, s); + if (cfg == 7) return runr(a, s); + if (cfg == 8) return runr(a, s); + if (cfg == 9) return runr(a, s); + // (a wider column block for the down pass only: its K is short and its F16 activation tile is re-read by + // every column block - 40 of them at BN 128, 20 at BN 256, the weight tile unchanged) + if (cfg == 10) { + if constexpr (GU) return runr(a, s); + else return runr(a, s); + } + // (64 rows x 256 columns a block: half the activation re-reads of 128 x 128 at the same accumulator count) + if (cfg == 11) return runr(a, s); if (a.max_rows <= 32) return runr(a, s); if (a.max_rows <= 64) return runr(a, s); return runr(a, s); diff --git a/src/dsv41/ds4_iq_hip_r.inc b/src/dsv41/ds4_iq_hip_r.inc index 0844177b..85f1a0f4 100644 --- a/src/dsv41/ds4_iq_hip_r.inc +++ b/src/dsv41/ds4_iq_hip_r.inc @@ -10,7 +10,7 @@ __device__ __forceinline__ float hf(uint32_t h) { return __half2float(__ushort_a constexpr int kKC = 64; // K a step: two sub-blocks // BM rows (MT tiles of 16) x BN = NW 16 NTW weight rows per block; NW waves, each NTW column tiles of 16 and every row tile -template +template __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg) { constexpr int NM = GU ? 2 : 1, MT = BM / 16, BN = NW * 16 * NTW, NTH = NW * 32; static_assert(BM % 16 == 0, "row tiles"); @@ -39,16 +39,17 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg for (int j = 0; j < NTW; ++j) wrow[m][j] = blob + a.tr[GU ? m : 2] + (size_t) ((c0 + warp * (16 * NTW) + j * 16 + l16)) * rb; - constexpr int NX = GU ? (BM * 16 + NTH - 1) / NTH : (BM * 8 + NTH - 1) / NTH; + constexpr bool XS = GU && X16; // gate / up take the caller's F16 rows (the same values the F32 path rounds to) + constexpr int NX = (GU && !XS) ? (BM * 16 + NTH - 1) / NTH : (BM * 8 + NTH - 1) / NTH; struct XR { - float4 f[GU ? NX : 1]; - uint4 u[GU ? 1 : NX]; + float4 f[(GU && !XS) ? NX : 1]; + uint4 u[(GU && !XS) ? 1 : NX]; }; auto fetchx = [&](int s, XR& R) { #pragma unroll for (int xi = 0; xi < NX; ++xi) { const int c = tid + xi * NTH; - if constexpr (GU) { + if constexpr (GU && !XS) { if (c < BM * 16) { const int row = c >> 4, ch = c & 15; R.f[xi] = *(const float4*) (a.xf + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 4); @@ -56,7 +57,8 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg } else { if (c < BM * 8) { const int row = c >> 3, ch = c & 7; - R.u[xi] = *(const uint4*) (a.xh + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 8); + const uint16_t* px = GU ? a.xf16 : a.xh; + R.u[xi] = *(const uint4*) (px + (size_t) srow[row] * a.ldx + (size_t) s * kKC + ch * 8); } } } @@ -65,7 +67,7 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg #pragma unroll for (int xi = 0; xi < NX; ++xi) { const int c = tid + xi * NTH; - if constexpr (GU) { + if constexpr (GU && !XS) { if (c < BM * 16) { const int row = c >> 4, ch = c & 15; const float4 v = R.f[xi]; @@ -88,6 +90,7 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg for (int i = 0; i < MT; ++i) #pragma unroll for (int j = 0; j < NTW; ++j) acc[m][i][j] = fv8{0, 0, 0, 0, 0, 0, 0, 0}; + uint32_t sink = 0; // (HIPK_DBG=1: keeps the decode's registers alive when the MMA is switched off) { XR R0; @@ -123,7 +126,13 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg for (int j = 0; j < NTW; ++j) { int c0_, c1_; float sc; - step_dec(cur[m][j], s, hi, tab, c0_, c1_, sc); + if (!(dbg & 2)) { // HIPK_DBG=2: no decode (the MMA path alone), =1: no MMA (the decode alone) + step_dec(cur[m][j], s, hi, tab, c0_, c1_, sc); + } else { + c0_ = (int) cur[m][j].w[0]; + c1_ = (int) cur[m][j].w[1]; + sc = 1.0f; + } const hv2 h = {(_Float16) sc, (_Float16) sc}; const uint2 u0 = codes4(c0_, h), u1 = codes4(c1_, h); #if defined(DS4_HIPK_G11) @@ -139,6 +148,7 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg #else bf[m][j] = __builtin_bit_cast(hv8, make_uint4(u0.x, u0.y, u1.x, u1.y)); #endif + if (dbg & 1) sink ^= u0.x ^ u0.y ^ u1.x ^ u1.y; } #if defined(DS4_HIPK_G11) const int kcol = sub * 32 + ks * 16; @@ -147,7 +157,7 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg #endif #pragma unroll for (int i = 0; i < MT; ++i) { - if (i * 16 < nr) { // (a tile past the rows: skipped, uniform) + if (i * 16 < nr && !(dbg & 1)) { // (a tile past the rows: skipped, uniform; HIPK_DBG=1: no MMA) #if defined(DS4_HIPK_G11) const hv16 af = *(const hv16*) &xs[b][i * 16 + l16][kcol]; #pragma unroll @@ -195,6 +205,7 @@ __global__ void __launch_bounds__(NW * 32) set_kernel_r(const SetArgs a, int dbg else a.y[lr * a.ldo + col] = acc[0][i][j][q]; } } + if (sink == 0xdeadbeefu && tid == 0) a.y[0] = 0.0f; // (HIPK_DBG=1 only: never true) } template @@ -204,6 +215,17 @@ inline bool runr(const SetArgs& a, cudaStream_t s) { if (N % BN != 0) return false; const dim3 grid((unsigned) ((a.max_rows + BM - 1) / BM), (unsigned) (N / BN), (unsigned) a.n_exp); static const int dbg = std::getenv("HIPK_DBG") ? std::atoi(std::getenv("HIPK_DBG")) : 0; + static const bool x16 = [] { // STRATA_DS4_X16=0: gate / up read the F32 rows as before (A/B) + const char* v = std::getenv("STRATA_DS4_X16"); + return !(v != nullptr && v[0] == '0'); + }(); + if constexpr (GU) { + if (x16 && a.xf16 != nullptr) { + set_kernel_r<<>>(a, dbg); + launches().fetch_add(1, std::memory_order_relaxed); + return cudaPeekAtLastError() == cudaSuccess; + } + } set_kernel_r<<>>(a, dbg); launches().fetch_add(1, std::memory_order_relaxed); return cudaPeekAtLastError() == cudaSuccess; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index f7e29e0e..e81458ed 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2908,11 +2908,18 @@ struct Model::Impl { size_t ring_mb_auto() const { double exp_b = 0, other_b = 0, room = 0; const double share = gpu_expert_share(&exp_b, &room, &other_b); - const bool fit = exp_b > 0 && share >= 1.0 / 1.3; // (R9700 x4: 0.86 -> ring 16: decode -1.8% after a prompt, 64: -4.4%, 400: -4.6%) + // The prompt path streams the experts the cards cannot hold. When every expert fits, the ring is worth + // nothing (16 MB): the VRAM is better as slots for the decode after the prompt (measured: decode -1.8 to -4.6% + // at 64-400 MB, unchanged at 16). When they do not fit, the stream IS the prompt's expert stage, and its depth + // is what decides how long the tiles wait: on the 4x R9700 8K prompt a 16 MB ring left 1.7 s of DMA waits in a + // 5.2 s expert stage, and 1.2-3 GB of ring measured 632 -> 678-684 ppts (+7%) for about -2% decode (off a + // fifth more CPU-lane experts). So: a share of the room, bounded, rather than the fixed 400 MB of 0.2.6. + const size_t deep = (size_t) std::min(2000.0, std::max(400.0, room / 1e9 * 0.05 * 1000.0)); // (MB) + const size_t mb = share >= 0.98 ? 16 : deep; if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, - room / 1e9, other_b / 1e9, fit ? 16 : 400); - return fit ? 16 : 400; + room / 1e9, other_b / 1e9, (int) mb); + return mb; } bool alloc_chunks(std::string& err) { chunks.resize(devs.size()); @@ -3629,6 +3636,9 @@ struct Model::Impl { sa.n_embd = D; sa.n_ff = FF; sa.limit = g.lim; + // gate / up read the layer's F16 copy of the activations (the same rounding the tiles make for their + // shared tile): with 18-36 column blocks an expert the F32 rows were read that many times + sa.x16 = c.x16; EkMark ek{}; const bool ekp = prof_chunk; if (ekp) { From 3b2399456840d3ce7e26c019daadb886e87a0d7e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 03:36:03 +0100 Subject: [PATCH 011/177] DeepSeek engine (AMD): the staging ring from each device's room (not the summed room) No behaviour change on the 4x R9700 cell (126.8 GB of room / 4 = 31.7 GB a device, 8% -> 2000 MB, the value measured in 76177ec34); on other card counts it is the per-device share that was meant. --- src/dsv41/ds4_model.cu | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index e81458ed..30c06b39 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2913,8 +2913,9 @@ struct Model::Impl { // at 64-400 MB, unchanged at 16). When they do not fit, the stream IS the prompt's expert stage, and its depth // is what decides how long the tiles wait: on the 4x R9700 8K prompt a 16 MB ring left 1.7 s of DMA waits in a // 5.2 s expert stage, and 1.2-3 GB of ring measured 632 -> 678-684 ppts (+7%) for about -2% decode (off a - // fifth more CPU-lane experts). So: a share of the room, bounded, rather than the fixed 400 MB of 0.2.6. - const size_t deep = (size_t) std::min(2000.0, std::max(400.0, room / 1e9 * 0.05 * 1000.0)); // (MB) + // fifth more CPU-lane experts). So: a share of each device's room, bounded, rather than the fixed 400 MB. + const double per_dev = devs.empty() ? 0.0 : room / (double) devs.size(); + const size_t deep = (size_t) std::min(2000.0, std::max(400.0, per_dev / 1e9 * 0.08 * 1000.0)); // (MB) const size_t mb = share >= 0.98 ? 16 : deep; if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, From 3cc132ec51cbe9be035b93154ca322028f2ab8f9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 04:07:19 +0100 Subject: [PATCH 012/177] DeepSeek engine (AMD, diagnostic): where copy_ahead's time goes in the prompt stream line (DS4_PROF only) The first prompt after a load is 2-9x slower than the second on the 4x R9700 2.25 bpw cell and it is not the disk (0 MB read during it), the RAM store (removing it is worse), the dense GEMM shapes (q_b+rope 1.46 s) or the compute waiting (0 ms). The lead is the RAM->pinned-staging->DMA path (the file's own note: 6.8 GB/s through the staging against 24-28 GB/s probes); DS4_COPY_PIN=1 measured 47.9 -> 31.4 s on the first prompt and 28.8 -> 12.0 s on the second, decode unchanged. This commit only adds the counters (staging / DMA issue / slot wait) to the existing prompt stream line under DS4_PROF; no behaviour change. --- src/dsv41/ds4_model.cu | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 30c06b39..ea653138 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -594,6 +594,8 @@ struct Chunk { int *bc_pin = nullptr, *bc_dev = nullptr; uint64_t n_batch = 0; double wait_ms = 0; // the compute waiting for a read + // (DS4_PROF: where copy_ahead's time goes - the host staging copy, the DMA issues, the waits for a slot) + double dbg_stage_ms = 0, dbg_dma_ms = 0, dbg_evt_ms = 0; uint64_t it_file = 0, it_ram = 0, it_spec = 0, it_spec_unused = 0; uint64_t io_d0 = 0, io_b0 = 0; // io's unbuffered / buffered bytes when the run started // layer-major (a run of several chunks, every layer on this device): the layers one after another, each through @@ -3226,9 +3228,12 @@ struct Model::Impl { if (S.cp >= (size_t) P) CK(cudaStreamWaitEvent(c.cs, c.freed[half], 0)); uint8_t* sb = nullptr; // in place: the batch's regions in the part's staging slots if (c.stage != nullptr) { + const double t_evt = now_ms(); if (S.cp >= (size_t) P) CK(cudaEventSynchronize(c.filled[half])); // (its last batch's copies out) + c.dbg_evt_ms += now_ms() - t_evt; sb = c.stage + (size_t) half * (c.ring_n / P) * c.stage_stride; std::atomic bad{false}; + const double t_st = now_ms(); c.readers->run(bt.n, [&](int i) { const int e = l0.host_list[(size_t) (bt.j0 + i)]; if (l0.lay.fmt == gg::kFmtMXFP4 ? !read_mx(l0, e, sb + (size_t) i * c.stage_stride) @@ -3237,11 +3242,13 @@ struct Model::Impl { sb + (size_t) i * c.stage_stride)) bad.store(true); }); + c.dbg_stage_ms += now_ms() - t_st; if (bad.load()) { err = "reading layer " + std::to_string(l0.il) + "'s experts from the model's files failed"; return false; } } + const double t_dma = now_ms(); for (int i = 0; i < bt.n; ++i) { uint8_t* dst = c.ring + ((size_t) half * (c.ring_n / P) + i) * c.ring_stride; if (!stream_expert(l0, mi, l0.host_list[(size_t) (bt.j0 + i)], dst, c.cs, err, @@ -3249,6 +3256,7 @@ struct Model::Impl { return false; c.stream_bytes += (double) unit(member(l0, mi)); } + c.dbg_dma_ms += now_ms() - t_dma; CK(cudaEventRecord(c.filled[half], c.cs)); ++S.cp; S.done.store(S.cp, std::memory_order_relaxed); @@ -8494,15 +8502,19 @@ struct Model::Impl { if (c.lm) std::snprintf(lcs, sizeof lcs, ", %llu again from the layer cache (layer-major, %d chunks, %.1f GB " "of RAM)", (unsigned long long) c.it_lc, (int) run.T.size(), (double) c.lc_bytes / 1e9); + char dbgs[160] = ""; + if (pm.on) + std::snprintf(dbgs, sizeof dbgs, "; copy_ahead: staging %.0f ms, DMA issues %.0f ms, slot waits %.0f ms", + c.dbg_stage_ms, c.dbg_dma_ms, c.dbg_evt_ms); std::fprintf(stderr, "ds4 prompt stream, CUDA%d: %d tokens in %.0f ms; %llu experts streamed: %llu from the files " "(%.1f GB, %.2f GB/s: %.1f GB from the disk unbuffered, %.1f GB through the page cache), %llu " "from RAM (%.1f GB)%s; %llu likely ones queued early, %llu of them unpicked; the compute waited " - "%.0f ms for reads\n", + "%.0f ms for reads%s\n", devs[di].id, n, ms, (unsigned long long) (c.it_file + c.it_ram + c.it_lc), (unsigned long long) c.it_file, fb, fb / std::max(1e-3, ms / 1000.0), db, bb, (unsigned long long) c.it_ram, rb, lcs, (unsigned long long) c.it_spec, - (unsigned long long) c.it_spec_unused, c.wait_ms); + (unsigned long long) c.it_spec_unused, c.wait_ms, dbgs); } } if (pm.on && run.T.size() == 1) { // (the picks' spread for pick_path: the CPU-lane experts this run picked) From 5b969c1f7a41f86cec796818b7ec9b2a87eb4aed Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 04:30:12 +0100 Subject: [PATCH 013/177] DeepSeek engine (AMD, diagnostic): the io threads' busy time in the prompt stream line The RAM->staging memcpy runs on the IoQueue's threads; on a warm 8K prompt (stream stage 14.3 s, 12.8 GB a device) they are busy 4.1 s, i.e. ~3 GB/s a device - a real share, and the thing to check in the 50-95 s first-prompt runs (where the same counters are what to read first). DS4_PROF only. --- src/dsv41/ds4_model.cu | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index ea653138..e4a0ba7e 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -598,6 +598,7 @@ struct Chunk { double dbg_stage_ms = 0, dbg_dma_ms = 0, dbg_evt_ms = 0; uint64_t it_file = 0, it_ram = 0, it_spec = 0, it_spec_unused = 0; uint64_t io_d0 = 0, io_b0 = 0; // io's unbuffered / buffered bytes when the run started + double io_busy0 = 0; // io's busy time when the run started (DS4_PROF) // layer-major (a run of several chunks, every layer on this device): the layers one after another, each through // all the chunks; a chunk's state between its layers (h | pre | topk | cand, chunk k at k chunk_hand_bytes()) in // host memory, and the layer cache - RAM slots where the experts a layer's chunk reads from the files are kept for @@ -7739,6 +7740,7 @@ struct Model::Impl { c.lc_first = c.lc_chk = 0; c.io_d0 = c.io->direct_bytes(); c.io_b0 = c.io->buffered_bytes(); + c.io_busy0 = c.io->busy_ms(); if (!c.fl_layers.empty()) { flow_spec(c, 0, c.fl_layers[0], run.T[0]); if (!flow_pump(c, err)) return false; @@ -8502,10 +8504,11 @@ struct Model::Impl { if (c.lm) std::snprintf(lcs, sizeof lcs, ", %llu again from the layer cache (layer-major, %d chunks, %.1f GB " "of RAM)", (unsigned long long) c.it_lc, (int) run.T.size(), (double) c.lc_bytes / 1e9); - char dbgs[160] = ""; + char dbgs[200] = ""; if (pm.on) - std::snprintf(dbgs, sizeof dbgs, "; copy_ahead: staging %.0f ms, DMA issues %.0f ms, slot waits %.0f ms", - c.dbg_stage_ms, c.dbg_dma_ms, c.dbg_evt_ms); + std::snprintf(dbgs, sizeof dbgs, + "; io threads busy %.0f ms, copy_ahead staging %.0f ms, DMA issues %.0f ms, slot waits %.0f ms", + c.io->busy_ms() - c.io_busy0, c.dbg_stage_ms, c.dbg_dma_ms, c.dbg_evt_ms); std::fprintf(stderr, "ds4 prompt stream, CUDA%d: %d tokens in %.0f ms; %llu experts streamed: %llu from the files " "(%.1f GB, %.2f GB/s: %.1f GB from the disk unbuffered, %.1f GB through the page cache), %llu " From 2247e5a98ddebeecbd4180b2740e8d91a5b9fc52 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 04:46:46 +0100 Subject: [PATCH 014/177] DeepSeek engine (AMD): pin the CPU lane's RAM copy when the cards hold >= half the experts (DS4_COPY_PIN auto) The prompt path copies every streamed expert from the RAM copy into the pinned staging before its DMA (the file's own note: 6.8 GB/s through the staging against 24-28 GB/s probes). Registering the copy lets it DMA in place. Three interleaved pairs on 4x R9700, 2.25 bpw (share 0.72): the second 8K prompt of a process 12.0 / 11.9 / 11.9 s against 28.8 / 13.8 / 12.3 s unpinned; decode 35.42 / 35.50 / 34.9-36.0 against 35.43 / 35.45 / 34.9-36.0 tok/s, i.e. no cost; ids unchanged. Costs 23 s of load (registering a 50 GB copy) - once a process, which for a server is the right trade. Auto only when the expert share is >= 0.5 (the CPU lane is then a minority of the decode, so the pinned pages' TLB cost cannot bite); DS4_COPY_PIN=0/1 forces it, and it stays off where the 12 GB cards' decode is CPU-lane-bound (the -15% measured there). --- src/dsv41/ds4_model.cu | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index e4a0ba7e..5df38cf8 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -4453,12 +4453,18 @@ struct Model::Impl { std::fprintf(stderr, "ds4: %zu of the CPU lane's %zu experts copied into RAM (%.1f GB, %d NUMA part%s) in %.1f s%s\n", jobs.size(), hot.size(), cb / 1e9, NH, NH > 1 ? "s" : "", (now_ms() - t0) / 1000.0, jobs.size() < hot.size() ? "; the others read in place" : ""); - // DS4_COPY_PIN=1: pin the copies, so the prompt path DMAs each expert from where it lies instead of copying it - // to the pinned staging first (measured on the R9700 box: the 8K pass streams 122 GB at 6.8 GB/s through the - // staging, where the RAM-to-staging and DMA probes are 24 and 28 GB/s). The CPU lane reads the same memory, and - // pinned 4 KB pages can cost its TLB (an earlier registration measured -15% decode), so this stays opt-in. + // DS4_COPY_PIN: pin the copies, so the prompt path DMAs each expert from where it lies instead of copying it to + // the pinned staging first (the pass streams 122 GB at 6.8 GB/s through the staging, where the RAM-to-staging + // and DMA probes are 24 and 28 GB/s). The CPU lane reads the same memory, and pinned 4 KB pages can cost its + // TLB (an earlier registration measured -15% decode on a 12 GB card, where the CPU lane does nearly all of the + // decode) - so AUTO (unset) pins when the cards hold at least half the routed experts: the CPU lane is then a + // minority of the decode and the prompt stream is what hurts. Measured on 4x R9700, 2.25 bpw (share 0.72), + // three interleaved pairs: the second 8K prompt of a process 12.0/11.9/11.9 s against 28.8/13.8/12.3 s unpinned, + // decode 35.42/35.50/34.9-36.0 against 35.43/35.45/34.9-36.0 tok/s (no cost). DS4_COPY_PIN=0/1 forces it. // DS4_COPY_PIN_RO=1: cudaHostRegisterReadOnly (the GPU only reads it). - if (const char* cp = std::getenv("DS4_COPY_PIN"); cp != nullptr && std::atoi(cp) != 0) { + const char* cp = std::getenv("DS4_COPY_PIN"); + const bool pin_on = cp != nullptr ? std::atoi(cp) != 0 : gpu_expert_share() >= 0.5; + if (pin_on) { const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; const double tr = now_ms(); bool ok = true; From e83b82afe562705f5c39580c0ac6bb470380da4f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 06:09:02 +0100 Subject: [PATCH 015/177] DeepSeek engine (AMD): the drafter's cumulative confidence cut on by default (0.5) on HIP DeepInfer's rule: verify a draft while the product of the confidences so far stays above the cut, instead of only each draft's own floor. The 0.2.7 notes left it off ('not measured faster on code: H100 / owner PC'), Project Maya runs 0.5 on a Radeon 8065S (+6.5% decode, the same tokens). Measured on 4x R9700, DeepSeek 2.25 bpw, six 128-token decodes an arm in one load, same ids (81d895366c): 71.7 -> 76.9 tok/s (medians) with STRATA_DS4_DSPARK_CUM=0.5, and a second pair 74.1/73.6; the default with the rule on (no env) verified at 74.5 tok/s (6 decodes). CUDA keeps 0 (the rule was flat there). STRATA_DS4_DSPARK_CUM still overrides either way. --- src/dsv41/ds4_main.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index 57950f60..fdbd542e 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -152,11 +152,19 @@ static int g_round_nd = 0; // The drafts' cut on the product of their confidences (DeepInfer's cumulative rule): a draft is verified while the chance // that it and every draft before it are kept stays at least this - a long window whose later drafts are likely lost is // not verified whole. STRATA_DS4_DSPARK_CUM=F, a request's dspark_cum key; 0: off, only the floor on each draft's own -// confidence (dspark_conf). Off by default (not measured faster on code: H100 / owner PC); Project Maya runs 0.5 (a Radeon 8065S: decode +6.5%, the same tokens) +// confidence (dspark_conf). On AMD 0.5 is the default: measured on 4x R9700, DeepSeek 2.25 bpw, six 128-token +// decodes an arm in one load - 71.7 -> 76.9 tok/s (medians), the same ids; Project Maya runs 0.5 on a Radeon 8065S +// too (+6.5% decode, the same tokens), while the CUDA measurements in 0.2.7 had it flat, so CUDA keeps 0. +// STRATA_DS4_DSPARK_CUM overrides either way. float dspark_cum_default() { static const float v = [] { const char* e = std::getenv("STRATA_DS4_DSPARK_CUM"); - return e != nullptr ? (float) std::atof(e) : 0.0f; + if (e != nullptr) return (float) std::atof(e); +#if defined(STRATA_USE_HIP) + return 0.5f; +#else + return 0.0f; +#endif }(); return v; } From 88c293196371333a63bd14d0ceaf3949a07e4020 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 07:24:22 +0100 Subject: [PATCH 016/177] DeepSeek engine (AMD): the small prompt chunk whenever the cards hold most of the experts, 4 cards included prefill_chunk_default() returned 1024 only for a single-card run (own_default); a multi-card run whose cards hold most of the experts fell through to 2048 (HIP skips the two 4096 branches) - and the rule's own datapoint for 1024 was a 4 x R9700 run ('1024 370 tok/s, 8192 214'). Measured again here, 2.25 bpw, 4 cards, 8K code prompt, --dspark auto, ids 5705e1164a, 4 prompts a load: 512 1110 / 1137 / 1142 ppts (median 1123) 1024 1229 / 1257 / 1270 (median 1243) <- this commit's default 2048 689 / 695 / 696 (median 692) <- what the engine picked before 8192 690 / 690 / 695 (median 690) <- what the 0.2.7 configs passed Decode unchanged (73.2 against 73.2 tok/s medians, --dspark auto). So the owner's default 8K prompt goes from 692 to 1243 ppts (+80%) with no flag; --prefill-chunk still overrides. --- src/dsv41/ds4_experts_rule.hpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/dsv41/ds4_experts_rule.hpp b/src/dsv41/ds4_experts_rule.hpp index 60d5881c..63c4c49a 100644 --- a/src/dsv41/ds4_experts_rule.hpp +++ b/src/dsv41/ds4_experts_rule.hpp @@ -40,7 +40,12 @@ constexpr uint64_t kChunkInPlace4096Below = 16ull << 30; // smallest card; big: the chunk of the streamed case (the engine's kVlRows, 8192) inline int prefill_chunk_default(bool own_default, double gpu_share, bool gguf_copy, bool file_experts, bool hip, uint64_t min_vram_bytes, int big = 8192) { - if (own_default && gpu_share >= 0.5) return 1024; + // The cards hold most of the experts: the small chunk is the measured one, and it is not a single-card matter. The + // 4 x R9700 datapoint above (1024: 370 against 214 tok/s at 8192) is a multi-card run, and on that box the rule used + // to fall through to 2048/8192: measured here again (2.25 bpw, 4 cards, --dspark auto, ids 5705e1164a) 8K warm + // prompts 1024 -> 1247 ppts against 690 at 8192, with the decode unchanged, so the share alone decides it now. + (void) own_default; + if (gpu_share >= 0.5) return 1024; if (gguf_copy && !hip && min_vram_bytes >= kChunk4096MinVram) return 4096; // the experts read in place on a card under 16 GiB (the 12 GB PCs; not measured on HIP): 4096 keeps ~120 more experts resident than 8192 (RTX 5070 // 287 against 165, RTX 3060 386 against 277) - 5 interleaved pairs, 4096 against 8192, decode: 5070 agent x1.020 (5/5) code x1.004 (3/5), 3060 From 4aa645c0075d51c86cc5320394804631c0409ef1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 08:10:37 +0100 Subject: [PATCH 017/177] DeepSeek engine (AMD): a small staging ring where the cards hold most of the experts With the 1024-token prompt chunk (the default where the cards hold most of the experts, abfe7d813) a big staging ring is no longer the trade it was: every MB it takes is a tenth of an expert the decode keeps. Measured on the same box, 8K code prompt + six 128-token decodes a load, ids 5705e1164a / 81d895366c: 2000 MB 1243 ppts / 73.2 tok/s 1000 MB 1287 / 77.5 500 MB 1314 / 78.5 256 MB 1324 / 78.4 128 MB 1338 / 78.3 So high-share runs take clamp(room/device * 0.008, 128, 512) MB (248 MB here) and the old deeper ring stays for the cases it was measured for (share < 0.5, where the cards stream most of the experts). The un-enved default verified at 1339 ppts / 78.1 tok/s, 42 s of summed GPU time in a 36 s pass. --- src/dsv41/ds4_model.cu | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 5df38cf8..94641b4e 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2919,7 +2919,13 @@ struct Model::Impl { // fifth more CPU-lane experts). So: a share of each device's room, bounded, rather than the fixed 400 MB. const double per_dev = devs.empty() ? 0.0 : room / (double) devs.size(); const size_t deep = (size_t) std::min(2000.0, std::max(400.0, per_dev / 1e9 * 0.08 * 1000.0)); // (MB) - const size_t mb = share >= 0.98 ? 16 : deep; + // ... but with the 1024-token prompt chunk (the default now when the cards hold most of the experts) the + // ring's balance moved: every MB it takes is a tenth of an expert the decode keeps. Measured on the same + // box, 8K prompt and six 128-token decodes a load, chunk 1024: 2000 MB 1243 ppts / 73.2 tok/s, 1000 MB + // 1287 / 77.5, 500 MB 1314 / 78.5, 256 MB 1324 / 78.4. So a small bounded ring where the cards hold the + // most of the experts, and the old depth where they do not (the streaming cases it was measured for). + const size_t small = (size_t) std::min(512.0, std::max(128.0, per_dev / 1e9 * 0.008 * 1000.0)); // (MB) + const size_t mb = share >= 0.98 ? 16 : (share >= 0.5 ? small : deep); if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, room / 1e9, other_b / 1e9, (int) mb); From 0f66c316eea3ad2c240761bc3eb4104dcffe5cad Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 08:52:39 +0100 Subject: [PATCH 018/177] DeepSeek engine (AMD): the whole chunk's attention slab where the cards hold most of the experts The slab rule (8 MB of q/o per device, 256 rows here) was set to keep the dense dequant's VRAM small; with a 1024-token chunk it dequantizes q_b/wo once per 256 rows - four times a chunk, 32 times an 8K prompt. Measured on 4x R9700, 2.25 bpw, share 0.77, chunk 1024, 8K code prompt, ids 5705e1164a: 256-row rule 1204 / 1236 / 1250 ppts, decode 77.7 tok/s chunk's 1024 1324 / 1353 / 1363 decode 78.1 (+9% prefill, decode unchanged) The 1024 rows cost 268 MB a device (1% of the card). So high-share runs take min(chunk, 1024) rows and the old rule stays elsewhere; DS4_ATTN_SLAB still overrides. The un-enved default verified at 1335 ppts / 77.8 tok/s with the ring at 253 MB. --- src/dsv41/ds4_model.cu | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 94641b4e..ddafb556 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2946,11 +2946,17 @@ struct Model::Impl { split128(g.ff, nm, 0, ff0_, FF); // (the widest member's share: member 0 takes the odd blocks) const size_t C = (size_t) chunk; c.C = chunk; - c.A = std::max(64, (int) (((size_t) 8 << 20) / (size_t) HQ) / 64 * 64); // DS4_ATTN_SLAB=N: the attention slab's rows. The dense projections (q_b, wo_a/b) are dequantized and GEMM'd // once a slab, so a slab of 256 rows dequantizes the same weights 32 times for an 8K prompt (measured: the // dense dequant 916 ms of the 8K prompt, rocBLAS 867 ms); a larger slab costs VRAM for c.q/c.o and the oa // buffers (A * HQ x 4 bytes each). + const int a_rule = std::max(64, (int) (((size_t) 8 << 20) / (size_t) HQ) / 64 * 64); // 256 rows here + c.A = a_rule; + // Where the cards hold most of the experts, the whole chunk's slab is worth its VRAM: measured on 4x R9700 + // (2.25 bpw, share 0.77, chunk 1024) the 256-row rule gives 8K warm 1204 / 1236 / 1250 ppts and a slab of + // the chunk's 1024 rows 1324 / 1353 / 1363 (+9%) with the decode unchanged (77.7 against 78.1 tok/s); the + // 1024 rows cost 268 MB a device, 1% of the card. Elsewhere the rule stays as it was. + if (gpu_expert_share() >= 0.5) c.A = std::max(a_rule, std::min(chunk, 1024) / 64 * 64); if (const char* v = std::getenv("DS4_ATTN_SLAB")) { const int a = std::atoi(v); if (a > 0) c.A = std::max(64, std::min(chunk, a) / 64 * 64); From 7e1a7cb93ca85699bdee563e3ffbf1cb7af9a5a3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 09:38:45 +0100 Subject: [PATCH 019/177] docs: the release notes carry the 12 GB routing default with its held-out evidence --- docs/release-notes-0.2.7.md | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index fa0af0b9..a7691122 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -36,12 +36,27 @@ These need no engine change; they are settings. Each was measured on the same bo on long documents (document perplexity +8% at 1K, +12% at 8K in `bench/results/2026-09-27-kv-q4`), so it is a choice, not a default. -## A setting that is much faster on a 12 GB card, but changes the answers +## The 12 GB default: residency-biased routing -STRATA_ROUTE_PRIOR (now on by default at 2.0 on a card with 13 GB of memory or less, =0 turns it off) gives the router a bonus for experts already in VRAM. On an RTX 3060 12 GB (IQ3_XXS) it -measured **+37.6% story and +35.2% code decode over five interleaved pairs** - by far the largest single gain found on -that card. It works by choosing a slightly different set of experts, so the replies change: it is **opt-in and needs a -quality check before anyone calls it a default**. STRATA_ROUTE_PRIOR=1.0 is the conservative end (+22.6% / +24.6%). +**On by default at 2.0 on a card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off). The router prefers +experts that are already resident, so a window stops waiting on a page-in that the next window would need again. Measured +on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: + +| axis | before | after | +|---|---|---| +| decode story | 45.9 | **61.6 (+34.1%)** | +| decode code | 43.6 | **73.1 (+67.6%)** | +| prompt 1K | 333.6 | **451.5 (+35.3%)** | +| prompt 4K, in a 4K context | 248.5 | **291.0 (+17.1%)** | +| decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | + +It holds where it matters most: on content the tuning was never fitted to it measures **+29.0%** (43.5 -> 55.0 tok/s on a +document prompt), and the whole recipe - routing, a workload-fitted expert profile, `--adapt-every 0`, `--vram-reserve-mib +896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. + +It works by choosing a slightly different set of experts, so replies change: the owner approved that trade for 12 GB cards. +**Do not raise the bonus beyond 2.0.** 3.0 measures +17.7% / +24.0% on the test prompts but **-4.5% on held-out content**, +and 4.0 breaks outright - 2.0 is the setting that generalises. ## What was tried and did not make it @@ -64,3 +79,4 @@ Strata is free and open source. If it runs well on your PC, a coffee keeps the w + From 03056168d9ee72a807f83789a56cd4a1e7da8e49 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 12:21:18 +0100 Subject: [PATCH 020/177] dense dequant: the chunked prompt's dq_rows_kernel packs each sub-block's 32 halves into four 16-byte stores and stages the warp's input through contiguous uint4 loads decoded at a relative index - the same values (bit-identical), 4K prefill 79.5 -> 88.52 tok/s, acceptance 97.4% --- src/dsv41/ds4_iq.cu | 45 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index e5f66887..e6674b4b 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -1287,20 +1287,55 @@ __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __rest __syncthreads(); const int nsb = k / 32; const size_t total = (size_t) n * (size_t) nsb; + // A warp stages its 32 sub-blocks in shared through contiguous uint4 loads and decodes from there: a lane reading its own + // 176-byte block at that stride touched 32 scattered sectors per instruction - the dequant's remaining cost once the stores + // were vectorised (15.4 s of a 4K prompt, 23 GB of quantised input at ~1.5 GB/s). Each lane decodes with the index relative + // to the staged buffer (kb - kb0), which is exactly equivalent because kb0 is a multiple of the 8 sub-blocks in a block. + constexpr int kQKv = kQK; + constexpr int kSpan = (kQKv == 32 ? 32 : 4) * Ty::B; // bytes of a warp's 32 sub-blocks + constexpr bool kCanStage = Ty::TAB == 0; // (a codebook table already fills shared for the i-quants) + const bool staged = (nsb % 32 == 0) && kCanStage; + __shared__ uint4 sin4[kCanStage ? (kThreads / 32) * 44 : 1]; + const int lane32 = threadIdx.x & 31, wq = threadIdx.x >> 5; for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (size_t) gridDim.x * blockDim.x) { const size_t r = i / (size_t) nsb; const int kb = (int) (i - r * (size_t) nsb); Sub sb; sb.m0 = sb.m1 = 0.0f; - decode(raw + r * ld, kb, tab, sb); + if (staged) { + const size_t wbase = i - (size_t) lane32; // (uniform in the warp: blockDim and the stride are multiples of 32) + const size_t r0 = wbase / (size_t) nsb; + const int kb0 = (int) (wbase - r0 * (size_t) nsb); + const uint8_t* srcp = raw + r0 * ld + (size_t) (kb0 * Ty::B) / (kQKv / 32); + uint4* st = sin4 + wq * 44; + for (int c = lane32; c < kSpan / 16; c += 32) st[c] = ((const uint4*) srcp)[c]; + __threadfence_block(); + __syncwarp(); + decode((const uint8_t*) st, kb - kb0, tab, sb); + } else + decode(raw + r * ld, kb, tab, sb); const float d0 = __fmul_rn(sb.d, (float) sb.s0), d1 = __fmul_rn(sb.d, (float) sb.s1); uint16_t* o = dst + r * (size_t) k + (size_t) kb * 32; + // (the 32 halves packed into four 16-byte stores: 32 two-byte stores a lane, each lane 64 bytes from the next, write + // ~16x the bytes they carry in DRAM sectors - measured as the dense dequant's whole cost: 6.6 GB to FP16 in 20.0 s) + uint32_t hw[16]; #pragma unroll - for (int j = 0; j < 32; ++j) { - const int q = (int) (int8_t) ((uint32_t) sb.q[j >> 2] >> (8 * (j & 3))); - const float v = j < 16 ? __fsub_rn(__fmul_rn(d0, (float) q), sb.m0) : __fsub_rn(__fmul_rn(d1, (float) q), sb.m1); - o[j] = bf16 ? strata::ds4::bf16_rn(v) : __half_as_ushort(__float2half_rn(v)); + for (int j = 0; j < 16; ++j) { + const int q0 = (int) (int8_t) ((uint32_t) sb.q[j >> 1] >> (8 * ((2 * j) & 3))); + const int q1 = (int) (int8_t) ((uint32_t) sb.q[j >> 1] >> (8 * ((2 * j + 1) & 3))); + const bool lo = (2 * j) < 16; + const float v0 = lo ? __fsub_rn(__fmul_rn(d0, (float) q0), sb.m0) : __fsub_rn(__fmul_rn(d1, (float) q0), sb.m1); + const bool lo1 = (2 * j + 1) < 16; + const float v1 = lo1 ? __fsub_rn(__fmul_rn(d0, (float) q1), sb.m0) : __fsub_rn(__fmul_rn(d1, (float) q1), sb.m1); + const uint32_t h0 = bf16 ? strata::ds4::bf16_rn(v0) : __half_as_ushort(__float2half_rn(v0)); + const uint32_t h1 = bf16 ? strata::ds4::bf16_rn(v1) : __half_as_ushort(__float2half_rn(v1)); + hw[j] = h0 | (h1 << 16); } + uint4* o4 = (uint4*) o; + o4[0] = make_uint4(hw[0], hw[1], hw[2], hw[3]); + o4[1] = make_uint4(hw[4], hw[5], hw[6], hw[7]); + o4[2] = make_uint4(hw[8], hw[9], hw[10], hw[11]); + o4[3] = make_uint4(hw[12], hw[13], hw[14], hw[15]); } } From e66d2758ed659aca1236e76b9d930eba27874102 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 12:46:27 +0100 Subject: [PATCH 021/177] docs: the release notes carry the two-conversation batching gain --- docs/release-notes-0.2.7.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index a7691122..9f6ebd44 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -27,6 +27,10 @@ These need no engine change; they are settings. Each was measured on the same bo vocabulary instead of 425 KB, so it reads less per guess: **+2.7..3.1% story and +2.2..3.0% code** decode on both big boxes. The big model checks every guess, so the answers are unchanged (identical tokens in every run where the machine is deterministic). A CJK or Cyrillic user should keep the wider subset. +- **`--slots 2`** - when the engine serves more than one conversation at a time (an agent with several sessions), decoding two + requests together returns **+10% aggregate throughput on the RTX PRO 5000 and +12% on the RTX 3060**, for a slightly higher + latency per token. Three and four slots add nothing measurable (+8.4% and +11.7%): the gain is all in the second slot, and + more slots cost KV memory. A single conversation gains nothing from it. - **`--prefill-pipe `** - on a two-card layer split, plan the prompt's chunks for the pipeline: **+15.4% at 4K, +22.5% at 8K, +2.7% at 16K** prompt on 2x RTX A4000 (5 interleaved pairs). `R` is the PC's own ratio; `setup --calibrate` measures it (1,500 on that box). From f9907b6d9ce53970823ba4315c86add652f63783 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 13:14:27 +0100 Subject: [PATCH 022/177] docs: the routing default is +67% with two conversations in flight --- docs/release-notes-0.2.7.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 9f6ebd44..76289d72 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -54,7 +54,8 @@ on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: | prompt 4K, in a 4K context | 248.5 | **291.0 (+17.1%)** | | decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | -It holds where it matters most: on content the tuning was never fitted to it measures **+29.0%** (43.5 -> 55.0 tok/s on a +It holds where it matters most: with **two conversations in flight** it measures **+67% aggregate** (59.7 against 35.6 tok/s), +and on content the tuning was never fitted to it **+29.0%** (43.5 -> 55.0 tok/s on a document prompt), and the whole recipe - routing, a workload-fitted expert profile, `--adapt-every 0`, `--vram-reserve-mib 896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. From 11b5a77fe99986d33a02a041c375bb7bc194547b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 13:23:56 +0100 Subject: [PATCH 023/177] docs: the agent scenario - two conversations nearly double throughput --- docs/release-notes-0.2.7.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 76289d72..0a044dfb 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -54,7 +54,9 @@ on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: | prompt 4K, in a 4K context | 248.5 | **291.0 (+17.1%)** | | decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | -It holds where it matters most: with **two conversations in flight** it measures **+67% aggregate** (59.7 against 35.6 tok/s), +It holds where it matters most: with **two conversations in flight** the whole recipe reads **31.2 -> 62.0 tok/s aggregate +(+99%)** and both answers arrive in 4.8 s instead of 9.7 s, and the routing default alone is **+67% aggregate** (59.7 against +35.6 tok/s) - and on content the tuning was never fitted to it **+29.0%** (43.5 -> 55.0 tok/s on a document prompt), and the whole recipe - routing, a workload-fitted expert profile, `--adapt-every 0`, `--vram-reserve-mib 896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. From 6bc27ebef73b2eeac2b94bac1f973a32ab5a7d16 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 13:34:58 +0100 Subject: [PATCH 024/177] docs: the agent scenario across all three boxes --- docs/release-notes-0.2.7.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 0a044dfb..91122a6b 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -55,8 +55,8 @@ on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: | decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | It holds where it matters most: with **two conversations in flight** the whole recipe reads **31.2 -> 62.0 tok/s aggregate -(+99%)** and both answers arrive in 4.8 s instead of 9.7 s, and the routing default alone is **+67% aggregate** (59.7 against -35.6 tok/s) - +(+99%)** on that card and +22% on the 2x A4000, both answers arriving in half the wall time on the 12 GB box, and the routing +default alone is **+67% aggregate** there (59.7 against 35.6 tok/s) - and on content the tuning was never fitted to it **+29.0%** (43.5 -> 55.0 tok/s on a document prompt), and the whole recipe - routing, a workload-fitted expert profile, `--adapt-every 0`, `--vram-reserve-mib 896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. From cca3dd2e33dd71de65c44bca5258b819b0badf8b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 15:07:37 +0100 Subject: [PATCH 025/177] dense GEMM: the chunked prompt's gemm() prefers the engine's own RDNA3 WMMA kernel (src/prefill/wmma_gemm.cu, now linked) over hipBLAS - 4.97 vs 20-40 TFLOPS at our shapes The dense GEMM was 11.1 s of a 4K prompt at hipBLAS's measured 4.97 TFLOPS (M 4096 N 2304 K 5120, the engine's call convention). A blocked WMMA kernel reaches 23.96 TFLOPS at that shape (128x128 tile, BK 32, 2-stage LDS, rocwmma; scripts/wmma2.cu) and the engine's own tuned kernel (BM 128 x BN 256, grouped tile order, raw wmma intrinsics) 20.8-20.9 at the wq_b shape and 38-41 at M 16384. gemm() now calls strata_pf_gemm_f16_ld with hipBLAS as the fallback (rows < 64, N < 512, K % 32, unaligned X: unchanged); STRATA_DENSE_PFGEMM=0 restores hipBLAS for an A/B. Same operands, the kernel's own k order (rounding-level). Measured on the box (eng-028, 4E224E7F -> 467D7320, 4K prompt fixture p4k, chunk 16384): 46.4 -> 38.1 s, 88.30 -> 107.63 tok/s; with DS4_SETTLE_MS=0;DS4_SETTLE_STORE=0 27.5 s = 148.98 tok/s. 8K 134.66 -> 218.31, 16K 158.6 -> 290.97, 32K 178.9 -> 316.92 (settle off). Decode unchanged in an interleaved A/B (old 15.17/16.73, new 17.38/18.48 tok/s) with acceptance 151/164 = 92% (93/98/100/100/90 per position). c.A (the attention slab, the reason each dense matrix is re-read 10-16x a prompt) takes STRATA_DS4_A_MB: 32 gives 107.63 -> 110.67, small because the expert reads now dominate. --- CMakeLists.txt | 6 ++++-- src/dsv41/ds4_model.cu | 23 +++++++++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c4e6e8a1..6e7a9b67 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -822,8 +822,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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}) + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill) + # strata_prefill: the RDNA3 WMMA dense GEMM (src/prefill/wmma_gemm.cu), which gemm() prefers over hipBLAS on gfx11 (measured + # 4.97 -> 20-40 TFLOPS on this part: the chunked prompt's dense GEMM is 11.1 s of a 4K prompt at the library's rate) + target_link_libraries(strata-dsv41 PRIVATE strata_prefill 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 diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 9e983c6f..807ac003 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -30,6 +30,7 @@ #include "strata/kernels/f16_bits.hpp" #include "strata/dsv41/moe_win.hpp" #include "strata/dsv41/sampler.hpp" +#include "wmma_gemm.h" // strata_pf_gemm_f16_ld: the RDNA3 WMMA dense GEMM (gemm() prefers it over hipBLAS on gfx11; -Isrc/prefill) #include #include @@ -2972,7 +2973,13 @@ struct Model::Impl { split128(g.ff, nm, 0, ff0_, FF); // (the widest member's share: member 0 takes the odd blocks) const size_t C = (size_t) chunk; c.C = chunk; - c.A = std::max(64, (int) (((size_t) 8 << 20) / (size_t) HQ) / 64 * 64); + // the attention slab's rows: 8 MB of q by default. Every dense GEMM of a layer is issued once a slab, so the slab + // width divides the prompt's dense weight traffic (the matrices are re-read once a slab): STRATA_DS4_A_MB widens it. + static const size_t a_mb = [] { + const char* v = std::getenv("STRATA_DS4_A_MB"); + return (size_t) (v != nullptr ? std::max(1, std::atoi(v)) : 8); + }(); + c.A = std::max(64, (int) ((a_mb << 20) / (size_t) HQ) / 64 * 64); // (the indexer's slab: its scores rows are the context wide - about 64 MB of them) c.AI = std::max(32, std::min(128, (int) (((size_t) 64 << 20) / (((size_t) o.max_context + 64) * 4)) / 32 * 32)); c.w16_elems = (size_t) 8 << 20; @@ -3041,15 +3048,27 @@ struct Model::Impl { return true; } - // y[r][c] = x16[r] . W[:, c] (+ beta y) for r < rows: W reconstructed to FP16 in whole 128-column blocks, cuBLAS + // y[r][c] = x16[r] . W[:, c] (+ beta y) for r < rows: W reconstructed to FP16 in whole 128-column blocks, then the product. + // The product prefers the engine's own RDNA3 WMMA kernel (src/prefill/wmma_gemm.cu) over hipBLAS: on gfx1151 hipBLAS + // measures 4.97 TFLOPS at this call convention while that kernel measures 20-40 (BM 128 x BN 256, grouped tile order), and + // the chunked prompt's dense GEMM is 11.1 s of a 4K prompt at the library's rate. Same operands and the same values (the + // k order differs, so it is rounding-level: the quality gate and the acceptance gate cover it); STRATA_DENSE_PFGEMM=0 keeps + // hipBLAS for an A/B. bool gemm(Dev& d, Chunk& c, const x3::Mat& m, const uint16_t* x16, int ldx, int rows, float* y, int ldy, float beta, std::string& err) { if (rows <= 0) return true; + static const bool pf = [] { + const char* v = std::getenv("STRATA_DENSE_PFGEMM"); + return v == nullptr || v[0] != '0'; + }(); const int cols = std::max(128, (int) std::min((size_t) m.n, c.w16_elems / (size_t) m.k) / 128 * 128); for (int c0 = 0; c0 < m.n; c0 += cols) { const int nc = std::min(cols, m.n - c0); if (m.fmt != 0) gg::rows(nc == m.n ? m : gg::view(m, c0, nc), c.w16, false, d.st); // (a GGUF's) else x3::reconstruct_rows(nc == m.n ? m : x3::view(m, c0, nc), c.w16, false, d.st); + if (pf && rows >= 64 && ((uintptr_t) x16 & 15u) == 0 && + strata_pf_gemm_f16_ld(x16, ldx, c.w16, m.k, y + c0, rows, nc, m.k, ldy, beta, d.st)) + continue; const float one = 1.0f; const cublasStatus_t st = cublasGemmEx(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, nc, rows, m.k, &one, c.w16, CUDA_R_16F, m.k, x16, CUDA_R_16F, ldx, &beta, y + c0, CUDA_R_32F, ldy, From 1ee6060afba9593b821d5c3048110baeb7114dcd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 15:08:43 +0100 Subject: [PATCH 026/177] docs: the 12 GB card's prompt figures are withdrawn - a five-pair repeat read +254% and -20.5% where the first read +35% and +17%, and that box's prompt swings 218-466 tok/s between arms --- docs/release-notes-0.2.7.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 91122a6b..c0345964 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -50,8 +50,7 @@ on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: |---|---|---| | decode story | 45.9 | **61.6 (+34.1%)** | | decode code | 43.6 | **73.1 (+67.6%)** | -| prompt 1K | 333.6 | **451.5 (+35.3%)** | -| prompt 4K, in a 4K context | 248.5 | **291.0 (+17.1%)** | +| prompt | **not claimed** - this box's prompt read swings between 218 and 466 tok/s across runs, and a repeat of the same five-pair A/B read +254% and -20.5% where the first read +35% and +17% | | decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | It holds where it matters most: with **two conversations in flight** the whole recipe reads **31.2 -> 62.0 tok/s aggregate From 67cfaf2ac65b5b353eafa6e9321c309319b75729 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 15:43:31 +0100 Subject: [PATCH 027/177] prompt streaming: the staging ring sizes from the VRAM room (400 -> 1200 MB on Strix Halo) and the attention slab defaults to 32 MB - 4K prompt 27.3 -> 21.0 s ring_mb_auto() returned a flat 400 MB on any box whose experts do not fit in VRAM, but on such a box the ring is exactly what lets a prompt queue its likely experts early. 400 -> 1200 MB measured on the box (settle off): the queue 3,200 -> 8,087 experts, the disk's effective rate 1.49 -> 2.44 GB/s, the compute's exposed read wait 11.4 -> 3.5 s, the 4K prompt 148.98 -> 190.98 tok/s; 16K 290.97 -> 315.01, 32K 316.92 -> 325.89. Decode unmoved in an interleaved A/B (17.54/16.39 against 17.61 tok/s). It is now a sixteenth of the VRAM room clamped to 400-1200 MB, so a smaller pool still loads; DS4_RING_MB still overrides. c.A: the attention slab decides how many times each dense matrix is re-read a prompt. 8 -> 32 MB (STRATA_DS4_A_MB): 32K 325.89 -> 357.78 tok/s, 16K 315.01 -> 328.04, 8K +1.6%, 4K flat, decode unmoved (16.81 against 17.60 tok/s interleaved, noise-limited) for ~0.4 GB of VRAM. Best measured prompt set with the two new defaults (DS4_SETTLE_MS=0;DS4_SETTLE_STORE=0, which is a prompt-only trade): 4K 195.18, 8K 258.47, 16K 328.04, 32K 357.78 tok/s. With the settle work at its default a 4K prompt is 31.3 s = 130.89 tok/s (was 88.30). --- src/dsv41/ds4_model.cu | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 807ac003..6d151af6 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2953,10 +2953,16 @@ struct Model::Impl { double exp_b = 0, other_b = 0, room = 0; const double share = gpu_expert_share(&exp_b, &room, &other_b); const bool fit = exp_b > 0 && share >= 1.0 / 1.3; // (R9700 x4: 0.86 -> ring 16: decode -1.8% after a prompt, 64: -4.4%, 400: -4.6%) + // A box whose experts do not fit (a unified-memory APU) streams them from the disk, and the ring is what lets the + // prompt queue its likely ones early: 400 -> 1200 MB on Strix Halo took the queue 3,200 -> 8,087 experts, the disk + // 1.49 -> 2.44 GB/s and the compute's exposed read wait 11.4 -> 3.5 s (4K prompt 27.3 -> 21.3 s, 148.98 -> 190.98 + // tok/s) with decode unchanged (17.54/16.39 against 17.61 tok/s interleaved). A sixteenth of the VRAM room, so a + // small pool still loads. DS4_RING_MB overrides. + const size_t want = (size_t) std::max(400.0, std::min(1200.0, room / 1e9 * 64.0)); if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, - room / 1e9, other_b / 1e9, fit ? 16 : 400); - return fit ? 16 : 400; + room / 1e9, other_b / 1e9, fit ? 16 : (int) want); + return fit ? 16 : want; } bool alloc_chunks(std::string& err) { chunks.resize(devs.size()); @@ -2973,11 +2979,13 @@ struct Model::Impl { split128(g.ff, nm, 0, ff0_, FF); // (the widest member's share: member 0 takes the odd blocks) const size_t C = (size_t) chunk; c.C = chunk; - // the attention slab's rows: 8 MB of q by default. Every dense GEMM of a layer is issued once a slab, so the slab - // width divides the prompt's dense weight traffic (the matrices are re-read once a slab): STRATA_DS4_A_MB widens it. + // the attention slab's rows: 32 MB of q. Every dense GEMM of a layer is issued once a slab, so the slab width + // divides the prompt's dense weight traffic (each matrix is re-read once a slab): 8 -> 32 MB took the 32K prompt + // 325.89 -> 357.78 tok/s, 16K 315.01 -> 328.04, 8K +1.6%, 4K flat, with decode unmoved (16.81 against 17.60 tok/s + // interleaved, noise-limited). STRATA_DS4_A_MB overrides (8 restores the old slab). static const size_t a_mb = [] { const char* v = std::getenv("STRATA_DS4_A_MB"); - return (size_t) (v != nullptr ? std::max(1, std::atoi(v)) : 8); + return (size_t) (v != nullptr ? std::max(1, std::atoi(v)) : 32); }(); c.A = std::max(64, (int) ((a_mb << 20) / (size_t) HQ) / 64 * 64); // (the indexer's slab: its scores rows are the context wide - about 64 MB of them) From 879b958a3e7aa708c45574d076936e3cb1c4e759 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 16:08:11 +0100 Subject: [PATCH 028/177] docs: setup is expected to choose --ple-io ram on a RAM-rich Linux PC - say to check setup --plan rather than asserting it --- docs/release-notes-0.2.7.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index c0345964..8c10493d 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -21,8 +21,8 @@ These need no engine change; they are settings. Each was measured on the same boxes. - **`--ple-io ram`** - the 28.8 GB n-gram table in RAM instead of read from the SSD row by row. On the 72 GB card - (251 GB RAM): prompt **+16.5% at 1K, +30.6% at 4K, +16.8% at 8K**, -2.6% at 16K. Setup already chooses it on - Linux PCs with RAM to spare. + (251 GB RAM): prompt **+16.5% at 1K, +30.6% at 4K, +16.8% at 8K**, -2.6% at 16K. Setup chooses it on a Linux PC + with RAM to spare - check `setup --plan` on yours before trusting that. - **`--mtp-draft-vocab draft_vocab_en.bin`** - the helper that guesses the next words considers 162 KB of the vocabulary instead of 425 KB, so it reads less per guess: **+2.7..3.1% story and +2.2..3.0% code** decode on both big boxes. The big model checks every guess, so the answers are unchanged (identical tokens in every run where From fd81df6972b656fbfd480be8cb16c4438384d1ff Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 16:16:28 +0100 Subject: [PATCH 029/177] DeepSeek engine (AMD): the matrix-core attention on by default for the chunked prompt fast_attn_enabled() was opt-in (DS4_FAST_ATTN=1); with the prompt chunk at 1024 it is worth far more than when it was gated: measured on 4x R9700, 2.25 bpw, 8K code prompts, three warm prompts a load, the same ids (5705e1164a) -- without it 1159 / 1180 / 1195 ppts (median 1180) with it 1327 / 1354 / 1360 ppts (median 1354, +14.7%) and after this commit the un-enved default reads 1314 / 1357 / 1369 (median 1357), i.e. identical to setting the flag, so a deployment no longer needs any environment at all. The QK/PV sums are the matrix cores' order, which the owner already approved for the prefill; the decode path keeps the scalar kernels. DS4_FAST_ATTN=0 turns it off (it is a no-op on CUDA, whose dispatch is not compiled). --- src/dsv41/ds4_kernels.cu | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index 7656f33a..a0b7c38a 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -1998,13 +1998,15 @@ bool split_enabled() { }(); return on; } -// DS4_FAST_ATTN=1: the chunked prompt's packed-KV attention on the matrix cores (sparse_attn_wmma_kernel). Opt-in: the -// QK/PV sums are the matrix cores' order, so the outputs differ from the scalar kernel's in the last places (the owner -// approved the trade for the prefill; the decode path stays on the scalar kernels). +// The chunked prompt's packed-KV attention on the matrix cores (sparse_attn_wmma_kernel). ON by default: measured on +// 4x R9700, 2.25 bpw, 8K code prompts, warm medians of three a load -- 1180 ppts without it, 1354 with it (+14.7%), +// the same ids (5705e1164a). The QK/PV sums are the matrix cores' order, so the last places differ from the scalar +// kernel's and the owner approved that trade for the prefill; the decode path stays on the scalar kernels. +// DS4_FAST_ATTN=0 turns it off. bool fast_attn_enabled() { static const bool on = [] { const char* e = std::getenv("DS4_FAST_ATTN"); - return e != nullptr && std::atoi(e) != 0; + return e != nullptr ? std::atoi(e) != 0 : true; }(); return on; } From 259532bf2e7457791114e66cade358a2a6415e44 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 17:07:53 +0100 Subject: [PATCH 030/177] prompt: the RAM store's post-prompt preload is off by default - it costs a 4K prompt 4.7 s and the decode that follows gains nothing cache_settle()'s store preload (DS4_SETTLE_STORE) read 2,243 hot experts into free store slots after every chunked prompt: 4,713 ms of a 4K prompt. Measured on the box (code fixture, prompt + 256 tokens, interleaved, 3 runs a side): with it on the decode is 13.9/14.4 s, with it off 14.2 s - no benefit - while the 4K prompt goes 31.3 -> 26.6 s (130.89 -> 153.78 tok/s). The swap loop above it is what the decode uses (it holds the CPU lane at ~5-7 k experts a run against ~14 k without), so that keeps its budget; DS4_SETTLE_STORE=1 restores the preload. --- src/dsv41/ds4_model.cu | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 6d151af6..48d6d54f 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -6282,7 +6282,10 @@ struct Model::Impl { if (sw_inflight == 0) break; // (nothing queued: every layer's best CPU-lane expert is not hotter than its coldest VRAM one) std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (store && env_f("DS4_SETTLE_STORE", 1.0f) != 0.0f) { // the RAM store too: a window prompt fills it through the CPU + // The RAM store's preload after a chunked prompt is off by default: measured on Strix Halo (code fixture, prompt + + // 256 tokens, 3 runs a side) it costs the prompt 4.7 s and the decode that follows gains nothing (13.9/14.4 s with it + // against 14.2 s without). The swaps above are what the decode actually uses; DS4_SETTLE_STORE=1 restores it. + if (store && env_f("DS4_SETTLE_STORE", 0.0f) != 0.0f) { // the RAM store too: a window prompt fills it through the CPU // lane's picks, a chunked one streams past it - the hottest CPU-lane experts of the prompt into its free slots std::vector>> hot; for (const Layer& l : L) { From 2e1fad783d232e4904903dfdd079e96aad949a21 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 17:35:48 +0100 Subject: [PATCH 031/177] host test offline-start: point STRATA_COMPONENTS_DIR at the test's own folder so the host cannot find an installed Strata Control. On a PC with the app installed the update check went through the installed Control (no host fetch, 45 s), so the test saw 0 outside calls and failed; it failed the same on v0.2.6. With the fix both tests pass in 2-12 s. --- apps/host/tests/offline-start.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/tests/offline-start.test.mjs b/apps/host/tests/offline-start.test.mjs index dd53ee4d..4968e131 100644 --- a/apps/host/tests/offline-start.test.mjs +++ b/apps/host/tests/offline-start.test.mjs @@ -26,7 +26,7 @@ async function startOfflineHost() { let output = ''; const host = spawn(process.execPath, ['--import', preload, 'server/index.mjs'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], - env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_PACKAGED: '1', STRATA_NET_LOG: log, STRATA_NO_ACQUIRE: '1', STRATA_REAL_ENGINE: '0', STRATA_TEST_HARDWARE: ROOMY_HOST }, + env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_PACKAGED: '1', STRATA_COMPONENTS_DIR: join(home, 'components'), STRATA_NET_LOG: log, STRATA_NO_ACQUIRE: '1', STRATA_REAL_ENGINE: '0', STRATA_TEST_HARDWARE: ROOMY_HOST }, }); host.stdout.on('data', d => { output += d; }); host.stderr.on('data', d => { output += d; }); let up = false; From 20c2f42bf106c6c58377e4fe77029b6d78e3fd85 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 17:36:16 +0100 Subject: [PATCH 032/177] ds4_iq.cu: the NUL character literal in dq_use_old_kernel had been written as a raw NUL byte by the merge script (nvcc: quoted string should contain at least one character); it is a backslash-zero escape again --- src/dsv41/ds4_iq.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index b0539d1d..931e3d33 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -1393,7 +1393,7 @@ __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __rest // prompt 79.5 -> 88.5 tok/s with it, so a gfx11 device defaults to it. DS4_DQ_OLD=1 forces it anywhere, DS4_DQ_OLD=0 forces kernel2 // anywhere. The detection is the device's gcnArchName (HIP only; a CUDA build has no gfx11). Decided once per device. static bool dq_use_old_kernel() { - if (const char* e = std::getenv("DS4_DQ_OLD"); e != nullptr && *e != '') return std::atoi(e) != 0; + if (const char* e = std::getenv("DS4_DQ_OLD"); e != nullptr && *e != '\0') return std::atoi(e) != 0; #if defined(STRATA_USE_HIP) static std::atomic cache[64]; // 0 unknown, 1 no, 2 yes int dev = 0; From 063b3c5dc8b2ea1eb4493d915d7295754ae3be5a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 17:48:36 +0100 Subject: [PATCH 033/177] DeepSeek engine: the RDNA3 WMMA dense GEMM call in gemm() is HIP-only (wmma_gemm.cu is part of the AMD builds; main's 0eea4a3d5 called strata_pf_gemm_f16_ld unconditionally, so a CUDA build failed to link: unresolved external) --- src/dsv41/ds4_model.cu | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index e224ad6a..deee99ab 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -3110,18 +3110,22 @@ struct Model::Impl { bool gemm(Dev& d, Chunk& c, const x3::Mat& m, const uint16_t* x16, int ldx, int rows, float* y, int ldy, float beta, std::string& err) { if (rows <= 0) return true; +#if defined(STRATA_USE_HIP) // (wmma_gemm.cu is part of the AMD builds only: a CUDA build has no such kernel and keeps cuBLAS) static const bool pf = [] { const char* v = std::getenv("STRATA_DENSE_PFGEMM"); return v == nullptr || v[0] != '0'; }(); +#endif const int cols = std::max(128, (int) std::min((size_t) m.n, c.w16_elems / (size_t) m.k) / 128 * 128); for (int c0 = 0; c0 < m.n; c0 += cols) { const int nc = std::min(cols, m.n - c0); if (m.fmt != 0) gg::rows(nc == m.n ? m : gg::view(m, c0, nc), c.w16, false, d.st); // (a GGUF's) else x3::reconstruct_rows(nc == m.n ? m : x3::view(m, c0, nc), c.w16, false, d.st); +#if defined(STRATA_USE_HIP) if (pf && rows >= 64 && ((uintptr_t) x16 & 15u) == 0 && strata_pf_gemm_f16_ld(x16, ldx, c.w16, m.k, y + c0, rows, nc, m.k, ldy, beta, d.st)) continue; +#endif const float one = 1.0f; const cublasStatus_t st = cublasGemmEx(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, nc, rows, m.k, &one, c.w16, CUDA_R_16F, m.k, x16, CUDA_R_16F, ldx, &beta, y + c0, CUDA_R_32F, ldy, From f681b9ad62b39cd1ae50e823c8b2bd871ab77e89 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:08:17 +0100 Subject: [PATCH 034/177] Manual mode: the look-only shell allowlist takes only options known to look (#3975) A command on the allowlist used to run without a card with any option except -delete/-exec/-execdir/-fprint/-fls/-ok. Write modes (sort -o, tree -o, uniq IN OUT), program-execution modes (sort --compress-program, rg --pre, git grep -O), date -s and tail -f got through, and so did git config -e, git branch --set-upstream-to and git remote ... forms. Each command now has a spec of the options and operands that only look (short and long, spelled in full); every other option, abbreviation or attached form asks. git subcommands have the same specs, a branch/tag name is taken only with a list option, git config only reads with --get. date takes only +FORMAT operands, uniq at most one operand, hostname none. less and more leave the list. Quoted texts are checked as operands too. `du -sh` no longer trips the 'sh' word check. Tests: apps/host/tests/gate-readonly.test.mjs (deny and allow cases for options, operands, spellings, quoting; every listed command asks for an unknown option). --- apps/host/server/agent/README.md | 2 +- .../host/server/agent/plugins/strata-gate.mjs | 236 +++++++++++++++--- apps/host/tests/gate-readonly.test.mjs | 148 +++++++++++ docs/SAFETY.md | 4 +- 4 files changed, 355 insertions(+), 35 deletions(-) create mode 100644 apps/host/tests/gate-readonly.test.mjs diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index b05bebcf..5afd94c1 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -61,7 +61,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha | Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | - Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. -- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked; MCP and unknown tools ask. +- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. - Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to ." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. - The mode is read once per turn; an unknown or missing value is Manual. diff --git a/apps/host/server/agent/plugins/strata-gate.mjs b/apps/host/server/agent/plugins/strata-gate.mjs index 96e59221..098ceea8 100644 --- a/apps/host/server/agent/plugins/strata-gate.mjs +++ b/apps/host/server/agent/plugins/strata-gate.mjs @@ -48,25 +48,196 @@ export const READ_ONLY_TOOLS = new Set([ const SHELL_TOOLS = new Set(['pwsh', 'bash']); -/** Commands that only look. Matched against the first word of every pipeline segment. */ -const SAFE_COMMANDS = new Set([ - // PowerShell - 'get-childitem', 'gci', 'ls', 'dir', 'get-content', 'gc', 'cat', 'type', 'get-item', 'gi', 'get-location', 'pwd', 'gl', - 'select-string', 'sls', 'measure-object', 'measure', 'select-object', 'select', 'where-object', 'where', 'sort-object', 'sort', - 'format-table', 'ft', 'format-list', 'fl', 'out-string', 'test-path', 'resolve-path', 'get-filehash', 'get-date', 'get-command', - 'get-process', 'get-itemproperty', 'write-output', 'echo', 'hostname', 'whoami', 'get-host', 'get-psdrive', 'get-help', - 'group-object', 'group', 'convertto-json', 'convertfrom-json', 'select-xml', 'compare-object', 'get-unique', 'tee-object-none', - // POSIX - 'head', 'tail', 'wc', 'grep', 'rg', 'egrep', 'fgrep', 'stat', 'file', 'du', 'df', 'uname', 'which', 'basename', 'dirname', - 'realpath', 'readlink', 'sort', 'uniq', 'cut', 'tr', 'less', 'more', 'date', 'id', 'env-none', 'tree', -]); +/** + * Which shell commands run without a card in Manual mode, and with which options. Safe by construction (#3975): a command is on the list WITH the + * options that are known to only look. Every other option, long or short, abbreviated or attached, makes the command ask. So a write mode + * (`sort -o`, `tree -o`, `uniq in out`), a program-execution mode (`sort --compress-program`, `rg --pre`, `git grep -O`), a setting mode + * (`date -s`) or one that never ends (`tail -f`) cannot slip in, and a word added to the list later starts with no options at all. + * + * A spec says what one command accepts: + * f short options without a value (letters, so `-la` is `-l -a`) v short options that need a value (`-k2`, `-k 2`) + * vn the same, and the value must be a number o short options with an optional value that must be attached (`-Iseconds`) + * n a bare `-5` is allowed l long options (`--name`, `--name=value`), spelled in full + * lv long options that need a value (`--name=value`, `--name value`) ps PowerShell parameter names, lower case, spelled in full + * max how many operands (files, patterns) are allowed op a check for each operand + * post a last check from the options seen and the operand count + */ +const words = (text) => (text ? text.trim().split(/\s+/) : []); +const spec = ({ f = '', v = '', vn = '', o = '', n = false, l = '', lv = '', ps = '', max = Infinity, op = null, post = null }) => + ({ f, v, vn, o, n, l: new Set(words(l)), lv: new Set(words(lv)), ps: ps ? new Set([...words(ps), ...PS_COMMON]) : null, max, op, post }); +/** Parameters every cmdlet has that only change how errors and warnings show. (-Debug asks a question and -OutVariable sets one: not listed.) */ +const PS_COMMON = ['erroraction', 'ea', 'warningaction', 'wa', 'informationaction', 'ia', 'verbose', 'vb']; +const NUMBER = /^[+-]?\d+[A-Za-z]{0,3}$/; + +/** What `ls`, `dir`, `gci` and `Get-ChildItem` take. */ +const LS = { f: 'aAbBcdDFgGhHiklLmnNopqQrRsStuUvxX1CZ', v: 'ITw', ps: 'path literalpath filter include exclude recurse depth name force file directory hidden readonly system attributes', + l: 'all almost-all human-readable recursive directory classify reverse size inode dereference color group-directories-first sort time time-style block-size indicator-style si numeric-uid-gid no-group literal hide ignore quote-name escape author file-type full-time width tabsize' }; +/** What `cat`, `type`, `gc` and `Get-Content` take. (-Wait never ends, so it is not here.) */ +const CAT = { f: 'AbeEnstTuv', ps: 'path literalpath totalcount tail head raw encoding readcount force filter include exclude delimiter stream asbytestream', + l: 'show-all number-nonblank show-ends number squeeze-blank show-tabs show-nonprinting' }; +const MEASURE = { ps: 'property sum average maximum minimum line word character ignorewhitespace inputobject standarddeviation allstats' }; +const SELECT = { ps: 'first last skip skiplast property expandproperty unique index excludeproperty inputobject' }; +const WHERE = { ps: 'property value inputobject eq ne gt lt ge le like notlike match notmatch contains notcontains in notin is isnot ceq cne cgt clt cge cle clike cnotlike cmatch cnotmatch ccontains cnotcontains cin cnotin' }; +const GROUP = { ps: 'property noelement ashashtable asstring casesensitive inputobject culture' }; +const FT = { ps: 'property autosize wrap hidetableheaders groupby view force expand repeatheader displayerror showerror inputobject' }; +const FL = { ps: 'property view groupby expand force displayerror showerror inputobject' }; +const SLS = { ps: 'pattern path literalpath simplematch casesensitive context list notmatch quiet allmatches include exclude encoding raw inputobject culture noemphasis' }; +const GETITEM = { ps: 'path literalpath name filter include exclude force stream' }; +const GETLOC = { ps: 'psprovider psdrive stack stackname' }; +const ECHO = { f: 'neE', ps: 'inputobject noenumerate' }; +/** The GNU/BSD grep family. */ +const GREP = { f: 'aiIlLcnvwHhEFGPqrRsTUyzZbxo', v: 'efdD', vn: 'ABCm', n: true, + l: 'extended-regexp fixed-strings basic-regexp perl-regexp ignore-case no-ignore-case word-regexp line-regexp invert-match count color colour files-with-matches files-without-match max-count only-matching quiet silent no-messages byte-offset with-filename no-filename label line-buffered initial-tab null after-context before-context context text recursive dereference-recursive include exclude exclude-dir binary-files line-number null-data no-group-separator group-separator regexp file directories devices binary' }; + +/** Commands that only look, each with the options that are known to be harmless. Matched against the first word of every pipeline segment. */ +const SPECS = new Map(); +const add = (names, s) => { for (const name of words(names)) SPECS.set(name, spec(s)); }; +// PowerShell +add('get-childitem gci', { ps: LS.ps }); +add('ls dir', LS); +add('get-content gc', { ps: CAT.ps }); +add('cat type', CAT); +add('get-item gi get-itemproperty', GETITEM); +add('get-location gl', GETLOC); +add('pwd', { ...GETLOC, f: 'LP' }); +add('select-string sls', SLS); +add('measure-object measure', MEASURE); +add('select-object select', SELECT); +add('where-object where', WHERE); +add('sort-object', { ps: 'property descending unique top bottom casesensitive culture stable inputobject' }); +add('format-table ft', FT); +add('format-list fl', FL); +add('out-string', { ps: 'stream width inputobject' }); +add('test-path', { ps: 'path literalpath pathtype isvalid filter include exclude olderthan newerthan' }); +add('resolve-path', { ps: 'path literalpath relative relativebasepath force' }); +add('get-filehash', { ps: 'path literalpath algorithm' }); +add('get-date', { ps: 'format uformat date asutc displayhint year month day hour minute second millisecond' }); +add('get-command', { ps: 'name commandtype module all syntax listimported totalcount noun verb fullyqualifiedmodule parametername parametertype' }); +add('get-process', { ps: 'name id includeusername module fileversioninfo inputobject' }); +add('write-output', { ps: ECHO.ps }); +add('echo', ECHO); +add('get-host', { ps: '' }); +add('get-psdrive', { ps: 'name psprovider scope literalname' }); +add('get-help', { ps: 'name full detailed examples parameter category component functionality role' }); +add('group-object group', GROUP); +add('convertto-json', { ps: 'depth compress enumsasstrings inputobject asarray escapehandling' }); +add('convertfrom-json', { ps: 'ashashtable depth inputobject noenumerate' }); +add('select-xml', { ps: 'xml path literalpath xpath content namespace' }); +add('compare-object', { ps: 'referenceobject differenceobject property includeequal excludedifferent passthru syncwindow casesensitive culture' }); +add('get-unique', { ps: 'inputobject asstring caseinsensitive onetype' }); +// POSIX. `sort` and `date` take no PowerShell names here: `sort -o FILE` writes, `date -s` sets the clock, and a PowerShell-looking `-Second` or `-Top` +// must not be read by a real sort or date as one of those. (Sort-Object and Get-Date above are the PowerShell forms.) +add('head', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); +add('tail', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); // no -f, -F, --follow, --retry, --pid, -s: those never end +add('wc', { f: 'lwcmL', l: 'lines words bytes chars max-line-length' }); +add('grep egrep fgrep', GREP); +add('rg', { // no --pre, --pre-glob, --hostname-bin (they run a program) and no -z/--search-zip (it runs decompressors) + f: 'iIsSnNHlcwFxvUoLaquhVpbP', v: 'efgtTr', vn: 'ABCjdMm', + l: 'ignore-case no-ignore-case smart-case case-sensitive fixed-strings word-regexp line-regexp invert-match count count-matches files-with-matches files-without-match files type-list hidden no-ignore no-ignore-vcs no-ignore-parent no-ignore-dot no-ignore-global no-ignore-messages follow line-number no-line-number with-filename no-filename column heading no-heading null only-matching quiet text multiline multiline-dotall pcre2 no-messages json stats trim unrestricted binary no-config vimgrep pretty byte-offset passthru crlf one-file-system no-unicode regexp file glob iglob type type-not max-count max-depth maxdepth context after-context before-context color replace threads sort sortr max-filesize max-columns path-separator encoding engine ignore-file glob-case-insensitive no-glob-case-insensitive' }); +add('stat', { f: 'LtxlnqrsFf', v: 'c', l: 'dereference file-system terse format printf' }); +add('file', { f: 'bhikLnNrvI', l: 'brief dereference no-dereference mime mime-type mime-encoding keep-going no-pad no-buffer raw' }); // no -C, -m, -f, -P (they write or read other files), no -z/-s/-p (they run decompressors, read devices, reset times) +add('du', { f: 'abchHklmsxLPSD0', v: 'tB', vn: 'd', l: 'all apparent-size bytes total dereference-args human-readable si summarize one-file-system dereference no-dereference separate-dirs count-links inodes null max-depth threshold block-size time time-style exclude' }); +add('df', { f: 'ahHiklmPTv', v: 'txB', l: 'all human-readable si inodes local portability print-type total sync no-sync output block-size type exclude-type' }); +add('uname', { f: 'asnrvmpio', max: 0, l: 'all kernel-name nodename kernel-release kernel-version machine processor hardware-platform operating-system' }); +add('which', { f: 'as', l: 'all' }); +add('basename', { f: 'az', v: 's', l: 'multiple zero suffix' }); +add('dirname', { f: 'z', l: 'zero' }); +add('realpath', { f: 'emsqzLP', l: 'canonicalize-existing canonicalize-missing no-symlinks quiet zero strip logical physical relative-to relative-base' }); +add('readlink', { f: 'femnqsvz', l: 'canonicalize canonicalize-existing canonicalize-missing no-newline quiet silent verbose zero' }); +add('sort', { f: 'bdfghiMnRrsuVzmcC', v: 'kt', l: 'ignore-leading-blanks dictionary-order ignore-case general-numeric-sort human-numeric-sort ignore-nonprinting month-sort numeric-sort random-sort reverse stable unique version-sort zero-terminated check merge sort field-separator key' }); +// uniq's second operand is its OUTPUT file, so it takes at most one. +add('uniq', { f: 'cdDuiz', vn: 'fsw', max: 1, l: 'count repeated all-repeated unique ignore-case skip-fields skip-chars check-chars zero-terminated group' }); +add('cut', { f: 'snz', v: 'bcfd', l: 'complement only-delimited zero-terminated bytes characters fields delimiter output-delimiter' }); +add('tr', { f: 'cCdst', max: 2 }); +add('date', { f: 'uR', o: 'I', v: 'dr', lv: 'date reference', l: 'utc universal rfc-email rfc-2822 iso-8601 rfc-3339', + op: (word) => word.startsWith('+') }); // a bare operand like 1026120026 SETS the clock; only +FORMAT is a format +add('id', { f: 'ugGnrazZ', l: 'user group groups name real context zero' }); +add('hostname', { f: 'sfiIdaAyv', max: 0 }); // `hostname NAME` renames the machine +add('whoami', { l: 'help version', op: (word) => /^\/(all|user|groups|priv|upn|fqdn|logonid|nh)$/i.test(word) }); +add('tree', { f: 'adfilpsugDFqNQrtvxCnASUchJX', v: 'LPIHT', vn: '', l: 'help version filelimit charset sort timefmt noreport dirsfirst filesfirst prune du si gitignore matchdirs ignore-case inodes device nolinks' }); // no -o, no -R +// `less` and `more` are not here: they wait for keys, and `less` can run commands. + +/** The names that run without a card (for the tests). */ +export const readOnlyCommandNames = () => [...SPECS.keys()]; + +/** git subcommands that only read, with the options they may take. */ +const GIT_VIEW = 'oneline graph decorate no-decorate all branches tags remotes stat shortstat numstat dirstat name-only name-status patch no-patch raw summary compact-summary abbrev-commit no-abbrev-commit abbrev reverse follow no-merges merges first-parent full-history simplify-by-decoration simplify-merges ancestry-path left-right left-only right-only cherry-pick cherry-mark cherry topo-order date-order author-date-order relative-date all-match invert-grep regexp-ignore-case extended-regexp fixed-strings perl-regexp no-color color color-words word-diff word-diff-regex minimal patience histogram diff-algorithm check exit-code quiet cached staged merge-base no-index no-ext-diff no-textconv find-renames find-copies find-copies-harder no-renames ignore-space-change ignore-all-space ignore-space-at-eol ignore-blank-lines ignore-cr-at-eol function-context show-function unified inter-hunk-context src-prefix dst-prefix no-prefix full-index binary text source use-mailmap mailmap no-mailmap log-size notes no-notes show-signature diff-merges boundary children parents no-walk sparse date format pretty author committer grep since until after before max-count skip min-parents max-parents diff-filter encoding stat-width stat-name-width stat-graph-width stat-count count'; +const LISTING = ['l', 'list', 'contains', 'no-contains', 'merged', 'no-merged', 'points-at']; +const GIT = new Map(Object.entries({ + status: spec({ f: 'sbvz', o: 'u', l: 'short branch porcelain long ignored untracked-files ignore-submodules renames no-renames find-renames show-stash ahead-behind no-ahead-behind column no-column verbose null' }), + log: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + diff: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + show: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + 'rev-list': spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + shortlog: spec({ f: 'sneciw', n: false, l: `${GIT_VIEW} summary numbered email committer group` }), + // Listing forms only. A name with no list option would CREATE a branch or a tag, and the options that change things are not here. + branch: spec({ f: 'avri', l: 'list all remotes verbose show-current ignore-case contains no-contains merged no-merged points-at sort format abbrev no-abbrev color no-color column no-column omit-empty', + post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }), + tag: spec({ f: 'li', o: 'n', l: 'list sort contains no-contains merged no-merged points-at format column no-column ignore-case omit-empty color no-color', + post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }), + remote: spec({ f: 'v', l: 'verbose', max: 0 }), + // `git config KEY` reads and `git config KEY VALUE` writes, so a key is only taken with --get; no --edit, --add, --unset, --file. + config: spec({ f: 'lz', l: 'list get get-all get-regexp show-origin show-scope local global system worktree bool int bool-or-int path expiry-date type null name-only includes no-includes', lv: 'default', + post: (seen, count) => (count > 0 ? ['get', 'get-all', 'get-regexp'].some(name => seen.has(name)) : seen.has('list') || seen.has('l')) }), + 'rev-parse': spec({ f: 'q', l: 'show-toplevel git-dir git-common-dir absolute-git-dir abbrev-ref symbolic symbolic-full-name short verify is-inside-work-tree is-inside-git-dir is-bare-repository is-shallow-repository show-prefix show-cdup show-superproject-working-tree all branches tags remotes quiet revs-only no-revs flags no-flags local-env-vars show-object-format path-format', lv: 'default git-path' }), + 'ls-files': spec({ f: 'cdmoiskuzvtfD', l: 'cached deleted modified others ignored stage directory unmerged killed no-empty-directory error-unmatch exclude-standard exclude full-name eol deduplicate recurse-submodules sparse abbrev resolve-undo format' }), + 'ls-tree': spec({ f: 'rtdlz', l: 'name-only name-status long full-name full-tree object-only abbrev format' }), + blame: spec({ f: 'wMCespltbfnc', v: 'L', l: 'porcelain line-porcelain incremental show-email show-name show-number date root abbrev' }), + describe: spec({ l: 'all tags always long dirty broken contains abbrev match exclude first-parent exact-match candidates' }), + 'cat-file': spec({ f: 'tsep', l: 'batch batch-check batch-all-objects allow-unknown-type buffer unordered follow-symlinks mailmap use-mailmap' }), // no --textconv, --filters + // No -O / --open-files-in-pager: they run a program on the matches. + grep: spec({ f: 'aiIlLcnvwHhEFGPqpWrzUo', v: 'e', vn: 'ABCm', n: true, l: 'no-index untracked cached no-exclude-standard exclude-standard recurse-submodules text ignore-case word-regexp invert-match full-name extended-regexp basic-regexp perl-regexp fixed-strings line-number column files-with-matches name-only files-without-match count null only-matching quiet no-color color break heading show-function function-context all-match and or not max-depth max-count threads after-context before-context context recursive no-recursive' }), +})); + +/** + * One command's words against its spec: every option has to be one the spec knows (anything else is not understood, so it asks). + * @param {ReturnType} sp + * @param {{t:string,q:boolean}[]} args the words after the command; q marks a quoted text, which is data and never an option + */ +function argumentsAreSafe(sp, args) { + const seen = new Set(); + let operands = 0, ended = false; + const operand = (arg) => { operands++; return operands <= sp.max && (!sp.op || sp.op(arg.t, arg.q)); }; + const valueOf = (i, numeric) => { // the next word as an option's value; it can be a quoted text, a number, or a word that is not an option + const arg = args[i + 1]; + if (!arg) return false; + return numeric ? NUMBER.test(arg.t) : arg.q || !arg.t.startsWith('-') || NUMBER.test(arg.t); + }; + for (let i = 0; i < args.length; i++) { + const { t, q } = args[i]; + if (q || ended || t === '-' || t[0] !== '-') { if (!operand(args[i])) return false; continue; } + if (t === '--') { ended = true; continue; } + if (t.startsWith('--')) { + const eq = t.indexOf('='); + const name = eq < 0 ? t.slice(2) : t.slice(2, eq); + if (sp.l.has(name)) { seen.add(name); continue; } + if (sp.lv.has(name)) { seen.add(name); if (eq < 0) { if (!valueOf(i, false)) return false; i++; } continue; } + return false; + } + if (sp.ps) { + const named = /^-([A-Za-z][A-Za-z0-9]*)(?::|$)/.exec(t); + if (named && sp.ps.has(named[1].toLowerCase())) { seen.add(named[1].toLowerCase()); continue; } + } + if (sp.n && /^-\d+$/.test(t)) continue; + for (let j = 1; j < t.length; j++) { + const c = t[j]; + if (sp.f.includes(c)) { seen.add(c); continue; } + if (sp.o.includes(c)) { seen.add(c); break; } + const numeric = sp.vn.includes(c); + if (!numeric && !sp.v.includes(c)) return false; + seen.add(c); + const rest = t.slice(j + 1); + if (rest) { if (numeric && !NUMBER.test(rest)) return false; } else { if (!valueOf(i, numeric)) return false; i++; } + break; + } + } + return sp.post ? sp.post(seen, operands) : true; +} -/** git subcommands that only read. */ -const SAFE_GIT = new Set(['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']); const SAFE_VERSION = /^(node|python|python3|py|npm|pnpm|git|dotnet|cargo|rustc|go|java|pip|pip3)\s+(--version|-v|-version|version)$/i; -/** Anything that can chain, redirect, expand or start something else is not read-only. */ -const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|\bsh\b|\bbash\b|\bpwsh\b|\bpowershell\b|\bcmd\b|-exec\b|-delete\b|-execdir\b/i; +/** Anything that can chain, redirect, expand or start something else is not read-only. (`sh` as a word, not inside an option like `du -sh`.) */ +const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|(?`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd * inside double quotes a $ or a backtick expands (a variable, a sub-command), and an unterminated quote means the text was not understood. * Either one gives null, and the command asks as before. * @param {string} text + * @param {string[]} [quoted] when given, receives the text inside each quote, in order (the checks on operands read it) * @returns {string|null} */ -export function maskQuotes(text) { +export function maskQuotes(text, quoted) { let out = ''; for (let i = 0; i < text.length; i++) { const c = text[i]; @@ -91,13 +263,14 @@ export function maskQuotes(text) { const before = text[i - 1], after = text[end + 1]; if ((before !== undefined && !/[\s|]/.test(before)) || (after !== undefined && !/[\s|]/.test(after)) || text[i + 1] === '-') return null; out += '"_"'; + quoted?.push(text.slice(i + 1, end)); i = end; } return out; } /** - * Whether a shell command only reads. Conservative by design: one unrecognised word and the answer is no. + * Whether a shell command only reads. Conservative by design: one unrecognised word or option and the answer is no. * Quoted text is data and is looked at after it has been set aside (maskQuotes): Get-ChildItem "C:\Users\x\Q&A" only lists. * @param {string} command * @returns {boolean} @@ -106,24 +279,21 @@ export function isReadOnlyShell(command) { const text = String(command ?? '').trim(); if (!text || text.length > 600) return false; if (SAFE_VERSION.test(text)) return true; - const masked = maskQuotes(text); + const quoted = []; + const masked = maskQuotes(text, quoted); if (masked === null || UNSAFE_SYNTAX.test(masked)) return false; - const segments = masked.split('|').map(s => s.trim()); - return segments.every((segment) => { - if (!segment) return false; - const words = segment.split(/\s+/); - const first = words[0].toLowerCase().replace(/^\.\\/, ''); + let next = 0; + const tokens = masked.split('|').map(segment => segment.trim()).map(segment => words(segment).map(w => (w === '"_"' ? { t: quoted[next++] ?? '', q: true } : { t: w, q: false }))); + return tokens.every((segment) => { + if (!segment.length || segment[0].q) return false; + const first = segment[0].t.toLowerCase().replace(/^\.\\/, ''); if (first === 'git') { - // `git config` and `git tag`/`branch`/`remote` can write when given a value; only the bare listing forms are safe. - const sub = (words[1] ?? '').toLowerCase(); - if (!SAFE_GIT.has(sub)) return false; - if (['config', 'tag', 'branch', 'remote'].includes(sub)) { - const rest = words.slice(2).filter(w => !w.startsWith('-') || /^(-l|-a|-v|-vv|--list|--all|--show-current|--get|--get-all)$/i.test(w)); - return rest.length === 0 || (sub === 'config' && words[2] === '--get') || (sub === 'remote' && words[2] === '-v'); - } - return !words.some(w => /^--(output|ext-diff|textconv)\b/i.test(w)); + const sub = segment[1]; + const sp = sub && !sub.q ? GIT.get(sub.t) : null; + return !!sp && argumentsAreSafe(sp, segment.slice(2)); } - return SAFE_COMMANDS.has(first) && !words.some(w => /^-(delete|exec|execdir|fprint|fls|ok)$/i.test(w)); + const sp = SPECS.get(first); + return !!sp && argumentsAreSafe(sp, segment.slice(1)); }); } diff --git a/apps/host/tests/gate-readonly.test.mjs b/apps/host/tests/gate-readonly.test.mjs new file mode 100644 index 00000000..5fd9d8e8 --- /dev/null +++ b/apps/host/tests/gate-readonly.test.mjs @@ -0,0 +1,148 @@ +// #3975 (P0): Manual mode's "read-only" shell allowlist must be safe by construction. A command without a card may only use options that are known to +// look and nothing else. The first block is what the issue reported (write and program-execution modes of allowlisted commands), the rest is the +// same class: options, operands, spellings and quoting. The last block is the commands people really type, which must keep running unasked. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { isReadOnlyShell, maskQuotes, readOnlyCommandNames } from '../server/agent/plugins/strata-gate.mjs'; + +const denied = (list) => { for (const c of list) assert.equal(isReadOnlyShell(c), false, `must ask: ${c}`); }; +const allowed = (list) => { for (const c of list) assert.equal(isReadOnlyShell(c), true, `must run unasked: ${c}`); }; + +test('#3975: the five confirmed cases and the rest of the issue table now ask', () => { + denied([ + 'sort --compress-program=sh a.txt', 'sort --compress-program sh a.txt', 'sort -o out.txt a.txt', 'sort --output=out.txt a.txt', + 'rg --pre sh pattern', 'rg --pre=sh pattern', + 'git grep -Osh pattern', 'git grep -O sh pattern', 'git grep --open-files-in-pager=sh pattern', + 'uniq in.txt out.txt', + 'tree -o out.txt', 'file -C -m x', 'date -s 12:00', 'date --set=12:00', 'tail -f app.log', + ]); +}); + +test('#3975: other spellings of the same options (attached, clustered, abbreviated, repeated) ask', () => { + denied([ + 'sort -oout.txt a.txt', 'sort -ro out.txt a.txt', 'sort -nro out.txt a.txt', 'sort --out=out.txt a.txt', 'sort --outp out.txt a.txt', + 'sort --comp=sh a.txt', 'sort -T /tmp a.txt', 'sort --files0-from=list a.txt', 'sort -n -u -o out a', + 'rg --pre-glob "*" x', 'rg --hostname-bin=sh x', 'rg -z x', 'rg --search-zip x', 'rg -uz x', 'rg --pre sh --files', + 'git grep -O"sh" x', 'git grep -nOsh x', 'git grep -O x', 'git grep --open x', 'git grep -l --open-files-in-pager=sh x', + 'uniq - out.txt', 'uniq -c in.txt out.txt', 'uniq -i -u in out', + 'tree -oout.txt', 'tree -a -o out.txt', 'tree -R', 'tree --output=out', + 'file -C', 'file --compile x', 'file -m magic x', 'file -f list', 'file -bC x', 'file --magic-file=x y', + 'date -sMonth', 'date -u -s now', 'date --set now', 'date 102612002026', 'date -u 1026', 'date -d now 1026', + 'tail -F app.log', 'tail --follow app.log', 'tail --follow=name app.log', 'tail -fn5 app.log', 'tail -n 1 -f app.log', 'tail --retry x', 'tail -f -n 1 x', + 'tail --pid=1 -f x', 'tail -s 1 x', + 'head -f x', 'wc --files0-from=list', 'du --files0-from=list', 'du -X file', 'stat --foo x', 'ls --foo', 'ls -@', 'cat -@ x', 'grep --foo x y', + 'hostname newname', 'hostname -F file', 'uname -n box', 'uname box', + ]); +}); + +test('#3975: git subcommands that write or run something when given the right option ask', () => { + denied([ + 'git diff --output=out.txt', 'git diff --out=out.txt', 'git log --output=out.txt', 'git show --output out HEAD', 'git log --ext-diff', 'git diff --ext-diff', + 'git diff --textconv', 'git log --textconv', 'git grep --textconv x', 'git cat-file --textconv HEAD:a', 'git cat-file --filters HEAD:a', 'git log --exec=sh', + 'git config -e', 'git config --edit', 'git config --global --edit', 'git config --global user.name x', 'git config user.name x', 'git config --unset user.name', + 'git config --add a.b c', 'git config --replace-all a.b c', 'git config --file x --list', 'git config --get', 'git config --get a --edit', + 'git branch --set-upstream-to=origin/main', 'git branch --unset-upstream', 'git branch -u origin/main', 'git branch -d x', 'git branch -D x', 'git branch -m new', + 'git branch --edit-description', 'git branch newbranch', 'git branch -a newbranch', 'git branch --track x origin/x', + 'git tag v1', 'git tag -a v1', 'git tag -d v1', 'git tag -s v1', 'git tag -v v1', 'git tag -a -m msg v1', 'git tag --edit', + 'git remote add o u', 'git remote show origin', 'git remote update', 'git remote prune origin', 'git remote set-url o u', 'git remote rename a b', + 'git -c core.pager=sh log', 'git --paginate log', 'git -C x status', 'git --git-dir=x log', 'git -p log', + 'git commit', 'git push', 'git checkout x', 'git stash', 'git reset', 'git clean -n', 'git fetch', 'git pull', 'git rev-parse --parseopt', 'git ls-files -x', + 'git status --foo', 'git log --foo', 'git blame --contents=x a', 'git diff -O orderfile', 'git diff --no-pager', + ]); +}); + +test('#3975: PowerShell commands: parameters that wait forever, reach other machines or open windows ask', () => { + denied([ + 'Get-Content a.txt -Wait', 'gc a.txt -Wait', 'type a.txt -Wait', 'Get-Process -ComputerName other', 'Get-Help Get-ChildItem -Online', 'Get-Help Get-ChildItem -ShowWindow', + 'Select-String -Pattern x -Foo', 'Get-ChildItem -Rec', 'Get-ChildItem -Debug', 'Get-ChildItem -OutVariable x', 'Get-ChildItem -ErrorVariable x', + 'Sort-Object -Foo', 'Get-Date -Foo', 'Get-FileHash a.txt -InputStream x', + ]); +}); + +test('#3975: pagers and anything not on the list ask', () => { + denied(['less a.txt', 'more a.txt', 'less -o log a.txt', 'find . -name x', 'xargs ls', 'awk 1 a', 'sed s/a/b/ a', 'env', 'tee a', 'printenv', 'mv a b', 'cp a b', 'touch a', 'mkdir a', 'dd if=a of=b']); +}); + +test('#3975: quoting cannot hide an option or an operand', () => { + denied([ + 'sort "--output=out" a', 'sort --out"put"=out a', 'sort --"output"=out a', "sort '-o' out a", 'sort -"o" out a', 'sort -o"out" a', 'sort --compress-program="sh" a', + 'rg --pre "sh" x', "rg --pre 'sh' x", 'git grep -O"sh" x', 'git grep "-Osh" x', + 'uniq a "b"', 'uniq "a" "b"', "uniq 'a' 'b'", 'date "1026120026"', "date '1026'", 'date "-s" now', 'date "-s now"', + 'tail "-f" x', "tail '-f' x", 'tail -n 1 "-f" x', + 'tree "-o" x', 'file "-C" x', 'git diff "--output=out.txt"', 'git "diff" --output=x', + // a quoted dash value is never taken for a value of a flag that wants a number + 'head -n "-f" x', + ]); +}); + +test('#3975: operands that would write or set something ask (uniq output file, date setting, hostname)', () => { + denied(['uniq a b', 'uniq a b c', 'date 1231', 'date 12311200', 'hostname a', 'whoami /foo', 'tr a b c', 'git tag v1.0', 'git branch topic']); +}); + +test('#3975: every command on the list asks for an unknown option, long or short', () => { + const names = readOnlyCommandNames(); + assert.ok(names.length > 40, 'the list is not empty'); + for (const name of names) { + assert.equal(isReadOnlyShell(`${name} -@`), false, `${name} -@`); + assert.equal(isReadOnlyShell(`${name} --zz-no-such-option`), false, `${name} --zz-no-such-option`); + assert.equal(isReadOnlyShell(`${name} --zz-no-such-option=1 x`), false, `${name} --zz-no-such-option=1 x`); + assert.equal(isReadOnlyShell(`Get-ChildItem | ${name} -@`), false, `piped ${name} -@`); + } + for (const sub of ['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']) { + assert.equal(isReadOnlyShell(`git ${sub} --zz-no-such-option`), false, `git ${sub} --zz-no-such-option`); + assert.equal(isReadOnlyShell(`git ${sub} -@`), false, `git ${sub} -@`); + } +}); + +test('#3975: commands people really type still run without a card', () => { + allowed([ + // sort, uniq, head, tail, wc, cut, tr + 'sort a.txt', 'sort -r a.txt', 'sort -n -k 2 a.txt', 'sort -u -t, -k2,2 a.txt', 'sort -nr a.txt', 'sort -k2,2nr a.txt', 'sort --reverse --numeric-sort a.txt', + 'uniq', 'uniq -c', 'uniq -c a.txt', 'uniq -d a.txt', 'uniq -f 1 a.txt', 'sort a.txt | uniq -c | sort -nr | head -5', + 'head a.txt', 'head -5 a.txt', 'head -n 5 a.txt', 'head -n5 a.txt', 'head -n -5 a.txt', 'head -c 100 a.txt', 'tail a.txt', 'tail -20 a.txt', 'tail -n 20 a.txt', 'tail -n +5 a.txt', 'tail -c 100 a.txt', + 'wc -l a.txt', 'wc -w a.txt', 'cat a.txt | wc -l', 'cut -d, -f1,3 a.txt', 'cut -c1-10 a.txt', 'tr a-z A-Z', 'tr -d "\\r"', 'tr -s " "', + // grep family and rg + 'grep foo a.txt', 'grep -rn foo src', 'grep -c foo a.txt', 'grep -E "a|b" a.txt', 'grep -A 3 foo a.txt', 'grep -i -v foo a.txt', 'grep -rl --include "*.js" foo .', 'egrep -n foo a.txt', 'fgrep -x foo a.txt', + 'rg foo', 'rg -n -i foo src', 'rg -l --type js foo', 'rg --files -g "*.md"', 'rg -C 3 foo', "rg foo -g '!node_modules'", 'rg -e foo -e bar', 'rg --hidden --no-ignore foo', 'rg --count-matches foo', 'rg -w -F "a.b"', 'rg --json foo', + // tree, file, stat, du, df, ls, dir + 'tree', 'tree -L 2', 'tree -a -I node_modules', 'tree -d src', 'tree -L 2 -d', + 'file a.bin', 'file -b --mime-type a.bin', 'file -i a.bin', 'file -L a.bin', + 'stat a.txt', 'stat -c %s a.txt', 'du -sh .', 'du -h --max-depth=1', 'du -ah -d 1', 'df -h', 'df -hT', 'df .', + 'ls', 'ls -la', 'ls -la src', 'ls -lh', 'ls -R', 'ls -1 --color=never', 'ls -lt | head -5', 'dir', 'dir /s', + // small ones + 'date', 'date -u', 'date +%s', 'date -u +%Y-%m-%dT%H:%M:%SZ', 'date -I', 'date -Iseconds', 'date -d @0', 'date --utc', 'date "+%Y-%m-%d"', "date '+%Y-%m-%d %H:%M'", + 'uname', 'uname -a', 'uname -m', 'hostname', 'hostname -s', 'whoami', 'whoami /groups', 'id', 'id -u', 'id -un', 'pwd', 'which node', 'which -a node', + 'basename a/b.txt', 'basename a/b.txt .txt', 'dirname a/b', 'realpath .', 'readlink -f a', 'echo hello', 'echo -n hello', 'cat a.txt', 'cat -n a.txt', + // git + 'git status', 'git status -s', 'git status --porcelain', 'git status -sb', 'git status --short --branch', 'git log', 'git log --oneline', 'git log --oneline -5', 'git log --oneline -n 5', + 'git log --stat -n 3', 'git log -p -1', 'git log --graph --oneline --decorate --all', 'git log --format=%H -1', 'git log --author=alice --since=2.weeks', 'git log -- a.txt', 'git log --follow -p a.txt', + 'git log main..HEAD', 'git log --oneline --no-merges origin/main..HEAD', 'git diff', 'git diff --stat', 'git diff --cached', 'git diff --name-only', 'git diff --name-status HEAD~1', 'git diff HEAD~1 -- a.txt', + 'git diff -U5', 'git diff --no-ext-diff', 'git diff main...HEAD', 'git diff -w', 'git show', 'git show HEAD', 'git show HEAD --stat', 'git show HEAD:a.txt', 'git show -s --format=%H HEAD', + 'git branch', 'git branch -a', 'git branch -v', 'git branch -vv', 'git branch -r', 'git branch --show-current', 'git branch --list', 'git branch --list "feat*"', 'git branch --contains HEAD', 'git branch --merged main', + 'git tag', 'git tag -l', 'git tag --list', 'git tag -l "v*"', 'git tag --sort=-creatordate', 'git tag --contains HEAD', 'git tag -n', + 'git remote', 'git remote -v', 'git config --get user.name', 'git config --list', 'git config --global --get user.email', 'git config -l', 'git config --get-all remote.origin.fetch', 'git config --show-origin --list', + 'git rev-parse HEAD', 'git rev-parse --abbrev-ref HEAD', 'git rev-parse --show-toplevel', 'git rev-parse --short HEAD', 'git rev-parse --is-inside-work-tree', 'git rev-parse --git-dir', + 'git ls-files', 'git ls-files --others --exclude-standard', 'git ls-files -m', 'git ls-files -s', 'git blame a.txt', 'git blame -L 1,10 a.txt', 'git describe --tags', 'git describe --always --dirty', + 'git shortlog -sn', 'git shortlog -s -n --all', 'git rev-list --count HEAD', 'git rev-list HEAD~5..HEAD', 'git cat-file -p HEAD', 'git cat-file -t HEAD', 'git ls-tree HEAD', 'git ls-tree -r --name-only HEAD', + 'git grep foo', 'git grep -n foo', 'git grep -n -i foo -- src', 'git grep -l foo', 'git grep -e foo --and -e bar', 'git grep -c foo', 'git grep -w -F "a.b"', 'git grep --no-index foo', + // PowerShell + 'Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'Get-ChildItem -Path . -Recurse -Filter *.mjs | Select-Object -First 5 FullName', 'Get-ChildItem -Force -ErrorAction SilentlyContinue', + 'ls -Recurse', 'ls -Force', 'gci -Recurse -File', 'dir -Name', 'Get-ChildItem -Directory -Depth 2', 'Get-Content a.txt', 'Get-Content a.txt -Raw', 'Get-Content a.txt -Tail 5', 'Get-Content a.txt -TotalCount 5', + 'Get-Content -Path a.txt', 'gc a.txt | Select-Object -First 3', 'cat a.txt | Select-String needle', 'type a.txt', 'Select-String -Path *.txt -Pattern foo -CaseSensitive', 'sls foo a.txt', 'Select-String -Pattern foo -Path a.txt -Context 2', + 'Get-Content a.txt | Measure-Object -Line', 'Measure-Object -Property Length -Sum', 'Get-ChildItem | Where-Object Length -gt 100', 'Get-ChildItem | Sort-Object Length -Descending', 'Get-ChildItem | Group-Object Extension', + 'Get-ChildItem | Select-Object Name, Length | Format-Table -AutoSize', 'Get-ChildItem | Format-List', 'Get-ChildItem | Out-String', 'Test-Path a.txt', 'Test-Path a.txt -PathType Leaf', 'Resolve-Path .', + 'Get-FileHash a.txt', 'Get-FileHash a.txt -Algorithm SHA256', 'Get-Date', 'Get-Date -Format yyyy-MM-dd', 'Get-Command node', 'Get-Command -Name node -All', 'Get-Process', 'Get-Process -Name node', 'Get-Item a.txt', 'gi a.txt', + 'Get-ItemProperty a.txt', 'Get-Location', 'pwd', 'Get-Help Get-ChildItem', 'Get-Help Get-ChildItem -Examples', 'Write-Output hello', 'hostname', 'whoami', 'Get-Host', 'Get-PSDrive', 'Get-PSDrive -Name C', + 'Get-Content a.json | ConvertFrom-Json', 'Get-Content a.json | ConvertFrom-Json | ConvertTo-Json -Depth 3', 'Compare-Object a b', 'Get-Content a | Get-Unique', + // versions + 'node --version', 'node -v', 'python --version', 'git --version', 'dotnet --version', 'java -version', 'npm -v', + ]); +}); + +test('#3975: maskQuotes still returns the quoted text to the caller, without changing what it returned before', () => { + const quoted = []; + assert.equal(maskQuotes('date "+%Y" \'a b\'', quoted), 'date "_" "_"'); + assert.deepEqual(quoted, ['+%Y', 'a b']); + assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name'); + assert.equal(maskQuotes('echo "$HOME"'), null); +}); diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 6145c448..e377f355 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -164,7 +164,9 @@ In **Manual**: - **These ask:** writing or editing a file, any command that is not on a short list of look-only commands, and every tool you connect. In the browser tool, opening a page, clicking and typing ask. - **These do not ask:** reading files, listing and searching folders, and look-only commands such as `ls`, `cat` and - `git status`. A command with a redirect, a chain (`;`, `&&`), a variable or anything else the check does not recognise asks. + `git status`. Each of those commands runs unasked only with options that just look: `sort -o FILE`, `rg --pre PROGRAM`, + `tail -f`, `date -s` and `git grep -O` ask, as does any option the check does not know. A command with a redirect, a + chain (`;`, `&&`), a variable or anything else the check does not recognise asks. - **Web search and opening web pages ask once per chat.** The first one in a chat shows a card with the search words and the service they go to, or with the address of the page. **Approve** covers the rest of that chat. **Deny** tells the assistant you did not allow the web, and it carries on without it. Plan and Bypass do not ask. The model picks the search words and From 89a68d8829b92b855d871ca4595a6be3cd529209 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:11:11 +0100 Subject: [PATCH 035/177] Chat: the transcript follows the answer only while the reader has not left; a wheel notch, finger or key moving up lets go at once, in the app chat and the served web page (#4014) --- apps/host/src/lib/follow-scroll.ts | 38 ++++++++++++++++ apps/host/src/screens/Chat.tsx | 22 ++++++--- apps/host/tests/follow-scroll.test.mjs | 39 ++++++++++++++++ serve/test_web_follow.py | 62 ++++++++++++++++++++++++++ serve/web/app.js | 32 ++++++++++++- 5 files changed, 186 insertions(+), 7 deletions(-) create mode 100644 apps/host/src/lib/follow-scroll.ts create mode 100644 apps/host/tests/follow-scroll.test.mjs create mode 100644 serve/test_web_follow.py diff --git a/apps/host/src/lib/follow-scroll.ts b/apps/host/src/lib/follow-scroll.ts new file mode 100644 index 00000000..25da2519 --- /dev/null +++ b/apps/host/src/lib/follow-scroll.ts @@ -0,0 +1,38 @@ +/** + * When a chat follows the newest token, and when the reader has let go (#4014). + * + * The old rule asked "is the reader within 120 px of the bottom?" on every streamed token and pulled the view + * back if so. One wheel notch is about 100 px, so it always landed inside that band and was undone by the next + * token; only a scrollbar drag, which jumps further, got away. The rule now follows what the reader did: + * a wheel, finger or key moving up lets go at once, and the chat follows again when the reader is back at + * the bottom. + */ +export interface Scroller { scrollHeight: number; scrollTop: number; clientHeight: number } + +/** Pixels of slack that still count as "at the bottom" (the same as `atBottom` in reasoning.ts). */ +export const FOLLOW_SLACK = 24; +/** Past this far from the bottom the "jump to latest" button is offered. */ +export const PILL_DISTANCE = 400; +/** A scroll this soon after the reader's own input was the reader's. */ +export const INPUT_WINDOW_MS = 400; + +export const distanceFromBottom = (el: Scroller): number => el.scrollHeight - el.scrollTop - el.clientHeight; + +/** + * Whether the chat should keep following after a scroll event. + * - back at the bottom: follow again; + * - the reader moved it (a wheel, finger, key or the scrollbar a moment ago) and it is not at the bottom: let go; + * - far away whatever moved it (a jump): let go; + * - otherwise (the page grew under a following reader and no input came): keep the state it had. + */ +export function followAfterScroll(distance: number, wasFollowing: boolean, msSinceInput: number): boolean { + if (distance <= FOLLOW_SLACK) return true; + if (msSinceInput <= INPUT_WINDOW_MS || distance > PILL_DISTANCE) return false; + return wasFollowing; +} + +/** A wheel turned up (negative delta) or a finger dragging the content down: the reader wants to go back. */ +export const wheelLeavesBottom = (deltaY: number): boolean => deltaY < 0; + +/** Keys that move a scroller up. */ +export const KEYS_UP = new Set(['PageUp', 'ArrowUp', 'Home']); diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 97dc34f2..385c3acc 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -40,6 +40,7 @@ import { composerCap, scrollBehavior } from '../lib/responsive'; import { relTime, cx, duration, tokens, tps } from '../lib/format'; import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store'; import { copyText } from '../lib/clipboard'; +import { KEYS_UP, PILL_DISTANCE, distanceFromBottom, followAfterScroll, wheelLeavesBottom } from '../lib/follow-scroll'; import { getSlashCommands } from '../lib/commands'; import { useLocation } from '../lib/router'; import { composerSends } from '../lib/shortcut-bindings'; @@ -212,6 +213,8 @@ export function ChatScreen() { }, [streaming]); /** Whether the reader is following the newest message rather than reading back. */ const pinned = useRef(true); + /** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */ + const readerInput = useRef(0); /** * Scrolls to the newest message and stays there. * @@ -266,8 +269,9 @@ export function ChatScreen() { const el = scroller.current; if (!el || (session?.showcase && !streaming)) return; - const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 120; - if (nearBottom) + // The reader's own scrolling decides (#4014): a wheel notch is about 100 px and used to land inside a 120 px band that pulled + // the view back on every token. `pinned` is set by the scroller's wheel, touch, key and scroll handlers below. + if (pinned.current) scrollToLatest(); }, [session?.messages.length, session?.messages.at(-1)?.content, scrollToLatest]); // Scroll position is remembered per conversation, so returning to one puts you @@ -421,9 +425,17 @@ export function ChatScreen() { // the way back is worth offering. // The threshold has to tolerate the height estimate moving under // us, or the pill flickers as turns render during a scroll. - const away = el.scrollHeight - el.scrollTop - el.clientHeight > 400; - pinned.current = !away; - setAwayFromBottom(away); + const distance = distanceFromBottom(el); + pinned.current = followAfterScroll(distance, pinned.current, Date.now() - readerInput.current); + setAwayFromBottom(distance > PILL_DISTANCE); + }} onWheel={(e) => { + readerInput.current = Date.now(); + if (wheelLeavesBottom(e.deltaY) && e.currentTarget.scrollTop > 0) + pinned.current = false; + }} onTouchMove={() => { readerInput.current = Date.now(); }} onPointerDown={() => { readerInput.current = Date.now(); }} onKeyDown={(e) => { + readerInput.current = Date.now(); + if (KEYS_UP.has(e.key) && e.target === e.currentTarget && e.currentTarget.scrollTop > 0) + pinned.current = false; }}>
diff --git a/apps/host/tests/follow-scroll.test.mjs b/apps/host/tests/follow-scroll.test.mjs new file mode 100644 index 00000000..e724696a --- /dev/null +++ b/apps/host/tests/follow-scroll.test.mjs @@ -0,0 +1,39 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { transform } from 'esbuild'; + +const { code } = await transform(await readFile(new URL('../src/lib/follow-scroll.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); +const f = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); + +test('a wheel notch up while an answer streams lets go at once (#4014)', () => { + assert.equal(f.wheelLeavesBottom(-100), true); + assert.equal(f.wheelLeavesBottom(100), false); + // the notch lands about 100 px from the bottom, inside the old 120 px band: it must not be pulled back + assert.equal(f.followAfterScroll(100, true, 20), false); + assert.equal(f.followAfterScroll(40, true, 20), false); +}); + +test('back at the bottom the chat follows again, by wheel, key, drag or the jump button', () => { + assert.equal(f.followAfterScroll(0, false, 10_000), true); + assert.equal(f.followAfterScroll(f.FOLLOW_SLACK, false, 10_000), true); + assert.equal(f.followAfterScroll(f.FOLLOW_SLACK + 1, false, 10_000), false); +}); + +test('the page growing under a following reader does not make the chat let go', () => { + // no input from the reader for a while, a few lines of the answer arrived: keep following + assert.equal(f.followAfterScroll(80, true, 5_000), true); + // a reader who had let go stays away while the answer grows + assert.equal(f.followAfterScroll(80, false, 5_000), false); + // far away whatever moved it (a scrollbar drag or a jump) + assert.equal(f.followAfterScroll(f.PILL_DISTANCE + 1, true, 5_000), false); +}); + +test('the chat screen uses the reader-driven rule, not the 120 px band', async () => { + const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8'); + assert.doesNotMatch(chat, /clientHeight < 120/); + assert.match(chat, /followAfterScroll\(/); + assert.match(chat, /onWheel=/); + // an upward wheel on a transcript that cannot scroll must not switch following off + assert.match(chat, /wheelLeavesBottom\(e\.deltaY\) && e\.currentTarget\.scrollTop > 0/); +}); diff --git a/serve/test_web_follow.py b/serve/test_web_follow.py new file mode 100644 index 00000000..5157ef98 --- /dev/null +++ b/serve/test_web_follow.py @@ -0,0 +1,62 @@ +"""serve/test_web_follow.py - the web chat follows the answer only while the reader has not left (#4014). + +The page used to pull the view back to the bottom on every frame when it was within 120 px of it, so one wheel notch +(about 100 px) could not scroll up while an answer streamed. Pins, with node, the page's own rule and that the wheel, +touch and keyboard listeners are wired. Skipped without node. + + python -m unittest serve.test_web_follow -v +""" +from __future__ import annotations + +import json +import shutil +import subprocess +import unittest +from pathlib import Path + +APP = Path(__file__).resolve().parent / "web" / "app.js" + + +def between(src: str, start: str, end: str) -> str: + a = src.index(start) + return src[a:src.index(end, a)] + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class WebFollow(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.src = APP.read_text(encoding="utf-8") + cls.rule = between(cls.src, "const FOLLOW_SLACK", "function scrollDown") + + def follow(self, distance, was, ms): + js = self.rule + f"\nconsole.log(JSON.stringify(followAfterScroll({distance}, {json.dumps(was)}, {ms})));" + out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30) + self.assertEqual(out.returncode, 0, out.stderr) + return json.loads(out.stdout) + + def test_a_wheel_notch_inside_the_old_band_is_not_pulled_back(self): + self.assertFalse(self.follow(100, True, 20)) + self.assertFalse(self.follow(40, True, 20)) + + def test_back_at_the_bottom_it_follows_again(self): + self.assertTrue(self.follow(0, False, 10_000)) + self.assertTrue(self.follow(24, False, 10_000)) + self.assertFalse(self.follow(25, False, 10_000)) + + def test_the_page_growing_under_a_following_reader_keeps_following(self): + self.assertTrue(self.follow(80, True, 5_000)) + self.assertFalse(self.follow(80, False, 5_000)) + self.assertFalse(self.follow(401, True, 5_000)) + + def test_the_old_120_px_rule_is_gone_and_the_reader_input_is_wired(self): + self.assertNotIn("< 120", between(self.src, "function renderChat", "$(\"chat\").addEventListener(\"click\"")) + watch = between(self.src, "(function watchReader()", "})();") + for event in ("wheel", "touchmove", "pointerdown", "keydown", "scroll"): + self.assertIn(f'"{event}"', watch) + # a wheel up on a chat that cannot scroll must not switch following off + self.assertIn("e.deltaY < 0 && s.scrollTop > 0", watch) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.js b/serve/web/app.js index ac84f85d..5dedc353 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -716,8 +716,36 @@ function renderChat() { messages.forEach((m, i) => chat.appendChild(msgEl(m, i))); scrollDown(true); } -function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; } -function scrollDown(force) { const s = $("chat-scroll"); if (force || nearBottom()) s.scrollTop = s.scrollHeight; } +// Follow the answer while the reader has not left (#4014). Asking "am I within 120 px of the bottom?" on every frame pulled +// the view back after every wheel notch (a notch is about 100 px), so scrolling up during a long answer only worked by +// dragging the scrollbar. Now the reader's own input lets go (wheel up, a finger or a key moving up, the scrollbar), and a +// scroll back to the bottom follows again. +let stickToBottom = true, lastReaderInput = 0; +const FOLLOW_SLACK = 24, FAR_AWAY = 400, INPUT_WINDOW_MS = 400; +function followAfterScroll(distance, wasFollowing, msSinceInput) { + if (distance <= FOLLOW_SLACK) return true; + if (msSinceInput <= INPUT_WINDOW_MS || distance > FAR_AWAY) return false; + return wasFollowing; +} +function scrollDown(force) { + const s = $("chat-scroll"); + if (force) stickToBottom = true; + if (stickToBottom) s.scrollTop = s.scrollHeight; +} +(function watchReader() { + const s = $("chat-scroll"); + const touch = () => { lastReaderInput = Date.now(); }; + s.addEventListener("wheel", (e) => { touch(); if (e.deltaY < 0 && s.scrollTop > 0) stickToBottom = false; }, {passive: true}); + s.addEventListener("touchmove", touch, {passive: true}); + s.addEventListener("pointerdown", touch, {passive: true}); + s.addEventListener("keydown", (e) => { + touch(); + if (["PageUp", "ArrowUp", "Home"].includes(e.key) && e.target === s && s.scrollTop > 0) stickToBottom = false; + }); + s.addEventListener("scroll", () => { + stickToBottom = followAfterScroll(s.scrollHeight - s.scrollTop - s.clientHeight, stickToBottom, Date.now() - lastReaderInput); + }, {passive: true}); +})(); $("chat").addEventListener("click", (e) => { const cc = e.target.closest("[data-code-copy]"); From 085dcded737f648480bf670ef12d7a9b2e5d1888 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:12:22 +0100 Subject: [PATCH 036/177] Monitor: the host reads the graphics card every 3 s only while a model runs or the Monitor is open, every 30 s otherwise, and the PCIe sample only while a model runs (#4066) --- apps/host/server/device-probes.mjs | 9 ++--- apps/host/server/index.mjs | 3 +- apps/host/server/monitor.mjs | 14 ++++++-- apps/host/server/sensor-pace.mjs | 16 +++++++++ apps/host/src/screens/Monitor.tsx | 11 ++++++- apps/host/tests/sensor-pace.test.mjs | 49 ++++++++++++++++++++++++++++ 6 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 apps/host/server/sensor-pace.mjs create mode 100644 apps/host/tests/sensor-pace.test.mjs diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs index f29bd666..cee55a4b 100644 --- a/apps/host/server/device-probes.mjs +++ b/apps/host/server/device-probes.mjs @@ -73,14 +73,15 @@ export async function detectDrmGpus() { } return result; } -export async function readGpuTelemetry(gpus) { +/** `transfer: false` skips the PCIe throughput sample (a second nvidia-smi); it only means something while a model runs. */ +export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, run = probe } = {}) { const now=new Date().toISOString(); const hasNvidia=gpus.some(g=>g.vendor==='nvidia'); - let raw=hasNvidia?await probe('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current','--format=csv,noheader,nounits'],2000):''; + let raw=hasNvidia?await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current','--format=csv,noheader,nounits'],2000):''; // Older drivers can reject a field; retain their basic sensors in that case. - if(hasNvidia&&!raw)raw=await probe('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used','--format=csv,noheader,nounits'],2000); + if(hasNvidia&&!raw)raw=await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used','--format=csv,noheader,nounits'],2000); const nvidia=new Map(parseNvidiaReadings(raw).map(r=>[r.id,r])); - const transfer=hasNvidia?parsePcieThroughput(await probe('nvidia-smi',['dmon','-s','t','-c','1'],1500)):new Map(); + const transfer=hasNvidia&&wantTransfer?parsePcieThroughput(await run('nvidia-smi',['dmon','-s','t','-c','1'],1500)):new Map(); return Promise.all(gpus.map(async gpu=>{ let reading=nvidia.get(gpu.id)??{id:gpu.id??`${gpu.vendor}:${gpu.index}`,temperatureC:null,utilizationPct:null,memoryUsedGb:null,powerW:null,powerLimitW:null,pcieGen:null,pcieGenMax:null,pcieWidth:null,pcieRxMbs:null}; if(gpu.vendor==='nvidia')reading={...reading,pcieRxMbs:transfer.get(gpu.sensorIndex??gpu.index)??null}; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 0025520a..b9640e1d 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -224,6 +224,7 @@ models.init(hub); engine.init(hub); engineInstall.init(hub); monitor.init(hub, boot); +monitor.setLiveProbe(() => native.hasLive()); serving.init(hub, { port: PORT, host: HOST }); runtimeModels=createRuntimeModels({hardware:()=>hardware.cachedHardware()??boot,library:()=>models.library(),requests:()=>serving.state().requests,real:models.REAL,changed:value=>{ if(!models.REAL){const primary=value.instances.find(i=>i.id===value.defaultId);if(store.get().loaded!==(primary?.variantId??null))store.update({loaded:primary?.variantId??null});} @@ -1586,7 +1587,7 @@ async function api(req, res, path, method, url) { if (cancelMatch && method === 'POST') return json(res, 200, serving.cancel(cancelMatch[1])); // --- monitor ------------------------------------------------------------ - if (path === '/api/monitor') return json(res, 200, monitor.snapshot()); + if (path === '/api/monitor') { monitor.watch(); return json(res, 200, monitor.snapshot()); } // --- skills / workspace ------------------------------------------------- if (path === '/api/skills' && method === 'GET') { diff --git a/apps/host/server/monitor.mjs b/apps/host/server/monitor.mjs index 4c673360..e07e291f 100644 --- a/apps/host/server/monitor.mjs +++ b/apps/host/server/monitor.mjs @@ -3,6 +3,7 @@ import { variant as catalogVariant, footprint } from './catalog.mjs'; import { detect, cachedHardware } from './hardware.mjs'; import { readGpuTelemetry, gpuMemoryTotals } from './device-probes.mjs'; import { createSystemSampler } from './system-telemetry.mjs'; +import { sensorPace, WATCH_MS } from './sensor-pace.mjs'; import { state as servingState } from './serving.mjs'; import { originalDashboard } from './monitor-dashboard.mjs'; import { get as getStore } from './store.mjs'; @@ -58,6 +59,14 @@ let hwCache = null; let ticker = null; let memoryWarningShown = false; let sensorsPending = false, sensorsAt = 0; +/* The Monitor screen asks (GET /api/monitor) every few seconds while it is open; a model that is loaded counts as live (#4066). */ +let watchedUntil = 0, liveProbe = () => false; +export function watch() { + const wasIdle = Date.now() >= watchedUntil; + watchedUntil = Date.now() + WATCH_MS; + if (wasIdle) sensorsAt = 0; // opening the Monitor after a quiet spell reads the card at once +} +export function setLiveProbe(probe) { liveProbe = typeof probe === 'function' ? probe : () => false; } let systemReading=null; const sampleSystem=createSystemSampler(); const finite = value => typeof value==='number'&&Number.isFinite(value); @@ -108,10 +117,11 @@ function approach(current, target, factor = 0.22) { } function tick() { - if(!sensorsPending&&Date.now()-sensorsAt>=3000){ + const pace=sensorPace({live:supervisor.status().running||!!liveProbe(),watchedUntil}); + if(!sensorsPending&&Date.now()-sensorsAt>=pace.intervalMs){ sensorsPending=true;sensorsAt=Date.now(); const hardware=cachedHardware()??hwCache; - void Promise.all([readGpuTelemetry(hardware?.gpus??[]),sampleSystem(hardware?.processors??[])]) + void Promise.all([readGpuTelemetry(hardware?.gpus??[],{transfer:pace.transfer}),sampleSystem(hardware?.processors??[])]) .then(([readings,system])=>{state.hardware.gpus=readings;systemReading=system;}) .catch(()=>{state.hardware.gpus=[];systemReading=null;}) .finally(()=>{sensorsPending=false;}); diff --git a/apps/host/server/sensor-pace.mjs b/apps/host/server/sensor-pace.mjs new file mode 100644 index 00000000..b8884bb8 --- /dev/null +++ b/apps/host/server/sensor-pace.mjs @@ -0,0 +1,16 @@ +/** + * How often the host asks the graphics card driver for its readings (#4066). + * It used to start two nvidia-smi processes every 3 s for as long as the app was open, even with nothing loaded and + * the Monitor out of sight; on some PCs that was felt as a stutter while typing. Now the 3 s pace is kept while a model + * runs or the Monitor is being looked at, and an idle app asks once every 30 s. + */ +export const ACTIVE_MS = 3000; +export const IDLE_MS = 30000; +/** The Monitor screen asks again every 10 s while it is open; this is how long one ask keeps the fast pace. */ +export const WATCH_MS = 25000; + +/** `live`: a model is loaded or an engine runs. `watchedUntil`: ms timestamp until which the Monitor was last seen open. */ +export function sensorPace({ live = false, watchedUntil = 0, now = Date.now() } = {}) { + const watched = now < watchedUntil; + return { intervalMs: live || watched ? ACTIVE_MS : IDLE_MS, transfer: !!live }; +} diff --git a/apps/host/src/screens/Monitor.tsx b/apps/host/src/screens/Monitor.tsx index 87cd4f58..451ea29d 100644 --- a/apps/host/src/screens/Monitor.tsx +++ b/apps/host/src/screens/Monitor.tsx @@ -2,7 +2,7 @@ import {localeTag} from '../lib/i18n'; import { tr } from '../lib/i18n'; import { scopedMonitor, instanceLabel, deviceLabel } from '../lib/runtime-models'; /** The original Strata dashboard, adapted to the current shell and device inventory. */ -import { useRef, useState, type ReactNode } from 'react'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; import { flushSync } from 'react-dom'; import { SnapshotDialog } from '../components/SnapshotDialog'; import { requestSummary } from '../lib/monitor-summary'; @@ -14,6 +14,7 @@ import { Screen } from '../components/layout'; import { contextLabel, duration, tokens, tps } from '../lib/format'; import { defaultGpuSet, gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware'; import { useStore } from '../lib/store'; +import { api } from '../lib/client'; import { useKept } from '../lib/kept-state'; import type { Hardware, MonitorState, ServeRequest } from '../lib/types'; import { useNative, nativeRouting, type NativeState } from '../lib/native'; @@ -57,6 +58,14 @@ function requestStatus(request: ServeRequest) { } export function MonitorScreen() { const native = useNative(); + // While this screen is open and visible the host reads the graphics card every 3 s; otherwise it asks only every 30 s (#4066). + useEffect(() => { + const ask = () => { if (typeof document === 'undefined' || document.visibilityState !== 'hidden') + void api.get('/api/monitor').catch(() => undefined); }; + ask(); + const timer = setInterval(ask, 10000); + return () => clearInterval(timer); + }, []); return ; } function LegacyMonitorScreen({ native }: { diff --git a/apps/host/tests/sensor-pace.test.mjs b/apps/host/tests/sensor-pace.test.mjs new file mode 100644 index 00000000..46d99f37 --- /dev/null +++ b/apps/host/tests/sensor-pace.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { sensorPace, ACTIVE_MS, IDLE_MS, WATCH_MS } from '../server/sensor-pace.mjs'; +import { readGpuTelemetry } from '../server/device-probes.mjs'; + +test('an idle app with the Monitor out of sight asks the card rarely (#4066)', () => { + const idle = sensorPace({ live: false, watchedUntil: 0, now: 1_000 }); + assert.equal(idle.intervalMs, IDLE_MS); + assert.equal(idle.transfer, false); + assert.ok(IDLE_MS >= 10 * ACTIVE_MS); +}); + +test('a running model or an open Monitor keeps the 3 s pace', () => { + assert.equal(sensorPace({ live: true, now: 1_000 }).intervalMs, ACTIVE_MS); + assert.equal(sensorPace({ live: true, now: 1_000 }).transfer, true); + const watched = sensorPace({ live: false, watchedUntil: 1_000 + WATCH_MS, now: 1_000 }); + assert.equal(watched.intervalMs, ACTIVE_MS); + assert.equal(watched.transfer, false, 'the PCIe sample only means something while a model runs'); + assert.equal(sensorPace({ live: false, watchedUntil: 1_000, now: 1_000 + 1 }).intervalMs, IDLE_MS); +}); + +const gpus = [{ id: 'GPU-1', vendor: 'nvidia', index: 0, sensorIndex: 0 }]; +const calls = []; +const run = async (cmd, args) => { + calls.push(args[0]); + return args[0] === 'dmon' ? '# gpu rxpci txpci\n# Idx MB/s MB/s\n 0 12 3' : 'GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16'; +}; + +test('without the PCIe sample one nvidia-smi process is started, with it two', async () => { + calls.length = 0; + const idle = await readGpuTelemetry(gpus, { transfer: false, run }); + assert.deepEqual(calls.map(c => c === 'dmon' ? 'dmon' : 'query'), ['query']); + assert.equal(idle[0].temperatureC, 41); + calls.length = 0; + await readGpuTelemetry(gpus, { run }); + assert.deepEqual(calls.map(c => c === 'dmon' ? 'dmon' : 'query'), ['query', 'dmon']); +}); + +test('the monitor uses the pace, the Monitor screen asks while it is open, and /api/monitor marks it watched', async () => { + const monitor = await readFile(new URL('../server/monitor.mjs', import.meta.url), 'utf8'); + assert.match(monitor, /sensorPace\(/); + assert.doesNotMatch(monitor, /sensorsAt>=3000/); + const index = await readFile(new URL('../server/index.mjs', import.meta.url), 'utf8'); + assert.match(index, /monitor\.watch\(\); return json\(res, 200, monitor\.snapshot\(\)\)/); + assert.match(index, /monitor\.setLiveProbe\(/); + const screen = await readFile(new URL('../src/screens/Monitor.tsx', import.meta.url), 'utf8'); + assert.match(screen, /api\.get\('\/api\/monitor'\)/); +}); From 9a1e768388bb01bba926064edd47ef4784bf5e1f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:14:26 +0100 Subject: [PATCH 037/177] App: the source-checkout server is started without an empty STRATA_API_KEY (#3851); a card taken out of the PC no longer decides the engine make, and a PC with two makes accepts a build for either (#3892) --- apps/host/server/bundled-engine.mjs | 78 +++++++++++++++------- apps/host/server/control-runtime.mjs | 11 +++ apps/host/server/native-control.mjs | 4 +- apps/host/tests/bundled-engine.test.mjs | 28 ++++++++ apps/host/tests/source-server-env.test.mjs | 15 +++++ 5 files changed, 111 insertions(+), 25 deletions(-) create mode 100644 apps/host/tests/source-server-env.test.mjs diff --git a/apps/host/server/bundled-engine.mjs b/apps/host/server/bundled-engine.mjs index 8d4fdc3f..f3ad0534 100644 --- a/apps/host/server/bundled-engine.mjs +++ b/apps/host/server/bundled-engine.mjs @@ -67,40 +67,70 @@ export function nvidiaDriverVersion() { /** Where the builds are published; the wrong-make sentence points here. */ export const RELEASES_URL = 'https://github.com/Niko1221/Strata/releases'; -/** The PCI vendor ids (`10de`, `1002`, `8086`) of the Windows display adapters; empty off Windows or when the registry cannot be read. */ -export function windowsDisplayVendors({ platform = process.platform, run = execFileSync } = {}) { +/** The PCI vendor ids of the display adapters Windows reports as present right now (PowerShell, Win32_VideoController); empty when that cannot be read. */ +export function windowsPresentVendors({ platform = process.platform, run = execFileSync } = {}) { + const found = new Set(); + if (platform !== 'win32') return found; + try { + const out = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID }'], { encoding: 'utf8', timeout: 15000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); + for (const match of String(out).matchAll(/VEN_([0-9A-F]{4})/gi)) found.add(match[1].toLowerCase()); + } catch { /* no PowerShell or a limited account: the registry answer stands */ } + return found; +} + +/** + * The PCI vendor ids (`10de`, `1002`, `8086`) of the Windows display adapters; empty off Windows or when the registry cannot be read. + * The registry keeps the entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when NVIDIA and AMD are both + * listed, only the makes Windows reports as present now count, the same rule Strata Control uses (engine_component.windows_display_adapters). + */ +export function windowsDisplayVendors({ platform = process.platform, run = execFileSync, present = windowsPresentVendors } = {}) { const found = new Set(); if (platform !== 'win32') return found; try { const out = run('reg', ['query', 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}', '/s', '/v', 'MatchingDeviceId'], { encoding: 'utf8', timeout: 8000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); for (const match of String(out).matchAll(/VEN_([0-9A-F]{4})/gi)) found.add(match[1].toLowerCase()); } catch { /* no registry access: the tools decide */ } + if (found.has('10de') && found.has('1002')) { + const now = present({ platform, run }); + const kept = new Set([...found].filter(vendor => now.has(vendor))); + if (kept.size) return kept; + } return found; } +const BACKEND_OF_VENDOR = [['10de', 'cuda'], ['1002', 'hip'], ['8086', 'sycl']]; + +/** + * Every engine family this PC's graphics cards can run, in the order NVIDIA, AMD, Intel; STRATA_ENGINE_BACKEND wins. A PC with two + * makes lists both, so a build for either make is accepted (recommend, never force). + */ +export function gpuBackendsHere(env = process.env, { vendors = windowsDisplayVendors() } = {}) { + const forced = String(env.STRATA_ENGINE_BACKEND ?? '').trim().toLowerCase(); + if (forced) return ['cuda', 'hip', 'sycl'].includes(forced) ? [forced] : []; + if (vendors.size) { + const list = BACKEND_OF_VENDOR.filter(([vendor]) => vendors.has(vendor)).map(([, backend]) => backend); + if (list.length) return list; + } + if (nvidiaDriverVersion()) return ['cuda']; + try { + const base = '/sys/class/drm'; + const seen = new Set(); + for (const card of readdirSync(base)) { + if (!/^card\d+$/.test(card)) continue; + try { seen.add(readFileSync(`${base}/${card}/device/vendor`, 'utf8').trim().toLowerCase()); } catch { /* no vendor file */ } + } + const list = [['0x10de', 'cuda'], ['0x1002', 'hip'], ['0x8086', 'sycl']].filter(([vendor]) => seen.has(vendor)).map(([, backend]) => backend); + if (list.length) return list; + } catch { /* not Linux */ } + return []; +} + /** * The engine family this PC's graphics card needs ('cuda', 'hip', 'sycl'), or null when it cannot be told. The same order as Control * (NVIDIA first, then AMD, then Intel); STRATA_ENGINE_BACKEND wins. Reads only the driver and (Linux) the PCI vendor of the display adapters. */ -export function gpuBackendHere(env = process.env, { vendors = windowsDisplayVendors() } = {}) { - const forced = String(env.STRATA_ENGINE_BACKEND ?? '').trim().toLowerCase(); - if (forced) return ['cuda', 'hip', 'sycl'].includes(forced) ? forced : null; - // Windows: the display adapters are the machine's own statement of which cards it has; a leftover nvidia-smi from a card that was - // taken out must not outvote them (#3688). Same order as Control: NVIDIA, then AMD, then Intel. - if (vendors.size) { - for (const [vendor, backend] of [['10de', 'cuda'], ['1002', 'hip'], ['8086', 'sycl']]) if (vendors.has(vendor)) return backend; - } - if (nvidiaDriverVersion()) return 'cuda'; - try { - const base = '/sys/class/drm'; - const vendors = new Set(); - for (const card of readdirSync(base)) { - if (!/^card\d+$/.test(card)) continue; - try { vendors.add(readFileSync(`${base}/${card}/device/vendor`, 'utf8').trim().toLowerCase()); } catch { /* no vendor file */ } - } - for (const [vendor, backend] of [['0x10de', 'cuda'], ['0x1002', 'hip'], ['0x8086', 'sycl']]) if (vendors.has(vendor)) return backend; - } catch { /* not Linux */ } - return null; +export function gpuBackendHere(env = process.env, options = {}) { + return gpuBackendsHere(env, options)[0] ?? null; } const HIP_FAMILIES = [['RX 9000', ['gfx1200', 'gfx1201']], ['RX 7000', ['gfx1100', 'gfx1101', 'gfx1102']], ['RX 6000', ['gfx1030', 'gfx1031']], ['Ryzen AI Max', ['gfx1151']]]; @@ -147,10 +177,12 @@ export async function installBundledEngine({ bundleDir, components, platform = n if (platform) packages = packages.filter(p => p.manifest.platform === platform); if (!packages.length) return { action: 'none' }; // A build for another make of graphics card than this PC has can never run here: it is not unpacked, and the caller says so in plain words. - const wanted = backend === undefined ? gpuBackendHere() : backend; + // A PC with two makes (an AMD card for the model, an NVIDIA card for the desktop) accepts a build for either (#3892). + const wantedList = backend === undefined ? gpuBackendsHere() : (Array.isArray(backend) ? backend : backend ? [backend] : []); + const wanted = wantedList[0] ?? null; if (wanted && ['cuda', 'hip', 'sycl'].includes(wanted)) { const gpu = packages.filter(p => ['cuda', 'hip', 'sycl'].includes(p.manifest.backend)); - const fits = packages.filter(p => !gpu.includes(p) || p.manifest.backend === wanted); + const fits = packages.filter(p => !gpu.includes(p) || wantedList.includes(p.manifest.backend)); if (gpu.length && !fits.length) { const first = gpu.sort((a, b) => compareVersions(b.manifest.version, a.manifest.version))[0].manifest; return { action: 'wrong-make', built: first.backend, here: wanted, notice: wrongMakeNotice(first, wanted) }; diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index f0f64dba..2be9e126 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -74,6 +74,17 @@ export function findControl({ env = process.env, platform = process.platform, ex return control; } +/** + * The environment of the server the host starts from a source checkout (#3851): the key travels in the run configuration, so a + * STRATA_API_KEY the host itself was started with is removed. Setting it to an empty string made serve/server.py stop with + * "an API key was given but it is empty". + */ +export function sourceServerEnvironment(env = process.env) { + const next = { ...env, PYTHONUNBUFFERED: '1', PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' }; + delete next.STRATA_API_KEY; + return next; +} + /** The environment Control runs in: nothing from the user's Python, and acquiring forbidden. */ export function controlEnvironment(control, { env = process.env, components = componentsDirectory({ env }), acquire = false } = {}) { const next = { ...env }; diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 50dcac5d..362304b8 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -13,7 +13,7 @@ import { USER_KEY, capture as captureUserArgs, merge as mergeUserArgs, setFlag a import { resolvePython, venvPython } from './python-resolver.mjs'; import os from 'node:os'; import { runtimeVision } from './native-vision.mjs'; -import { componentsDirectory, installerEnvironment, controlEnvironment } from './control-runtime.mjs'; +import { componentsDirectory, installerEnvironment, controlEnvironment, sourceServerEnvironment } from './control-runtime.mjs'; import { createEngineStep } from './engine-step.mjs'; import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder, syncDataFolder, terminalSettingsFile } from './model-folder.mjs'; import { createAutoTune, writeTuneConfig } from './native-autotune.mjs'; @@ -329,7 +329,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} try{await startWith(retryConfig);append(id,'Strata Control reports the engine is ready (second try).');} catch(second){const said2=humanStartError(second);instance.status='error';instance.error=said2;/* the first stop and the second try stay in job.details; the pop-up shows the last stop once */emit();throw new Error(instance.error);}}} } else { - proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONUTF8:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); + proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:sourceServerEnvironment()}); instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();}); proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit(); diff --git a/apps/host/tests/bundled-engine.test.mjs b/apps/host/tests/bundled-engine.test.mjs index 74464eed..551c8fe4 100644 --- a/apps/host/tests/bundled-engine.test.mjs +++ b/apps/host/tests/bundled-engine.test.mjs @@ -290,3 +290,31 @@ test('macOS: the engine bundle inside a signed .app stays (deleting it breaks th t.cleanup(); } }); + +test('a card taken out of the PC does not decide the make; two present makes accept a build for either (#3892)', async () => { + const { gpuBackendsHere, windowsDisplayVendors } = await import('../server/bundled-engine.mjs'); + const nl = String.fromCharCode(10); + const registry = 'MatchingDeviceId REG_SZ PCI/VEN_10DE&DEV_2882' + nl + 'MatchingDeviceId REG_SZ PCI/VEN_1002&DEV_7550'; + // the NVIDIA card was swapped for a Radeon: Windows still lists its driver entry, but only the AMD card is present + assert.deepEqual([...windowsDisplayVendors({ platform: 'win32', run: () => registry, present: () => new Set(['1002']) })], ['1002']); + assert.equal(gpuBackendsHere({}, { vendors: new Set(['1002']) })[0], 'hip'); + // both cards present: both makes count, NVIDIA first + assert.deepEqual([...windowsDisplayVendors({ platform: 'win32', run: () => registry, present: () => new Set(['1002', '10de']) })].sort(), ['1002', '10de']); + assert.deepEqual(gpuBackendsHere({}, { vendors: new Set(['10de', '1002']) }), ['cuda', 'hip']); + // present cannot be read: the registry answer stands + assert.equal(windowsDisplayVendors({ platform: 'win32', run: () => registry, present: () => new Set() }).size, 2); + // the second source is only asked when two makes are listed + assert.equal(windowsDisplayVendors({ platform: 'win32', run: () => 'MatchingDeviceId REG_SZ PCI/VEN_1002&DEV_7550', present: () => { throw new Error('must not run'); } }).size, 1); + assert.deepEqual(gpuBackendsHere({ STRATA_ENGINE_BACKEND: 'hip' }, { vendors: new Set(['10de', '1002']) }), ['hip']); + + const t = setup(); + try { + const name = makePackage(t.bundle, '0.2.0', { platform: 'windows-x86_64', backend: 'hip', variant: 'rx9070' }); + const manifest = JSON.parse(readFileSync(join(t.bundle, name, 'engine-component.json'), 'utf8')); + manifest.archs = ['gfx1201']; + writeFileSync(join(t.bundle, name, 'engine-component.json'), JSON.stringify(manifest)); + // an AMD build on a PC with an NVIDIA desktop card and an AMD model card is unpacked, not refused + const result = await installBundledEngine({ bundleDir: t.bundle, components: t.components, backend: ['cuda', 'hip'] }); + assert.equal(result.action, 'installed'); + } finally { t.cleanup(); } +}); diff --git a/apps/host/tests/source-server-env.test.mjs b/apps/host/tests/source-server-env.test.mjs new file mode 100644 index 00000000..21519280 --- /dev/null +++ b/apps/host/tests/source-server-env.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { sourceServerEnvironment } from '../server/control-runtime.mjs'; + +test('the source-checkout server never gets an empty STRATA_API_KEY (#3851)', async () => { + const env = sourceServerEnvironment({ PATH: 'x', STRATA_API_KEY: 'from-the-shell' }); + assert.equal('STRATA_API_KEY' in env, false); + assert.equal(env.PATH, 'x'); + assert.equal(env.PYTHONUTF8, '1'); + assert.equal('STRATA_API_KEY' in sourceServerEnvironment({}), false); + const control = await readFile(new URL('../server/native-control.mjs', import.meta.url), 'utf8'); + assert.doesNotMatch(control, /STRATA_API_KEY:\s*''/); + assert.match(control, /env:sourceServerEnvironment\(\)/); +}); From cd72accac33570b02d04da737942591ec5925293 Mon Sep 17 00:00:00 2001 From: thisisspartan <207055105+thisisspartan@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:17:49 +0100 Subject: [PATCH 038/177] Web page: a request that timed out in the queue shows a Timeout badge in Recent requests (PR #3991 by thisisspartan) --- serve/test_web_badges.py | 32 ++++++++++++++++++++++++++++++++ serve/web/app.js | 3 ++- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 serve/test_web_badges.py diff --git a/serve/test_web_badges.py b/serve/test_web_badges.py new file mode 100644 index 00000000..fcfb8860 --- /dev/null +++ b/serve/test_web_badges.py @@ -0,0 +1,32 @@ +"""serve/test_web_badges.py - the Recent requests table has a badge for every way a request can end (#3991). + +A request that waits past the queue limit ends with finish "timeout"; the Status cell showed the raw word. Reads the page source. +""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +APP = Path(__file__).resolve().parent / "web" / "app.js" +SERVER = Path(__file__).resolve().parent / "server.py" + + +class FinishBadges(unittest.TestCase): + def test_a_timed_out_request_has_a_badge(self): + src = APP.read_text(encoding="utf-8") + table = src[src.index("const badge = {stop:"):] + table = table[:table.index("};")] + self.assertRegex(table, r'timeout: \["st-badge--queued", "Timeout"\]') + + def test_every_finish_the_server_stores_has_a_badge(self): + src = APP.read_text(encoding="utf-8") + table = src[src.index("const badge = {stop:"):] + table = table[:table.index("};")] + for finish in ("stop", "length", "cancel", "disconnect", "error", "timeout"): + self.assertRegex(table, rf"\b{finish}:", finish) + self.assertIn('"timeout"', SERVER.read_text(encoding="utf-8")) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.js b/serve/web/app.js index 5dedc353..856df8ca 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -344,7 +344,8 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { body.innerHTML = `No requests yet`; } else { const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"], - disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"]}; + disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"], + timeout: ["st-badge--queued", "Timeout"]}; body.innerHTML = requests.slice(0, reqShowAll ? requests.length : 12).map((r) => { const [cls, text] = badge[r.finish] || ["", r.finish || "–"]; const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); From eb1c40038c0b9e74b9a8653426e80c956e7018b0 Mon Sep 17 00:00:00 2001 From: MaKla89 <33317175+MaKla89@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:18:15 +0100 Subject: [PATCH 039/177] App sharing: the shared and tunnel address answers a browser's CORS preflight and sends Access-Control headers when an API key is set; without a key nothing changes (PR #3853 by MaKla89, #3208) --- apps/host/server/local-share.mjs | 16 +++++- apps/host/tests/cors-share.test.mjs | 83 +++++++++++++++++++++++++++++ docs/DETAILS.md | 5 +- 3 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 apps/host/tests/cors-share.test.mjs diff --git a/apps/host/server/local-share.mjs b/apps/host/server/local-share.mjs index bcbfc2c4..e8659c61 100644 --- a/apps/host/server/local-share.mjs +++ b/apps/host/server/local-share.mjs @@ -14,8 +14,22 @@ export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0 if (listener) throw new Error('Sharing is already starting.'); listener = http.createServer(async (req, res) => { const path = apiPath(new URL(req.url ?? '/', 'http://localhost').pathname); + const method = req.method ?? 'GET'; + // #3208: with an API key set, a browser page of any site can call the shared API - the key decides, not the + // origin. The browser's preflight (OPTIONS) never carries the key (the spec says so), so it is answered here, + // before the path check and the key check; the real request that follows still goes through both. Without a + // key no CORS headers go out, as before: the listener stays "a device on this network" (SECURITY.md), and a + // web page of another site on the internet cannot read the model through it. + if (hasKey()) { + res.setHeader('access-control-allow-origin', '*'); + res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS'); + // the headers the preflight asks for (SDKs add their own; Anthropic browser clients send anthropic-version) + res.setHeader('access-control-allow-headers', String(req.headers['access-control-request-headers'] ?? '') || 'authorization, content-type, x-api-key, x-strata-client, anthropic-version, anthropic-beta'); + res.setHeader('access-control-max-age', '600'); + if (method === 'OPTIONS') { res.writeHead(204); res.end(); return; } + } if (!['/v1/models','/v1/chat/completions','/v1/messages'].includes(path)) { res.writeHead(404); res.end('Not found'); return; } - try { await handle(req, res, path, req.method ?? 'GET'); } + try { await handle(req, res, path, method); } catch { if (!res.headersSent) res.writeHead(500); res.end('Request failed'); } }); try { await new Promise((resolve,reject) => { listener.once('error',reject); listener.listen(port,host,resolve); }); } diff --git a/apps/host/tests/cors-share.test.mjs b/apps/host/tests/cors-share.test.mjs new file mode 100644 index 00000000..dd2552a0 --- /dev/null +++ b/apps/host/tests/cors-share.test.mjs @@ -0,0 +1,83 @@ +// #3208: the local-network share listener answers browser CORS the way the app's own API does - when an API key is set. +// The reporter's chatbot page (a browser on another machine) could not get past the preflight: OPTIONS carries no key +// (the spec says so), openai() checks the key first, so every preflight got 401 and no answer had a CORS header. +// Without a key the listener sends no CORS headers, so it stays "a device on this network" (SECURITY.md). +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createLocalShare } from '../server/local-share.mjs'; + +/** openai() as index.mjs runs it: the key check first (no key set means every client passes), then path and method. */ +const openaiLike = key => (req, res, path, method) => { + if (key && req.headers.authorization !== 'Bearer test-only-key') { + res.writeHead(401, { 'content-type': 'application/json' }); + res.end('{"error":"Invalid API key"}'); + return; + } + if (path === '/v1/models' && method === 'GET') { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{"object":"list","data":[]}'); + return; + } + res.writeHead(404, { 'content-type': 'application/json' }); + res.end('{"error":"No route"}'); +}; + +const preflight = (root, origin, extra = {}) => fetch(`${root}/v1/models`, { + method: 'OPTIONS', + headers: { origin, 'access-control-request-method': 'GET', ...extra }, +}); + +test('with a key, the shared listener answers the preflight without one and allows any origin', async () => { + const share = createLocalShare({ handle: openaiLike(true), hasKey: () => true, host: '127.0.0.1', port: 0 }); + try { + const { url } = await share.start(); + const root = url.replace(/\/v1$/, ''); + const res = await preflight(root, 'http://192.168.1.20:9999', { 'access-control-request-headers': 'authorization,content-type' }); + assert.equal(res.status, 204); + assert.equal(res.headers.get('access-control-allow-origin'), '*'); + assert.match(res.headers.get('access-control-allow-methods'), /OPTIONS/); + assert.equal(res.headers.get('access-control-allow-headers'), 'authorization,content-type'); + assert.equal(res.headers.get('access-control-max-age'), '600'); + // a preflight that asks for nothing still names the headers the SDKs and Anthropic browser clients send + const plain = await preflight(root, 'http://example.org'); + assert.match(plain.headers.get('access-control-allow-headers'), /authorization/); + assert.match(plain.headers.get('access-control-allow-headers'), /anthropic-version/); + } finally { await share.stop(); } +}); + +test('with a key, real answers carry Access-Control-Allow-Origin too - the 401 for a missing key as well', async () => { + const share = createLocalShare({ handle: openaiLike(true), hasKey: () => true, host: '127.0.0.1', port: 0 }); + try { + const { url } = await share.start(); + const ok = await fetch(url + '/models', { headers: { origin: 'http://example.org', authorization: 'Bearer test-only-key' } }); + assert.equal(ok.status, 200); + assert.equal(ok.headers.get('access-control-allow-origin'), '*'); + const denied = await fetch(url + '/models', { headers: { origin: 'http://example.org' } }); + assert.equal(denied.status, 401); + assert.equal(denied.headers.get('access-control-allow-origin'), '*', 'the browser must see the real 401, not a CORS wall'); + } finally { await share.stop(); } +}); + +test('a preflight grants nothing: the shared listener still answers no host control, only inference', async () => { + const share = createLocalShare({ handle: openaiLike(true), hasKey: () => true, host: '127.0.0.1', port: 0 }); + try { + const { url } = await share.start(); + const root = url.replace(/\/v1$/, ''); + assert.equal((await fetch(root + '/api/tasks', { method: 'OPTIONS', headers: { origin: 'http://example.org' } })).status, 204); + assert.equal((await fetch(root + '/api/tasks', { headers: { authorization: 'Bearer test-only-key' } })).status, 404); + } finally { await share.stop(); } +}); + +test('without a key nothing changes: no CORS headers, and the preflight falls through as before', async () => { + const share = createLocalShare({ handle: openaiLike(false), hasKey: () => false, host: '127.0.0.1', port: 0 }); + try { + const { url } = await share.start(); + const root = url.replace(/\/v1$/, ''); + const pre = await preflight(root, 'http://example.org', { 'access-control-request-headers': 'authorization,content-type' }); + assert.equal(pre.status, 404, 'OPTIONS /v1/models reaches the route check, as before the fix'); + assert.equal(pre.headers.get('access-control-allow-origin'), null); + const get = await fetch(url + '/models', { headers: { origin: 'http://example.org' } }); + assert.equal(get.status, 200, 'a device on the network still uses the keyless share'); + assert.equal(get.headers.get('access-control-allow-origin'), null, 'a keyless share never lets a web page of another site read the model'); + } finally { await share.stop(); } +}); diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 43538ddc..4255fc62 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -552,7 +552,10 @@ tables per token). The scaling is fixed for the whole run, because the KV cache - **Browser pages (CORS):** off by default. `"cors_origins": ["https://chat.example.com"]` lets those origins call `/v1/*`; `["*"]` lets any page and is only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools. It belongs to the engine's own server; the desktop app answers browser pages on its own API address and already allows - pages of any site there. + pages of any site there. When you share with other devices or run a tunnel, the shared address answers them too, with an + API key: the key decides, not the site. The browser's preflight (`OPTIONS`) is answered without a key, since a browser never + sends one with it; the request that follows still needs the key. Without an API key the shared address sends no CORS + headers, so a page of another site cannot read your model through it - only devices on your network can. - **Host names (DNS rebinding):** without an API key the server answers only requests whose `Host` is `localhost`, an IP address, the address it listens on, or (when it listens beyond this PC) this PC's name and `host.docker.internal`. Others get **403** naming the setting. Add a name with `"allowed_hosts": ["strata.example.com"]` or From dc1fd367d32af743bd0f5ae63d9e840212694cd5 Mon Sep 17 00:00:00 2001 From: toel1234 <55331794+toel1234@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:05 +0100 Subject: [PATCH 040/177] procs: an engine adopted by systemd --user is found as an orphan, and ending it waits on the start token until the process is really gone (PR #3254 by toel1234) --- strata_control/procs.py | 12 ++++++--- tests/terminal/test_procs.py | 50 ++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/strata_control/procs.py b/strata_control/procs.py index b550c07b..db176b36 100644 --- a/strata_control/procs.py +++ b/strata_control/procs.py @@ -309,10 +309,13 @@ def end_one(record: dict, *, grace: float = 8.0) -> str: if not is_same(pid, record["token"], record["cmd"]): drop_record(pid) return "gone" + # once signalled, the start token alone says it still runs: an exiting process has an empty command line on Linux + def running(): + return start_token(pid) == record["token"] if not WINDOWS: _signal_verified(record, signal.SIGTERM) deadline = time.monotonic() + grace - while time.monotonic() < deadline and is_same(pid, record["token"], record["cmd"]): + while time.monotonic() < deadline and running(): time.sleep(0.1) if is_same(pid, record["token"], record["cmd"]): _signal_verified(record, signal.SIGKILL) @@ -320,9 +323,9 @@ def end_one(record: dict, *, grace: float = 8.0) -> str: if is_same(pid, record["token"], record["cmd"]): subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True) # one PID, verified just above deadline = time.monotonic() + 10 - while time.monotonic() < deadline and is_same(pid, record["token"], record["cmd"]): + while time.monotonic() < deadline and running(): time.sleep(0.1) - if is_same(pid, record["token"], record["cmd"]): + if running(): return "stuck" drop_record(pid) return "ended" @@ -354,7 +357,8 @@ def orphans_of(engine_exe: str) -> list[Ident]: return [] mine = {os.getpid()} try: - mine.update(q.pid for q in psutil.Process().parents() if q.pid != 1) # pid 1 adopts orphans: it is not a starter + # pid 1 and a subreaper such as `systemd --user` (an ancestor of every desktop terminal) adopt orphans: they are not starters + mine.update(q.pid for q in psutil.Process().parents() if q.pid != 1 and q.name().lower() not in INIT_NAMES) except psutil.Error: pass found = [] diff --git a/tests/terminal/test_procs.py b/tests/terminal/test_procs.py index 087021fa..c71ce742 100644 --- a/tests/terminal/test_procs.py +++ b/tests/terminal/test_procs.py @@ -137,6 +137,56 @@ class Procs(unittest.TestCase): self.assertIsNone(live.poll()) self.assertIsNone(procs.start_token(orphan_pid)) +class SubreaperOrphans(unittest.TestCase): + """An engine adopted by `systemd --user` is an orphan (#3254), and a dying process is waited for by its start token.""" + + class Gone(Exception): + pass + + def fake_psutil(self, ancestors, parent_name): + class Err(Exception): + pass + + class NoSuch(Err): + pass + + def proc(pid, name, ppid=1): + return mock.Mock(pid=pid, **{"name.return_value": name, "exe.return_value": "/x/engine", "info": { + "pid": pid, "ppid": ppid, "cmdline": ["engine", "--serve"], "create_time": 100.0}}) + + me = mock.Mock(**{"parents.return_value": [proc(p, n) for p, n in ancestors]}) + engine = proc(7000, "engine", ppid=5000) + parent = proc(5000, parent_name) + parent.create_time.return_value = 50.0 + parent.status.return_value = "running" + fake = mock.Mock(Error=Err, NoSuchProcess=NoSuch, STATUS_ZOMBIE="zombie") + fake.Process.side_effect = lambda pid=None: me if pid is None else parent + fake.process_iter.return_value = [engine] + return fake + + def found(self, ancestors, parent_name): + fake = self.fake_psutil(ancestors, parent_name) + with mock.patch.object(procs, "psutil", fake), mock.patch.object(procs, "same_file", return_value=True), \ + mock.patch.object(procs, "identify", side_effect=lambda pid: ("ident", pid)): + return procs.orphans_of("/x/engine") + + def test_an_engine_adopted_by_systemd_user_is_an_orphan_even_when_it_is_an_ancestor_of_the_terminal(self): + # systemd --user (pid 5000) is an ancestor of every desktop terminal and adopts what loses its parent + self.assertEqual(self.found([(5000, "systemd"), (6000, "bash")], "systemd"), [("ident", 7000)]) + + def test_an_engine_whose_parent_is_a_real_ancestor_is_not_an_orphan(self): + # started by this server's own shell: not touched + self.assertEqual(self.found([(5000, "bash"), (6000, "tmux")], "bash"), []) + + def test_ending_waits_on_the_start_token_not_on_an_empty_command_line(self): + record = {"pid": 4242, "token": "t1", "cmd": ["engine", "--serve"]} + tokens = iter(["t1", "t1", None]) # still exiting twice, then gone + with mock.patch.object(procs, "WINDOWS", False), mock.patch.object(procs, "is_same", side_effect=[True, False, False]) as same, \ + mock.patch.object(procs, "_signal_verified"), mock.patch.object(procs, "start_token", side_effect=lambda pid: next(tokens)), \ + mock.patch.object(procs, "drop_record"), mock.patch.object(procs.time, "sleep"): + self.assertEqual(procs.end_one(record, grace=5), "ended") + self.assertGreaterEqual(same.call_count, 1) + if __name__ == "__main__": unittest.main() From d398f353252a43d782e20531290be74e5a231f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A9=E7=A9=BABlond?= <8587572+hurui200320@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:09 +0100 Subject: [PATCH 041/177] docker: the build context carries the nested tools/ scripts the Terminal bundle reads (#3974) docker/build.sh staged only top-level tools/*.py, so the Terminal stage stopped at 'installer tool missing: tools/dsv41/tune.py'. Ported from PR #3974 by hurui200320: the pathspec is tools/**/*.py, the no-.git fallback finds nested files, and the context test reads INSTALLER_TOOLS and INSTALLER_SCRIPTS from packaging/package_terminal.py. Fixes the failure that images built from v0.2.4.1 and v0.2.4.2 had. --- docker/build.sh | 7 +++++-- tests/terminal/test_docker_files.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docker/build.sh b/docker/build.sh index bba83ff2..3048b8bc 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -61,14 +61,17 @@ commit=${STRATA_BUILD_COMMIT:-$(git -C "$repo" rev-parse HEAD 2>/dev/null || tru case "$commit" in *[!0-9a-f]*|"") commit="" ;; esac # 1. the Terminal's sources: exactly what packaging/package_terminal.py copies (the working tree, so local edits are in the image) +# tools/: every .py at any depth, because the bundle's DeepSeek scripts are nested (INSTALLER_SCRIPTS in package_terminal.py names dsv41/*: +# the Dockerfile's terminal stage stops at "installer tool missing: tools/dsv41/tune.py" when only the top-level modules are in the context) cd "$repo" paths="packaging bin strata.py strata_control strata_cli serve requirements.txt requirements-monitor.txt docs/MANAGEMENT_PROTOCOL.md docs/TERMINAL_LAUNCH.md data bench/prompts/standard-v1 setup.py ref/load.py CMakeLists.txt" if git rev-parse --git-dir >/dev/null 2>&1; then # shellcheck disable=SC2086 - { git ls-files -z -- $paths ':(glob)tools/*.py'; } | tar --null -T - -cf - | tar -xf - -C "$ctx/terminal-src" + { git ls-files -z -- $paths ':(glob)tools/**/*.py'; } | tar --null -T - -cf - | tar -xf - -C "$ctx/terminal-src" else + tools_py=$(find tools -name '*.py') # nested too: the bundle's dsv41 scripts live in tools/dsv41/ # shellcheck disable=SC2086 - tar -cf - --exclude='__pycache__' $paths tools/*.py | tar -xf - -C "$ctx/terminal-src" + tar -cf - --exclude='__pycache__' $paths $tools_py | tar -xf - -C "$ctx/terminal-src" fi # 2. the engine package(s): hard-linked when on the same file system (no second copy of GBs), copied otherwise diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index 0792d65f..a51cee8a 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -54,6 +54,16 @@ class Scripts(unittest.TestCase): self.assertTrue((ctx / "Dockerfile").is_file()) self.assertTrue((ctx / "terminal-src" / "docs" / "TERMINAL_LAUNCH.md").is_file()) self.assertTrue((ctx / "engine" / "pkg" / "engine-component.json").is_file()) + # the bundle reads tools/ modules by path as well (INSTALLER_SCRIPTS), and the DeepSeek ones are nested: every name must be in the + # context, or package_terminal.py stops the build at "installer tool missing: tools/.py" (the image build after v0.2.4.1 was broken this way) + pt = ast.parse((ROOT / "packaging" / "package_terminal.py").read_text(encoding="utf-8")) + tools: set[str] = set() + for node in pt.body: + if isinstance(node, ast.Assign) and any(getattr(t, "id", "") in ("INSTALLER_TOOLS", "INSTALLER_SCRIPTS") for t in node.targets): + tools.update(ast.literal_eval(node.value)) + self.assertTrue({"dsv41/pack_gguf", "dsv41/tune"} <= tools) # the nested ones this assertion exists for + for name in sorted(tools): + self.assertTrue((ctx / "terminal-src" / "tools" / f"{name}.py").is_file(), f"build.sh did not copy tools/{name}.py into the context") def test_scripts_use_unix_line_ends(self): for name in ("entrypoint.sh", "strata-wrapper.sh", "healthcheck.sh", "build.sh", "publish.sh"): From e0469a585f606d5cd846174044323cb1da3ec160 Mon Sep 17 00:00:00 2001 From: i-Vladimir-i <291339861+i-Vladimir-i@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:27 +0100 Subject: [PATCH 042/177] MCP chat: at the tool-round limit the model gets one final reply with no tools from the results already found, instead of the turn ending without an answer (PR #3741 by i-Vladimir-i) --- docs/DETAILS.md | 3 +- serve/server.py | 19 +++++++--- serve/test_mcp.py | 94 ++++++++++++++++++++++++++++++++++++++++++++--- serve/web/app.js | 2 +- 4 files changed, 106 insertions(+), 12 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 4255fc62..bd5b7f4c 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -769,7 +769,8 @@ after a change. transport is not supported). `"disabled": true` leaves an entry out. - Servers start with Strata. The server window says what each offers or why it did not start. The Monitor tab lists them, and the Sampling drawer has **Use tools from MCP servers** (on by default). A server that stops later is started again at its next call. -- In the chat each call shows as a small block. The model reads the result and goes on, up to `max_rounds` calls in a row. A tool +- In the chat each call shows as a small block. The model reads the result and goes on, up to `max_rounds` rounds of calls (one round can hold several calls). At the limit + the model gets one final reply with no tools, using the results already found, so the answer is not cut off. A tool that fails or takes longer than `timeout_s` gives the model an `error: ...` result. Results longer than `max_result_chars` are cut with a note. Stop stops a running tool too. - Only the chat page uses them. API clients see the API exactly as before and keep their own tools. A request to diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..2a7dc325 100644 --- a/serve/server.py +++ b/serve/server.py @@ -5719,13 +5719,15 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, """Service.run with the MCP tools executed here: the model writes a call to an MCP tool, the server runs it, adds the call and its result to the conversation and lets the model continue - up to `max_rounds` times. Yields what Service.run yields (text, thinking, the request's own tool calls) plus ("mcp", {...}) for the tool activity, and - one ("done", ...) at the very end with the output tokens of every round. + one ("done", ...) at the very end with the output tokens of every round. After the last tool round, one final + reply uses the results already obtained, with no tools offered or executed. `mcp_names`: the MCP tools this request offered; any other call is one of the request's own tools and ends the turn as always (the client answers it). MCP calls written in the same answer are then not run (their results could not reach the model before the client's).""" max_rounds = int(hub.settings["max_rounds"]) total, rounds, done = 0, 0, None + finalizing = False messages = list(messages) while True: text, reasoning, calls, own_calls = [], [], [], 0 @@ -5749,10 +5751,7 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, reasoning.append(ev.text) yield kind, x total += done["completion_tokens"] - run_them = calls and not own_calls and done["finish"] == "stop" and not cancel.is_set() - if run_them and rounds >= max_rounds: - yield "mcp", {"event": "limit", "max_rounds": max_rounds} - run_them = False + run_them = calls and not own_calls and not finalizing and done["finish"] == "stop" and not cancel.is_set() if not run_them: for c in calls: # announced, never run: close them in the client's view yield "mcp", {"event": "result", "id": c.id, "ok": False, "skipped": True, "text": "not run", @@ -5797,6 +5796,16 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) messages += [{"role": "tool", "content": r} for r in results] + if rounds >= max_rounds: + finalizing = True + tools = None + system_end = next((index for index, message in enumerate(messages) + if message.get("role") not in ("system", "developer")), len(messages)) + messages.insert(system_end, {"role": "system", "content": + f"The tool-use limit of {max_rounds} rounds has been reached. No tools are available for this final " + "reply. Answer the user's original request in their language using the results already obtained. " + "Explain any gaps in the available evidence. Do not request or emit further tool calls."}) + yield "mcp", {"event": "limit", "max_rounds": max_rounds} try: ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req, cancel=cancel) except ClientGone: # #1999: the client left while a picture was prepared diff --git a/serve/test_mcp.py b/serve/test_mcp.py index 2c414ef0..055089d9 100644 --- a/serve/test_mcp.py +++ b/serve/test_mcp.py @@ -365,14 +365,98 @@ class ToolLoop(unittest.TestCase): self.assertNotIn("y" * 501, second) def test_max_rounds(self): - self.start(call_script("fake__echo", text="again")) # the model never stops calling + self.start(call_script("fake__echo", text="first result"), + call_script("fake__echo", text="second result"), "\n\nSummary of both results.") code, text = self.post({"strata_mcp": True}) - mcp = [c["strata_mcp"] for c in self.chunks(text) if "strata_mcp" in c] - self.assertEqual(len(self.engine.prompts), 3) # 2 rounds of tools, then the limit + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + mcp = [chunk["strata_mcp"] for chunk in chunks if "strata_mcp" in chunk] + self.assertEqual(len(self.engine.prompts), 3) self.assertEqual(sum(m["event"] == "call" for m in mcp), 2) self.assertIn({"event": "limit", "max_rounds": 2}, mcp) - self.assertTrue(mcp[-1].get("skipped")) - self.assertEqual(self.chunks(text)[-1]["choices"][0]["finish_reason"], "stop") + self.assertFalse(any(m.get("skipped") for m in mcp)) + self.assertIn("Summary of both results.", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + final_prompt = self.engine.prompt_text(2) + self.assertIn("\nfirst result\n", final_prompt) + self.assertIn("\nsecond result\n", final_prompt) + self.assertIn("No tools are available for this final reply", final_prompt) + self.assertNotIn("", final_prompt) + self.assertEqual(chunks[-1]["choices"][0]["finish_reason"], "stop") + self.assertEqual(chunks[-1]["usage"]["prompt_tokens"], len(self.engine.prompts[2])) + + def test_max_rounds_non_stream_with_existing_system(self): + self.hub.settings["max_rounds"] = 1 + self.start(call_script("fake__add", a=2, b=3), "\n\nThe result is 5.") + code, text = self.post({"strata_mcp": True, "messages": [ + {"role": "system", "content": "Keep answers concise."}, + {"role": "developer", "content": "Use the provided evidence."}, + {"role": "user", "content": "Add 2 and 3."}]}, stream=False) + self.assertEqual(code, 200, text) + response = json.loads(text) + self.assertIn("The result is 5.", response["choices"][0]["message"]["content"]) + final_prompt = self.engine.prompt_text(1) + self.assertIn("Keep answers concise.", final_prompt) + self.assertIn("Use the provided evidence.", final_prompt) + self.assertIn("\n5\n", final_prompt) + self.assertNotIn("", final_prompt) + + def test_max_rounds_counts_rounds_with_multiple_calls(self): + self.hub.settings["max_rounds"] = 1 + self.start(call_script("fake__echo", text="source A") + "\n" + + call_script("fake__echo", text="source B"), "\n\nBoth sources agree.") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + mcp = [chunk["strata_mcp"] for chunk in chunks if "strata_mcp" in chunk] + calls = [event for event in mcp if event["event"] == "call"] + self.assertEqual([event["round"] for event in calls], [1, 1]) + self.assertEqual(len(self.engine.prompts), 2) + self.assertIn("\nsource A\n", self.engine.prompt_text(1)) + self.assertIn("\nsource B\n", self.engine.prompt_text(1)) + self.assertIn("Both sources agree.", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + + def test_sixteen_rounds_then_final_answer(self): + self.hub.settings["max_rounds"] = 16 + scripts = [call_script("fake__echo", text=f"source {index}") for index in range(16)] + self.start(*scripts, "\n\nSummary after sixteen rounds.") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + mcp = [chunk["strata_mcp"] for chunk in chunks if "strata_mcp" in chunk] + self.assertEqual(sum(event["event"] == "call" for event in mcp), 16) + self.assertIn({"event": "limit", "max_rounds": 16}, mcp) + self.assertEqual(len(self.engine.prompts), 17) + final_prompt = self.engine.prompt_text(16) + self.assertIn("\nsource 0\n", final_prompt) + self.assertIn("\nsource 15\n", final_prompt) + self.assertNotIn("", final_prompt) + self.assertIn("Summary after sixteen rounds.", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + + def test_max_rounds_preserves_errors_and_disables_client_tools(self): + self.hub.settings["max_rounds"] = 1 + own = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}] + self.start(call_script("fake__fail"), "\n\nThe source failed; here is what is known.") + code, text = self.post({"strata_mcp": True, "tools": own}) + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + self.assertFalse(any(chunk["choices"][0]["delta"].get("tool_calls") for chunk in chunks)) + self.assertIn("error: it failed on purpose", self.engine.prompt_text(1)) + self.assertNotIn("", self.engine.prompt_text(1)) + self.assertIn("here is what is known", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + + def test_max_rounds_does_not_execute_more_calls(self): + self.hub.settings["max_rounds"] = 1 + self.start(call_script("fake__echo", text="known"), call_script("fake__echo", text="must not run")) + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + self.assertEqual(len(self.engine.prompts), 2) + mcp = [chunk["strata_mcp"] for chunk in self.chunks(text) if "strata_mcp" in chunk] + self.assertEqual(sum(event["event"] == "call" for event in mcp), 1) + self.assertNotIn("must not run", Path(self.log.name).read_text()) def test_stop_during_a_tool(self): """Closing the connection while a slow tool runs stops the tool (notifications/cancelled) and the loop.""" diff --git a/serve/web/app.js b/serve/web/app.js index 856df8ca..d01ff297 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -910,7 +910,7 @@ async function send() { for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; } const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length; if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${ran} tool call${ran > 1 ? "s" : ""}`; - if (m.limit) m.meta = `${m.meta || ""} · stopped at the limit of ${m.limit} tool rounds (mcp.max_rounds)`; + if (m.limit) m.meta = `${m.meta || ""} · tool limit reached (${m.limit} rounds, mcp.max_rounds)`; busy = null; setBusy(false); if (frame) cancelAnimationFrame(frame); From 255861c442ed4a0f1e4e797899d6207c85051ab8 Mon Sep 17 00:00:00 2001 From: Roberto Jose Etcheverry Romero <63941860+robertoetcheverryr@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:35 +0100 Subject: [PATCH 043/177] docker: the root Dockerfile passes the source commit to the Terminal stage (#3644) .git is not in the build context, so package_terminal.py had no commit to put in the archive and the documented source build stopped. Ported from PR #3644 by robertoetcheverryr: ARG STRATA_COMMIT / ENV STRATA_BUILD_COMMIT as in docker/Dockerfile, and the two 'From source' commands in docs/DOCKER.md pass --build-arg STRATA_COMMIT=$(git rev-parse HEAD). Added: .dockerignore leaves out the folders docker/entrypoint.sh creates in a mounted data/ (install, state, home, Strata-data). A dangling data/install/third_party/llama.cpp link in a clone that had been mounted made the Terminal stage fail with a copytree error (seen in the review thread of #3644). Not built with docker here (no docker on this PC). --- .dockerignore | 5 +++++ Dockerfile | 2 ++ docs/DOCKER.md | 15 ++++++++------- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/.dockerignore b/.dockerignore index 4f341af3..2550d9bf 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,6 +17,11 @@ __pycache__/ /mtp/ /models/ /Strata-data/ +# the folders docker/entrypoint.sh creates in a mounted data/ (a link to llama.cpp, the models, the keys): never part of a build (#3644) +/data/install/ +/data/state/ +/data/home/ +/data/Strata-data/ third_party/llama.cpp/ third_party/*.zip *.done diff --git a/Dockerfile b/Dockerfile index 82f096cf..eba34a01 100644 --- a/Dockerfile +++ b/Dockerfile @@ -68,6 +68,8 @@ RUN set -e; \ # ---- 2. the Terminal (the release archive, built here) FROM ${RUNTIME_BASE} AS terminal +ARG STRATA_COMMIT= +ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT} 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/ diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 81672d74..3ea6f661 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -296,13 +296,14 @@ to the system or the graphics driver (`packaging/binary_deps.py`); finally it ch library inside the finished image. A package that fails any of these stops the build. Nothing is pushed anywhere. `docker/smoke-test.sh` runs the checks we ran on real cards (serves, key, chat, tool call, monitor, clean stop, memory freed, restart); see its first lines for the variables. -**From source.** `docker build -t strata:src .` in the repository compiles the CUDA 13 engine inside Docker, makes the package -and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, much faster). For a GTX 10, P100 or -V100 build the CUDA 12 variant: `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 .` (the build turns on the Pascal / Volta code by itself -when an architecture below 75 is listed, and names the package `cuda12` with driver 575.51). For AMD and Intel -builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result with -`packaging/package_engine.py` and use `docker/build.sh`. +**From source.** `docker build -t strata:src --build-arg STRATA_COMMIT=$(git rev-parse HEAD) .` in the repository compiles the CUDA 13 +engine inside Docker, makes the package and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, +much faster). `.git` is not copied into the build, so the commit comes in as `STRATA_COMMIT`; without it the Terminal stage stops. +For a GTX 10, P100 or V100 build the CUDA 12 variant: `docker build -t strata:src-cuda12 --build-arg STRATA_COMMIT=$(git rev-parse HEAD) +--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 .` +(the build turns on the Pascal / Volta code by itself when an architecture below 75 is listed, and names the package `cuda12` with +driver 575.51). For AMD and Intel builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result +with `packaging/package_engine.py` and use `docker/build.sh`. ## Publishing the images (for maintainers) From a8755042bd7f43d5e3373dd803c3edda2fc5d1ae Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:19:38 +0100 Subject: [PATCH 044/177] Delete a model: every part of a multi-part GGUF goes with it (the run config names only the first), and a part another model names stays (#3716) --- tests/desktop/test_control_install.py | 26 ++++++++++++++++++++++++++ tools/strata_mcp.py | 19 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.py index a886cd32..d306de27 100644 --- a/tests/desktop/test_control_install.py +++ b/tests/desktop/test_control_install.py @@ -468,6 +468,32 @@ class DeleteModelTests(unittest.TestCase): self.assertFalse(pack.exists()) self.assertTrue(mine.is_file(), "a file the person brought stays") + def test_every_part_of_a_multi_part_model_goes_with_it_and_a_part_another_model_uses_stays(self): + # The run config names only the first part; the others used to stay on disk (#3716). + folder = self.data / "models" / "IQ3_XXS" + parts = [self.make(folder / f"Big-0000{i}-of-00003.gguf", 5000) for i in (1, 2, 3)] + for part in parts: + self.make(part.with_name(part.name + ".done"), 1) + (self.root / "strata-iq3xxs.json").write_text(json.dumps({"exe": "component:strata-engine", "args": [ + "--native", str(parts[0]), "--max-context", "32768"]}), encoding="utf-8") + plan = self.tools.strata_remove(model="iq3xxs")["plan"] + removed = {Path(x["path"]).name for x in plan["remove"]} + self.assertTrue({p.name for p in parts} <= removed, removed) + result = self.tools.strata_remove(model="iq3xxs", confirm=True) + self.assertEqual(result["failed"], []) + self.assertEqual([p.exists() for p in parts], [False, False, False]) + self.assertFalse(folder.exists()) + + def test_a_part_that_another_model_names_is_kept_when_a_multi_part_model_is_deleted(self): + folder = self.data / "models" / "IQ3_XXS" + parts = [self.make(folder / f"Big-0000{i}-of-00002.gguf", 5000) for i in (1, 2)] + for part in parts: + self.make(part.with_name(part.name + ".done"), 1) + (self.root / "strata-iq3xxs.json").write_text(json.dumps({"exe": "component:strata-engine", "args": ["--native", str(parts[0])]}), encoding="utf-8") + (self.root / "strata-twin.json").write_text(json.dumps({"exe": "component:strata-engine", "args": ["--native", str(parts[0])]}), encoding="utf-8") + self.tools.strata_remove(model="iq3xxs", confirm=True) + self.assertTrue(all(p.is_file() for p in parts), "the twin config still uses every part") + class LocalGgufInstallTests(unittest.TestCase): def test_a_plan_from_a_local_folder_adopts_the_files_and_needs_no_download_space(self): diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 5a5eb2fe..5b5efcf5 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -704,6 +704,23 @@ class Strata: once_d.append(d) return once, once_d + @staticmethod + def with_shards(files: list) -> list: + """The files plus the other parts of every multi-part GGUF among them (name-00001-of-00004.gguf: the config names only the + first), so deleting a model takes all its parts and never leaves 100 GB behind (#3716).""" + out, seen = [], set() + for f in files: + names = [Path(f)] + m = SHARD_NAME.match(str(f)) + if m: + names += [Path(f"{m.group(1)}-{i:05d}-of-{m.group(3)}.gguf") for i in range(1, int(m.group(3)) + 1)] + for n in names: + key = norm(n) + if key not in seen: + seen.add(key) + out.append(n) + return out + @staticmethod def tree_bytes(path: Path) -> int: if path.is_file(): @@ -791,11 +808,13 @@ class Strata: (the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders.""" cfg = self.read_config(config) files, dirs = self.model_paths(cfg) + files = self.with_shards(files) used_files, used_dirs = set(), set() for other in self.configs(): if norm(other) == norm(config): continue f, d = self.model_paths(self.read_config(other)) + f = self.with_shards(f) used_files |= {norm(x) for x in f} used_dirs |= {norm(x) for x in d} remove, keep = [], [] From 68ba321accbf098ca41cdb36cf834e5ceb863771 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:19:38 +0100 Subject: [PATCH 045/177] launch: a model folder is found whatever its letter case, so a downloaded model is not offered again on a case-sensitive disk (#3996); a log path the person set in the config is kept (#3656); --dspark takes on|off|auto|none and the word reaches the engine (#3959) --- strata_cli/launch/catalog.py | 19 +++++ strata_cli/launch/cmd.py | 5 ++ strata_cli/launch/modelstate.py | 2 +- strata_cli/launch/runner.py | 16 ++++- strata_cli/launch/settings.py | 13 +++- tests/terminal/test_launch.py | 20 ++++++ tests/terminal/test_launch_own_log.py | 33 +++++++++ tests/terminal/test_model_folder_case.py | 89 ++++++++++++++++++++++++ 8 files changed, 193 insertions(+), 4 deletions(-) create mode 100644 tests/terminal/test_launch_own_log.py create mode 100644 tests/terminal/test_model_folder_case.py diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py index a7d61fcc..bddc41d9 100644 --- a/strata_cli/launch/catalog.py +++ b/strata_cli/launch/catalog.py @@ -397,6 +397,25 @@ class Catalog: _m, families, _c, _s = self.tables() return (families[family].get("tag", "") + model).lower() + def model_folder(self, base: Path, family: str, model: str) -> Path: + """The folder a model's files are in under `base/models`. setup.py names it with the case kept (`models/IQ3_S`), the run-config tag is + lower case (`iq3_s`): on a case-sensitive disk the two are different folders, so the one that exists wins, and a folder that differs + only in case is found (#3996). When none exists yet it is setup's own name, because that is where the download will go.""" + _m, families, _c, _s = self.tables() + models = Path(base) / "models" + own = models / (families[family].get("tag", "") + model) + lower = models / self.tag_of(family, model) + for candidate in (own, lower): + if candidate.is_dir(): + return candidate + try: + for entry in models.iterdir(): + if entry.name.lower() == lower.name and entry.is_dir(): + return entry + except OSError: + pass + return own + def kv_gb(self, tokens: int, kv: str = "int8") -> float: """The conversation memory for this many tokens, in GB (setup.py's UD_FIT_KV_BYTES: 13 attention layers).""" mod = self.strata.setup_module() diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 48cd78ed..cac1afab 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -114,6 +114,9 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] "Main does the last steps of every answer; a helper holds part of the model") g.add_argument("--tune", type=_choice("a tuning mode", S.TUNE_MODES), metavar="quick|thorough|skip", help="find the fastest settings first (default: skip here; the guided screens suggest quick the first time)") g.add_argument("--tune-allow-small", action="store_true", help="let the tuner also try settings that can change answers very slightly") + g.add_argument("--dspark", type=_choice("a DSpark mode", ("on", "off", "auto", "none")), metavar="on|off|auto|none", + help="DeepSeek: the DSpark drafter that guesses ahead (auto loads it only where it helps; off still loads it on some cards). " + "The same as --set dspark=") g.add_argument("--set", action="append", default=[], metavar="KEY=VALUE", help="an advanced engine setting or STRATA_* variable, e.g. prefill=65536 (repeat); unknown names get a warning, not a refusal") g.add_argument("--pool-cores", metavar="LIST", @@ -279,6 +282,8 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet s.no_key = False if a.set: s.extra = {**s.extra, **S.settings_from_pairs(a.set)} + if a.dspark: + s.extra = {**s.extra, "--dspark": a.dspark} if a.pool_cores: text = a.pool_cores.replace(" ", "") if not re.fullmatch(r"\d+(-\d+(:\d+)?)?(,\d+(-\d+(:\d+)?)?)*", text): diff --git a/strata_cli/launch/modelstate.py b/strata_cli/launch/modelstate.py index a87c361a..a2f81974 100644 --- a/strata_cli/launch/modelstate.py +++ b/strata_cli/launch/modelstate.py @@ -156,7 +156,7 @@ def assess(catalog, family: str | None, model: str | None, *, vision: str = "off # not installed: whatever of the weights is in the model's folder counts if family and model: base = data or Path(catalog.data_dir()) - folder = base / "models" / catalog.tag_of(family, model) + folder = catalog.model_folder(base, family, model) got = 0 try: got = sum(f.stat().st_size for f in folder.glob("*.gguf") if not f.name.lower().startswith("mmproj")) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index d9440541..5b2a4b3c 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -489,6 +489,18 @@ def apply_experts(cfg: dict, experts: int | None) -> None: cfg["args"] = out + ["--experts", str(int(experts))] +_SETUP_LOG_NAME = re.compile(r"^strata-[A-Za-z0-9_.-]+\.log$") + + +def own_log_path(base: dict) -> str | None: + """The log path a person wrote into the model's config themselves (#3656): setup names its own `strata-.log`, so any other + name is theirs and a launch keeps it instead of writing its per-profile log file.""" + value = base.get("log") + if not isinstance(value, str) or not value.strip(): + return None + return None if _SETUP_LOG_NAME.match(Path(value.replace("\\", "/")).name) else value + + def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str], log: str | None = None, gpus: "list[int] | dict | None" = None, experts: int | None = None) -> dict: """The private run config of this launch: the installed one plus the choices that are not setup's (host, port, key, cards, advanced).""" @@ -508,7 +520,7 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str] cfg["open_browser"] = False # strata launch never opens a browser by itself (only `--open` does, after the start) if isinstance(cfg.get("args"), list): cfg["args"] = [a for a in cfg["args"] if a != "--open"] - if log: + if log and not own_log_path(base): cfg["log"] = log apply_cards(cfg, gpus) from strata_control import drafting as _drafting @@ -1060,7 +1072,7 @@ class Runner: s, cat = self.s, self.catalog data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or cat.data_dir()) models_dir = data / "models" - job = {"folder": str(models_dir / cat.tag_of(s.family, s.model)), + job = {"folder": str(cat.model_folder(data, s.family, s.model)), "total_gb": float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0)} try: setup_module = cat.strata.setup_module() diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index f2f7ef94..0f57fb6d 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -277,15 +277,26 @@ def settings_from_pairs(pairs: list[str]) -> dict[str, str]: return out +#: Options whose value is a WORD the engine reads (on, off, auto, none): the word goes through as typed. Making "on" a bare flag +#: started strata-dsv41 with a lone `--dspark`, which it refuses ("--dspark needs a value", #3959), and "off" removed the flag instead of +#: switching the drafter off. +WORD_VALUE_FLAGS = frozenset({"--dspark"}) + + def as_argv_changes(extra: dict[str, str], bool_flags: frozenset[str]) -> tuple[dict[str, Any], dict[str, str | None]]: """Turn the Advanced table's values into `tune_knobs.apply_to_argv` changes and environment changes. - A flag without a value (or on/true/yes) is "present"; off/false/no/none removes it; anything else is a value.""" + A flag without a value (or on/true/yes) is "present"; off/false/no/none removes it; anything else is a value. + A word-valued option (WORD_VALUE_FLAGS) keeps its word.""" args: dict[str, Any] = {} env: dict[str, str | None] = {} for key, value in extra.items(): if key.startswith("--"): low = value.lower() + if key in WORD_VALUE_FLAGS and key not in bool_flags: + if low: + args[key] = low + continue # an empty value is no change, as for every option that takes one (#3504) if low == "" and key not in bool_flags: continue # an empty value for an option that takes one is no change, never a bare flag (#3504) if key in bool_flags or low in ("on", "true", "yes", ""): diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index ccb9b7cd..d3f4b35a 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -832,6 +832,26 @@ class FlagsCommand(unittest.TestCase): self.assertNotIn("--pool-cores", p["settings"]["extra"]) self.assertTrue(any("pool-cores" in w for w in p["warnings"])) + def test_dspark_takes_a_word_and_the_word_reaches_the_engine_line(self): + # --set dspark=on used to start strata-dsv41 with a lone "--dspark" ("--dspark needs a value", #3959) + from strata_cli.launch import settings as S + from strata_control import tune_knobs + base = ["--pack", "p", "--max-context", "262144"] + for word in ("on", "off", "auto", "none"): + a, _ = S.as_argv_changes({"--dspark": word}, tune_knobs.BOOL_FLAGS) + self.assertEqual(a, {"--dspark": word}) + out = tune_knobs.apply_to_argv(base + ["--dspark", "auto"], a) + self.assertEqual(out[out.index("--dspark") + 1], word, word) + self.assertEqual(out.count("--dspark"), 1) + a, _ = S.as_argv_changes({"--dspark": "ON", "--dspark-conf": "0.7"}, tune_knobs.BOOL_FLAGS) + self.assertEqual(a, {"--dspark": "on", "--dspark-conf": "0.7"}) + self.assertEqual(S.as_argv_changes({"--dspark": ""}, tune_knobs.BOOL_FLAGS)[0], {}) + code, out, _err = run_cli(["launch", "--help"]) + self.assertIn("--dspark", out) + p = self.plan("--model", "q2_0", "--dspark", "on") + self.assertEqual(p["settings"]["extra"], {"--dspark": "on"}) + self.assertIn("--set dspark=on", p["flags"]) + def test_api_key_flags(self): p = self.plan("--model", "q2_0", "--access", "lan", "--api-key", "sk-mine") self.assertEqual(p["settings"]["api_key"], "set") diff --git a/tests/terminal/test_launch_own_log.py b/tests/terminal/test_launch_own_log.py new file mode 100644 index 00000000..73210ec7 --- /dev/null +++ b/tests/terminal/test_launch_own_log.py @@ -0,0 +1,33 @@ +"""A launch keeps the log path the person wrote into the model's config (#3656).""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from strata_cli.launch import runner, settings as S # noqa: E402 +from strata_control import tune_knobs # noqa: E402 + + +def derive(base): + return runner.derive_config(base, S.LaunchSettings(), bool_flags=tune_knobs.BOOL_FLAGS, log="C:/launch/q2_0.engine.log") + + +class OwnLog(unittest.TestCase): + def test_the_setup_log_name_is_replaced_by_the_launch_log(self): + for name in ("M:/Strata/strata-iq3_xxs.log", "/home/me/strata/strata-q2_0.log", "M:\Strata\strata-iq3_s.log"): + self.assertEqual(derive({"exe": "e", "args": [], "log": name})["log"], "C:/launch/q2_0.engine.log", name) + self.assertEqual(derive({"exe": "e", "args": []})["log"], "C:/launch/q2_0.engine.log") + + def test_a_log_path_the_person_chose_is_kept(self): + for name in ("M:/logs/history.log", "/var/log/strata/engine.log", "D:\notes\iq3.txt"): + self.assertEqual(derive({"exe": "e", "args": [], "log": name})["log"], name, name) + self.assertEqual(runner.own_log_path({"log": "M:/Strata/strata-iq3_xxs.log"}), None) + self.assertEqual(runner.own_log_path({"log": ""}), None) + self.assertEqual(runner.own_log_path({"log": 5}), None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_model_folder_case.py b/tests/terminal/test_model_folder_case.py new file mode 100644 index 00000000..ea807557 --- /dev/null +++ b/tests/terminal/test_model_folder_case.py @@ -0,0 +1,89 @@ +"""strata launch finds a model folder whatever its letter case (#3996). + +setup.py writes `models/IQ3_S` (the model name's case kept); the run-config tag is lower case (`iq3_s`). On a case-sensitive disk the +launch lookup missed the downloaded folder and offered the whole download again. The tests make the disk case-sensitive on any system by +answering `Path.is_dir` from the names the folder really lists. +""" +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from strata_cli.launch import modelstate # noqa: E402 +from strata_cli.launch.catalog import Catalog # noqa: E402 + +_real_is_dir = Path.is_dir + + +def _case_sensitive_is_dir(self): + try: + listed = {entry.name for entry in self.parent.iterdir()} + except OSError: + return False + return self.name in listed and _real_is_dir(self) + + +class StubCatalog: + """Just what model_folder and assess use.""" + tables = lambda self: ({}, {"qwen": {"tag": ""}}, None, None) # noqa: E731 + tag_of = Catalog.tag_of + model_folder = Catalog.model_folder + + def __init__(self, data: Path): + self._data = data + + def data_dir(self): + return self._data + + def rows(self): + return [mock.Mock(family="qwen", model="IQ3_S", download_gb=83.6, images=False)] + + def installed_config(self, tag): + return None + + +class ModelFolderCase(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.data = Path(self.tmp.name) + patch = mock.patch.object(Path, "is_dir", _case_sensitive_is_dir) + patch.start() + self.addCleanup(patch.stop) + self.cat = StubCatalog(self.data) + + def test_the_folder_setup_wrote_is_found(self): + folder = self.data / "models" / "IQ3_S" + folder.mkdir(parents=True) + self.assertEqual(self.cat.model_folder(self.data, "qwen", "IQ3_S").name, "IQ3_S") + + def test_a_lower_case_folder_is_found_too(self): + (self.data / "models" / "iq3_s").mkdir(parents=True) + self.assertEqual(self.cat.model_folder(self.data, "qwen", "IQ3_S").name, "iq3_s") + + def test_a_folder_that_differs_only_in_case_is_found(self): + (self.data / "models" / "Iq3_S").mkdir(parents=True) + self.assertEqual(self.cat.model_folder(self.data, "qwen", "IQ3_S").name, "Iq3_S") + + def test_nothing_there_yet_is_the_name_setup_will_write(self): + (self.data / "models").mkdir(parents=True) + self.assertEqual(self.cat.model_folder(self.data, "qwen", "IQ3_S").name, "IQ3_S") + self.assertEqual(self.cat.model_folder(self.data / "missing", "qwen", "IQ3_S").name, "IQ3_S") + + def test_a_downloaded_model_in_setups_folder_is_counted_by_the_launch_plan(self): + folder = self.data / "models" / "IQ3_S" + folder.mkdir(parents=True) + (folder / "m-00001-of-00002.gguf").write_bytes(b"x" * 1000) + state = modelstate.assess(self.cat, "qwen", "IQ3_S", data_dir=self.data) + self.assertAlmostEqual(state.on_disk_gb, 1000 / 1e9) + empty = modelstate.assess(self.cat, "qwen", "IQ3_S", data_dir=self.data / "other") + self.assertEqual(empty.on_disk_gb, 0.0) + + +if __name__ == "__main__": + unittest.main() From 7c4c20799c2cd8b3a0d91d25f4a7355eedf8643f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:19:39 +0100 Subject: [PATCH 046/177] Residency-biased routing default is CUDA-discrete-only: read from the device properties once in Verifier::init (never first inside a graph capture), off in HIP builds and on integrated GPUs, a line in the log when it is on; the wide HC up read never defaults on in a HIP build (gfx12 reports compute capability 12.0 too) --- docs/DETAILS.md | 4 +-- docs/release-notes-0.2.7.md | 3 +- src/core/verify.cpp | 54 ++++++++++++++++++++++++------------ src/kernels/cuda/fused_gr.cu | 6 ++++ 4 files changed, 47 insertions(+), 20 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 43538ddc..afd8290a 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -899,7 +899,7 @@ them on your own card. | `STRATA_PREFILL_EQUAL=1` | CUDA | A prompt segment is read in chunks of equal size, not full chunks and a short last one. Changes rounding. | | | `STRATA_OWNED_PRICE=exact` | CUDA | The cache sizing prices the prompt path's own buffers by their real allocation. | | | `STRATA_IQ_MT_MIN=1`, `STRATA_IQ3S_MT1=1` | CPU | See [Draft layer](#draft-layer) (reproducible output; the second gives IQ3_S the multi-token kernel for one token on Alder Lake and later without AVX-512). | | -| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended. | +| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended, except that 0.2.7 turns `STRATA_ROUTE_PRIOR=2.0` on by itself on a discrete NVIDIA card of 13 GiB or less (the owner approved the quality trade for 12 GB cards); `STRATA_ROUTE_PRIOR=0` turns it off. It is never a default on a Radeon, an integrated GPU or a bigger card. | | `STRATA_HOST_CORE=last\|sibling` (or `--host-core`) | Windows | `last` puts the host thread on the last physical core, away from the core that gets the GPU's interrupts. `sibling` keeps it on the first core's other hardware thread, so the workers keep every core. The default `first` leaves a hybrid CPU as it is. | One layer-split box went from a ±6% swing to steady and 8% faster. | | `--pool-affinity measure` | Hybrid CPUs, native packs | Times the `all` and `p-cores` layouts at start (about a second) and takes the faster. The measurement is taken once; where the E-cores' speed changes while the engine runs, `--pool-affinity p-cores` is the steady choice. | | | `STRATA_KEEP_EMPTY_TURNS=1`, `STRATA_TOPK_STREAM=0` | | See [TROUBLESHOOTING.md](TROUBLESHOOTING.md). | | @@ -1078,7 +1078,7 @@ On 12.0 cards (sm_120) these also apply: prompt time and start-up time, which is why smaller PCs keep the SSD reads. A prompt chunk above 8192 (`--prefill auto:16384` or `auto:32768`) is not bit-exact on CUDA, so the default stays 8192 on -NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR=0.5` stays opt-in because it raises KL. +NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR` raises KL, so below 0.2.7 it was opt-in; 0.2.7 sets 2.0 by itself only on a discrete NVIDIA card of 13 GiB or less. --- diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 8c10493d..8166d70d 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -42,7 +42,8 @@ These need no engine change; they are settings. Each was measured on the same bo ## The 12 GB default: residency-biased routing -**On by default at 2.0 on a card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off). The router prefers +**On by default at 2.0 on a discrete NVIDIA card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off; +not a default on a Radeon, a Strix Halo or any integrated GPU, where it was not measured). The router prefers experts that are already resident, so a window stops waiting on a page-in that the next window would need again. Measured on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 6c7d1a1b..b9d4eede 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -204,6 +204,32 @@ inline int g_side_mixer() { return per_dev[dev] - 1; #endif } +// STRATA_ROUTE_PRIOR=lambda: residency-biased routing (the top-10 picked again with a logit bonus for the resident +// experts; route_prior.cu). Unset: 2.0 on a DISCRETE NVIDIA card of 13 GiB or less (CUDA builds only), 0 elsewhere. +// Measured on an RTX 3060 12 GB only (IQ3_XXS, 5 interleaved pairs: +37.6% / +35.2% decode); the owner approved the +// quality trade for 12 GB cards (it changes which experts run). Not a default in a HIP build (a 12 GB Radeon, or a +// Strix Halo whose reported VRAM is a small carve-out of unified memory: unmeasured there) and not on an integrated GPU. +// STRATA_ROUTE_PRIOR=0 turns it off, any other value wins everywhere. The default is read from the device properties +// (no allocation, no stream work), and Verifier::init asks once per card, so the first ask is never inside a graph capture. +inline float g_route_prior() { + static const char* const env_s = std::getenv("STRATA_ROUTE_PRIOR"); + static const float env = env_s ? (float) std::atof(env_s) : 0.0f; + if (env_s != nullptr) return env; +#if defined(STRATA_USE_HIP) || defined(STRATA_GPU_METAL) + return 0.0f; +#else + static float per_dev[64]; // 0 unknown, else prior + 1 + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0.0f; } + if (per_dev[dev] == 0.0f) { + cudaDeviceProp p; + const bool ok = cudaGetDeviceProperties(&p, dev) == cudaSuccess; + if (!ok) cudaGetLastError(); + per_dev[dev] = 1.0f + (ok && !p.integrated && (double) p.totalGlobalMem / 1073741824.0 <= 13.0 ? 2.0f : 0.0f); + } + return per_dev[dev] - 1.0f; +#endif +} inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; } #define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) @@ -703,6 +729,12 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& release_gpu_fn().store(&release_live_verifiers); cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there rr_stats_ = route_resident_cfg().stats_on(device_); // STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capture + { // once per card, here: record_window (graph capture) only reads the cached value + const float rp = g_route_prior(); + if (rp > 0.0f && std::getenv("STRATA_ROUTE_PRIOR") == nullptr) + std::fprintf(stderr, "strata verify: residency-biased routing is on by default on this card (STRATA_ROUTE_PRIOR=%.1f: a card of 13 GiB " + "or less; it changes which experts run; STRATA_ROUTE_PRIOR=0 turns it off)\n", (double) rp); + } strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there strata::kernels::fused_gr_persist_init(); // opt-in STRATA_HC_PERSIST=1 (HIP) wt_ = &wt; @@ -1966,23 +1998,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; } - // STRATA_ROUTE_PRIOR=lambda: the top-10 picked again with a logit bonus for the resident experts; the weights - // stay the router's (route_prior.cu). **On by default at 2.0 on a card of 13 GiB or less**, where the expert - // cache cannot hold the model: measured on an RTX 3060 12 GB (IQ3_XXS), 5 interleaved pairs, story 44.2 -> - // 60.9 tok/s (+37.6%) and code 47.3 -> 64.0 (+35.2%); at 1.0 it is +22.6% / +24.6%. The owner approved the - // quality trade for 12 GB cards (it changes which experts run). It is NOT a default where the cache holds - // the model: on an RTX PRO 5000 72 GB it measured -1.9% / -0.5% and on 2x RTX A4000 -4.2% / +11.0%, so - // STRATA_ROUTE_PRIOR=0 turns it off and any explicit value wins. - static const float route_prior = [] { - const char* v = std::getenv("STRATA_ROUTE_PRIOR"); - if (v != nullptr) return (float) std::atof(v); - int dev = 0; - if (cudaGetDevice(&dev) != cudaSuccess) return 0.0f; - size_t free_b = 0, total_b = 0; - if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) return 0.0f; - cudaGetLastError(); // drop what a query on a device without a context leaves behind - return (double) total_b / 1073741824.0 <= 13.0 ? 2.0f : 0.0f; - }(); + // STRATA_ROUTE_PRIOR=lambda (changes the output): the top-10 picked again with a logit bonus for the resident + // experts; the weights stay the router's (route_prior.cu). The default is g_route_prior() above: 2.0 on a + // discrete CUDA card of 13 GiB or less, off elsewhere (measured on an RTX 3060 12 GB: story +37.6%, code +35.2%; + // on an RTX PRO 5000 72 GB -1.9% / -0.5%, on 2x RTX A4000 -4.2% / +11.0%, hence not a default on bigger cards). + const float route_prior = g_route_prior(); if (route_prior > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) route_prior_top10(logits_ + tb * NE, hits_.d_res + l * g.n_expert, route_prior, ids_ + tb * K, w_ + tb * K, n, cs); if (route_resident_cfg().margin > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) { diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index a70b7abe..73a9089b 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -444,6 +444,11 @@ constexpr int UPW_BLOCKS = N / UPW_COLS; /// resident, 5 interleaved pairs of fresh engines): story 197.6 -> 201.3 tok/s (+1.9%), code 243.5 -> 245.1 (+0.7%), /// the produced token ids identical in 6/6 runs; the isolated read (fused_gr_bench) is bitwise the old kernel's. bool gr_up_wide_on() { +#if defined(__HIPCC__) + // A HIP build never takes it: gfx1200 / gfx1201 report compute capability 12.0 too, and sm120_default() would turn the + // CUDA-measured kernel on there (unmeasured on AMD). The persistent HC read is the HIP card's own opt-in. + return false; +#else static const int env = [] { const char* v = std::getenv("STRATA_GR_UP_WIDE"); return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; @@ -460,6 +465,7 @@ bool gr_up_wide_on() { cudaGetLastError(); // drop what an attribute query on a CPU-only box leaves behind } return per_dev[dev] == 2; +#endif } template From 24c3f24ae168bc4ff592112d38e0915eb0c0652e Mon Sep 17 00:00:00 2001 From: jackbapa <58503557+jackbapa@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:43 +0100 Subject: [PATCH 047/177] Tests: the ACL checks compare trustees through the SDDL alias, so an account that Windows writes as LA passes (PR #3406 by jackbapa) --- tests/terminal/test_private_files.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/terminal/test_private_files.py b/tests/terminal/test_private_files.py index 6da7d197..e6ce1b36 100644 --- a/tests/terminal/test_private_files.py +++ b/tests/terminal/test_private_files.py @@ -4,6 +4,7 @@ from __future__ import annotations import json import os +import re import stat import sys import tempfile @@ -15,6 +16,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from strata_control import private_files as pf # noqa: E402 +def resolved(sddl: str) -> str: + """``sddl`` with every trustee alias (``LA`` is the built-in Administrator) written as its string SID.""" + return re.sub(r";;;([^)]*)\)", lambda match: f";;;{pf._string_sid(match.group(1))})", sddl) + + class PrivateFileTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -39,7 +45,7 @@ class PrivateFileTests(unittest.TestCase): if pf.WINDOWS: # the child inherits the directory's single entry rather than the profile's sddl = pf.dacl_sddl(child) - self.assertIn(pf.current_user_sid(), sddl) + self.assertIn(pf.current_user_sid(), resolved(sddl)) self.assertNotIn("S-1-1-0", sddl) self.assertNotIn(";;;SY)", sddl) self.assertNotIn(";;;BA)", sddl) @@ -63,7 +69,7 @@ class PrivateFileTests(unittest.TestCase): self.assertFalse(pf.is_private(path), "a fresh file inherits SYSTEM/Administrators entries") pf.restrict_to_current_user(path) sddl = pf.dacl_sddl(path) - self.assertEqual(sddl, f"D:PAI(A;;FA;;;{pf.current_user_sid()})") + self.assertEqual(resolved(sddl), f"D:PAI(A;;FA;;;{pf.current_user_sid()})") # nobody else: no Everyone, Users, Authenticated Users, SYSTEM or Administrators for sid in ("WD", "BU", "AU", "SY", "BA", "S-1-1-0", "S-1-5-32-545"): self.assertNotIn(f";;;{sid})", sddl) @@ -126,7 +132,7 @@ class ElevatedRunLockoutTests(unittest.TestCase): with self.assertRaises(PermissionError): path.read_bytes() self.assertEqual(pf.read_bytes_repairing(path), b'{"name": "x"}') - self.assertIn(pf.current_user_sid(), pf.dacl_sddl(path)) + self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(path))) self.assertEqual(path.read_bytes(), b'{"name": "x"}') def test_a_locked_folder_and_what_is_inside_are_repaired_as_a_tree(self): @@ -146,14 +152,14 @@ class ElevatedRunLockoutTests(unittest.TestCase): self.assertEqual(report["failed"], 0) self.assertEqual((folder / "a.json").read_bytes(), b"{}") self.assertEqual((folder / "sub" / "b.json").read_bytes(), b"{}") - self.assertIn(pf.current_user_sid(), pf.dacl_sddl(folder / "sub" / "b.json")) + self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(folder / "sub" / "b.json"))) def test_a_folder_made_with_private_mkdir_names_the_user_explicitly(self): made = pf.private_mkdir(self.root / "x" / "y", parents=True) - self.assertIn(pf.current_user_sid(), pf.dacl_sddl(made)) - self.assertIn(pf.current_user_sid(), pf.dacl_sddl(made.parent)) + self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(made))) + self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(made.parent))) (made / "file.json").write_text("{}") - self.assertIn(pf.current_user_sid(), pf.dacl_sddl(made / "file.json")) + self.assertIn(pf.current_user_sid(), resolved(pf.dacl_sddl(made / "file.json"))) self.assertEqual((made / "file.json").read_text(), "{}") def test_the_process_defaults_can_be_set_for_the_user(self): From 9e2c0b6eb080816325626f7666833bff4ef5b643 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:19:55 +0100 Subject: [PATCH 048/177] docker: test that both Dockerfiles take the source commit and the source-build commands pass it (#3644) --- tests/terminal/test_docker_files.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index a51cee8a..3f2a5520 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -197,6 +197,18 @@ class Publishing(unittest.TestCase): for item in payload: self.assertTrue(any(item == p or item.startswith(p.rstrip("/") + "/") for p in listed), f"build.sh does not copy {item}") + def test_the_source_build_passes_the_commit_to_the_terminal_stage(self): + """.git is not in the build context (.dockerignore), so the root Dockerfile's terminal stage gets the commit as a build argument, the way + docker/Dockerfile does; without it package_terminal.py stops (#3644). The documented source-build commands pass it.""" + for dockerfile in (ROOT / "Dockerfile", DOCKER / "Dockerfile"): + text = dockerfile.read_text(encoding="utf-8") + self.assertRegex(text, r"(?m)^ARG STRATA_COMMIT=", dockerfile.name) + self.assertIn("ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT}", text, dockerfile.name) + self.assertIn(".git", (ROOT / ".dockerignore").read_text(encoding="utf-8").split()) + doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8") + self.assertEqual(doc.count("docker build -t strata:src"), doc.count("--build-arg STRATA_COMMIT=$(git rev-parse HEAD)")) + self.assertIn("/data/install/", (ROOT / ".dockerignore").read_text(encoding="utf-8")) + def test_workflow_is_manual_and_pushes_only_on_request(self): data = yaml.safe_load(self.WORKFLOW.read_text(encoding="utf-8")) triggers = data.get("on", data.get(True)) # YAML 1.1 reads a bare `on` as True From 19bfcb33f033476208084a609d0d59624d79d080 Mon Sep 17 00:00:00 2001 From: BColsey <5873142+BColsey@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:19:55 +0100 Subject: [PATCH 049/177] Tests: the Terminal fixtures write settings where the platform keeps them and no longer swap os.name or assume a Windows ACL on Linux (PR #3782 by BColsey) --- tests/terminal/test_discovery.py | 8 +++++--- tests/terminal/test_gfx_selection.py | 7 ++++++- tests/terminal/test_launch_tui.py | 2 +- tests/terminal/test_private_files.py | 9 +++++++++ tests/terminal/test_shared_models_folder.py | 2 +- 5 files changed, 22 insertions(+), 6 deletions(-) diff --git a/tests/terminal/test_discovery.py b/tests/terminal/test_discovery.py index 98cd13c3..05e0b318 100644 --- a/tests/terminal/test_discovery.py +++ b/tests/terminal/test_discovery.py @@ -65,6 +65,8 @@ class GuiLayout(unittest.TestCase): self.env = {"LOCALAPPDATA": str(base / "local"), "XDG_DATA_HOME": str(base / "local"), "APPDATA": str(base / "roaming"), "XDG_CONFIG_HOME": str(base / "config"), "USERPROFILE": str(base / "home"), "HOME": str(base / "home"), "XDG_STATE_HOME": str(base / "state"), "XDG_DOCUMENTS_DIR": ""} + settings = Path(self.env["APPDATA"]) / "Strata" if os.name == "nt" else Path(self.env["XDG_CONFIG_HOME"]) / "strata" + self.settings_path = settings / "settings.json" patch = mock.patch.dict(os.environ, self.env) patch.start() self.addCleanup(patch.stop) @@ -142,7 +144,7 @@ class GuiLayout(unittest.TestCase): old = self.base / "T-Strata" old.mkdir() (old / "strata-qwen-iq3_xxs.json").write_text(json.dumps({"exe": "e", "tokenizer": "t", "args": []})) - settings = Path(os.environ["APPDATA"]) / "Strata" / "settings.json" + settings = self.settings_path settings.parent.mkdir(parents=True) settings.write_text(json.dumps({"installs": [str(old)]})) got = models.list_installed() @@ -155,7 +157,7 @@ class GuiLayout(unittest.TestCase): (old / "strata-x.json").write_text(json.dumps({"exe": "e", "tokenizer": "t", "args": []})) app_settings = self.install.parent / "app-settings.json" with mock.patch.dict(os.environ, {"STRATA_SETTINGS_FILE": str(app_settings)}): - settings = Path(os.environ["APPDATA"]) / "Strata" / "settings.json" + settings = self.settings_path settings.parent.mkdir(parents=True) settings.write_text(json.dumps({"installs": [str(old)]})) self.assertEqual([m["id"] for m in models.list_installed()["models"]], ["gyro-gyro-s"]) @@ -258,7 +260,7 @@ class GuiLayout(unittest.TestCase): def test_an_own_setting_beats_the_apps_folder(self): mine = self.base / "mine" mine.mkdir() - settings = Path(os.environ["APPDATA"]) / "Strata" / "settings.json" + settings = self.settings_path settings.parent.mkdir(parents=True, exist_ok=True) settings.write_text(json.dumps({"data_dir": str(mine)})) self.assertEqual(self.catalog().data_dir().resolve(), mine.resolve()) diff --git a/tests/terminal/test_gfx_selection.py b/tests/terminal/test_gfx_selection.py index e02ef41f..b2e56ea9 100644 --- a/tests/terminal/test_gfx_selection.py +++ b/tests/terminal/test_gfx_selection.py @@ -3,6 +3,7 @@ build, 0.1.46.1) then won over the rx9070 one (0.1.46). Selection must follow th from __future__ import annotations import unittest +from types import SimpleNamespace from unittest import mock from strata_control import engine_component as ec, feed as feedmod, updater @@ -80,7 +81,11 @@ class Names(unittest.TestCase): class Detection(unittest.TestCase): def test_windows_without_hipinfo_reads_the_gfx_from_the_adapters(self): adapters = [{"vendor": "1002", "device": 0x7550, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0}] - with mock.patch.object(updater.os, "name", "nt"), mock.patch.object(updater.shutil, "which", return_value=None), \ + # Keep pathlib on the host platform while both hardware probes model Windows. + windows = SimpleNamespace(name="nt") + with mock.patch.object(updater, "os", windows), mock.patch.object(ec, "os", windows), \ + mock.patch.object(updater, "Path", return_value=SimpleNamespace(is_dir=lambda: False)), \ + mock.patch.object(updater.shutil, "which", return_value=None), \ mock.patch.object(ec, "windows_display_adapters", return_value=adapters): self.assertEqual(updater._gfx_names(), ["gfx1201"]) self.assertEqual(updater._amd_card_names(), ["AMD Radeon RX 9070 XT"]) diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index dff55798..4aaf5eb7 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -699,7 +699,7 @@ class AccessStep(Base): await press(pilot, *self.reach(), "down", "down") t = text_of(app) self.assertIn("cloudflared is not installed on this computer", t) - self.assertIn("quick tunnel", t) + self.assertIn("quick tunnel", flat(app)) await press(pilot, "enter") self.assertEqual(ctx.settings.access, "cloudflare") self.assertIn("Save as preset, then launch", text_of(app)) diff --git a/tests/terminal/test_private_files.py b/tests/terminal/test_private_files.py index e6ce1b36..adfc64b3 100644 --- a/tests/terminal/test_private_files.py +++ b/tests/terminal/test_private_files.py @@ -77,9 +77,18 @@ class PrivateFileTests(unittest.TestCase): def test_a_file_made_in_the_profile_is_unshared_but_not_strictly_private(self): path = self.root / "inherited.json" path.write_text("{}") + if not pf.WINDOWS: + # POSIX files have mode bits rather than an inherited profile ACL. + # Specify the private mode instead of depending on the process umask. + path.chmod(0o600) self.assertTrue(pf.is_unshared(path)) if pf.WINDOWS: self.assertFalse(pf.is_private(path)) # SYSTEM and Administrators still inherit + else: + self.assertTrue(pf.is_private(path)) + path.chmod(0o644) + self.assertFalse(pf.is_unshared(path)) + self.assertFalse(pf.is_private(path)) @unittest.skipUnless(pf.WINDOWS, "NTFS ACLs") def test_everyone_is_noticed_by_the_relaxed_check_too(self): diff --git a/tests/terminal/test_shared_models_folder.py b/tests/terminal/test_shared_models_folder.py index 069c019f..c6357619 100644 --- a/tests/terminal/test_shared_models_folder.py +++ b/tests/terminal/test_shared_models_folder.py @@ -13,7 +13,7 @@ from tests.terminal.test_discovery import GuiLayout class SharedModelsFolder(GuiLayout): def files(self): - mine = Path(os.environ["APPDATA"]) / "Strata" / "settings.json" + mine = self.settings_path mine.parent.mkdir(parents=True, exist_ok=True) return mine, discovery.app_settings_file() From d2c69e6d4b19069084d760462047a505c953273d Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:17 +0100 Subject: [PATCH 050/177] tools/strata_bench.py: read CMakeLists.txt as UTF-8, not with the locale's code page (#4011, #2792) Ported from PR #4011 by SuperDistance. project_version() read CMakeLists.txt with Path.read_text() and no encoding, which raised UnicodeDecodeError on Windows code pages such as cp936. The test makes read_text default to each of 14 Windows code pages. The same crash was reported in #3235 and #3414. --- tools/strata_bench.py | 3 ++- tools/test_strata_bench.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 93d92ee1..0bb0711d 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -563,7 +563,8 @@ def detect_quant(view: dict) -> str | None: def project_version() -> str | None: try: - m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text()) + # UTF-8 as setup.py reads it, whatever the locale's code page (#2792) + m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")) return m.group(1) if m else None except OSError: return None diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 30d3978b..986ab1a3 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -339,6 +339,24 @@ class ReportTests(unittest.TestCase): def test_no_server_is_an_error_not_a_crash(self): self.assertEqual(B.main(["--url", "http://127.0.0.1:9", "--quiet"]), 2) + def test_project_version_does_not_use_the_locale_code_page(self): + # #2792: on Windows a text file read without an encoding is decoded with the locale's code page, and CMakeLists.txt + # is UTF-8 with non-ASCII text. Path.read_text here defaults to each Windows ANSI code page in turn. + original = Path.read_text + with tempfile.TemporaryDirectory() as d: + root = Path(d) + (root / "CMakeLists.txt").write_bytes( + "cmake_minimum_required(VERSION 3.24)\n# notes — § €\nproject(strata VERSION 9.8.7 LANGUAGES CXX)\n" + .encode("utf-8")) + for code_page in ("cp874", "cp932", "cp936", "cp949", "cp950", "cp1250", "cp1251", "cp1252", "cp1253", + "cp1254", "cp1255", "cp1256", "cp1257", "cp1258"): + def locale_default(self, encoding=None, errors=None, **kw): + return original(self, encoding=encoding or code_page, errors=errors, **kw) + + with self.subTest(code_page=code_page), mock.patch.object(B, "ROOT", root), \ + mock.patch.object(Path, "read_text", locale_default): + self.assertEqual(B.project_version(), "9.8.7") + if __name__ == "__main__": unittest.main() From c7833932a1a3515bb6e4f4c27255f4bb90a53fc4 Mon Sep 17 00:00:00 2001 From: zapabob <130830376+zapabob@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:17 +0100 Subject: [PATCH 051/177] App: a model load validates and parses the same captured text of its settings file, so a file changed between two reads cannot start with unchecked settings (PR #3954 by zapabob) --- apps/host/server/native-control.mjs | 6 +-- apps/host/server/run-config-check.mjs | 8 ++++ apps/host/tests/native-settings-file.test.mjs | 45 +++++++++++++++++++ apps/host/tests/run-config-check.test.mjs | 16 ++++++- 4 files changed, 71 insertions(+), 4 deletions(-) diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 362304b8..895ec054 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -18,7 +18,7 @@ import { createEngineStep } from './engine-step.mjs'; import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder, syncDataFolder, terminalSettingsFile } from './model-folder.mjs'; import { createAutoTune, writeTuneConfig } from './native-autotune.mjs'; import { plainError, PHASE_TEXT } from './update-messages.mjs'; -import { checkRunConfig, describeIssues } from './run-config-check.mjs'; +import { checkAndParseRunConfig, checkRunConfig, describeIssues } from './run-config-check.mjs'; import { openTextFile } from './open-text-file.mjs'; import { markEngine, engineRefusal } from './engine-version.mjs'; import { friendlyModelName } from './model-names.mjs'; @@ -150,7 +150,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function settingsFile(model){const {path}=recordFile(model);return {model,path,name:basename(path),...checkRunConfig(readFileSync(path,'utf8')),note:'Changes you make in the file apply the next time the model starts.'};} async function openSettingsFile(model,options={}){const info=settingsFile(model);await openTextFile(info.path,options);return info;} /* A mistake in the file holds the start back with the line, instead of an engine that dies on it. Warnings (an unknown key) never do. */ - function assertSettingsFile(path){const check=checkRunConfig(readFileSync(path,'utf8'));if(!check.ok)throw new Error(`The settings file for this model has a mistake, so the model was not started. ${describeIssues(check.issues,'error').join(' ')}`);} + function checkedSettingsConfig(text){const check=checkAndParseRunConfig(text);if(!check.ok)throw new Error(`The settings file for this model has a mistake, so the model was not started. ${describeIssues(check.issues,'error').join(' ')}`);return check.config;} function settings(model){const {entry,config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true,capabilities:{dsExperts:ownEngine(config)&&dsExpertsSupported(config)},speedSwitches:speedSwitchRows(config.env??{},{deepseek:ownEngine(config),arch:config.arch??null,backend:config.backend??entry?.backend??snapshot.installed?.engine?.backend??null,gpus:snapshot.hardware?.gpus??[]})};} function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};if(patch.ds_experts!=null&&!dsExpertsSupported(config))throw new Error('The Speed choice needs the newer DeepSeek engine. Update the engine in Settings, then choose it.');for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if('vram_reserve_mib' in patch){const base=captureUserArgs(next);const mine=setUserFlag(base,'--vram-reserve-mib',patch.vram_reserve_mib);if(mine.length)next[USER_KEY]=mine;else delete next[USER_KEY];next.args=mine.length&&patch.vram_reserve_mib!==null?mergeUserArgs(next.args??[],mine):setUserFlag(next.args??[],'--vram-reserve-mib',null);delete next.ui_reserve_applied;if(Array.isArray(next.args_written))next.args_written=[...next.args];}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} @@ -276,7 +276,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} /* Which drafter runs, when it is not the one that was asked for (the engine's own words, "Drafting: MTP (DFlash2 didn't fit)"): under Details of the load. */ async function noteDrafting(job,instance,key){let note='';try{const r=await fetcher(`http://127.0.0.1:${instance.port}/metrics`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(r.ok)note=String((await r.json())?.engine?.drafting_note??'');}catch{/* a convenience */}const lines=[job.drafterNote,note].filter(Boolean);if(lines.length)job.details=[job.details,...lines].filter(Boolean).join('\n');} async function loadEngine(job,args){ - await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));}if(!entry.ready){const error=missingFilesError(args.model,entry.missing);append(args.model,error.details[0]);throw error;} + await refresh(true);if(job.state!=='running')return;const {entry,path:configFile}=recordFile(args.model);const config=checkedSettingsConfig(readFileSync(configFile,'utf8'));if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));}if(!entry.ready){const error=missingFilesError(args.model,entry.missing);append(args.model,error.details[0]);throw error;} if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); const {cfg,resources,visionPreferences,parallelChoice,parallelNote:chosenNote}=buildConfig(args,config); diff --git a/apps/host/server/run-config-check.mjs b/apps/host/server/run-config-check.mjs index fc8956a8..12ca8b84 100644 --- a/apps/host/server/run-config-check.mjs +++ b/apps/host/server/run-config-check.mjs @@ -134,6 +134,14 @@ export function checkRunConfig(text, { known = KNOWN_KEYS } = {}) { return { ok: !issues.some(i => i.level === 'error'), issues }; } +/** Validate and parse one captured text value, so callers use the checked snapshot. */ +export function checkAndParseRunConfig(text, options) { + text = String(text ?? ''); + const checked = checkRunConfig(text, options); + if (!checked.ok) return { ...checked, config: null }; + return { ...checked, config: JSON.parse(text.replace(/^\uFEFF/, '')) }; +} + /** The English lines of the issues, `Line 12: …`, for the Details of a refused start. */ export function describeIssues(issues, level) { return issues.filter(i => !level || i.level === level).map(i => `${i.line ? `Line ${i.line}: ` : ''}${i.message}`); diff --git a/apps/host/tests/native-settings-file.test.mjs b/apps/host/tests/native-settings-file.test.mjs index 055110b2..e12cc9db 100644 --- a/apps/host/tests/native-settings-file.test.mjs +++ b/apps/host/tests/native-settings-file.test.mjs @@ -1,11 +1,56 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync, writeFileSync } from 'node:fs'; +import fs from 'node:fs'; +import { syncBuiltinESMExports } from 'node:module'; import { join } from 'node:path'; import { nativeFixture, finishJob } from './helpers/native-fixture.mjs'; const configOf = f => join(f.repo, 'strata-iq2_xs.json'); +for (const validFirst of [true, false]) test(`a load ${validFirst ? 'uses a valid' : 'refuses an invalid'} captured config even if the file changes after reading`, async t => { + const f = nativeFixture(); + try { + await f.control.refresh(true); + const path = configOf(f), good = JSON.parse(readFileSync(path, 'utf8')); + good.parallel = 2; + const valid = '\uFEFF' + JSON.stringify(good), invalid = JSON.stringify({ ...good, parallel: 99 }); + writeFileSync(path, validFirst ? valid : invalid); + // Let status discovery finish normally. Replace the real file immediately after + // the first read following the model-path check, before a second read can occur. + const realpath = fs.realpathSync, read = fs.readFileSync; + let capture = false; + t.mock.method(fs, 'realpathSync', (...args) => { + const result = realpath(...args); + if (args[0] === path) capture = true; + return result; + }); + t.mock.method(fs, 'readFileSync', (...args) => { + const result = read(...args); + if (capture && args[0] === path) { + capture = false; + writeFileSync(path, validFirst ? invalid : valid); + } + return result; + }); + syncBuiltinESMExports(); + const done = await finishJob(f.control, f.control.operation('load', { model: 'iq2_xs' }).id); + assert.equal(done.state, validFirst ? 'done' : 'error', done.error); + if (validFirst) { + const instance = f.control.resolveInstance(done.result.instanceId); + assert.equal(JSON.parse(read(instance.configPath, 'utf8')).parallel, 2); + } else { + assert.match(done.error, /"parallel" must be a whole number/); + assert.equal(f.control.state().instances.length, 0); + assert.equal(f.calls.some(c => c.args.some(a => /serve[/\\]server\.py$/.test(String(a)))), false); + } + } finally { + t.mock.restoreAll(); + syncBuiltinESMExports(); + await f.cleanup(); + } +}); + test('the settings file is found, checked, and opened in the text editor', async () => { const f = nativeFixture(); try { diff --git a/apps/host/tests/run-config-check.test.mjs b/apps/host/tests/run-config-check.test.mjs index 5cd00c80..a3fbe0c0 100644 --- a/apps/host/tests/run-config-check.test.mjs +++ b/apps/host/tests/run-config-check.test.mjs @@ -2,7 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { build } from 'esbuild'; -import { KNOWN_KEYS, checkRunConfig, describeIssues, nearestKey } from '../server/run-config-check.mjs'; +import { KNOWN_KEYS, checkAndParseRunConfig, checkRunConfig, describeIssues, nearestKey } from '../server/run-config-check.mjs'; import { NATIVE_FIELDS } from '../server/native-settings.mjs'; import { openTextFile, textEditorCommand } from '../server/open-text-file.mjs'; @@ -23,6 +23,20 @@ test('a normal run config has no issues', () => { assert.deepEqual(checkRunConfig('\uFEFF{}'), { ok: true, issues: [] }, 'Notepad’s byte-order mark is fine'); }); +test('the checked configuration is parsed from the same captured text', () => { + const text = '\uFEFF{"parallel":2,"args":["--ple-io","mmap"]}'; + const checked = checkAndParseRunConfig(text); + assert.deepEqual(checked, { + ok: true, + issues: [], + config: { parallel: 2, args: ['--ple-io', 'mmap'] }, + }); + const refused = checkAndParseRunConfig('{"parallel":99}'); + assert.equal(refused.ok, false); + assert.equal(refused.config, null); + assert.equal(refused.issues[0].code, 'whole-range'); +}); + test('every key the app edits is a known key', () => { for (const field of NATIVE_FIELDS) assert.ok(KNOWN_KEYS.has(field.id), field.id); }); From 14bef6bb4647ca409cf75851ddf2bde07e810ab5 Mon Sep 17 00:00:00 2001 From: jubeater <11894816+jubeater@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:42 +0100 Subject: [PATCH 052/177] setup: hand component engines to the server for validation (#4027, #4026) _start() checked cfg['exe'] with Path.exists(), so a run config whose engine is component:strata-engine was refused as a missing file before the server could resolve and verify it. Ported from PR #4027 by jubeater. A component reference is no longer tested as a file; model files and literal engine paths are checked as before. ensure_engine_for, the Windows HIP runtime repair and the HIP architecture lookup skip the source-build engine folder for a component. Eight tests (tools/test_setup_component_start.py). --- setup.py | 12 +++- tools/test_setup_component_start.py | 98 +++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 tools/test_setup_component_start.py diff --git a/setup.py b/setup.py index 55f8941f..0213d6c4 100644 --- a/setup.py +++ b/setup.py @@ -69,6 +69,7 @@ tls.install() # #3722: HTTPS checks the server against the operating system from strata_control import atomic from strata_control import draft_layer from strata_control import dsv41_context +from strata_control import engine_component from strata_control.discovery import in_trash from strata_control import user_args @@ -6851,7 +6852,10 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab, --vram-reserve-mib).""" cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) - missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] + component = engine_component.is_reference(cfg["exe"]) + # The server resolves and verifies component engines; the reference itself is not a file. + files = ([] if component else [cfg["exe"]]) + [a for a in cfg["args"] if a.endswith(".gguf")] + missing = [p for p in files if not Path(p).exists()] if missing: fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") keep = {k: v for k, v in (keep or {}).items() if v is not None} @@ -6879,12 +6883,12 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port or cfg.get("port", 8080))] if cfg.get("backend") == "hip": # AMD, numbered as HIP numbers them (setup's KFD order) - if WIN: + if WIN and not component: hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461: also fixes a 0.1.34 install amd = amd_gpus() if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd) - built = (engine_archs_hip() or []) + built = [] if component else (engine_archs_hip() or []) miss = [x for x in cards if built and x["arch"] not in built] if miss: fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), @@ -7297,6 +7301,8 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a card gets the engine compiled for all of them, before the start. A Pascal / Volta card added to a model on the CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it).""" + if engine_component.is_reference(cfg.get("exe")): + return cfg # the server checks the installed component, not ROOT/engine tk = config_toolkit(cfg) if tk == 13 and any(int(g["arch"]) < CUDA13_MIN_ARCH for g in cards): return use_cuda12(cards, cfg_path, cfg, yes) diff --git a/tools/test_setup_component_start.py b/tools/test_setup_component_start.py new file mode 100644 index 00000000..e9104db2 --- /dev/null +++ b/tools/test_setup_component_start.py @@ -0,0 +1,98 @@ +"""Setup can start a component-backed config without treating the reference as a file. + + python -m unittest tools.test_setup_component_start -v +""" +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import setup + + +class ComponentStart(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.config = self.root / "strata-iq3_s.json" + self.gguf = self.root / "model.gguf" + self.gguf.write_bytes(b"GGUF") + self.cards = [{"index": i, "name": f"RTX {i}", "arch": "89", "vram_gb": 24.0} for i in range(2)] + + def run_start(self, exe="component:strata-engine", backend="cuda", gpu=0, win=False, keep=None): + cfg = {"exe": exe, "backend": backend, "args": ["--native", str(self.gguf)], + "gpu": gpu, "gpus_asked": True, "model_name": "test", "port": 8080} + self.config.write_text(json.dumps(cfg), encoding="utf-8") + self.output = io.StringIO() + with contextlib.ExitStack() as st: + st.enter_context(contextlib.redirect_stdout(self.output)) + st.enter_context(mock.patch.object(setup, "WIN", win)) + st.enter_context(mock.patch.dict(os.environ, {"STRATA_EXECV": ""})) + st.enter_context(mock.patch.object(setup, "gpus", return_value=self.cards)) + st.enter_context(mock.patch.object(setup, "amd_gpus", return_value=[ + {"index": i, "name": f"Radeon {i}", "arch": "gfx1201", "vram_gb": 24.0} for i in range(2)])) + st.enter_context(mock.patch.object(setup, "check_gpus")) + st.enter_context(mock.patch.object(setup, "split_budget", return_value=False)) + st.enter_context(mock.patch.object(setup, "split_mmap", return_value=False)) + st.enter_context(mock.patch.object(setup, "recommend_remote_expert_opt")) + st.enter_context(mock.patch.object(setup, "old_gpus_opt_in", return_value=[])) + for name in ("engine_runs_on", "engine_archs_hip", "hip_runtime_beside_exe"): + st.enter_context(mock.patch.object(setup, name, side_effect=AssertionError("legacy engine lookup: " + name))) + self.server = st.enter_context(mock.patch.object(setup.subprocess, "call", return_value=0)) + return setup.start(self.config, None, gpu=gpu, open_browser=False, yes=True, keep=keep) + + def test_component_reaches_the_server_and_keeps_its_reference(self): + self.assertEqual(self.run_start(), 0) + self.server.assert_called_once() + argv = self.server.call_args.args[0] + self.assertIn(str(setup.ROOT / "serve" / "server.py"), argv) + self.assertEqual(argv[argv.index("--config") + 1], str(self.config)) + self.assertEqual(self.server.call_args.kwargs["env"][setup.acquisition.ENV], "1") + self.assertEqual(json.loads(self.config.read_text())["exe"], "component:strata-engine") + + def test_component_uses_saved_gpu_without_looking_for_a_source_build(self): + self.assertEqual(self.run_start(gpu=None), 0) + self.server.assert_called_once() + + def test_component_can_save_several_gpus_without_looking_for_a_source_build(self): + self.assertEqual(self.run_start(gpu=[0, 1]), 0) + self.assertEqual(json.loads(self.config.read_text())["gpu"], [0, 1]) + + def test_windows_hip_component_does_not_repair_the_legacy_engine_folder(self): + self.assertEqual(self.run_start(backend="hip", win=True), 0) + self.server.assert_called_once() + + def test_hip_component_does_not_read_source_build_architectures(self): + self.assertEqual(self.run_start(backend="hip", gpu=[0, 1]), 0) + self.server.assert_called_once() + + def test_missing_model_file_is_still_reported(self): + self.gguf.unlink() + with self.assertRaises(SystemExit): + self.run_start() + self.assertIn(str(self.gguf), self.output.getvalue()) + self.server.assert_not_called() + + def test_missing_literal_engine_path_is_still_reported(self): + missing = str(self.root / "strata") + with self.assertRaises(SystemExit): + self.run_start(exe=missing) + self.assertIn(missing, self.output.getvalue()) + self.server.assert_not_called() + + def test_component_reference_survives_saving_start_settings(self): + self.assertEqual(self.run_start(keep={"host": "127.0.0.1", "vram_reserve_mib": 1024}), 0) + saved = json.loads(self.config.read_text()) + self.assertEqual(saved["exe"], "component:strata-engine") + self.assertEqual(saved["args"][-2:], ["--vram-reserve-mib", "1024"]) + + +if __name__ == "__main__": + unittest.main() From f4999223795d1b307ae948073e81363a3b305c2d Mon Sep 17 00:00:00 2001 From: medking82 <19301787+medking82@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:52 +0100 Subject: [PATCH 053/177] App: the composer's effort (Off, Low, Medium, High, Max) reaches saved API models that support reasoning, with the OpenRouter mapping; unknown support keeps the provider default (PR #3363 by medking82) --- apps/host/server/index.mjs | 9 +- apps/host/server/model-providers.mjs | 11 ++- apps/host/tests/api-reasoning-effort.test.mjs | 96 +++++++++++++++++++ apps/host/tests/mock-model-api.mjs | 3 +- 4 files changed, 112 insertions(+), 7 deletions(-) create mode 100644 apps/host/tests/api-reasoning-effort.test.mjs diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index b9640e1d..d28418c8 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -115,7 +115,7 @@ const WORKSPACE_NAME = process.env.STRATA_WORKSPACE ? basename(WORKSPACE) : 'Str const insideApp = path => { const rel = relative(ROOT, resolve(path)); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); }; const hub = new EventHub(); -const modelProviders = createModelProviders({ directory: store.DATA_DIR, changed: value => hub.send('providers', withPictureAnswers(value)) }); +const modelProviders = createModelProviders({ directory: store.DATA_DIR, knownThinks: (connection, modelId) => visionProbe.knownThinks(connection, modelId), changed: value => hub.send('providers', withPictureAnswers(value)) }); const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () => store.MODELS_DIR, real: models.REAL, changed: value => hub.send('image-models', value) }); /* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */ const CONTROL = findControl(); @@ -558,17 +558,18 @@ function clientName(req) { return 'Local client'; } -async function runRemoteTurn({ selection, message, history, images = [], onFrame, signal, workspaceId }) { +async function runRemoteTurn({ selection, message, history, images = [], thinking, onFrame, signal, workspaceId }) { const controller = new AbortController(); const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal; let entry; const started = Date.now(); try { const { connection, model } = modelProviders.resolve(selection); + if (connection.protocol === 'openai-chat' && model.reasoning == null) await visionProbe.check(connection, model.id); const appliedSkills = selectSkills(skillState, message, workspaceId); entry = serving.open({ client: 'Strata chat', endpoint: connection.protocol === 'anthropic' ? '/messages' : connection.protocol === 'openai-responses' ? '/responses' : '/chat/completions', model: `${connection.name} · ${model.name}`, cancel: () => controller.abort(new DOMException('Cancelled by the user', 'AbortError')) }); serving.mark(entry.id, { state: 'generating' }); - const result = await modelProviders.stream({ selection, message, history, images, signal: requestSignal, systemPrompt: ['You are Strata, a helpful assistant. Answer clearly. Do not claim to have read files or performed actions unless their results are included in the conversation.', skillInstructions(appliedSkills)].filter(Boolean).join('\n\n'), onFrame: frame => { + const result = await modelProviders.stream({ selection, message, history, images, thinking, signal: requestSignal, systemPrompt: ['You are Strata, a helpful assistant. Answer clearly. Do not claim to have read files or performed actions unless their results are included in the conversation.', skillInstructions(appliedSkills)].filter(Boolean).join('\n\n'), onFrame: frame => { if (frame.type === 'start') noteSkillUse(appliedSkills); if (frame.type === 'done') serving.mark(entry.id, { tokensIn: frame.tokensIn, tokensOut: frame.tokensOut, usageSource: frame.usageSource }); onFrame({ ...frame, requestId: entry.id, model: model.name, contextMax: model.contextMax, remoteModel: true, ...(frame.type === 'start' ? { skills: appliedSkills.map(s => s.name) } : {}) }); @@ -631,7 +632,7 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI } async function runTurn({ message, history = [], onFrame, signal, client, workspaceId = null, sessionId = null, remoteModel = null, runtimeModelId = undefined, nativeModelId, images=[], useTools=false, thinking='medium', thinkingBudget=0 }) { - if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, images, onFrame, signal, workspaceId }); + if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, images, thinking, onFrame, signal, workspaceId }); if(native.hasLive()||nativeModelId){ let instance;try{instance=native.resolveInstance(nativeModelId??native.state().defaultId);}catch(e){const message=plainNoModel(e.message);onFrame({type:'error',message});return {error:message};}const started=Date.now(),cancel=new AbortController(); const entry=serving.open({client:client??'Strata chat',endpoint:'/chat/completions',model:instance.apiModelId,instanceId:instance.id,gpuIds:instance.gpus.map(String),cancel:()=>cancel.abort()}); diff --git a/apps/host/server/model-providers.mjs b/apps/host/server/model-providers.mjs index 30fa6fbd..3c6bf33e 100644 --- a/apps/host/server/model-providers.mjs +++ b/apps/host/server/model-providers.mjs @@ -1,5 +1,6 @@ /** Saved API connections. Secrets never leave the host's private credentials file. */ import { modelReadsPictures, modelSupportsReasoning } from './vision-probe.mjs'; +import { isOpenRouter, OPENROUTER_EFFORTS } from './agent/profile.mjs'; import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; @@ -49,7 +50,7 @@ export function normalizeBaseUrl(value) { const publicConnection = ({ apiKey, ...connection }) => ({ ...connection, apiKeySet: !!apiKey }); const numeric = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null; -export function createModelProviders({ directory, changed = () => {}, fetchImpl = fetch }) { +export function createModelProviders({ directory, changed = () => {}, fetchImpl = fetch, knownThinks = () => null }) { mkdirSync(directory, { recursive: true }); const file = join(directory, 'model-providers.json'); let connections = []; @@ -142,7 +143,7 @@ export function createModelProviders({ directory, changed = () => {}, fetchImpl const models = [...new Map(rows.filter(m => text(m.id, 256)).map(m => [m.id, { id: text(m.id, 256), name: text(m.display_name ?? m.name) || text(m.id, 256), contextMax: numeric(m.context_length ?? m.max_context_length ?? m.context_window), maxOutput: numeric(m.max_output_tokens ?? m.max_completion_tokens ?? m.top_provider?.max_completion_tokens), vision: modelReadsPictures(m), reasoning: modelSupportsReasoning(m) }])).values()]; return { models: models.sort((a, b) => a.name.localeCompare(b.name)) }; } - async function stream({ selection, message, history = [], systemPrompt = '', images = [], signal, onFrame }) { + async function stream({ selection, message, history = [], systemPrompt = '', images = [], thinking, signal, onFrame }) { const { connection, model } = resolve(selection); const started = Date.now(); const messages = history.filter(m => ['user', 'assistant'].includes(m.role) && typeof m.content === 'string').slice(-40).map(m => ({ role: m.role, content: m.content })); @@ -155,6 +156,12 @@ export function createModelProviders({ directory, changed = () => {}, fetchImpl : protocol === 'openai-responses' ? { model: model.id, input: messages, instructions: systemPrompt, stream: true, store: false } : { model: model.id, messages: [...(systemPrompt ? [{ role: 'system', content: systemPrompt }] : []), ...messages], stream: true, ...(['openai', 'deepseek', 'openrouter', 'google', 'moonshotai'].includes(connection.provider) ? { stream_options: { include_usage: true } } : {}) }; + // Match the native composer's effort names. Unknown support and other protocols keep provider defaults. + const choice = typeof thinking === 'string' ? thinking.toLowerCase() : ''; + if (protocol === 'openai-chat' && (model.reasoning ?? knownThinks(connection, model.id)) === true && ['off', 'low', 'medium', 'high', 'max'].includes(choice)) { + if (isOpenRouter(connection)) payload.reasoning = { effort: OPENROUTER_EFFORTS[choice] }; + else payload.reasoning_effort = ({ off: 'none', max: 'high' })[choice] ?? choice; + } const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(10 * 60 * 1000)]) : AbortSignal.timeout(10 * 60 * 1000); const res = await request(connection, protocol === 'anthropic' ? 'messages' : protocol === 'openai-responses' ? 'responses' : 'chat/completions', { method: 'POST', body: JSON.stringify(payload), signal: requestSignal }); if (!res.body) fail('The model API returned an empty response.'); diff --git a/apps/host/tests/api-reasoning-effort.test.mjs b/apps/host/tests/api-reasoning-effort.test.mjs new file mode 100644 index 00000000..6fda28ed --- /dev/null +++ b/apps/host/tests/api-reasoning-effort.test.mjs @@ -0,0 +1,96 @@ +/** Behavioral checks use only disposable files and a loopback mock API. */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {spawn} from 'node:child_process'; +import {once} from 'node:events'; +import {createServer} from 'node:net'; +import {createModelProviders} from '../server/model-providers.mjs'; +import {createMockModelApi} from './mock-model-api.mjs'; +import {createVisionProbe} from '../server/vision-probe.mjs'; +import {ROOMY_HOST} from './helpers/hardware.mjs'; +const choices={Off:'none',Low:'low',Medium:'medium',High:'high',Max:'high'}; +const history=[{role:'user',content:'Earlier question'},{role:'assistant',content:'Earlier answer'}]; +async function fixture(t,options={}){ + const mock=await createMockModelApi(),directory=mkdtempSync(join(tmpdir(),'strata-api-effort-')); + t.after(async()=>{await mock.close();rmSync(directory,{recursive:true,force:true});}); + const probe=createVisionProbe(),service=createModelProviders({directory,knownThinks:(c,id)=>probe.knownThinks(c,id)}); + const connection=service.save({kind:'custom',name:'Fixture',baseUrl:mock.baseUrl,protocol:'openai-chat',apiKey:'fixture-key',models:[{id:'mock-reasoning',reasoning:true}],...options}).connections[0]; + return {mock,service,connection,probe,selection:{connectionId:connection.id,modelId:connection.models[0].id}}; +} +test('saved reasoning models receive all official composer choices with the remaining request unchanged',async t=>{ + const f=await fixture(t); + for(const [thinking,effort] of Object.entries(choices)){ + const frames=[];await f.service.stream({selection:f.selection,message:'Next question',history,systemPrompt:'Fixture instructions',thinking,thinkingBudget:1234,onFrame:f=>frames.push(f)}); + const request=f.mock.requests.at(-1); + assert.equal(request.path,'/v1/chat/completions');assert.equal(request.headers.authorization,'Bearer fixture-key'); + assert.deepEqual(request.body,{model:'mock-reasoning',messages:[{role:'system',content:'Fixture instructions'},...history,{role:'user',content:'Next question'}],stream:true,reasoning_effort:effort}); + assert.equal(frames.at(-1).type,'done'); + } +}); +test('invalid or omitted efforts keep the provider default',async t=>{ + const f=await fixture(t); + for(const thinking of [undefined,null,false,1,{},'','Default','Provider Default','ultra','none','__proto__']){ + await f.service.stream({selection:f.selection,message:'Test',thinking,onFrame:()=>{}}); + assert.equal(Object.hasOwn(f.mock.requests.at(-1).body,'reasoning_effort'),false); + } +}); + +test('direct OpenRouter chat uses the same effort format and Max mapping as agent chat',async t=>{ + const f=await fixture(t,{kind:'provider',provider:'openrouter'}); + for(const [thinking,effort] of Object.entries({...choices,Max:'xhigh'})){ + await f.service.stream({selection:f.selection,message:'Test',thinking,onFrame:()=>{}}); + const payload=f.mock.requests.at(-1).body; + assert.deepEqual(payload.reasoning,{effort}); + assert.equal(Object.hasOwn(payload,'reasoning_effort'),false); + } +}); +test('saved false and unknown support cannot be overridden by request capability fields',async t=>{ + for(const reasoning of [false,null]){ + const f=await fixture(t,{models:[{id:'mock-chat',reasoning}]}); + await f.service.stream({selection:{...f.selection,reasoning:true,thinks:true},message:'Test',thinking:'High',reasoning:true,thinks:true,onFrame:()=>{}}); + assert.equal(Object.hasOwn(f.mock.requests.at(-1).body,'reasoning_effort'),false); + } +}); +test('host-owned probe support is used only when the saved answer is unknown',async t=>{ + for(const reasoning of [null,false]){ + const f=await fixture(t,{models:[{id:'mock-reasoning',reasoning}]}); + await f.probe.check(f.service.resolve(f.selection).connection,'mock-reasoning');assert.equal(f.probe.knownThinks(f.connection,'mock-reasoning'),true); + await f.service.stream({selection:f.selection,message:'Test',thinking:'Low',onFrame:()=>{}}); + assert.equal(f.mock.requests.at(-1).body.reasoning_effort,reasoning===false?undefined:'low'); + } +}); +test('Responses and Anthropic retain their existing payloads even for reasoning models',async t=>{ + for(const protocol of ['openai-responses','anthropic']){ + const f=await fixture(t,{protocol});await f.service.stream({selection:f.selection,message:'Test',onFrame:()=>{}});const before=f.mock.requests.at(-1).body; + await f.service.stream({selection:f.selection,message:'Test',thinking:'Max',thinkingBudget:1234,onFrame:()=>{}});assert.deepEqual(f.mock.requests.at(-1).body,before); + } +}); +async function freePort(){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;} +test('host forwards incoming composer choices using saved and probed support without trusting client capabilities',{timeout:30000},async t=>{ + const mock=await createMockModelApi(),home=mkdtempSync(join(tmpdir(),'strata-api-effort-host-')); + let child,exited; + t.after(async()=>{if(child&&child.exitCode===null){child.kill();await exited;}await mock.close();rmSync(home,{recursive:true,force:true,maxRetries:3});}); + mkdirSync(join(home,'data'));writeFileSync(join(home,'spy.log'),''); + // No picker/discovery call precedes the first chat: this also exercises cold probe routing. + const models=[{id:'mock-chat',reasoning:true},{id:'mock-reasoning',reasoning:null},{id:'plain',reasoning:false},{id:'unknown',reasoning:null}]; + writeFileSync(join(home,'data','model-providers.json'),JSON.stringify([{id:'fixture',kind:'custom',name:'Fixture',baseUrl:mock.baseUrl,protocol:'openai-chat',apiKey:'fixture-key',models}])); + const port=await freePort(),base=`http://127.0.0.1:${port}`; + const env={...process.env,STRATA_HOME:home,STRATA_MODELS_DIR:join(home,'models'),STRATA_WORKSPACE:join(home,'work'),STRATA_SETTINGS_FILE:join(home,'settings.json'),STRATA_COMPONENTS_DIR:join(home,'components'),STRATA_CONTROL_DIR:join(home,'no-control'),STRATA_HARNESS_DIR:join(home,'no-harness'),STRATA_NATIVE_REPO:join(home,'no-repo'),STRATA_PORT:String(port),STRATA_SHARE_PORT:String(await freePort()),STRATA_TUNNEL_PORT:String(await freePort()),STRATA_BIND:'127.0.0.1',STRATA_REAL_ENGINE:'0',STRATA_TEST_HARDWARE:ROOMY_HOST,STRATA_AGENT:'off',STRATA_NO_ACQUIRE:'1',ACQUIRE_SPY_LOG:join(home,'spy.log')}; + child=spawn(process.execPath,['--import','./tests/helpers/acquire-spy.mjs','server/index.mjs'],{cwd:join(import.meta.dirname,'..'),windowsHide:true,stdio:'ignore',env}); + exited=once(child,'exit'); + let up=false;for(let n=0;n<100&&!up;n++){try{up=(await fetch(base+'/api/health')).ok;}catch{}if(!up)await new Promise(r=>setTimeout(r,100));}assert.ok(up,'fixture host started'); + const before=readFileSync(join(home,'data','model-providers.json'),'utf8'); + for(const model of models)for(const [thinking,effort] of Object.entries(choices)){ + const res=await fetch(base+'/api/chat/stream',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({message:'Next question',history,thinking,thinkingBudget:1234,agent:false,useTools:false,mode:'bypass',remoteModel:{connectionId:'fixture',modelId:model.id,reasoning:true,thinks:true}})}); + assert.equal(res.status,200);const frames=(await res.text()).trim().split('\n').map(JSON.parse); + assert.equal(frames.some(f=>f.type==='error'),false,JSON.stringify(frames));assert.equal(frames.at(-1).type,'done'); + const request=mock.requests.filter(r=>r.path==='/v1/chat/completions').at(-1); + assert.equal(request.body.model,model.id);assert.equal(request.headers.authorization,'Bearer fixture-key');assert.deepEqual(request.body.messages.slice(-3),[...history,{role:'user',content:'Next question'}]); + assert.equal(request.body.reasoning_effort,['plain','unknown'].includes(model.id)?undefined:effort);assert.equal(Object.hasOwn(request.body,'reasoning_budget_tokens'),false); + } + assert.equal(readFileSync(join(home,'data','model-providers.json'),'utf8'),before); + assert.equal(readFileSync(join(home,'spy.log'),'utf8'),'','no external requests or software acquisition'); +}); diff --git a/apps/host/tests/mock-model-api.mjs b/apps/host/tests/mock-model-api.mjs index 0fa24ec2..c6991ff8 100644 --- a/apps/host/tests/mock-model-api.mjs +++ b/apps/host/tests/mock-model-api.mjs @@ -12,8 +12,9 @@ export async function createMockModelApi(port = 0) { if (req.url.includes('/models')) { res.setHeader('content-type', 'application/json'); const paginated = req.url.includes('limit=100'); - res.end(JSON.stringify({ data: req.url.includes('after_id=') ? [{ id: 'second-model', display_name: 'Second model' }] : [{ id: 'mock-chat', name: 'Test chat model', context_length: 32768 }, { id: 'mock-reasoning', name: 'Test reasoning model', context_length: 65536 }], ...(paginated ? { has_more: !req.url.includes('after_id='), last_id: 'mock-reasoning' } : {}) })); return; + res.end(JSON.stringify({ data: req.url.includes('after_id=') ? [{ id: 'second-model', display_name: 'Second model' }] : [{ id: 'mock-chat', name: 'Test chat model', context_length: 32768 }, { id: 'mock-reasoning', name: 'Test reasoning model', context_length: 65536, input_modalities: ['text'], supported_parameters: ['reasoning'] }], ...(paginated ? { has_more: !req.url.includes('after_id='), last_id: 'mock-reasoning' } : {}) })); return; } + if (req.url === '/props') { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ modalities: { vision: false } })); return; } res.writeHead(200, { 'content-type': 'text/event-stream' }); const send = value => res.write(`data: ${JSON.stringify(value)}\r\n\r\n`); if (body.model === 'truncated') { send({ choices: [{ index: 0, delta: { content: 'Partial' } }] }); res.end(); return; } From e2e99ae54aae9a5a28938223679ab9a5ec4ef33c Mon Sep 17 00:00:00 2001 From: kossum <127719370+kossum@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:21:07 +0100 Subject: [PATCH 054/177] Windows: the token default DACL grants generic rights, so a child process can still be opened after adopt_user_defaults (#3428, #3399) adopt_user_defaults() set the token's default DACL with FA (FILE_ALL_ACCESS). That default also applies to new process objects, and the file mask has no process query or set-information right, so a child could not be reopened by PID: the HighQoS helper timed out and procs.start_token could not record the child. GA lets Windows map the mask to the object being created; the principals are unchanged. Ported from PR #3428 by kossum (QoS reopen test). Test from PR #3399 by midhatn (a live child is identified and recorded) added; both fail without the change and pass with it. Co-authored-by: MIDHAT NASHAR <35053211+midhatn@users.noreply.github.com> --- strata_control/private_files.py | 5 +- tests/terminal/test_default_object_access.py | 54 ++++++++++++++++++++ tests/terminal/test_private_files.py | 31 +++++++++++ 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 tests/terminal/test_default_object_access.py diff --git a/strata_control/private_files.py b/strata_control/private_files.py index 318fee9a..b272d1bb 100644 --- a/strata_control/private_files.py +++ b/strata_control/private_files.py @@ -372,8 +372,11 @@ def adopt_user_defaults() -> bool: ok_owner = bool(_advapi.SetTokenInformation(token, _TOKEN_OWNER, ctypes.byref(_Owner(psid)), ctypes.sizeof(_Owner))) descriptor = ctypes.c_void_p() + # A token default DACL also applies to processes, not just files. FA is + # FILE_ALL_ACCESS (0x1f01ff), which omits process query/set-information. + # GA is mapped to the full rights of the object being created. if not _advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW( - f"D:(A;;FA;;;{sid})(A;;FA;;;SY)(A;;FA;;;BA)", _SDDL_REVISION_1, ctypes.byref(descriptor), None): + f"D:(A;;GA;;;{sid})(A;;GA;;;SY)(A;;GA;;;BA)", _SDDL_REVISION_1, ctypes.byref(descriptor), None): return False present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), ctypes.c_void_p() if not _advapi.GetSecurityDescriptorDacl(descriptor, ctypes.byref(present), ctypes.byref(dacl), diff --git a/tests/terminal/test_default_object_access.py b/tests/terminal/test_default_object_access.py new file mode 100644 index 00000000..b2f9ae70 --- /dev/null +++ b/tests/terminal/test_default_object_access.py @@ -0,0 +1,54 @@ +"""Windows token defaults must permit identifying children, not just opening files.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PROBE = r""" +import json, subprocess, sys +from pathlib import Path +from strata_control import private_files, procs + +assert private_files.adopt_user_defaults() +child = subprocess.Popen( + [sys.executable, "-c", "import time; print('ready', flush=True); time.sleep(30)"], + stdout=subprocess.PIPE, text=True, +) +try: + assert child.stdout.readline().strip() == "ready" + assert child.poll() is None + token = procs.start_token(child.pid) + assert token is not None, "live child became unreadable after adopting user defaults" + recorded = procs.write_record(child.pid, "engine") + assert recorded == token, "child identity could not be recorded" + print(json.dumps({"identified": True, "recorded": True}), flush=True) +finally: + child.kill() + child.wait(timeout=10) + child.stdout.close() +""" + + +@unittest.skipUnless(os.name == "nt", "Windows token default DACL") +class DefaultObjectAccess(unittest.TestCase): + def test_adopting_user_defaults_preserves_child_identity(self): + # Token defaults affect every subsequent object creation in this process. + # Exercise them in a disposable helper, not in the test runner itself. + with tempfile.TemporaryDirectory(prefix="strata-default-access-") as folder: + env = dict(os.environ, LOCALAPPDATA=folder, PYTHONPATH=str(ROOT)) + result = subprocess.run( + [sys.executable, "-c", PROBE], cwd=ROOT, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=25, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), {"identified": True, "recorded": True}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_private_files.py b/tests/terminal/test_private_files.py index 6da7d197..df80af0d 100644 --- a/tests/terminal/test_private_files.py +++ b/tests/terminal/test_private_files.py @@ -163,6 +163,37 @@ class ElevatedRunLockoutTests(unittest.TestCase): path.write_text("{}") self.assertEqual(path.read_text(), "{}") + def test_default_dacl_allows_reopening_child_process_for_qos(self): + import subprocess + import sys + # Isolate token changes and keep this test independent of the test runner's defaults. + script = ''' +import ctypes +from ctypes import wintypes +import subprocess +import sys +from strata_control import private_files as pf +from serve import winjob +assert pf.adopt_user_defaults() +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) +k32.OpenProcess.restype = wintypes.HANDLE +k32.CloseHandle.argtypes = (wintypes.HANDLE,) +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) +try: + handle = k32.OpenProcess(0x1000 | 0x0200, False, child.pid) + assert handle, "OpenProcess failed: %s" % ctypes.get_last_error() + try: + assert winjob.no_throttle(handle), "Setting child QoS failed" + finally: + k32.CloseHandle(handle) +finally: + child.terminate() + child.wait() +''' + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=40) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_only_the_users_own_folders_are_ever_repaired(self): self.assertFalse(pf.repair_access(os.environ.get("SystemRoot", "C:\Windows") + "\System32\drivers")) From 1e4ae3ddbf32ada59e97488d00ea113538ff7dbc Mon Sep 17 00:00:00 2001 From: medking82 <19301787+medking82@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:21:08 +0100 Subject: [PATCH 055/177] Models page: a failed preparation is shown only on the model it belongs to, not on the next model you select (PR #3361 by medking82) --- apps/host/src/components/NativeModels.tsx | 7 +++- .../tests/guided-setup-empty-catalog.test.mjs | 42 ++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 1ea22472..ec40a713 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -84,7 +84,12 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }, [selectedSize?.id, installed?.ready, resourceProfile, vision, native?.jobs.filter(j => j.state === 'done').length]); useEffect(() => { if (tunedNow?.fields.kv) setKv(tunedNow.fields.kv as typeof kv); if (tunedNow?.fields.lowRam) setLowRam(tunedNow.fields.lowRam as typeof lowRam); }, [tunedNow]); const active = native?.jobs.find(j => j.state === 'running'); - const job = native?.jobs.find(j => j.id === jobId) ?? (!jobId ? native?.jobs.filter(j => ['load', 'install'].includes(j.kind)).at(-1) : undefined); + // Catalog groups share quantization names. A remembered job must still belong + // to the selected version; another family's failure stays in diagnostics. + const selectedJob = (j: NativeJob) => !!selectedSize && (j.model === selectedSize.id || + (j.model === selectedSize.model && j.family === selectedSize.sourceFamily)); + const job = native?.jobs.find(j => j.id === jobId && selectedJob(j)) ?? + native?.jobs.filter(j => ['load', 'install'].includes(j.kind) && selectedJob(j)).at(-1); const noFit = selectedSize?.on_this_pc === 'does not fit'; // Graphics cards (strata_control/gpu_fit.py: the one rule of the app, the Terminal and setup): the recommended option is pre-selected, the person may pick another // A card a loaded model already uses (a second model on it usually does not fit): said on its row, and not the pre-selected one while another is free. diff --git a/apps/host/tests/guided-setup-empty-catalog.test.mjs b/apps/host/tests/guided-setup-empty-catalog.test.mjs index 17c87ca6..b826ce81 100644 --- a/apps/host/tests/guided-setup-empty-catalog.test.mjs +++ b/apps/host/tests/guided-setup-empty-catalog.test.mjs @@ -25,6 +25,7 @@ const stubs={ store:stubFor('store.ts',{useStore:'sel=>sel(globalThis.__store)'}), client:stubFor('client.ts',{}), router:stubFor('router.ts',{}), + 'kept-state':stubFor('kept-state.ts',{useKept:'(key,initial)=>[globalThis.__kept?.[key]??initial,()=>{}]'}), }; let dir,mod; @@ -32,7 +33,7 @@ async function load(){ if(mod)return mod; dir=mkdtempSync(join(tmpdir(),'strata-gs-')); const stubPlugin={name:'stubs',setup(b){ - b.onResolve({filter:/\/lib\/(native|store|client|router)$/},args=>({path:args.path.split('/').pop(),namespace:'stub'})); + b.onResolve({filter:/\/lib\/(native|store|client|router|kept-state)$/},args=>({path:args.path.split('/').pop(),namespace:'stub'})); b.onLoad({filter:/.*/,namespace:'stub'},args=>({contents:stubs[args.path],loader:'js',resolveDir:root})); }}; const entry=join(dir,'entry.tsx'); @@ -82,3 +83,42 @@ test('GuidedSetup lists the real catalog when it has one',async()=>{ const html=m.renderToString(m.createElement(m.GuidedSetup)); assert.match(html,/IQ3_XXS/); }); + +const failedJob=(id,model,family)=>({id,kind:'install',model,family,state:'error', + startedAt:'2026-01-01T00:00:00.000Z',summary:'Previous preparation failed', + error:'Data_dir C:\\Users\\Example\\.strata\\models: a new data folder must be named Strata',result:null}); +async function renderModelJobs(jobs,kept={}){ + const m=await load(); + const size=(id,model)=>({id,model,download_gb:50,ram_needed_gb:48,experts_gb:30,about:'',on_this_pc:'fits',installed:false}); + globalThis.__native={...base,jobs,catalog:{contexts:[32768,65536],families:[ + {family:'qwen',title:'Qwen3.8-Flash-Next',about:'',images:false,experimental:false,sizes:[size('iq3_s','IQ3_S')]}, + {family:'swift',title:'Qwen3.8-Flash-Next (Swift)',about:'',images:false,experimental:false,sizes:[size('swift-iq3_s','IQ3_S')]}, + ]}}; + globalThis.__store=store();globalThis.__kept=kept; + try{return m.renderToString(m.createElement(m.NativeModels));}finally{globalThis.__kept={};} +} + +test('NativeModels does not attach another family’s failed preparation to the selected version',async()=>{ + const job=failedJob('old-swift','IQ3_S','swift'),jobs=[job]; + assert.doesNotMatch(await renderModelJobs(jobs),/Data_dir/); + assert.equal(jobs[0],job,'the job is retained for diagnostics'); +}); + +test('NativeModels ignores a remembered job after selecting a different model',async()=>{ + assert.doesNotMatch(await renderModelJobs([failedJob('old-swift','swift-iq3_s','swift')],{'models.job':'old-swift'}),/Data_dir/); +}); + +test('NativeModels still shows the selected canonical model’s real failure',async()=>{ + assert.match(await renderModelJobs([failedJob('current','iq3_s')]),/Data_dir/); +}); + +test('NativeModels identifies aliases by source family and keeps matching remembered errors',async()=>{ + assert.match(await renderModelJobs([failedJob('current','IQ3_S','qwen')],{'models.job':'current'}),/Data_dir/); + assert.doesNotMatch(await renderModelJobs([failedJob('ambiguous','IQ3_S')]),/Data_dir/); +}); + +test('NativeModels falls back to the latest job for the selected version, not an unrelated remembered job',async()=>{ + const own=failedJob('own','iq3_s'),other={...failedJob('other','swift-iq3_s','swift'),error:'Other model error'}; + const html=await renderModelJobs([own,other],{'models.job':'other'}); + assert.match(html,/Data_dir/);assert.doesNotMatch(html,/Other model error/); +}); From df6928400f6eb584ff647830922474421dd8fc78 Mon Sep 17 00:00:00 2001 From: medking82 <19301787+medking82@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:21:20 +0100 Subject: [PATCH 056/177] Agent: the staged Harness keeps output room in small contexts (8K): a guarded, hash-checked correction of pi-ai 1.1.0's safety margin below 64K (PR #3684 by medking82) --- apps/desktop/scripts/harness-budget.mjs | 52 ++++++++ apps/desktop/scripts/stage-harness.mjs | 5 + apps/host/server/agent/README.md | 7 + .../pi-ai-1.1.0-simple-options.js.fixture | 73 ++++++++++ apps/host/tests/fixtures/pi-ai-LICENSE | 25 ++++ apps/host/tests/harness-budget.test.mjs | 126 ++++++++++++++++++ 6 files changed, 288 insertions(+) create mode 100644 apps/desktop/scripts/harness-budget.mjs create mode 100644 apps/host/tests/fixtures/pi-ai-1.1.0-simple-options.js.fixture create mode 100644 apps/host/tests/fixtures/pi-ai-LICENSE create mode 100644 apps/host/tests/harness-budget.test.mjs diff --git a/apps/desktop/scripts/harness-budget.mjs b/apps/desktop/scripts/harness-budget.mjs new file mode 100644 index 00000000..4f588d75 --- /dev/null +++ b/apps/desktop/scripts/harness-budget.mjs @@ -0,0 +1,52 @@ +/** Strata's output-budget correction for the staged pi-ai copy. */ +import { createHash } from 'node:crypto'; +import { lstatSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +export const HARNESS_BUDGET_PATCH = Object.freeze({ + id: 'strata-pi-ai-context-safety-v2', + package: '@earendil-works/pi-ai', + version: '1.1.0', + file: 'node_modules/@earendil-works/pi-ai/dist/api/simple-options.js', + beforeSha256: '9b3cc0ae6daa86fdc050bc0cb0f3f986401e64ccddbde6757183c9f8ad411be2', +}); + +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); +const oldClamp = 'const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;'; +// Small windows also need room after tool results; a fixed margin must not +// consume all remaining estimated space. Keep the old 64K+ calculation. +const newClamp = `const remaining = model.contextWindow - estimateContextTokens(context).tokens; + const safety = model.contextWindow >= 65536 ? CONTEXT_SAFETY_TOKENS + : Math.min(CONTEXT_SAFETY_TOKENS, Math.floor(model.contextWindow / 16), Math.max(0, Math.floor(remaining / 2))); + const available = remaining - safety;`; + +/** + * Patch only a flattened, disposable staged Harness. Returns the BUNDLE.json + * provenance entry; the caller records it when writing the bundle manifest. + * A repeat application or any unknown package/source fails before writing. + */ +export function patchStagedHarnessBudget(stagedRoot) { + const fail = message => { throw new Error(`Harness output-budget patch: ${message}`); }; + const root = realpathSync(resolve(stagedRoot)); + const packageDir = join(root, 'node_modules', '@earendil-works', 'pi-ai'); + const target = join(root, HARNESS_BUDGET_PATCH.file); + let manifest, before; + try { + manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8')); + // Flattening must have removed links; never write through a shared source file. + if (realpathSync(target) !== target || !lstatSync(target).isFile() || lstatSync(target).nlink !== 1) + fail('expected an unlinked staged module'); + before = readFileSync(target); + } catch (error) { + fail(`cannot read a standalone staged pi-ai dependency (${error.message})`); + } + if (manifest?.name !== HARNESS_BUDGET_PATCH.package || manifest?.version !== HARNESS_BUDGET_PATCH.version) + fail('expected @earendil-works/pi-ai 1.1.0; review the patch before staging a different dependency'); + if (sha256(before) !== HARNESS_BUDGET_PATCH.beforeSha256) + fail('unexpected simple-options.js SHA-256; review the dependency source before staging'); + const source = before.toString('utf8'); + if (source.split(oldClamp).length !== 2) fail('expected exactly one known context clamp'); + const after = Buffer.from(source.replace(oldClamp, newClamp)); + writeFileSync(target, after); + return { ...HARNESS_BUDGET_PATCH, afterSha256: sha256(after) }; +} diff --git a/apps/desktop/scripts/stage-harness.mjs b/apps/desktop/scripts/stage-harness.mjs index 7327d88e..0e6738ea 100644 --- a/apps/desktop/scripts/stage-harness.mjs +++ b/apps/desktop/scripts/stage-harness.mjs @@ -19,6 +19,7 @@ import { join, relative, resolve, sep } from 'node:path'; import { createHash } from 'node:crypto'; import { flattenPnpm } from './flatten-pnpm.mjs'; import { isOtherOsBinaryFolder, missingHarnessImports } from './harness-prune.mjs'; +import { patchStagedHarnessBudget } from './harness-budget.mjs'; const args = process.argv.slice(2); const opt = (name, fallback) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : fallback; }; @@ -144,6 +145,9 @@ function prune(dir) { } prune(out); +// Strata's provenance-recorded output-budget correction applies only to this copy. +const patches = [patchStagedHarnessBudget(out)]; + // --- licence: the MIT text and the third-party notices travel with the files --------------------------------------------- for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) { if (existsSync(join(src, name))) cpSync(join(src, name), join(out, name)); @@ -156,6 +160,7 @@ const total = size(out); writeFileSync(join(out, 'BUNDLE.json'), JSON.stringify({ component: 'deepseek-harness', version: cli.version, commit, license: 'MIT', platform, node: process.version, bytes: total.bytes, files: total.files, entry: 'apps/cli/lib/bin.js', builtAt: new Date().toISOString(), + patches, note: 'Pruned production install (pnpm deploy --prod). No package manager runs on the user\'s PC.', }, null, 2)); diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index b05bebcf..dbc520c5 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -93,6 +93,13 @@ What the person chose is saved by `tools-settings.mjs` (inside the host's settin ## Thinking and the output budget +The Harness staging script (`apps/desktop/scripts/stage-harness.mjs`) applies Strata's guarded pi-ai 1.1.0 patch to its staged copy +(`harness-budget.mjs`, #3684): below 64K the context safety room is at most `min(4096, floor(contextWindow / 16))` and never more +than half the estimated remaining room, so an 8K window keeps output room after a tool result instead of ending with a one-token +cap. The caller's output cap and the one-token floor remain; windows of 64K or more keep the previous calculation. `BUNDLE.json.patches` +records the patch identity, the dependency version and the before/after SHA-256. Unknown dependency bytes stop staging for review. +Source and already-installed Harness copies are not changed. + - A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). - `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves. pi-ai sends the window minus the prompt. App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. diff --git a/apps/host/tests/fixtures/pi-ai-1.1.0-simple-options.js.fixture b/apps/host/tests/fixtures/pi-ai-1.1.0-simple-options.js.fixture new file mode 100644 index 00000000..4e36f350 --- /dev/null +++ b/apps/host/tests/fixtures/pi-ai-1.1.0-simple-options.js.fixture @@ -0,0 +1,73 @@ +import { clampThinkingLevel } from "../models.js"; +import { estimateContextTokens } from "../utils/estimate.js"; +const CONTEXT_SAFETY_TOKENS = 4096; +const MIN_MAX_TOKENS = 1; +export function clampMaxTokensToContext(model, context, maxTokens) { + if (model.contextWindow <= 0) + return Math.max(MIN_MAX_TOKENS, maxTokens); + const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS; + return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available)); +} +export function resolveSamplingParams(model, thinkingLevel, requestParams) { + const effectiveThinkingLevel = clampThinkingLevel(model, thinkingLevel); + const thinkingLevelParams = model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel]; + return model.samplingParams || thinkingLevelParams || requestParams + ? { ...model.samplingParams, ...thinkingLevelParams, ...requestParams } + : undefined; +} +export function buildBaseOptions(model, context, options, apiKey) { + const samplingParams = resolveSamplingParams(model, options?.reasoning ?? "off", options?.samplingParams); + return { + temperature: options?.temperature, + samplingParams, + maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens), + signal: options?.signal, + telemetryContext: options?.telemetryContext, + apiKey: apiKey || options?.apiKey, + fetch: options?.fetch, + transport: options?.transport, + cacheRetention: options?.cacheRetention, + sessionId: options?.sessionId, + headers: options?.headers, + onPayload: options?.onPayload, + onResponse: options?.onResponse, + onProviderStreamEvent: options?.onProviderStreamEvent, + timeoutMs: options?.timeoutMs, + websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs, + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + metadata: options?.metadata, + env: options?.env, + }; +} +/** Tokens always left for the answer when a thinking budget shares the response ceiling. */ +export const MIN_ANSWER_TOKENS = 1024; +export const DEFAULT_THINKING_BUDGETS = { + minimal: 1024, + low: 2048, + medium: 8192, + high: 16384, +}; +export function clampReasoning(effort) { + return effort === "xhigh" || effort === "max" ? "high" : effort; +} +export function thinkingBudgetForLevel(reasoningLevel, customBudgets) { + const budgets = { ...DEFAULT_THINKING_BUDGETS, ...customBudgets }; + const level = clampReasoning(reasoningLevel); + return budgets[level]; +} +/** Cap a thinking budget so at least MIN_ANSWER_TOKENS remain under a shared response ceiling. */ +export function clampThinkingBudgetToAnswerRoom(thinkingBudget, ceiling) { + return Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS)); +} +export function adjustMaxTokensForThinking( +// Undefined means no explicit caller cap. Use the model cap and fit thinking inside it. +baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) { + let thinkingBudget = thinkingBudgetForLevel(reasoningLevel, customBudgets); + const maxTokens = baseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens); + if (maxTokens <= thinkingBudget) { + thinkingBudget = clampThinkingBudgetToAnswerRoom(thinkingBudget, maxTokens); + } + return { maxTokens, thinkingBudget }; +} +//# sourceMappingURL=simple-options.js.map \ No newline at end of file diff --git a/apps/host/tests/fixtures/pi-ai-LICENSE b/apps/host/tests/fixtures/pi-ai-LICENSE new file mode 100644 index 00000000..4c382c58 --- /dev/null +++ b/apps/host/tests/fixtures/pi-ai-LICENSE @@ -0,0 +1,25 @@ +pi-ai-1.1.0-simple-options.js.fixture is copied from @earendil-works/pi-ai 1.1.0, +dist/api/simple-options.js. Its exact bytes are a staging-patch regression fixture. +Upstream: https://github.com/earendil-works/pi/tree/main/packages/ai + +MIT License + +Copyright (c) 2025 Mario Zechner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/host/tests/harness-budget.test.mjs b/apps/host/tests/harness-budget.test.mjs new file mode 100644 index 00000000..5d8a86b5 --- /dev/null +++ b/apps/host/tests/harness-budget.test.mjs @@ -0,0 +1,126 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { runInNewContext } from 'node:vm'; +import { HARNESS_BUDGET_PATCH, patchStagedHarnessBudget } from '../../desktop/scripts/harness-budget.mjs'; + +// Exact MIT-licensed pi-ai 1.1.0 module; arithmetic fixture, not native tokenization. +const original = readFileSync(new URL('./fixtures/pi-ai-1.1.0-simple-options.js.fixture', import.meta.url), 'utf8').replaceAll('\r\n', '\n'); +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); +function staged(t, { source = original, manifest = { name: '@earendil-works/pi-ai', version: '1.1.0' } } = {}) { + const root = mkdtempSync(join(tmpdir(), 'strata-harness-budget-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const file = join(root, HARNESS_BUDGET_PATCH.file), packageFile = join(root, 'node_modules', '@earendil-works', 'pi-ai', 'package.json'); + mkdirSync(join(file, '..'), { recursive: true }); + writeFileSync(file, source); writeFileSync(packageFile, JSON.stringify(manifest)); + return { root, file, packageFile }; +} +function patched(t) { + const fixture = staged(t), provenance = patchStagedHarnessBudget(fixture.root); + return { ...fixture, provenance, clamp: clampOf(readFileSync(fixture.file, 'utf8')) }; +} +function clampOf(source) { + const code = source.replace(/^import .*;\n/gm, '').replace(/^export /gm, ''); + return runInNewContext(`${code}\nclampMaxTokensToContext;`, { + estimateContextTokens: context => ({ tokens: context.tokens }), + clampThinkingLevel: (_model, level) => level, + }); +} + +test('staged pi-ai leaves output room at 8K Context', t => { + assert.equal(clampOf(original)({ contextWindow: 8192 }, { tokens: 6545 }, 4096), 1, 'The Original Regression'); + const { clamp } = patched(t); + assert.equal(clamp({ contextWindow: 8192 }, { tokens: 6545 }, 4096), 1135); +}); + +test('small-window safety leaves answer room after a tool result', t => { + const { clamp } = patched(t); + assert.equal(clamp({ contextWindow: 8192 }, { tokens: 7750 }, 4096), 221); + assert.equal(clamp({ contextWindow: 8192 }, { tokens: 8000 }, 4096), 96); + assert.equal(clamp({ contextWindow: 8192 }, { tokens: 8000 }, 32), 32); +}); + +test('the staged correction retains caller caps and the no-room floor', t => { + const { clamp } = patched(t); + for (const cap of [1, 128]) assert.equal(clamp({ contextWindow: 8192 }, { tokens: 6545 }, cap), cap); + for (const tokens of [8191, 8192, 9000]) assert.equal(clamp({ contextWindow: 8192 }, { tokens }, 4096), 1); +}); + +test('32K scales safety to 2048; 64K and larger keep the original calculation', t => { + const { clamp } = patched(t), old = clampOf(original); + assert.equal(clamp({ contextWindow: 32768 }, { tokens: 6545 }, 32768), 24175); + assert.equal(clamp({ contextWindow: 65536 }, { tokens: 6545 }, 65536), 54895); + assert.equal(clamp({ contextWindow: 131072 }, { tokens: 6545 }, 131072), 120431); + for (const window of [65536, 131072, 262144]) { + for (const tokens of [0, 6545, window - 4096, window]) { + for (const cap of [1, 128, 32768, window]) + assert.equal(clamp({ contextWindow: window }, { tokens }, cap), old({ contextWindow: window }, { tokens }, cap)); + } + } +}); + +test('unknown and nonpositive context paths retain their previous behavior', t => { + const { clamp } = patched(t), old = clampOf(original); + for (const window of [0, -1, null, undefined, NaN]) { + for (const cap of [0, 1, 128, 4096]) + assert.equal(clamp({ contextWindow: window }, { tokens: 6545 }, cap), old({ contextWindow: window }, { tokens: 6545 }, cap)); + } +}); + +test('patch provenance records its identity, exact dependency and before/after hashes', t => { + const { file, packageFile, provenance } = patched(t); + assert.equal(sha256(original), HARNESS_BUDGET_PATCH.beforeSha256); + assert.deepEqual(provenance, { id: 'strata-pi-ai-context-safety-v2', package: '@earendil-works/pi-ai', version: '1.1.0', + file: HARNESS_BUDGET_PATCH.file, beforeSha256: sha256(original), afterSha256: sha256(readFileSync(file)) }); + assert.notEqual(provenance.beforeSha256, provenance.afterSha256); + assert.deepEqual(JSON.parse(readFileSync(packageFile, 'utf8')), { name: '@earendil-works/pi-ai', version: '1.1.0' }); + const changed = original.replace('const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;', + `const remaining = model.contextWindow - estimateContextTokens(context).tokens; + const safety = model.contextWindow >= 65536 ? CONTEXT_SAFETY_TOKENS + : Math.min(CONTEXT_SAFETY_TOKENS, Math.floor(model.contextWindow / 16), Math.max(0, Math.floor(remaining / 2))); + const available = remaining - safety;`); + assert.equal(readFileSync(file, 'utf8'), changed, 'Only The Known Clamp Changes'); +}); + +test('malformed or unexpected dependencies fail before writing', t => { + const cases = [ + { manifest: { name: '@earendil-works/pi-ai', version: '1.2.0' } }, + { manifest: { name: 'another-package', version: '1.1.0' } }, + { manifest: null }, + { source: original + '\n' }, + { source: original.replace('CONTEXT_SAFETY_TOKENS = 4096', 'CONTEXT_SAFETY_TOKENS = 1024') }, + ]; + for (const value of cases) { + const f = staged(t, value), before = readFileSync(f.file), manifest = readFileSync(f.packageFile); + assert.throws(() => patchStagedHarnessBudget(f.root), /Harness output-budget patch:/); + assert.deepEqual(readFileSync(f.file), before); assert.deepEqual(readFileSync(f.packageFile), manifest); + } + const f = staged(t); writeFileSync(f.packageFile, '{bad json'); + assert.throws(() => patchStagedHarnessBudget(f.root), /cannot read a standalone staged pi-ai dependency/); + assert.equal(readFileSync(f.file, 'utf8'), original); assert.equal(readFileSync(f.packageFile, 'utf8'), '{bad json'); +}); + +test('a repeated patch rejects already-changed bytes without writing again', t => { + const f = patched(t), before = readFileSync(f.file); + assert.throws(() => patchStagedHarnessBudget(f.root), /unexpected simple-options.js SHA-256/); + assert.deepEqual(readFileSync(f.file), before); +}); + +test('staging refuses a module hardlinked to another copy', t => { + const f = staged(t), other = join(f.root, 'source-module.js'); linkSync(f.file, other); + assert.throws(() => patchStagedHarnessBudget(f.root), /expected an unlinked staged module/); + assert.equal(readFileSync(other, 'utf8'), original); assert.equal(readFileSync(f.file, 'utf8'), original); +}); + +test('patching a disposable copy leaves the installed original hash unchanged', { + skip: !process.env.STRATA_TEST_PI_AI_DIR, +}, t => { + const installed = join(process.env.STRATA_TEST_PI_AI_DIR, 'dist', 'api', 'simple-options.js'); + const before = sha256(readFileSync(installed)); + assert.equal(before, HARNESS_BUDGET_PATCH.beforeSha256); + const f = staged(t, { source: readFileSync(installed) }); patchStagedHarnessBudget(f.root); + assert.equal(sha256(readFileSync(installed)), before); +}); From 3e81173d635c5daa3e2337490ebb1409764d7c6f Mon Sep 17 00:00:00 2001 From: MegaRushX <339630542+MegaRushX@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:21:36 +0100 Subject: [PATCH 057/177] chat.py: fenced code blocks in streamed answers are coloured on a terminal; prose is untouched (PR #1895 by MegaRushX) --- chat.py | 8 +- highlight.py | 138 ++++++++++++++++++++++++++ tests/terminal/test_chat_highlight.py | 78 +++++++++++++++ 3 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 highlight.py create mode 100644 tests/terminal/test_chat_highlight.py diff --git a/chat.py b/chat.py index 124c7278..668e18a0 100644 --- a/chat.py +++ b/chat.py @@ -18,6 +18,8 @@ import sys import time import urllib.request +from highlight import StreamHighlighter + def stream(url, messages, think, max_tokens): body = {"model": "strata", "messages": messages, "stream": True, "max_tokens": max_tokens, @@ -43,6 +45,7 @@ def main() -> int: a = ap.parse_args() url = f"http://{a.host}:{a.port}/v1/chat/completions" gray, reset = ("\033[90m", "\033[0m") if sys.stdout.isatty() else ("", "") + hl = StreamHighlighter(color=sys.stdout.isatty()) messages, pending = [], [] think = "none" if a.no_think else a.think print(f"Strata chat ({url}). /image = attach a picture, /think none|low|medium|high (now: {think}), " @@ -98,11 +101,14 @@ def main() -> int: if in_think: print(reset + "\n", end="") in_think = False - print(content, end="", flush=True) + print(hl.feed(content), end="", flush=True) answer.append(content) n += 1 if in_think: print(reset, end="") + out = hl.flush() + if out: + print(out, end="") except OSError as e: print(f"\n(could not reach the server at {url}: {e})") messages.pop() diff --git a/highlight.py b/highlight.py new file mode 100644 index 00000000..7f276adb --- /dev/null +++ b/highlight.py @@ -0,0 +1,138 @@ +"""Syntax highlighting for chat.py's streamed output: fenced code blocks get colored (tags, strings, comments, +keywords, numbers), everything else passes through unchanged. Standard library only, no dependency. + + from highlight import StreamHighlighter + hl = StreamHighlighter(color=True) + out = hl.feed(streamed_chunk) # complete lines, highlighted; a partial last line is held back + out += hl.flush() # the held-back tail (unclosed fence included) +""" +from __future__ import annotations + +import re + + +# ANSI colors; a disabled colorer returns the text unchanged +class _Palette: + def __init__(self, color: bool): + self.on = color + + def paint(self, text: str, code: str) -> str: + return f"\033[{code}m{text}\033[0m" if self.on else text + + +# one regex per language family; the first matching family paints the line +_PY_KEYWORDS = ("False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", + "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield") +_JS_KEYWORDS = ("async", "await", "break", "case", "catch", "class", "const", "continue", "default", "delete", + "do", "else", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", + "instanceof", "let", "new", "null", "return", "static", "super", "switch", "this", "throw", "true", + "try", "typeof", "undefined", "var", "void", "while", "yield") +_C_KEYWORDS = ("alignas", "auto", "bool", "break", "case", "catch", "char", "class", "const", "constexpr", + "continue", "default", "delete", "do", "double", "else", "enum", "explicit", "extern", "false", + "float", "for", "friend", "if", "inline", "int", "long", "namespace", "new", "noexcept", "nullptr", + "private", "protected", "public", "return", "short", "signed", "sizeof", "static", "struct", + "switch", "template", "this", "throw", "true", "try", "typedef", "typename", "union", "unsigned", + "using", "virtual", "void", "while") +_SHELL_KEYWORDS = ("case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "in", "then", + "until", "while") +_JSON_KEYS = ("false", "null", "true") + +_STR = r"(\"(?:[^\"\\]|\\.)*\")" # "..." with escapes +_SQ_STR = r"('(?:[^'\\]|\\.)*')" +_COMMENT = r"(#.*$)" +_SLASH_COMMENT = r"(//.*$)" +_NUM = r"\b(\d[\w.]*)\b" + +_FAMILIES = { + "markup": ({"html", "htm", "xml", "svg", "vue", "jsx", "tsx"}, + re.compile(r"()|(<[A-Za-z][\w:.-]*/?>?)|()|([A-Za-z-]+)(?==)"), + {1: "36;1", 2: "96", 3: "96", 4: "94"}), + "python": ({"py", "python"}, + re.compile(rf"{_COMMENT}|{_SQ_STR}|{_STR}|\b({'|'.join(_PY_KEYWORDS)})\b|{_NUM}"), + {1: "90", 2: "33", 3: "33", 4: "35;1", 5: "34"}), + "c-like": ({"c", "cc", "cpp", "c++", "h", "hpp", "cu", "hip", "java", "kt", "rs", "go", "cs"}, + re.compile(rf"{_SLASH_COMMENT}|{_STR}|\b({'|'.join(_C_KEYWORDS)})\b|\b(0x[0-9a-fA-F]+|\d[\w.]*)\b"), + {1: "90", 2: "33", 3: "35;1", 4: "34"}), + "js-like": ({"js", "javascript", "ts", "typescript", "mjs"}, + re.compile(rf"{_SLASH_COMMENT}|{_STR}|{_SQ_STR}|(`[^`]*`)|\b({'|'.join(_JS_KEYWORDS)})\b|{_NUM}"), + {1: "90", 2: "33", 3: "33", 4: "33", 5: "35;1", 6: "34"}), + "shell": ({"sh", "bash", "zsh", "shell", "console", "bat", "cmd", "powershell", "ps1"}, + re.compile(rf"{_COMMENT}|{_SQ_STR}|{_STR}|\b({'|'.join(_SHELL_KEYWORDS)})\b|(^\s*\$)"), + {1: "90", 2: "33", 3: "33", 4: "35;1", 5: "90"}), + "json": ({"json", "jsonc", "json5"}, + re.compile(rf"{_SLASH_COMMENT}|{_STR}(?=\s*:)|\b({'|'.join(_JSON_KEYS)})\b|\b(-?\d[\w.]*)\b"), + {1: "90", 2: "94", 3: "35;1", 4: "34"}), + "css": ({"css", "scss", "less"}, + re.compile(r"(/\*.*?\*/)|([.#][\w-]+)|([\w-]+)(?=\s*:)|\b(\d[\w.%]*)\b"), + {1: "90", 2: "96", 3: "94", 4: "34"}), + "sql": ({"sql"}, + re.compile(r"(--.*$)|('[^']*')|\b(select|from|where|insert|into|update|set|delete|join|left|right|inner|" + r"outer|on|group|by|order|having|limit|create|table|alter|drop|and|or|not|null|as)\b", + re.IGNORECASE), + {1: "90", 2: "33", 3: "35;1"}), + "diff": ({"diff", "patch"}, + re.compile(r"^(\+[^+]*)|^(-.*)|^(@@.*@@)"), + {1: "32", 2: "31", 3: "36"}), +} + +_FENCE_RE = re.compile(r"^\s*(```|~~~)\s*([\w+#-]*)") +_LANG_ALIAS = {"c++": "c-like", "javascript": "js-like", "typescript": "js-like", "python": "python", + "py": "python", "shell": "shell", "bash": "shell", "console": "shell"} + + +def _family(lang: str): + lang = _LANG_ALIAS.get(lang.lower(), lang.lower()) + for exts, rx, colors in _FAMILIES.values(): + if lang in exts: + return rx, colors + return None, None + + +class StreamHighlighter: + """Line-buffered highlighter for streamed text. feed() returns complete lines (highlighted inside fenced code + blocks); flush() returns the held-back tail. Outside code fences the text is returned unchanged (color on or + off), so prose never gets painted. All characters other than the added ANSI escapes pass through unchanged.""" + + def __init__(self, color: bool = True): + self.color = color + self._pal = _Palette(color) + self._buf = "" # held-back partial line + self._in_fence = False + self._rx = None + self._colors = None + + def feed(self, chunk: str) -> str: + self._buf += chunk + out = [] + while "\n" in self._buf: + line, self._buf = self._buf.split("\n", 1) + out.append(self._line(line)) + out.append("\n") + return "".join(out) + + def flush(self) -> str: + tail, self._buf = self._buf, "" + return self._line(tail) if tail else "" + + def _line(self, line: str) -> str: + fence = _FENCE_RE.match(line) + if fence: + marker, lang = fence.group(1), fence.group(2) + if self._in_fence: + self._in_fence, self._rx, self._colors = False, None, None + return self._pal.paint(line, "90") + self._in_fence = True + self._rx, self._colors = _family(lang) + if not self._rx: + return self._pal.paint(line, "90") + return self._pal.paint(marker, "90") + self._pal.paint(lang, "94") + line[fence.end():] + if not self._in_fence or not self._rx: + return line + return self._rx.sub(self._sub, line) + + def _sub(self, m: re.Match) -> str: + for gi, code in self._colors.items(): + if m.group(gi) is not None: + return self._pal.paint(m.group(gi), code) + return m.group(0) diff --git a/tests/terminal/test_chat_highlight.py b/tests/terminal/test_chat_highlight.py new file mode 100644 index 00000000..d34fe3d3 --- /dev/null +++ b/tests/terminal/test_chat_highlight.py @@ -0,0 +1,78 @@ +"""highlight.py: fenced code blocks in chat.py's streamed output get syntax highlighting (tags, strings, comments, +keywords, numbers), prose passes through unchanged, and a fence split across streamed chunks still opens. + + python -m pytest tests/terminal/test_chat_highlight.py (no GPU, no downloads) +""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from highlight import StreamHighlighter # noqa: E402 + +RESET = "\033[0m" + + +def colored(text, code): + return f"\033[{code}m{text}{RESET}" + + +class TestHighlight(unittest.TestCase): + def test_prose_unchanged_with_color(self): + hl = StreamHighlighter(color=True) + self.assertEqual(hl.feed("hello world\n"), "hello world\n") + self.assertEqual(hl.flush(), "") + + def test_prose_unchanged_without_color(self): + hl = StreamHighlighter(color=False) + self.assertEqual(hl.feed("def f(x):\n return x\n"), "def f(x):\n return x\n") + + def test_python_block_is_highlighted(self): + hl = StreamHighlighter(color=True) + out = hl.feed("```python\nfor i in range(3): # loop\n print(i)\n```\n") + self.assertIn(colored("for", "35;1"), out) + self.assertIn(colored("# loop", "90"), out) + self.assertIn(colored("in", "35;1"), out) + lines = out.split("\n") + self.assertTrue(lines[-1] == "" and lines[-2] == colored("```", "90")) + # prose after the fence is unchanged + self.assertEqual(hl.feed("plain again\n"), "plain again\n") + + def test_html_tags_highlighted(self): + hl = StreamHighlighter(color=True) + out = hl.feed("```html\n
hi
\n```\n") + self.assertIn(colored("", "96"), out) + self.assertIn(colored("class", "94"), out) + + def test_fence_split_across_chunks(self): + hl = StreamHighlighter(color=True) + out = hl.feed("code:\n``") + hl.feed("`py\nimport os\n```\n") + self.assertIn(colored("import", "35;1"), out) + self.assertIn(colored("```", "90"), out) + self.assertIn(colored("py", "94"), out) + + def test_partial_line_held_back_then_flushed(self): + hl = StreamHighlighter(color=False) + self.assertEqual(hl.feed("abc"), "") + self.assertEqual(hl.feed("def\nxyz"), "abcdef\n") + self.assertEqual(hl.flush(), "xyz") + + def test_unknown_language_passes_through(self): + hl = StreamHighlighter(color=True) + out = hl.feed("```brainfuck\n+++++\n```\n") + self.assertIn("+++++", out) + self.assertIn(colored("```brainfuck", "90"), out) + + def test_streaming_bytes_preserved(self): + text = "```python\ndef f(x):\n return x**2\n```\ndone\n" + hl = StreamHighlighter(color=True) + out = hl.feed(text) + self.assertEqual(out.replace(RESET, "").replace("\033[35;1m", "").replace("\033[90m", "") + .replace("\033[33m", "").replace("\033[34m", "").replace("\033[94m", ""), text) + self.assertEqual(hl.flush(), "") + + +if __name__ == "__main__": + unittest.main() From cc2c628cbe09cbc1351e086e8cca1d78a1b86a7f Mon Sep 17 00:00:00 2001 From: Demetree Kallergis <1394829+demetree@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:22:30 +0100 Subject: [PATCH 058/177] setup (Mac): say when an update was asked for a model that is not installed (#3848) metal/setup_mac.py returned right after the engine step on --update while the model questions had been asked, so choosing a model the Mac did not have ended with no download and no word. The update now names the missing model (or image encoder) and points at ./setup.sh --setup; an update for a model that is installed prints what it printed before. Ported from PR #3848 by demetree, with its two tests (mocked; not run on a Mac). --- metal/setup_mac.py | 12 ++++++++++ tools/test_setup_mac.py | 50 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/metal/setup_mac.py b/metal/setup_mac.py index b939e246..774ac3b2 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -433,6 +433,18 @@ def main(argv=None) -> int: (BUILD_DIR / "BUILD.json").unlink(missing_ok=True) exe = build_engine(llama) if a.update: + # update.sh's own text: "The model files are not touched". The questions are asked anyway, so when the + # answers name a model (or an image encoder) that is not here, say it: a silent exit reads like a broken + # download (an M1 Max chose IQ3_S in update.sh and got no model and no message). + files = [Path(a.gguf_dir) / n if a.gguf_dir else models_root / tag / n for n in model_shard_names(model)] + pack = S.find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() + pack_done = (pack / "native_experts.txt").exists() and (pack / "tokenizer" / "vocab.json").exists() + if not (all(f.exists() and S.done(f) for f in files) and pack_done): + S.warn(f"{model} is not installed here, and an update does not download model files: nothing was installed") + S.say(f" to download and prepare {model}: ./setup.sh --setup") + elif vision == "yes" and not (models_root / fam["mmproj"]).exists(): + S.warn("the image encoder is not downloaded here, and an update does not download model files") + S.say(" to add image support: ./setup.sh --setup") return 0 # ---- 5. the model diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py index 92f2a596..463a9a72 100644 --- a/tools/test_setup_mac.py +++ b/tools/test_setup_mac.py @@ -389,6 +389,56 @@ class ControlMode(unittest.TestCase): self.assertIn('if sys.platform == "darwin" and CONTROL:', src) +class UpdateFlow(unittest.TestCase): + """update.sh asks the same questions as a setup run but does not download model files: a model chosen there must + be named, not dropped in silence (an M1 Max picked IQ3_S in update.sh and got no model and no message).""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.data = Path(self.tmp.name).resolve() / "data" + self.models = Path(self.tmp.name).resolve() / "own" + self.data.mkdir() + self.models.mkdir() + self.said, self.warned = [], [] + + def run_update(self, argv=("--update", "--model", "IQ3_S", "--vision", "no", "--yes")): + with mock.patch.object(M, "mac_configs", lambda: []), \ + mock.patch.object(M.S, "data_folder_for", lambda a: (self.data, [])), \ + mock.patch.object(M, "mac_info", lambda run=None: {"chip": "Apple M1 Max", "ram_gb": 32.0, + "macos": "26.6.2", "arm64": True, "clt": True}), \ + mock.patch.object(M, "mac_problems", lambda info: []), \ + mock.patch.object(M.S, "free_gb", lambda p: 200.0), \ + mock.patch.object(M.S, "step", lambda *a, **k: None), \ + mock.patch.object(M.S, "say", lambda *a, **k: self.said.append(" ".join(str(x) for x in a))), \ + mock.patch.object(M.S, "ok", lambda *a, **k: None), \ + mock.patch.object(M.S, "warn", lambda *a, **k: self.warned.append(" ".join(str(x) for x in a))), \ + mock.patch.object(M.S, "pip_install", lambda *a, **k: None), \ + mock.patch.object(M.S, "get_llama_cpp", lambda: self.data / "llama"), \ + mock.patch.object(M, "build_engine", lambda llama, jobs=None: self.data / "strata"), \ + mock.patch.object(M.S, "download", side_effect=AssertionError("an update must not download")): + return M.main([*argv, "--data-dir", str(self.data), "--gguf-dir", str(self.models)]) + + def test_a_model_chosen_in_an_update_is_named_not_dropped(self): + self.assertEqual(self.run_update(), 0) + self.assertIn("IQ3_S is not installed here", " ".join(self.warned)) + self.assertIn("does not download model files", " ".join(self.warned)) + self.assertIn("./setup.sh --setup", " ".join(self.said)) + + def test_an_installed_model_keeps_the_update_quiet(self): + for n in M.model_shard_names("IQ3_S"): + f = self.models / n + f.write_bytes(b"x") + f.with_name(f.name + ".done").write_text("whole") + tag = M.S.FAMILIES["qwen"]["tag"] + "IQ3_S" + pack = self.data / "packs" / tag.lower() + (pack / "tokenizer").mkdir(parents=True) + (pack / "native_experts.txt").write_text("x") + (pack / "tokenizer" / "vocab.json").write_text("{}") + self.assertEqual(self.run_update(), 0) + self.assertFalse([w for w in self.warned if "not installed here" in w], self.warned) + + class Source(unittest.TestCase): """setup.py hands a Mac over before its own parser runs, so the Mac parser has to know --source: source_hint() recommends it on every platform (#2363).""" From 7c9b6f3a28e84b81651e73b656e3eb8b240e8d17 Mon Sep 17 00:00:00 2001 From: cuijinkuo <39847058+cuijinkuo@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:22:31 +0100 Subject: [PATCH 059/177] MCP chat: opt-in mcp.image_results caches PNG/JPEG/WebP tool results beside the config, shows them in the web chat with an authenticated download and passes them to the vision reader (PR #2473 by cuijinkuo) --- .gitignore | 4 + docs/MCP_IMAGES.md | 25 ++++ serve/mcp.py | 62 ++++++++- serve/server.py | 48 ++++++- serve/test_mcp_media.py | 289 ++++++++++++++++++++++++++++++++++++++++ serve/web/app.css | 6 + serve/web/app.js | 45 ++++++- 7 files changed, 471 insertions(+), 8 deletions(-) create mode 100644 docs/MCP_IMAGES.md create mode 100644 serve/test_mcp_media.py diff --git a/.gitignore b/.gitignore index c6cfb336..88ad4c7b 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,10 @@ build-vision-cuda12.bat /.ccache/ /.rocm-win/ +# Optional MCP raster cache +*.tool-media/ +/.tool-media/ + # local Windows HIP packaging output dist-hip/ diff --git a/docs/MCP_IMAGES.md b/docs/MCP_IMAGES.md new file mode 100644 index 00000000..610558fe --- /dev/null +++ b/docs/MCP_IMAGES.md @@ -0,0 +1,25 @@ +# MCP raster images in the web chat + +Enable this optional feature with `"mcp": {"image_results": true}` in the run configuration (alongside existing MCP settings). The value must be a JSON boolean (`true` or `false`); strings and numbers are rejected. It is disabled by default; text-only tool output and stream event fields remain unchanged when disabled. + +MCP image results are cached by SHA-256 next to the run configuration, in `.tool-media/`. The web chat receives small same-origin references instead of embedding base64 in chat history. PNG, JPEG and WebP are supported; SVG and arbitrary file/resource URIs are not rendered. Each call displays at most four images, each with at most 24 million base64 characters (about 18 MB decoded). If the cache cannot be written, the chat retains the text result and logs the cache error. + +`GET /tool-media/.` uses the existing server API authentication, validates the basename, and serves only cached raster files. The web client fetches images with its existing authorization headers, displays them outside collapsed tool details, and provides a blob download link. The cache persists across server restarts; if its files are removed, older image references are replaced with an image-omitted text note when preparing later turns. Disabling the feature or removing MCP configuration does the same, while preserving the tool text and allowing the conversation to continue. Malformed references are still rejected. A global disk-retention policy is not implemented yet. + +When the server has a vision encoder, tool images enter its existing image preparation path. Subsequent browser turns send `strata-tool-media:` references; the authenticated server resolves these only inside its cache. With no vision encoder, images remain visible to the user and the model receives the existing text-only fallback. This adds image transport, not a vision model. + +Search and image generation are supplied by configured MCP servers. Strata does not bundle a paid search provider or a ComfyUI installation. Machine-specific adapters and lifecycle hooks are not included in this change. + +## Validation without a GPU + +```powershell +python -m unittest serve.test_mcp serve.test_mcp_media +node --check serve/web/app.js +git diff --check +``` + +The transport tests use an existing mock engine and scripted tool response. They verify authenticated binary delivery, invalid media rejection, path traversal refusal, streaming metadata, forwarding to vision preparation and subsequent-turn cache resolution. They do not establish visual understanding or generation quality. + +## Browser layout checks + +Use a configured image MCP fixture and the mock engine; no GPU is needed for the transport or layout check. Include a long tool name and long text result, and check a running call while Stop is visible. At viewport widths 320, 390, 640, 768 and 1280 pixels, the document must not be wider than the viewport and the preview must fit its chat bubble. Also expand tool details, reload the page, and check that the preview and download link return. A missing cache may remove the picture but must not prevent the next text turn. diff --git a/serve/mcp.py b/serve/mcp.py index 116251af..326249ec 100644 --- a/serve/mcp.py +++ b/serve/mcp.py @@ -19,6 +19,9 @@ breaking. from __future__ import annotations import collections +import base64 +import hashlib +from pathlib import Path import json import os import re @@ -34,7 +37,7 @@ import urllib.request from serve import lifeline PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given -DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0} +DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0, "image_results": False} class McpError(RuntimeError): @@ -486,6 +489,42 @@ def result_text(result: dict) -> str: return "\n".join(parts) +def cache_images(result, directory): + """Keep raster tool outputs outside chat history; never expose arbitrary tool paths.""" + images = [] + directory = Path(directory) + types = {"image/png": ("png", b"\x89PNG\r\n\x1a\n"), "image/jpeg": ("jpg", b"\xff\xd8\xff"), + "image/webp": ("webp", b"RIFF")} + for block in result.get("content") or []: + if not isinstance(block, dict): + continue + mime = block.get("mimeType") + if block.get("type") != "image" or mime not in types or len(images) >= 4: + continue + encoded = block.get("data") + if not isinstance(encoded, str) or len(encoded) > 24_000_000: + continue + try: + data = base64.b64decode(encoded, validate=True) + except (ValueError, TypeError): + continue + ext, magic = types[mime] + if not data.startswith(magic) or (ext == "webp" and data[8:12] != b"WEBP"): + continue + directory.mkdir(parents=True, exist_ok=True) + name = hashlib.sha256(data).hexdigest() + "." + ext + target = directory / name + if not target.exists(): + temporary = directory / (name + "." + os.urandom(8).hex() + ".tmp") + try: + temporary.write_bytes(data) + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + images.append({"url": "tool-media/" + name, "mimeType": mime, "name": "tool-image." + ext}) + return images + + def _clean(name: str) -> str: return re.sub(r"[^A-Za-z0-9_-]", "_", str(name)) or "x" @@ -494,6 +533,7 @@ class McpHub: """Every configured server, and the merged, namespaced tool list the model sees.""" def __init__(self, servers: dict[str, dict], settings: dict | None = None): + self.media_dir = None self.settings = {**DEFAULTS, **(settings or {})} self.servers = {name: McpServer(name, cfg, self.settings) for name, cfg in servers.items()} self.threads: list[threading.Thread] = [] @@ -560,6 +600,14 @@ class McpHub: res = server.call(tool, arguments if isinstance(arguments, dict) else {}, float(self.settings["timeout_s"]), cancel) text, ok = result_text(res), not res.get("isError") + if ok and self.settings["image_results"] and self.media_dir is not None: + try: + images = cache_images(res, self.media_dir) + except OSError as e: + print(f"[strata] MCP image cache unavailable: {e}", file=sys.stderr, flush=True) + else: + if images: + out["images"] = images if not ok: text = "error: " + (text or "the tool reported an error") except McpCancelled: @@ -571,6 +619,10 @@ class McpHub: if cap > 0 and full > cap: text = text[:cap] + (f"\n\n[... truncated: the tool returned {full:,} characters; only the first " f"{cap:,} are shown]") + if ok and out.get("images"): + out["model_content"] = [{"type": "text", "text": text.replace(": not shown to the model]", ": image attached]")}] + [ + {"type": "image", "source": str(Path(self.media_dir) / im["url"].split("/")[-1])} + for im in out["images"]] out.update(ok=ok, text=text, chars=full, truncated=cap > 0 and full > cap, ms=int((time.monotonic() - t0) * 1000)) return out @@ -627,11 +679,15 @@ def servers_from(block, where: str) -> dict[str, dict]: def settings_from(cfg: dict) -> dict: - """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s.""" + """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s, image_results.""" out = {} for key, value in (cfg.get("mcp") or {}).items(): number = isinstance(value, (int, float)) and not isinstance(value, bool) - if key in ("timeout_s", "start_timeout_s"): + if key == "image_results": + if not isinstance(value, bool): + raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a boolean") + out[key] = value + elif key in ("timeout_s", "start_timeout_s"): if not number or value <= 0: raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a number of seconds > 0") out[key] = float(value) diff --git a/serve/server.py b/serve/server.py index 2a7dc325..334fab8b 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4824,6 +4824,24 @@ class Service: prompt; with thinking, Service.run writes it once the thinking is over.""" # `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop # between pictures and raise ClientGone + # Cached tool images are references in browser history, never arbitrary file paths or huge base64 strings. + for message in messages: + for part in message.get("content", []) if isinstance(message.get("content"), list) else []: + source = part.get("source", "") if isinstance(part, dict) else "" + if isinstance(part, dict) and part.get("type") == "image" and isinstance(source, str) and source.startswith("strata-tool-media:"): + name = source[len("strata-tool-media:"):] + if not re.fullmatch(r"[0-9a-f]{64}\.(png|jpg|webp)", name): + raise ValueError("invalid tool image reference") + # Clients resend old tool results. A removed cache or disabled feature must not poison + # every later turn; keep the other text and replace only the unavailable picture. + media_dir = self.mcp.media_dir if self.mcp is not None else None + image = Path(media_dir) / name if media_dir is not None else None + if image is None or not image.is_file(): + why = "tool image cache is disabled" if image is None else "cached tool image is no longer available" + part.clear() + part.update(type="text", text=f"[image omitted: {why}]") + else: + part["source"] = str(image) fetched = self._note_unreadable_tool_images(messages, cancel) ids = encoded_ids = self.encode_prompt(messages, tools, kwargs) if force and kwargs.get("enable_thinking", True) is False: @@ -5787,8 +5805,10 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, r = box["r"] print(f"[strata] tool {c.name}: {'ok' if r['ok'] else 'error'}, {r['chars']:,} characters in " f"{r['ms'] / 1000:.1f} s{' (truncated for the model)' if r['truncated'] else ''}", flush=True) - results.append(r["text"]) - yield "mcp", {"event": "result", "id": c.id, **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}} + results.append(r.get("model_content", r["text"]) if svc.vision is not None else r["text"]) + yield "mcp", {"event": "result", "id": c.id, + **({"images": r["images"], "vision": svc.vision is not None} if r.get("images") else {}), + **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}} if cancel.is_set() or len(results) < len(calls): done = {**done, "finish": "cancel"} break @@ -6381,6 +6401,28 @@ def make_handler(svc: Service): def do_GET(self): path = self.path.split("?")[0].rstrip("/") + if path.startswith("/tool-media/"): + if not self._authorized(): + return + name = path[len("/tool-media/"):] + hub = svc.mcp + if not re.fullmatch(r"[0-9a-f]{64}\.(png|jpg|webp)", name) or not hub or not hub.media_dir: + self._json(404, {"error": {"message": "not found"}}) + return + file = Path(hub.media_dir) / name + if not file.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = file.read_bytes() + self.send_response(200) + self.send_header("Content-Type", {".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp"}[file.suffix]) + self.send_header("Content-Length", str(len(body))) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Cache-Control", "private, max-age=86400") + self.send_header("Cross-Origin-Resource-Policy", "same-origin") + self.end_headers() + self.wfile.write(body) + return if path.startswith("/fonts/"): # the web app's font (Outfit, OFL: serve/web/fonts); the page falls back to the system font name = path[len("/fonts/"):] @@ -8618,6 +8660,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in if hub is not None: import atexit svc.mcp = hub + if hub.settings["image_results"]: + hub.media_dir = Path(a.config).with_suffix(".tool-media") if a.config else Path.cwd() / ".tool-media" print(f"[strata] starting {len(hub.servers)} MCP server{'s' * (len(hub.servers) != 1)} for the web app's " f"chat: {', '.join(hub.servers)}", flush=True) hub.start() diff --git a/serve/test_mcp_media.py b/serve/test_mcp_media.py new file mode 100644 index 00000000..25a53bf3 --- /dev/null +++ b/serve/test_mcp_media.py @@ -0,0 +1,289 @@ +"""Raster MCP delivery: cache bounds, authenticated downloads and vision forwarding; no GPU.""" +import base64 +import json +import tempfile +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest.mock import patch +from serve.mcp import cache_images, hub_from_config +from serve.frontend import ChatTemplate, images_of +from serve.server import ByteTokenizer, Service, serve +from serve.test_mcp import ScriptedEngine, call_script +from serve import test_mcp as fixtures +PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jB0kAAAAASUVORK5CYII=') + +def image(data=PNG, mime='image/png'): + return {'type': 'image', 'mimeType': mime, 'data': base64.b64encode(data).decode()} + +class Configuration(unittest.TestCase): + def test_documented_switch_reaches_hub_and_tool_result(self): + hub = hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, + 'mcp': {'image_results': True}}) + self.assertTrue(hub.settings['image_results']) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + with tempfile.TemporaryDirectory() as tmp: + hub.media_dir = Path(tmp) + with patch.object(server, 'call', return_value={'content': [image()]}): + result = hub.call('fake__image', {}) + self.assertEqual(len(result['images']), 1) + self.assertEqual(result['model_content'][1]['type'], 'image') + + def test_disabled_and_omitted_switch_stay_off(self): + for settings in ({}, {'image_results': False}): + with self.subTest(settings=settings): + hub = hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, 'mcp': settings}) + self.assertFalse(hub.settings['image_results']) + + def test_switch_rejects_non_booleans(self): + for value in ('true', 'false', 0, 1, None, [], {}): + with self.subTest(value=value), self.assertRaisesRegex(SystemExit, 'expected a boolean'): + hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, + 'mcp': {'image_results': value}}) + +class Cache(unittest.TestCase): + + def test_image_text_obeys_result_cap(self): + from serve.mcp import McpHub + hub = McpHub({'fake': {'command': 'unused'}}, {'max_result_chars': 1000, 'image_results': True}) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + with tempfile.TemporaryDirectory() as tmp: + hub.media_dir = Path(tmp) + with patch.object(server, 'call', return_value={'content': [{'type': 'text', 'text': 'x' * 100000}, image()]}): + result = hub.call('fake__image', {}) + self.assertTrue(result['truncated']) + self.assertLessEqual(len(result['model_content'][0]['text']), len(result['text'])) + self.assertNotIn('x' * 1001, result['model_content'][0]['text']) + self.assertEqual(len(result['images']), 1) + + def test_disabled_is_identical_to_text_only_result(self): + from serve.mcp import McpHub, result_text + hub = McpHub({'fake': {'command': 'unused'}}) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + result = {'content': [{'type': 'text', 'text': 'hello'}, image()]} + with tempfile.TemporaryDirectory() as tmp: + hub.media_dir = Path(tmp) / 'unused' + with patch.object(server, 'call', return_value=result), patch('serve.mcp.cache_images') as cache: + output = hub.call('fake__image', {}) + cache.assert_not_called() + self.assertEqual(output['text'], result_text(result)) + self.assertNotIn('images', output) + self.assertNotIn('model_content', output) + self.assertFalse(hub.media_dir.exists()) + + def test_cache_failure_keeps_text_result(self): + from serve.mcp import McpHub + hub = McpHub({'fake': {'command': 'unused'}}, {'image_results': True}) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + hub.media_dir = Path('unused') + with patch.object(server, 'call', return_value={'content': [{'type': 'text', 'text': 'hello'}, image()]}), patch('serve.mcp.cache_images', side_effect=OSError('disk full')): + output = hub.call('fake__image', {}) + self.assertTrue(output['ok']) + self.assertIn('hello', output['text']) + self.assertNotIn('model_content', output) + + def test_null_and_non_object_content(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(cache_images({'content': None}, tmp), []) + self.assertEqual(cache_images({'content': [None, False, 'bad', image()]}, tmp), cache_images({'content': [image()]}, tmp)) + + def test_cache_deduplicates_and_preserves_bytes(self): + with tempfile.TemporaryDirectory() as tmp: + a = cache_images({'content': [image()]}, tmp) + b = cache_images({'content': [image()]}, tmp) + self.assertEqual(a, b) + self.assertEqual(len(list(Path(tmp).iterdir())), 1) + self.assertEqual((Path(tmp) / a[0]['url'].split('/')[-1]).read_bytes(), PNG) + + def test_rejects_invalid_and_active_content(self): + with tempfile.TemporaryDirectory() as tmp: + blocks = [image(b'not a PNG'), image(b'', 'image/svg+xml'), {'type': 'image', 'mimeType': 'image/png', 'data': '***'}] + self.assertEqual(cache_images({'content': blocks}, tmp), []) + + def test_caps_images_per_result(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(len(cache_images({'content': [image()] * 8}, tmp)), 4) + + def test_authenticated_download_and_traversal(self): + with tempfile.TemporaryDirectory() as tmp: + media = cache_images({'content': [image()]}, tmp)[0] + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + + class Hub: + media_dir = tmp + svc.mcp = Hub() + svc.api_key = 'test-key' + httpd = serve(svc, port=0) + base = f'http://127.0.0.1:{httpd.server_address[1]}/' + try: + with self.assertRaises(urllib.error.HTTPError) as error: + urllib.request.urlopen(base + media['url']) + self.assertEqual(error.exception.code, 401) + req = urllib.request.Request(base + media['url'], headers={'Authorization': 'Bearer test-key'}) + with urllib.request.urlopen(req) as response: + self.assertEqual(response.read(), PNG) + self.assertEqual(response.headers['Content-Type'], 'image/png') + req = urllib.request.Request(base + 'tool-media/../../secret.png', headers={'Authorization': 'Bearer test-key'}) + with self.assertRaises(urllib.error.HTTPError) as error: + urllib.request.urlopen(req) + self.assertEqual(error.exception.code, 404) + finally: + httpd.shutdown() + httpd.server_close() + +class HistoryReferences(unittest.TestCase): + + def test_reference_resolves_only_to_cache(self): + with tempfile.TemporaryDirectory() as tmp: + im = cache_images({'content': [image()]}, tmp)[0] + name = im['url'].split('/')[-1] + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + + class Hub: + media_dir = tmp + svc.mcp = Hub() + message = [{'role': 'tool', 'content': [{'type': 'image', 'source': 'strata-tool-media:' + name}]}] + with patch.object(svc, '_note_unreadable_tool_images', return_value={}): + with self.assertRaisesRegex(ValueError, 'without the vision encoder'): + svc.prepare(message, [], {}, 16) + self.assertEqual(images_of(message), [str(Path(tmp) / name)]) + + def test_mixed_missing_and_valid_pictures_keeps_valid_vision(self): + with tempfile.TemporaryDirectory() as tmp: + media = cache_images({'content': [image()]}, tmp)[0] + source = str(Path(tmp) / media['url'].split('/')[-1]) + rows = Path(tmp) / 'img.sve' + rows.write_bytes(b'rows') + class Vision: + dir = Path(tmp) + + def encode(self, value): + if value != source: + raise AssertionError('Only the valid cached image may reach the encoder') + return rows, 3 + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, + ChatTemplate(Path(__file__).parent / 'chat_template.jinja'), vision=Vision()) + class Hub: + media_dir = tmp + svc.mcp = Hub() + messages = [{'role': 'tool', 'content': [ + {'type': 'text', 'text': 'Retain this text.'}, + {'type': 'image', 'source': 'strata-tool-media:' + '0' * 64 + '.png'}, + {'type': 'image', 'source': 'strata-tool-media:' + media['url'].split('/')[-1]}]}] + try: + ids, _, _ = svc.prepare(messages, [], {}, 16) + prompt = tok.decode(ids) + self.assertIn('Retain this text.', prompt) + self.assertIn('[image omitted:', prompt) + self.assertEqual(images_of(messages), [source]) + self.assertEqual(ids.count(tok.encode('<|image_pad|>', parse_special=True)[0]), 3) + finally: + if svc.embeddings.path: + svc.embeddings.path.unlink(missing_ok=True) + + def test_bad_reference_cannot_read_other_files(self): + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + with self.assertRaisesRegex(ValueError, 'invalid tool image reference'): + svc.prepare([{'role': 'tool', 'content': [{'type': 'image', 'source': 'strata-tool-media:../../secret.png'}]}], [], {}, 16) + +class ImageLoop(unittest.TestCase): + setUp = fixtures.ToolLoop.setUp + tearDown = fixtures.ToolLoop.tearDown + start = fixtures.ToolLoop.start + post = fixtures.ToolLoop.post + chunks = staticmethod(fixtures.ToolLoop.chunks) + + def check_stale_history(self, state): + self.start('\n\nText reply survives.') + with tempfile.TemporaryDirectory() as tmp: + self.hub.media_dir = Path(tmp) if state == 'missing' else None + if state == 'no_hub': + self.svc.mcp = None + history = [ + {'role': 'user', 'content': 'Create a picture'}, + {'role': 'assistant', 'content': '', 'tool_calls': [ + {'id': 'old', 'type': 'function', 'function': {'name': 'fake__echo', 'arguments': '{}'}}]}, + {'role': 'tool', 'tool_call_id': 'old', 'content': [ + {'type': 'text', 'text': 'Keep this original tool text.'}, + {'type': 'image_url', 'image_url': {'url': 'strata-tool-media:' + '0' * 64 + '.png'}}]}, + {'role': 'user', 'content': 'Continue with text only'}] + # API clients resend the original unmodified history on every later turn. + for turn in range(2): + for stream in (False, True): + with self.subTest(state=state, turn=turn, stream=stream): + code, text = self.post({'messages': history}, stream=stream) + self.assertEqual(code, 200, text) + if stream: + answer = ''.join(c['choices'][0]['delta'].get('content', '') for c in self.chunks(text)) + else: + answer = json.loads(text)['choices'][0]['message']['content'] + self.assertIn('Text reply survives.', answer) + prompt = self.engine.prompt_text(turn * 2 + int(stream)) + self.assertIn('Keep this original tool text.', prompt) + self.assertIn('[image omitted:', prompt) + self.assertNotIn('strata-tool-media:', prompt) + + def test_missing_cache_history_continues_across_turns(self): + self.check_stale_history('missing') + + def test_disabled_cache_history_continues_across_turns(self): + self.check_stale_history('disabled') + + def test_removed_mcp_history_continues_across_turns(self): + self.check_stale_history('no_hub') + + def test_malformed_history_still_rejected_over_http(self): + self.start('\n\nShould not run.') + self.svc.mcp = None + for name in ('../../secret.png', 'a' * 64 + '.svg', 'A' * 64 + '.png', 'short.png'): + with self.subTest(name=name): + code, text = self.post({'messages': [{'role': 'tool', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'strata-tool-media:' + name}}]}]}, stream=False) + self.assertEqual(code, 400) + self.assertIn('invalid tool image reference', text) + self.assertEqual(self.engine.prompts, []) + + def test_default_stream_has_no_image_fields(self): + self.start(call_script('fake__echo', text='hello'), '\n\nDone.') + code, text = self.post({'strata_mcp': True}) + self.assertEqual(code, 200) + event = [c['strata_mcp'] for c in self.chunks(text) if c.get('strata_mcp', {}).get('event') == 'result'][0] + self.assertEqual(set(event), {'event', 'id', 'ok', 'text', 'chars', 'truncated', 'ms'}) + + def test_image_result_streams_and_reaches_vision_prepare(self): + with tempfile.TemporaryDirectory() as tmp: + self.hub.settings['image_results'] = True + self.hub.media_dir = Path(tmp) + im = cache_images({'content': [image()]}, tmp) + source = str(Path(tmp) / im[0]['url'].split('/')[-1]) + self.start(call_script('fake__echo', text='picture'), '\n\nImage received.') + self.svc.vision = object() + native = self.svc.prepare + seen = [] + + def prepare(messages, *args, **kwargs): + seen.extend(images_of(messages)) + clean = [{**m, 'content': 'image delivered'} if isinstance(m.get('content'), list) else m for m in messages] + return native(clean, *args, **kwargs) + result = {'ok': True, 'text': 'image delivered', 'chars': 15, 'truncated': False, 'ms': 1, 'images': im, 'model_content': [{'type': 'text', 'text': 'image delivered'}, {'type': 'image', 'source': source}]} + with patch.object(self.hub, 'call', return_value=result), patch.object(self.svc, 'prepare', side_effect=prepare): + code, text = self.post({'strata_mcp': True}) + self.assertEqual(code, 200) + self.assertIn(source, seen) + events = [c['strata_mcp'] for c in self.chunks(text) if 'strata_mcp' in c] + self.assertEqual(events[-1]['images'], im) + answer = ''.join((c['choices'][0]['delta'].get('content', '') for c in self.chunks(text))) + self.assertIn('Image received.', answer) diff --git a/serve/web/app.css b/serve/web/app.css index f9bad8cc..de457cc7 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -197,3 +197,9 @@ main { flex: 1; min-height: 0; display: flex; } .img-results figure{margin:0} .img-results img{max-width:100%;border-radius:var(--st-r-lg);display:block} .img-results figcaption{font-size:var(--st-fs-sm, 13px);color:var(--st-ink-2, inherit);margin-top:4px} + +/* Raster MCP results remain visible outside the collapsed tool details. */ +.tool-image { margin: 16px 0; max-width: 100%; } +.tool-image img { display: block; width: 100%; max-width: 640px; height: auto; border-radius: var(--st-r-md); } +.tool-image figcaption { margin-top: 10px; } +.tool-image a:not([href]) { opacity: .5; pointer-events: none; } diff --git a/serve/web/app.js b/serve/web/app.js index d01ff297..86fb16a8 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -658,6 +658,38 @@ function toolHtml(t, k) { `${esc(label)}${t.ms != null && t.state !== "skipped" ? `${fmt(t.ms / 1000, 1)} s` : ""}` + `${icon("chevron", "st-icon st-icon--sm st-chev")}
${body}
`; } +// Raster tool results are same-origin cached files; credentials stay in request headers. +const mediaBlobs = new Map(); +let mediaEpoch = 0; +function clearToolMedia() { + mediaEpoch++; + for (const pending of mediaBlobs.values()) pending.then((url) => URL.revokeObjectURL(url), () => {}); + mediaBlobs.clear(); +} +window.addEventListener("pagehide", clearToolMedia); +window.addEventListener("pageshow", (event) => { if (event.persisted) hydrateToolImages(document); }); +function safeToolMedia(url) { return typeof url === "string" && /^tool-media\/[0-9a-f]{64}\.(png|jpg|webp)$/.test(url); } +function toolImages(t) { + return (t.images || []).filter((im) => safeToolMedia(im.url)).map((im) => + `
Tool image` + + `
Download image
`).join(""); +} +function hydrateToolImages(root) { + root.querySelectorAll("[data-tool-image]").forEach((img) => { + const url = img.dataset.toolImage, epoch = mediaEpoch; + if (!safeToolMedia(url)) return; + if (!mediaBlobs.has(url)) mediaBlobs.set(url, fetch(url, {headers: headers()}).then((r) => { + if (!r.ok) throw new Error("Image unavailable"); + return r.blob(); + }).then((b) => URL.createObjectURL(b)).catch((e) => {if (epoch === mediaEpoch) mediaBlobs.delete(url); throw e;})); + mediaBlobs.get(url).then((blob) => { + if (epoch !== mediaEpoch || !img.isConnected) return; + img.src = blob; + const a = img.closest("figure").querySelector("[data-tool-download]"); + a.href = blob; + }).catch(() => { img.alt = "Image unavailable; try refreshing"; }); + }); +} // the answer's text with the tool blocks where the model called them function answerHtml(m) { if (!m.tools || !m.tools.length) return markdown(m.text || ""); @@ -666,7 +698,7 @@ function answerHtml(m) { const at = Math.min(Math.max(t.at || 0, pos), m.text.length); if (at > pos) html += markdown(m.text.slice(pos, at)); pos = at; - html += toolHtml(t, k); + html += toolHtml(t, k) + toolImages(t); }); return html + markdown(m.text.slice(pos)); } @@ -679,7 +711,7 @@ function onTool(m, x) { if (x.event === "call") { Object.assign(t, {name: x.name, server: x.server, tool: x.tool, arguments: x.arguments, round: x.round, state: "running"}); } else if (x.event === "result") { - Object.assign(t, {result: x.text, ok: x.ok, chars: x.chars, truncated: x.truncated, ms: x.ms, + Object.assign(t, {result: x.text, ok: x.ok, chars: x.chars, truncated: x.truncated, ms: x.ms, images: x.images || [], vision: x.vision === true, state: x.skipped ? "skipped" : x.ok ? "done" : "error"}); } } @@ -705,6 +737,7 @@ function updateAssistant(el, m, streaming) { bubble.innerHTML = m.reasoning ? `Writing` : ``; } else { bubble.innerHTML = answerHtml(m); + hydrateToolImages(bubble); if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor"); } el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? "Stopped" : ""); @@ -805,7 +838,12 @@ function assistantMessages(m) { const at = Math.min(Math.max(pos, calls[0].at || 0), m.text.length); out.push({role: "assistant", content: m.text.slice(pos, at).trim(), tool_calls: calls.map((t) => ({id: t.id, type: "function", function: {name: t.name, arguments: JSON.stringify(t.arguments || {})}}))}); - for (const t of calls) out.push({role: "tool", tool_call_id: t.id, content: t.result}); + for (const t of calls) { + const pictures = t.vision ? (t.images || []).filter((im) => safeToolMedia(im.url)) : []; + const content = pictures.length ? [{type: "text", text: t.result}, ...pictures.map((im) => + ({type: "image_url", image_url: {url: "strata-tool-media:" + im.url.split("/").pop()}}))] : t.result; + out.push({role: "tool", tool_call_id: t.id, content}); + } pos = at; } const rest = m.text.slice(pos).trim(); @@ -931,6 +969,7 @@ $("new-btn").onclick = () => { if (busy) { toast("warn", "Still writing", "Stop the answer first."); return; } if (!messages.length) return; const backup = messages; + clearToolMedia(); messages = []; saveChat(); renderChat(); From 3cda075b5152f854634c9cdd41e5cc5977ca3c47 Mon Sep 17 00:00:00 2001 From: xxxliqu1dxxx <83290244+xxxliqu1dxxx@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:23:22 +0100 Subject: [PATCH 060/177] setup (AMD, Linux): the engine probes get the engine's lib_dirs on LD_LIBRARY_PATH (#3305) engine_env put the ROCm library folders first on PATH, which only Windows' loader reads. On AMD Linux strata --families exited 127 on libhipblas.so.3, so setup falsely said the engine does not run Qwen3.6. On Linux and elsewhere the folders now go first on LD_LIBRARY_PATH (an existing value is kept); Windows keeps PATH. Ported from PR #3305 by xxxliqu1dxxx (resubmission of #2914), with its tests. --- setup.py | 10 +++++++--- tools/test_setup_amd.py | 20 ++++++++++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index 0213d6c4..c1a06ab6 100644 --- a/setup.py +++ b/setup.py @@ -4197,12 +4197,16 @@ def amd_gpus_windows(adapters=None, registry=None) -> list[dict]: def engine_env(eng: Path) -> dict: """The environment for running an installed engine's own programs (`strata --families`, `strata-device - --list-devices`): the ready-made Windows HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin, which the - loader finds through PATH only (#2372: a launch without it shows a "not found" dialog per DLL and prints nothing).""" + --list-devices`): the engine's ROCm library folders (its BUILD.json "lib_dirs") first on the dynamic-library path - + on Windows that is PATH, where the ready-made HIP engine keeps hipblas.dll / libhipblaslt.dll in its rocm/bin and the + loader finds them only through PATH (#2372: a launch without it shows a "not found" dialog per DLL and prints + nothing); on Linux and elsewhere it is LD_LIBRARY_PATH, where a probe without it exits 127 on libhipblas.so.3 and + prints nothing.""" env = dict(os.environ) dirs = [str(d) for d in hip_lib_dirs(eng)] if dirs: - env["PATH"] = os.pathsep.join(dirs + [env.get("PATH", "")]) + var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) return env diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index cd853654..fa2847b5 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -675,14 +675,25 @@ class EngineLaunchEnv(unittest.TestCase): (eng / "BUILD.json").write_text('{"backend": "hip", "lib_dirs": ["rocm/bin"]}', encoding="utf-8") return eng - def test_engine_env_puts_rocm_bin_first(self): + def test_engine_env_puts_rocm_bin_first_on_windows(self): with tempfile.TemporaryDirectory() as t: eng = self.engine(Path(t)) - with mock.patch.dict("os.environ", {"PATH": "C:\\Windows"}): + with mock.patch.dict("os.environ", {"PATH": "C:\\Windows"}), \ + mock.patch.object(setup.os, "name", "nt"): env = setup.engine_env(eng) self.assertEqual(env["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) self.assertTrue(env["PATH"].endswith("C:\\Windows")) + def test_engine_env_puts_rocm_bin_first_on_ld_library_path(self): + with tempfile.TemporaryDirectory() as t: + eng = self.engine(Path(t)) + with mock.patch.dict("os.environ", {"PATH": "/usr/bin", "LD_LIBRARY_PATH": "/usr/lib"}), \ + mock.patch.object(setup.os, "name", "posix"): + env = setup.engine_env(eng) + self.assertEqual(env["LD_LIBRARY_PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) + self.assertTrue(env["LD_LIBRARY_PATH"].endswith("/usr/lib")) + self.assertEqual(env["PATH"], "/usr/bin") + def test_engine_without_lib_dirs_keeps_the_environment(self): with tempfile.TemporaryDirectory() as t: with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}): @@ -696,7 +707,8 @@ class EngineLaunchEnv(unittest.TestCase): return mock.Mock(stdout="qwen4exp qwen35moe\n") with tempfile.TemporaryDirectory() as t: eng = self.engine(Path(t)) - with mock.patch.object(setup.subprocess, "run", fake_run): + with mock.patch.object(setup.subprocess, "run", fake_run), \ + mock.patch.object(setup.os, "name", "nt"): names = setup.engine_families(eng) self.assertEqual(names, {"qwen4exp", "qwen35moe"}) self.assertEqual(seen["cmd"][1], "--families") @@ -712,7 +724,7 @@ class EngineLaunchEnv(unittest.TestCase): eng = self.engine(Path(t)) probe = eng / ("strata-device.exe" if setup.WIN else "strata-device") probe.write_text("x") - with mock.patch.object(setup.subprocess, "run", fake_run), mock.patch.object(setup, "hip_runtime_beside_exe", lambda d: None): + with mock.patch.object(setup.subprocess, "run", fake_run), mock.patch.object(setup, "hip_runtime_beside_exe", lambda d: None), mock.patch.object(setup.os, "name", "nt"): found = setup.hip_devices(probe) self.assertEqual(found[0]["arch"], "gfx1100") self.assertEqual(seen["env"]["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin")) From bc939b6303e23b5e8693a8430ba46a054b394b45 Mon Sep 17 00:00:00 2001 From: Patrick Schaub <11846736+pschaub@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:23:38 +0100 Subject: [PATCH 061/177] docs/SAFETY.md: strata launch updates an installed DeepSeek engine package by itself (#4028, #4022) The page said that starting a model never downloads and that nothing checks for updates in the background. Since 0.2.4.2 strata launch with a DeepSeek model checks the signed feed (10 s at most, silent without a connection) and replaces an older installed DeepSeek engine package. Ported from PR #4028 by pschaub (wording from issue #4022), checked against strata_cli/launch/runner.py upgrade_dsv41_engine. --- docs/SAFETY.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/SAFETY.md b/docs/SAFETY.md index e377f355..43412633 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -10,11 +10,13 @@ you trust can check it. Where Strata does less than you might hope, the page say outside model service, you open the server to other devices or to the internet, or the agent searches the web or opens a page (see [What the agent can do](#what-the-coding-agent-can-do-on-your-pc)). - **There is no telemetry.** Strata sends no usage data, no crash reports and no analytics, and has no account to sign in to. -- **Starting and running a model never downloads anything.** Downloads and updates are separate steps that you start. +- **Starting and running a model never downloads anything**, except that `strata launch` updates an installed DeepSeek + engine package by itself when the signed feed has a newer one (below). Other downloads and updates are steps that you start. - **The server listens on your PC only.** Reaching it from another device needs an API key. - **Once a model is downloaded, Strata runs without internet.** Starting, loading, serving and chatting need no connection. Only things you ask for use it: the agent's web search and web pages, an outside model service, the tunnel, - and installs and updates (a first model install also fetches llama.cpp's preparation scripts). + and installs and updates (a first model install also fetches llama.cpp's preparation scripts), plus the DeepSeek engine + check of `strata launch` (without a connection it gives up after at most 10 s and the launch goes on). - **Downloads are checked.** Updates come from a signed feed. Every model file has a fixed SHA-256 and size, and an install stops if the pinned version of a file is gone (the details are [below](#how-downloads-are-checked)). - **In its default mode the coding agent asks before it changes anything**, and once per chat before its first web search or web page. @@ -44,7 +46,7 @@ Like any download, each connection below shows the other side your IP address an | --- | --- | --- | | Model files, the picture reader, the speed-up layer (MTP) | huggingface.co, or the mirror in `HF_ENDPOINT` if you set one | When you install a model | | The same files from ModelScope, for PCs that cannot reach Hugging Face | modelscope.cn | Only if you ask for it (`--source modelscope`). Strata never switches to it by itself | -| Engine, Terminal and Control updates | The signed feed on GitHub Releases of Niko1221/Strata | When you install an engine, press **Update engine** or **Check for updates**, or run `strata update`. Opening **Settings, Engine** does not connect: it shows the result of your last check | +| Engine, Terminal and Control updates | The signed feed on GitHub Releases of Niko1221/Strata | When you install an engine, press **Update engine** or **Check for updates**, or run `strata update`; the DeepSeek engine also on `strata launch` (below). Opening **Settings, Engine** does not connect: it shows the result of your last check | | App updates | `latest.json` on the same GitHub Releases, through Tauri's updater | When you press **Check for updates** or **Update Strata** | | llama.cpp source code (a fixed commit) | github.com/ggml-org/llama.cpp | During a model install, if it is not on your PC yet. Strata uses only its model-preparation scripts | | Web search and web pages | DuckDuckGo, with Bing as the second source; or Exa, Perplexity or DeepSeek if you save a key for them. Any page the agent is asked to open goes to that page's site | When the agent uses its search or "open web pages" tool. In Manual mode it asks you first, once per chat | @@ -61,7 +63,11 @@ That is the full list found in the code. Some details: - **Nothing checks for updates in the background.** The app does not check when it starts, and not when you open Settings, Engine either: that screen shows the result of your last check, or nothing if you have not checked. The checks in the table run when you press a button or run a command. With no connection, the check says so and nothing else happens. The Terminal fetches an engine by itself only when none is - installed, and `strata launch` asks first. + installed, and `strata launch` asks first. One exception: `strata launch` with a DeepSeek model first checks whether the + signed feed can be reached (at most 10 s; without a connection it says nothing and goes on), then reads it, and when it has + a newer DeepSeek engine package for this PC, fetches and checks it, starts it once (`--version`), switches to it and removes + the older one. On a failure the installed one keeps running. Not when the launch is given `--dsv41-package` or + `STRATA_DSV41_EXE` is set (`strata_cli/launch/runner.py`, `upgrade_dsv41_engine`). - **Starting and serving never download.** `strata serve` and the app's load button fetch nothing. The app sets `STRATA_PACKAGED=1` and `STRATA_NO_ACQUIRE=1` for its parts (`apps/desktop/src-tauri/src/main.rs`), and the downloaders refuse to run under them (`strata_control/acquisition.py`, `apps/host/server/acquisition.mjs`). That is why the app From 9a0462a011acccaffae53784494313c691fbac14 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:24:01 +0100 Subject: [PATCH 062/177] Chat: sending a message still scrolls to it when the reader had scrolled up (#4014) --- apps/host/src/screens/Chat.tsx | 7 ++++++- apps/host/tests/follow-scroll.test.mjs | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 385c3acc..3fbc90d3 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -215,6 +215,7 @@ export function ChatScreen() { const pinned = useRef(true); /** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */ const readerInput = useRef(0); + const messageCount = useRef(0); /** * Scrolls to the newest message and stays there. * @@ -271,7 +272,11 @@ export function ChatScreen() { return; // The reader's own scrolling decides (#4014): a wheel notch is about 100 px and used to land inside a 120 px band that pulled // the view back on every token. `pinned` is set by the scroller's wheel, touch, key and scroll handlers below. - if (pinned.current) + const count = session?.messages.length ?? 0; + const sent = count > messageCount.current && session?.messages.at(-1)?.role === 'user'; + messageCount.current = count; + // Sending a message always brings the reader to it, as it did before; only the answer's growth waits for the reader. + if (pinned.current || sent) scrollToLatest(); }, [session?.messages.length, session?.messages.at(-1)?.content, scrollToLatest]); // Scroll position is remembered per conversation, so returning to one puts you diff --git a/apps/host/tests/follow-scroll.test.mjs b/apps/host/tests/follow-scroll.test.mjs index e724696a..1fdc95fe 100644 --- a/apps/host/tests/follow-scroll.test.mjs +++ b/apps/host/tests/follow-scroll.test.mjs @@ -34,6 +34,8 @@ test('the chat screen uses the reader-driven rule, not the 120 px band', async ( assert.doesNotMatch(chat, /clientHeight < 120/); assert.match(chat, /followAfterScroll\(/); assert.match(chat, /onWheel=/); + // sending a message still brings the reader to it, even from far up + assert.match(chat, /pinned\.current \|\| sent/); // an upward wheel on a transcript that cannot scroll must not switch following off assert.match(chat, /wheelLeavesBottom\(e\.deltaY\) && e\.currentTarget\.scrollTop > 0/); }); From 800730103c67fe6c1159c3e01d01bab388ec55b8 Mon Sep 17 00:00:00 2001 From: ctr-137 <343917439+ctr-137@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:24:35 +0100 Subject: [PATCH 063/177] tools/strata_bench.py: the redactor replaces a folder before the short user name inside it (#3619, #3326) Substitutions were ordered by the length of their regular expression, and a user name wrapped in word bounds outranked the Strata or home folder that contains it, so a report kept /home//Strata instead of . They are now ordered by the text they replace. Ported from PR #3619 by ctr-137 with its test (Linux and Windows layouts). --- tools/strata_bench.py | 8 ++++---- tools/test_strata_bench.py | 26 +++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 0bb0711d..be0e39cf 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -68,14 +68,14 @@ BURST_MAX_TOKENS = 128 def redactor(extra: list[str] = (), key: str = ""): """-> f(text) -> text with this machine's home folders, user and host names, the Strata folder, IP addresses and the API key replaced. Applied to everything that is written or printed from the server's or the machine's own text.""" - subs: list[tuple[re.Pattern, str]] = [] + subs: list[tuple[re.Pattern, str, int]] = [] def add(value, label, word=False): if value and len(str(value)) >= 4: v = str(value) for form in sorted({v, v.replace("\\", "/"), v.replace("/", "\\")}, key=len, reverse=True): pat = re.escape(form) - subs.append((re.compile(r"(?") add(Path.home(), "") @@ -89,7 +89,7 @@ def redactor(extra: list[str] = (), key: str = ""): for x in extra: add(x, "", True) add(key, "") - subs.sort(key=lambda p: -len(p[0].pattern)) + subs.sort(key=lambda s: -s[2]) # by the text that is replaced: the word wrappers would make a short user name outrank the folder holding it path_user = re.compile(r"(?i)([A-Za-z]:)?([\\/])(Users|home)([\\/])(?!<)[^\\/\s\"':;,]+") ip4 = re.compile(r"\b(?:192\.168|10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])|169\.254)\.\d{1,3}\.\d{1,3}\b") bearer = re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}") @@ -97,7 +97,7 @@ def redactor(extra: list[str] = (), key: str = ""): def f(text): if not isinstance(text, str): return text - for pat, label in subs: + for pat, label, _ in subs: text = pat.sub(label, text) text = path_user.sub(lambda m: f"{m.group(1) or ''}{m.group(2)}{m.group(3)}{m.group(4)}", text) text = bearer.sub(r"\1", text) diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 986ab1a3..80babc65 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -12,7 +12,7 @@ import threading import unittest from unittest import mock from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path +from pathlib import Path, PurePosixPath, PureWindowsPath sys.path.insert(0, str(Path(__file__).resolve().parent)) import strata_bench as B # noqa: E402 @@ -186,6 +186,30 @@ class RedactionTests(unittest.TestCase): if len(user) >= 4: self.assertNotIn(user, red(f"hello {user} world")) + def test_a_folder_under_a_short_home_keeps_its_own_placeholder(self): + # issue #3326 with a fixed machine (user name "dgbox", the repository directly under the home folder): + # a name is wrapped in word bounds, which makes its pattern longer than the pattern of the folder + # holding it, so the name won and the report kept the folder layout instead of and . + def red(root, home, user, host, tmp): + with mock.patch.object(B, "ROOT", root), mock.patch.object(B.Path, "home", return_value=home), \ + mock.patch.object(B.getpass, "getuser", return_value=user), \ + mock.patch.object(B.socket, "gethostname", return_value=host), \ + mock.patch.object(B.platform, "node", return_value=host), \ + mock.patch.object(B.tempfile, "gettempdir", return_value=tmp): + return B.redactor() + + linux = red(PurePosixPath("/home/dgbox/Strata"), PurePosixPath("/home/dgbox"), "dgbox", "dgbox-ubuntu-server", "/tmp") + self.assertEqual(linux("loading /home/dgbox/Strata/strata-x.json"), "loading /strata-x.json") + self.assertEqual(linux("dgbox-ubuntu-server wrote /home/dgbox/Strata/bench/results/run/results.json"), + " wrote /bench/results/run/results.json") + self.assertEqual(linux("in /home/dgbox/data"), "in /data") + self.assertEqual(linux("hello dgbox world"), "hello world") + self.assertEqual(linux("log /tmp/strata.log"), "log /strata.log") + win = red(PureWindowsPath(r"C:\Users\dgbox\Strata"), PureWindowsPath(r"C:\Users\dgbox"), "dgbox", "dgbox-pc", + r"C:\Users\dgbox\AppData\Local\Temp") + self.assertEqual(win(r"in C:\Users\dgbox\data"), r"in \data") + self.assertEqual(win(r"loading C:\Users\dgbox\Strata\strata-x.json"), r"loading \strata-x.json") + def test_objects_are_redacted_deeply(self): red = B.redactor() out = B.redact_obj({"a": [{"p": r"D:\Users\zed\x"}], "n": 3}, red) From 1be7eb77c1757e5a49a359007f8d5020292e6d46 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:25:25 +0100 Subject: [PATCH 064/177] tests: the setup golden compares the platform's vision binary names, and test_nvfp4_local_pack skips without pytest (#3325) tools/test_setup_golden normalized strata.exe but not strata-vision.exe, so all 25 baseline entries failed on Linux (48 subtests). VEXE and HVEXE are mapped to and like EXE, and the baseline records . test_nvfp4_local_pack imports pytest, which is not in requirements.txt; under python -m unittest discover the module is now skipped with a reason instead of failing to import. --- tools/test_nvfp4_local_pack.py | 7 ++++- tools/test_setup_golden.json | 50 +++++++++++++++++----------------- tools/test_setup_golden.py | 6 +++- 3 files changed, 36 insertions(+), 27 deletions(-) diff --git a/tools/test_nvfp4_local_pack.py b/tools/test_nvfp4_local_pack.py index 6d85b619..dd6fbe32 100644 --- a/tools/test_nvfp4_local_pack.py +++ b/tools/test_nvfp4_local_pack.py @@ -3,7 +3,12 @@ import pathlib import sys import numpy as np -import pytest +import unittest + +try: + import pytest +except ImportError: # not in requirements.txt: python -m unittest skips this module instead of failing to import it (#3325) + raise unittest.SkipTest("pytest is not installed") sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) import nvfp4_local_pack as P # noqa: E402 diff --git a/tools/test_setup_golden.json b/tools/test_setup_golden.json index e4e654c2..284c0a92 100644 --- a/tools/test_setup_golden.json +++ b/tools/test_setup_golden.json @@ -43,7 +43,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -95,7 +95,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -147,7 +147,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -199,7 +199,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -253,7 +253,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -313,7 +313,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -373,7 +373,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -433,7 +433,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -493,7 +493,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -550,7 +550,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -608,7 +608,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -667,7 +667,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -725,7 +725,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -784,7 +784,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -840,7 +840,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -891,7 +891,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -943,7 +943,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -995,7 +995,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1045,7 +1045,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1098,7 +1098,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": true, "max_tokens": 1024, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1148,7 +1148,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1199,7 +1199,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_xxs/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1250,7 +1250,7 @@ "port": 8080, "tokenizer": "/data/packs/q2_0/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1301,7 +1301,7 @@ "port": 8080, "tokenizer": "/data/packs/iq3_s/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", @@ -1354,7 +1354,7 @@ "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", "vision": { - "exe": "/engine/strata-vision.exe", + "exe": "/engine/", "gpu": false, "max_tokens": 300, "mmproj": "/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index eb940cee..2ac754e3 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -56,7 +56,11 @@ def normalize(v, t: Path): if isinstance(v, list): return [normalize(x, t) for x in v] if isinstance(v, str): - return re.sub(rf"(?", v.replace(str(t), "").replace("\\", "/")) # #973: only the whole name, not "strata-x.log" on Linux + v = v.replace(str(t), "").replace("\\", "/") + # the platform's own names of the programs (strata.exe or strata, strata-vision.exe or strata-vision, ...) so the baseline compares on Windows and Linux (#3325) + for name, label in ((setup.HVEXE, ""), (setup.VEXE, ""), (setup.EXE, "")): + v = re.sub(rf"(? Date: Mon, 26 Oct 2026 18:26:18 +0100 Subject: [PATCH 065/177] sycl/tools/build.sh exits with the build's own status (#2990) The script ended with a grep pipeline, so a failed compile exited 0 (and, before the ocloc check was added at the end, a good build exited 1). A build.sh && next-step chain then ran after a failure. The status of cmake --build is kept and the script exits with it. The test runs the real script with a stub cmake on PATH (good build: 0, failed compile: 1; the old script exits 0 on the failed compile). --- docs/A770_SPEED_SPEC.md | 7 +-- sycl/tools/build.sh | 4 +- tests/terminal/test_sycl_build_script.py | 74 ++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_sycl_build_script.py diff --git a/docs/A770_SPEED_SPEC.md b/docs/A770_SPEED_SPEC.md index 14ea3398..66fa7e10 100644 --- a/docs/A770_SPEED_SPEC.md +++ b/docs/A770_SPEED_SPEC.md @@ -445,10 +445,9 @@ docker run --rm -u "$(id -u):$(id -g)" -v "$PWD/..:/work" strata-sycl-dev \ cmake --build /work/strata-v0.1.40.3/build-sycl --target strata -j 8" ``` -Use the actual `cmake --build` exit status: `sycl/tools/build.sh` currently -prints `BUILD EXIT 0` but can itself return nonzero because its last failure- -search pipeline finds no failures. Do not chain tests behind that misleading -script status. +Use the actual `cmake --build` exit status. `sycl/tools/build.sh` from 0.2.7 on exits with it; older copies +printed `BUILD EXIT 0` but could return nonzero because their last failure-search pipeline found no failures. +Do not chain tests behind the status of an older script. ## Artifacts and implementation sequence diff --git a/sycl/tools/build.sh b/sycl/tools/build.sh index 144dd427..046c2e2f 100755 --- a/sycl/tools/build.sh +++ b/sycl/tools/build.sh @@ -41,9 +41,11 @@ b=${BUILD_DIR:-$repo/build-sycl} # an existing build folder keeps its cache: a switch given now reaches it (only this one, so AOT and the rest stay as configured) [ -z "${I8_ESIMD:-}" ] || cmake -S $repo/sycl -B $b -DSTRATA_SYCL_I8_ESIMD="$I8_ESIMD" >/dev/null 2>&1 cmake --build $b -j ${JOBS:-12} ${1:+--target "$@"} -- -k 0 2>&1 | tee $b/build.log | grep -E '^FAILED|error:|^ninja: build stopped|Linking|^\[[0-9]+/[0-9]+\] Linking' | tail -40 -echo "BUILD EXIT ${PIPESTATUS[0]}" +rc=${PIPESTATUS[0]} # cmake's status, kept: the script ends with this, not with the status of the greps below (#2990) +echo "BUILD EXIT $rc" grep -c 'error:' $b/build.log | sed 's/^/errors: /' grep -E '^FAILED' $b/build.log | sed 's#.*/##' | sort | uniq | head -60 if grep -q 'IGC: Internal Compiler Error' $b/build.log 2>/dev/null; then echo "build.sh: the device compiler (ocloc $(ocloc_version || echo '?')) crashed: try docker build --pull -t strata-sycl-dev sycl/tools or I8_ESIMD=OFF (#3219)" fi +exit "$rc" diff --git a/tests/terminal/test_sycl_build_script.py b/tests/terminal/test_sycl_build_script.py new file mode 100644 index 00000000..71d93ee4 --- /dev/null +++ b/tests/terminal/test_sycl_build_script.py @@ -0,0 +1,74 @@ +"""sycl/tools/build.sh exits with the build's own status (#2990): 0 after a good build, nonzero after a failed one. + +It once ended with a grep pipeline, so a good build exited 1 (nothing to find) and a failed compile exited 0, and a `build.sh && next-step` chain ran +the wrong way round. The test runs the real script with a stub cmake on PATH; no compiler, no oneAPI, no docker. +""" +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "sycl" / "tools" / "build.sh" +BASH = shutil.which("bash") # the full path: on Windows a bare "bash" can start the WSL launcher in System32 instead of Git bash +CYGPATH = shutil.which("cygpath") + + +def sh_path(p) -> str: + if CYGPATH is None: + return str(p) + return subprocess.run([CYGPATH, "-u", str(p)], capture_output=True, text=True, check=True).stdout.strip() + + +STUB = """#!/bin/sh +# a stand-in for cmake: `cmake --build DIR ...` prints what ninja prints and exits with STUB_RC; any other call does nothing +case "$1" in + --build) + echo "[1/2] Building CXX object CMakeFiles/strata.dir/main.cpp.o" + if [ "${STUB_RC:-0}" != 0 ]; then + echo "FAILED: [code=1] CMakeFiles/strata.dir/main.cpp.o" + echo "main.cpp:1:21: error: 'x' was not declared in this scope" + echo "ninja: build stopped: cannot make progress due to previous errors." + else + echo "[2/2] Linking CXX executable strata" + fi + exit "${STUB_RC:-0}" ;; +esac +exit 0 +""" + + +@unittest.skipIf(BASH is None, "needs bash") +class BuildScriptStatus(unittest.TestCase): + def run_script(self, rc: int): + with tempfile.TemporaryDirectory() as tmp: + bindir, build = Path(tmp) / "bin", Path(tmp) / "build" + bindir.mkdir() + build.mkdir() + (build / "build.ninja").write_text("", encoding="utf-8") # an existing build folder: the script does not configure it + (bindir / "cmake").write_text(STUB, encoding="utf-8", newline="\n") + (bindir / "cmake").chmod(0o755) + env = dict(os.environ, PATH=sh_path(bindir) + os.pathsep + os.environ["PATH"], STUB_RC=str(rc), REPO=sh_path(ROOT), + BUILD_DIR=sh_path(build), AOT="", I8_ESIMD="OFF") + done = subprocess.run([BASH, sh_path(SCRIPT), "strata"], capture_output=True, text=True, env=env, timeout=120) + return done + + def test_a_good_build_exits_zero(self): + done = self.run_script(0) + self.assertIn("BUILD EXIT 0", done.stdout) + self.assertIn("errors: 0", done.stdout) + self.assertEqual(done.returncode, 0, done.stdout + done.stderr) + + def test_a_failed_compile_exits_nonzero_with_the_builds_status(self): + done = self.run_script(1) + self.assertIn("BUILD EXIT 1", done.stdout) + self.assertIn("errors: 1", done.stdout) + self.assertEqual(done.returncode, 1, done.stdout + done.stderr) + + +if __name__ == "__main__": + unittest.main() From 590c69a578709de9f52fa1f2efed08c042f34fa1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:27:27 +0100 Subject: [PATCH 066/177] cmake/ggml_tq_overlay_test.cmake sets CMP0057 NEW so IN_LIST works under CMake 3.x (#3412) A cmake -P script has no cmake_minimum_required, so CMake 3.x used the OLD behaviour and stopped at 'if given arguments ... IN_LIST: Unknown arguments' (ctest ggml_tq_overlay with CMake 3.31). Checked with pip cmake 3.31.6 and 4.4.3 against the pinned llama.cpp: both print 'ggml_tq_overlay_test: ok'. A static test keeps the policy before the first IN_LIST in every cmake/*_test.cmake. --- cmake/ggml_tq_overlay_test.cmake | 2 ++ tests/terminal/test_cmake_script_policies.py | 29 ++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/terminal/test_cmake_script_policies.py diff --git a/cmake/ggml_tq_overlay_test.cmake b/cmake/ggml_tq_overlay_test.cmake index e56604c8..ca637e5f 100644 --- a/cmake/ggml_tq_overlay_test.cmake +++ b/cmake/ggml_tq_overlay_test.cmake @@ -1,6 +1,8 @@ # cmake -DLLAMA= -DOUT= -P cmake/ggml_tq_overlay_test.cmake # The trellis MMQ overlay on a pinned llama.cpp: it generates, every copied header is the pinned one except the patched # ones, and the patched ones only gain lines (TQ routing, three externs, config copies of IQ2_XS's). +# a -P script has no cmake_minimum_required, so CMake 3.x applies the OLD CMP0057 and IN_LIST below is not an operator (#3412) +cmake_policy(SET CMP0057 NEW) get_filename_component(CMAKE_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE) include(${CMAKE_CURRENT_LIST_DIR}/strata_ggml_tq_overlay.cmake) file(REMOVE_RECURSE "${OUT}") diff --git a/tests/terminal/test_cmake_script_policies.py b/tests/terminal/test_cmake_script_policies.py new file mode 100644 index 00000000..cad4e98d --- /dev/null +++ b/tests/terminal/test_cmake_script_policies.py @@ -0,0 +1,29 @@ +"""A `cmake -P` script has no cmake_minimum_required, so CMake 3.x applies the OLD behaviour of CMP0057 and `IN_LIST` is not an operator +(ctest ggml_tq_overlay stopped at its first IN_LIST with CMake 3.31, #3412). Every script in cmake/ that is run with -P and uses IN_LIST +sets the policy before the first use. (Static check: the project accepts CMake 3.24 and newer, and CMake 4 sets the policy by itself.)""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +CMAKE = Path(__file__).resolve().parents[2] / "cmake" + + +class ScriptPolicies(unittest.TestCase): + def test_p_scripts_that_use_in_list_set_cmp0057_first(self): + found = 0 + for path in sorted(CMAKE.glob("*_test.cmake")): + text = path.read_text(encoding="utf-8") + code = re.sub(r"(?m)^\s*#.*$", "", text) + if "IN_LIST" not in code: + continue + found += 1 + policy = re.search(r"cmake_policy\(\s*SET\s+CMP0057\s+NEW\s*\)", code) or re.search(r"cmake_minimum_required\(\s*VERSION\s+3\.(1[0-9]|[2-9]\d)", code) + self.assertTrue(policy, f"{path.name} uses IN_LIST without CMP0057 NEW") + self.assertLess(policy.start(), code.index("IN_LIST"), f"{path.name} sets the policy after its first IN_LIST") + self.assertGreaterEqual(found, 1) + + +if __name__ == "__main__": + unittest.main() From bf994ca4141c81d089e6975bc01eea9474f48ae8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:28:23 +0100 Subject: [PATCH 067/177] setup: a build folder configured with another generator is configured again instead of stopping cmake (#4038) The manual build in docs/INSTALL.md uses CMake's default generator (Unix Makefiles on Linux) in build/, and setup --build always asks for Ninja, so cmake stopped with 'Does not match the generator used previously'. cmake_build now reads CMAKE_GENERATOR from the folder's CMakeCache.txt; when it is not Ninja it says so in one line and removes the cache and CMakeFiles (no other file). A Ninja folder or a new folder is untouched. Tests: tools/test_setup_build_dir.py. --- setup.py | 26 +++++++++++ tools/test_setup_build_dir.py | 86 +++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 tools/test_setup_build_dir.py diff --git a/setup.py b/setup.py index c1a06ab6..f994d32e 100644 --- a/setup.py +++ b/setup.py @@ -5577,9 +5577,35 @@ def ensure_build_tools(): return cmake, ninja +def configured_generator(bdir: Path) -> str | None: + """The generator a build folder was configured with (CMakeCache.txt), None when it was never configured.""" + try: + for line in (Path(bdir) / "CMakeCache.txt").read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith("CMAKE_GENERATOR:"): + return line.split("=", 1)[1].strip() + except OSError: + pass + return None + + +def fresh_if_other_generator(bdir: Path, generator: str = "Ninja") -> bool: + """CMake refuses to configure a folder with another generator than the one it was made with ("Does not match the generator used + previously"). The manual build in docs/INSTALL.md uses CMake's default, Unix Makefiles on Linux, in the same build/ folder (#4038). + Such a folder is configured afresh: its cache is removed (the compiled objects of the other generator are not reused anyway), with one + plain line. True when it did.""" + had = configured_generator(bdir) + if had is None or had == generator: + return False + say(f" {Path(bdir).name}/ was configured with {had}; setup builds with {generator}, so it is configured again (the other build is not used)") + (Path(bdir) / "CMakeCache.txt").unlink(missing_ok=True) + shutil.rmtree(Path(bdir) / "CMakeFiles", ignore_errors=True) + return True + + def cmake_build(src, bdir, target, defs, vcvars, bat_name): acquisition.require("a compile (cmake)") cmake, ninja = ensure_build_tools() + fresh_if_other_generator(bdir) conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), "-DCMAKE_BUILD_TYPE=Release", *defs] build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] diff --git a/tools/test_setup_build_dir.py b/tools/test_setup_build_dir.py new file mode 100644 index 00000000..b69add3d --- /dev/null +++ b/tools/test_setup_build_dir.py @@ -0,0 +1,86 @@ +"""A build folder made by the manual build in docs/INSTALL.md (CMake's default generator) does not stop setup --build (#4038). + +CMake refuses a folder configured with another generator ("Does not match the generator used previously: Unix Makefiles"), and setup +always asks for Ninja. The folder is configured afresh, with one plain line; a folder made with Ninja, or never configured, is left alone. + + python -m unittest tools.test_setup_build_dir +""" +from __future__ import annotations + +import contextlib +import io +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +def configured(folder: Path, generator: str) -> Path: + folder.mkdir(parents=True, exist_ok=True) + (folder / "CMakeCache.txt").write_text( + f"# This is the CMakeCache file.\nCMAKE_BUILD_TYPE:STRING=Release\nCMAKE_GENERATOR:INTERNAL={generator}\nCMAKE_HOME_DIRECTORY:INTERNAL=/x\n", encoding="utf-8") + (folder / "CMakeFiles").mkdir(exist_ok=True) + (folder / "CMakeFiles" / "marker.txt").write_text("x", encoding="utf-8") + (folder / "keep.o").write_text("object", encoding="utf-8") + return folder + + +class OtherGenerator(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def call(self, folder): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return setup.fresh_if_other_generator(folder), out.getvalue() + + def test_the_generator_is_read_from_the_cache(self): + self.assertEqual(setup.configured_generator(configured(self.root / "a", "Unix Makefiles")), "Unix Makefiles") + self.assertEqual(setup.configured_generator(configured(self.root / "b", "Ninja")), "Ninja") + self.assertIsNone(setup.configured_generator(self.root / "never")) + + def test_a_folder_made_with_makefiles_is_configured_again(self): + folder = configured(self.root / "build", "Unix Makefiles") + again, said = self.call(folder) + self.assertTrue(again) + self.assertIn("Unix Makefiles", said) + self.assertIn("Ninja", said) + self.assertFalse((folder / "CMakeCache.txt").exists()) + self.assertFalse((folder / "CMakeFiles").exists()) + self.assertTrue((folder / "keep.o").exists(), "only the CMake cache goes, no other file of the folder") + + def test_a_ninja_folder_and_a_new_folder_are_left_alone(self): + folder = configured(self.root / "ninja", "Ninja") + again, said = self.call(folder) + self.assertFalse(again) + self.assertEqual(said, "") + self.assertTrue((folder / "CMakeCache.txt").exists() and (folder / "CMakeFiles" / "marker.txt").exists()) + self.assertEqual(self.call(self.root / "new"), (False, "")) + self.assertFalse((self.root / "new").exists(), "a folder that does not exist is not created by the check") + + def test_cmake_build_does_it_before_it_configures(self): + folder = configured(self.root / "build", "Unix Makefiles") + seen = [] + + def fake_run(cmd, **kw): + seen.append((list(map(str, cmd)), (folder / "CMakeCache.txt").exists())) + return mock.Mock(returncode=0) + + with mock.patch.object(setup, "ensure_build_tools", return_value=("cmake", "ninja")), \ + mock.patch.object(setup.acquisition, "require"), mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "run", fake_run), contextlib.redirect_stdout(io.StringIO()): + setup.cmake_build(self.root, folder, "strata", [], None, "") + configure = seen[0] + self.assertIn("Ninja", configure[0]) + self.assertFalse(configure[1], "the old cache was gone when cmake was asked to configure") + + +if __name__ == "__main__": + unittest.main() From 3b64abf5e095ee493739f701fda7161d2e6fcef4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:29:34 +0100 Subject: [PATCH 068/177] DeepSeek drafter cumulative cut 0.5 by default on gfx1200/gfx1201 only (Model::gpus_are_gfx12); Strix Halo, other AMD and CUDA keep 0 until measured --- src/dsv41/ds4_main.cpp | 25 +++++++++---------------- src/dsv41/ds4_model.cu | 16 ++++++++++++++++ src/dsv41/ds4_model.hpp | 2 ++ 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index fdbd542e..2c11b876 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -152,21 +152,14 @@ static int g_round_nd = 0; // The drafts' cut on the product of their confidences (DeepInfer's cumulative rule): a draft is verified while the chance // that it and every draft before it are kept stays at least this - a long window whose later drafts are likely lost is // not verified whole. STRATA_DS4_DSPARK_CUM=F, a request's dspark_cum key; 0: off, only the floor on each draft's own -// confidence (dspark_conf). On AMD 0.5 is the default: measured on 4x R9700, DeepSeek 2.25 bpw, six 128-token -// decodes an arm in one load - 71.7 -> 76.9 tok/s (medians), the same ids; Project Maya runs 0.5 on a Radeon 8065S -// too (+6.5% decode, the same tokens), while the CUDA measurements in 0.2.7 had it flat, so CUDA keeps 0. -// STRATA_DS4_DSPARK_CUM overrides either way. -float dspark_cum_default() { - static const float v = [] { - const char* e = std::getenv("STRATA_DS4_DSPARK_CUM"); - if (e != nullptr) return (float) std::atof(e); -#if defined(STRATA_USE_HIP) - return 0.5f; -#else - return 0.0f; -#endif - }(); - return v; +// confidence (dspark_conf). 0.5 is the default on gfx1200 / gfx1201 (RDNA4: R9700, RX 9000) only: measured on 4x R9700, DeepSeek 2.25 bpw, +// six 128-token decodes an arm in one load - 71.7 -> 76.9 tok/s (medians), the same ids. Project Maya ran 0.5 on a Radeon 8065S (Strix Halo, +// gfx1151: +6.5% decode, the same tokens), but that is a single datapoint on a box the 0.2.7 defaults have not been tested on, so +// Strix keeps 0 until it is; the CUDA measurements in 0.2.7 had it flat, so CUDA keeps 0. STRATA_DS4_DSPARK_CUM overrides everywhere. +float dspark_cum_default(const strata::ds4::Model& m) { + static const char* const e = std::getenv("STRATA_DS4_DSPARK_CUM"); + if (e != nullptr) return (float) std::atof(e); + return m.gpus_are_gfx12() ? 0.5f : 0.0f; } // One round of decoding after `tok` (the token at pos(), not fed yet): with the drafter, its drafts while their @@ -184,7 +177,7 @@ bool round(strata::ds4::Model& m, int tok, int room, bool spec, float conf_min, g_round_conf = conf; g_round_nd = (int) drafts.size(); int keep = 0; - if (cum_min < 0) cum_min = dspark_cum_default(); + if (cum_min < 0) cum_min = dspark_cum_default(m); float cum = 1.0f; while (keep < (int) drafts.size() && keep < room - 1 && conf[(size_t) keep] >= conf_min && (cum *= conf[(size_t) keep]) >= cum_min) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 8c3052ae..0286e716 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -811,6 +811,7 @@ struct Model::Impl { std::vector groups; std::vector> workers; // threads mode: one per device bool par = false; // threads mode (the windows: decode) + mutable int all_gfx12 = -1; // gpus_are_gfx12(): -1 not asked yet bool prompt_par = false; // the prompt path's chunks (a thread a GPU), as --tp / --threads asked unsigned win_seq = 0; // the windows the threads ran (the hand-offs' seq) // the chunked prompt path (threads mode): chunk tokens a pass, runs shorter than chunk_min in windows @@ -9663,6 +9664,21 @@ void Model::set_images(std::vector images) { p_->imgs = std::move(images); } int Model::draft_block() const { return p_->g.n_mtp > 0 ? p_->g.d_block : 0; } +bool Model::gpus_are_gfx12() const { + if (p_->all_gfx12 < 0) { + bool yes = false; +#if defined(STRATA_USE_HIP) + yes = !p_->devs.empty(); + for (const auto& d : p_->devs) { + cudaDeviceProp prop{}; + yes = yes && cudaGetDeviceProperties(&prop, d.id) == cudaSuccess && + (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0); + } +#endif + p_->all_gfx12 = yes ? 1 : 0; + } + return p_->all_gfx12 == 1; +} bool Model::draft(int y, std::vector& d, std::vector& c, std::string& err, float t, float tp, int tk, float mp, uint64_t seed, uint64_t counter) { return p_->draft(y, d, c, err, t, tp, tk, mp, seed, counter); diff --git a/src/dsv41/ds4_model.hpp b/src/dsv41/ds4_model.hpp index 9cac562c..afa9d2a6 100644 --- a/src/dsv41/ds4_model.hpp +++ b/src/dsv41/ds4_model.hpp @@ -129,6 +129,8 @@ public: /// DeepSeek's reference does. verify() keeps a draft d with probability min(1, p(d) / q(d)) over the request's /// chain - the speculative-sampling rule, so every token is still distributed as the model's own draw. int draft_block() const; + /// every GPU the engine uses is a gfx1200 / gfx1201 (RDNA4: R9700, RX 9000) in a HIP build, false anywhere else (decided once) + bool gpus_are_gfx12() const; bool draft(int y, std::vector& drafts, std::vector& conf, std::string& err, float temperature = 0.0f, float top_p = 1.0f, int top_k = 0, float min_p = 0.0f, uint64_t seed = 0, uint64_t counter = 0); bool verify(int y, const std::vector& drafts, float temperature, float top_p, int top_k, float min_p, From 484c6893375c579170685e32445ccf7a3e152c2d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:33:37 +0100 Subject: [PATCH 069/177] DeepSeek: the 4 x R9700 share-based defaults (small chunk for multi-card tp runs, whole-chunk slab, small staging ring, pinned copy at share >= 0.5) apply to HIP builds only; the staging ring takes a hip flag; tests for both branches --- src/dsv41/ds4_experts_rule.hpp | 11 ++++--- src/dsv41/ds4_model.cu | 20 ++++++++---- tests/dsv41/experts_rule_test.cpp | 52 +++++++++++++++++-------------- 3 files changed, 50 insertions(+), 33 deletions(-) diff --git a/src/dsv41/ds4_experts_rule.hpp b/src/dsv41/ds4_experts_rule.hpp index 50e23d98..746822ea 100644 --- a/src/dsv41/ds4_experts_rule.hpp +++ b/src/dsv41/ds4_experts_rule.hpp @@ -47,7 +47,7 @@ inline int prefill_chunk_default(bool own_default, double gpu_share, bool gguf_c // `strata launch` writes for 4 or more AMD cards), share 0.86: 1024 370 against 214 tok/s at 8192; and with the engine's own default tp // (2, pairs of cards, nothing written), where the rule used to fall through to 2048/8192: 2.25 bpw, --dspark auto, ids 5705e1164a, 8K // warm prompts 1024 -> 1247 ppts against 690 at 8192, decode unchanged. So a multi-card tp run takes it too. One card with the default - // tp, and `--threads on` (it stalled at the first 8K prompt in the 4-card runs), keep their old defaults: not measured with 1024. + // tp, `--threads on` (it stalled at the first 8K prompt in the 4-card runs) and a build that is not HIP keep their old defaults: not measured with 1024. // An explicit --prefill-chunk N wins over all of this (the call site takes the rule only when none was given). if ((own_default || multi_tp) && gpu_share >= 0.5) return 1024; if (gguf_copy && !hip && min_vram_bytes >= kChunk4096MinVram) return 4096; @@ -81,7 +81,8 @@ inline bool copy_all_fits(double lane_bytes, uint64_t ram_avail, double ram_marg // ppts with the 256-row rule against 1324 / 1353 / 1363 with a 1024-row slab (+9%), decode 77.7 against 78.1 tok/s, 268 MB a device (1% of // the card). That branch asks for min(chunk, 1024) rows whatever the spare room (the spare of such a box is negative: its room is all // experts), and never less than the base; the automatic growth on top of it still applies where the room is there. A unified-memory GPU -// (the caller passes env 0 there) and DS4_ATTN_SLAB=0 never take either branch. +// (the caller passes env 0 there) and DS4_ATTN_SLAB=0 never take either branch. The caller passes 0 for `expert_share` in a build that is not +// HIP: that branch is the 4 x R9700 measurement. inline int attn_slab_rows(int env, int chunk, int base, double spare_bytes, double bytes_per_row, double expert_share = 0.0) { auto clampn = [&](int a) { return std::max(64, std::min(chunk, a) / 64 * 64); }; if (env == 0) return base; @@ -107,11 +108,13 @@ inline int attn_slab_rows(int env, int chunk, int base, double spare_bytes, doub // summed room, 64 MB a GB, 400..1200 MB. Measured on Strix Halo only (400 -> 1200: the queue 3,200 -> 8,087 experts, 4K prompt 27.3 // -> 21.3 s, decode unchanged); a discrete card in this band is not measured and takes the same, VRAM-bounded, rule. // A unified-memory GPU never takes the small ring (its datapoint is the 1200 MB one): it keeps the 16 MB "fit" rule at 1/1.3. -inline int staging_ring_mb(double share, double room_bytes, int n_dev, bool integrated) { +// `hip`: the 0.5..0.82 band and the 0.82 threshold are the 4 x R9700 measurements, so only a HIP build takes them; any other build keeps main's +// rule there (16 MB from 1/1.3, the streamed ring below it) until a CUDA multi-card rig is measured. +inline int staging_ring_mb(double share, double room_bytes, int n_dev, bool integrated, bool hip) { const double GB = 1e9; const double per_dev = n_dev > 0 ? room_bytes / (double) n_dev : 0.0; const double streamed = std::min(1200.0, std::max(400.0, room_bytes / GB * 64.0)); - if (integrated) return share >= 1.0 / 1.3 ? 16 : (int) streamed; + if (integrated || !hip) return share >= 1.0 / 1.3 ? 16 : (int) streamed; if (share >= 0.82) return 16; if (share >= 0.5) return (int) std::min(512.0, std::max(128.0, per_dev / GB * 8.0)); return (int) streamed; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 0286e716..d35398e2 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -78,6 +78,14 @@ namespace gg = strata::ds4::gguf; namespace { +// The DeepSeek engine's share-based defaults (small chunk, whole-chunk slab, small ring, pinned copy) are the 4 x R9700 measurements: only a HIP +// build takes them. +#if defined(__HIP_PLATFORM_AMD__) || defined(__HIPCC__) +constexpr bool kHipBuild = true; +#else +constexpr bool kHipBuild = false; +#endif + double now_ms() { return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); } @@ -2032,7 +2040,7 @@ struct Model::Impl { // most (4 x R9700: 8192 214, 1024 370) the small one wins; with the experts copied into RAM (--mmap-experts off) 4096 beats 8192 by 7-9% // (H100 32 GiB: 2048 502, 4096 538, 8192 495). A GGUF pack always has file_experts set (copied only by --mmap-experts off). const bool own_default = !(par || o.tp > 1); // (a run with tp 1 and no --threads: `strata launch` writes --tp 1 for 4+ AMD cards, --tp 2 for 2-3 and nothing for one card = the engine's tp 2) - const bool multi_tp = !own_default && !o.threads && devs.size() >= 2; // (the 4-card default-tp run the 1024 chunk was also measured on; an explicit --prefill-chunk below wins over the rule) + const bool multi_tp = kHipBuild && !own_default && !o.threads && devs.size() >= 2; // (the 4-card default-tp run the 1024 chunk was also measured on; an explicit --prefill-chunk below wins over the rule) const bool gguf_copy = pk.gguf && (o.mmap_experts == 0 || (store_gb() <= 0.0 && auto_copy_all)); uint64_t vmin_bytes = ~0ull; for (const Dev& dv : devs) vmin_bytes = std::min(vmin_bytes, (uint64_t) dv.total); @@ -2975,7 +2983,7 @@ struct Model::Impl { cudaDeviceProp ip{}; if (cudaGetDeviceProperties(&ip, d.id) == cudaSuccess && ip.integrated != 0) unified = true; } - const size_t mb = (size_t) strata::ds4::staging_ring_mb(exp_b > 0 ? share : 0.0, room, (int) devs.size(), unified); + const size_t mb = (size_t) strata::ds4::staging_ring_mb(exp_b > 0 ? share : 0.0, room, (int) devs.size(), unified, kHipBuild); if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, room / 1e9, other_b / 1e9, (int) mb); @@ -3035,11 +3043,11 @@ struct Model::Impl { const int base = c.A; // one rule (ds4_experts_rule.hpp: attn_slab_rows): the chunk's whole slab (<= 1024 rows) where the cards hold half the // experts or more (4 x R9700, +9% prompt), up to 2048 rows where the VRAM is spare, the base otherwise - c.A = strata::ds4::attn_slab_rows(env, chunk, base, spare, bpr, share); + c.A = strata::ds4::attn_slab_rows(env, chunk, base, spare, bpr, kHipBuild ? share : 0.0); if (env < 0 && c.A > base) { slab_auto_grew_ = true; if (di == 0 && o.verbose) { - if (share >= 0.5) + if (kHipBuild && share >= 0.5) std::fprintf(stderr, "ds4: attention slab %d rows (automatic: the cards hold %.0f%% of the experts; DS4_ATTN_SLAB=0 keeps %d)\n", c.A, share * 100.0, base); else @@ -4591,10 +4599,10 @@ struct Model::Impl { // DS4_COPY_PIN_RO=1: cudaHostRegisterReadOnly (the GPU only reads it). // 0.2.7: DS4_COPY_PIN unset = ON when EITHER condition measured reliable holds: (a) the whole arena is on explicit 2 MB pages (a pin of a // THP arena registers 4 KB pages and the DMA rate was erratic on the 12 GB cell: 11.9 s one prompt, 30.4 s the next), or (b) the - // cards hold at least half the routed experts (4 x R9700: the pin was reliable in 4/4 runs there, see above). =0 is the off + // cards hold at least half the routed experts in a HIP build (4 x R9700: the pin was reliable in 4/4 runs there, see above). =0 is the off // switch, =1 pins any arena. const char* cp = std::getenv("DS4_COPY_PIN"); - const bool pin_copies = cp != nullptr ? std::atoi(cp) != 0 : ((arena_all_huge || gpu_expert_share() >= 0.5) && !ram_chunks.empty()); + const bool pin_copies = cp != nullptr ? std::atoi(cp) != 0 : ((arena_all_huge || (kHipBuild && gpu_expert_share() >= 0.5)) && !ram_chunks.empty()); if (pin_copies) { const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; const double tr = now_ms(); diff --git a/tests/dsv41/experts_rule_test.cpp b/tests/dsv41/experts_rule_test.cpp index fa1691bb..fdaf50fe 100644 --- a/tests/dsv41/experts_rule_test.cpp +++ b/tests/dsv41/experts_rule_test.cpp @@ -104,36 +104,42 @@ int main() { CHECK_EQ(attn_slab_rows(512, 1024, 256, 1e18, bpr, 0.77), 512); // DS4_ATTN_SLAB=N: that many rows whatever the share CHECK_EQ(attn_slab_rows(-1, 1024, 1024, -5.0e9, bpr, 0.77), 1024); // a unified-memory base (32 MB of q = 1024 rows) is kept } - // the staging ring (MB): staging_ring_mb(share, room_bytes, n_dev, integrated) + // the staging ring (MB): staging_ring_mb(share, room_bytes, n_dev, integrated, hip) { const double GB = 1e9; // the cards hold the experts: 16 MB, discrete (4 x R9700 at 0.86 and a card that holds everything) - CHECK_EQ(staging_ring_mb(0.86, 4 * 30 * GB, 4, false), 16); - CHECK_EQ(staging_ring_mb(1.00, 70 * GB, 1, false), 16); - CHECK_EQ(staging_ring_mb(0.82, 4 * 30 * GB, 4, false), 16); + CHECK_EQ(staging_ring_mb(0.86, 4 * 30 * GB, 4, false, true), 16); + CHECK_EQ(staging_ring_mb(1.00, 70 * GB, 1, false, true), 16); + CHECK_EQ(staging_ring_mb(0.82, 4 * 30 * GB, 4, false, true), 16); // they hold most of them (4 x R9700, share 0.72-0.77, 31 GB of room a device): 8 MB a GB of one device's room = 248 MB - CHECK_EQ(staging_ring_mb(0.77, 4 * 31 * GB, 4, false), 248); - CHECK_EQ(staging_ring_mb(0.72, 4 * 31 * GB, 4, false), 248); - CHECK_EQ(staging_ring_mb(0.81, 4 * 31 * GB, 4, false), 248); - CHECK_EQ(staging_ring_mb(0.77, 4 * 10 * GB, 4, false), 128); // small devices: at least 128 - CHECK_EQ(staging_ring_mb(0.60, 3 * 90 * GB, 3, false), 512); // big devices: at most 512 - CHECK_EQ(staging_ring_mb(0.50, 2 * 31 * GB, 2, false), 248); // the per-device room, not the summed one (1 card: 31 GB -> 248 too) - CHECK_EQ(staging_ring_mb(0.60, 31 * GB, 1, false), 248); + CHECK_EQ(staging_ring_mb(0.77, 4 * 31 * GB, 4, false, true), 248); + CHECK_EQ(staging_ring_mb(0.72, 4 * 31 * GB, 4, false, true), 248); + CHECK_EQ(staging_ring_mb(0.81, 4 * 31 * GB, 4, false, true), 248); + CHECK_EQ(staging_ring_mb(0.77, 4 * 10 * GB, 4, false, true), 128); // small devices: at least 128 + CHECK_EQ(staging_ring_mb(0.60, 3 * 90 * GB, 3, false, true), 512); // big devices: at most 512 + CHECK_EQ(staging_ring_mb(0.50, 2 * 31 * GB, 2, false, true), 248); // the per-device room, not the summed one (1 card: 31 GB -> 248 too) + CHECK_EQ(staging_ring_mb(0.60, 31 * GB, 1, false, true), 248); // they hold under half (discrete): 64 MB a GB of the summed room, 400..1200 (streamed; not measured on a discrete card) - CHECK_EQ(staging_ring_mb(0.19, 31 * GB, 1, false), 1200); - CHECK_EQ(staging_ring_mb(0.06, 10 * GB, 1, false), 640); // a 12 GB card - CHECK_EQ(staging_ring_mb(0.06, 4 * GB, 1, false), 400); // a small pool still gets 400 - CHECK_EQ(staging_ring_mb(0.40, 2 * 31 * GB, 2, false), 1200); // capped - CHECK_EQ(staging_ring_mb(0.49, 4 * 31 * GB, 4, false), 1200); + CHECK_EQ(staging_ring_mb(0.19, 31 * GB, 1, false, true), 1200); + CHECK_EQ(staging_ring_mb(0.06, 10 * GB, 1, false, true), 640); // a 12 GB card + CHECK_EQ(staging_ring_mb(0.06, 4 * GB, 1, false, true), 400); // a small pool still gets 400 + CHECK_EQ(staging_ring_mb(0.40, 2 * 31 * GB, 2, false, true), 1200); // capped + CHECK_EQ(staging_ring_mb(0.49, 4 * 31 * GB, 4, false, true), 1200); // a unified-memory GPU (Strix Halo): never the small ring; the streamed 400..1200 MB under 1/1.3, 16 above - CHECK_EQ(staging_ring_mb(0.60, 40 * GB, 1, true), 1200); // share 0.6 would be the small ring on a discrete card - CHECK_EQ(staging_ring_mb(0.30, 18.75 * GB, 1, true), 1200); - CHECK_EQ(staging_ring_mb(0.30, 12 * GB, 1, true), 768); - CHECK_EQ(staging_ring_mb(0.30, 5 * GB, 1, true), 400); - CHECK_EQ(staging_ring_mb(0.77, 40 * GB, 1, true), 16); // main's "fit" threshold, 1/1.3 = 0.769 - CHECK_EQ(staging_ring_mb(0.76, 40 * GB, 1, true), 1200); + CHECK_EQ(staging_ring_mb(0.60, 40 * GB, 1, true, true), 1200); // share 0.6 would be the small ring on a discrete card + CHECK_EQ(staging_ring_mb(0.30, 18.75 * GB, 1, true, true), 1200); + CHECK_EQ(staging_ring_mb(0.30, 12 * GB, 1, true, true), 768); + CHECK_EQ(staging_ring_mb(0.30, 5 * GB, 1, true, true), 400); + CHECK_EQ(staging_ring_mb(0.77, 40 * GB, 1, true, true), 16); // main's "fit" threshold, 1/1.3 = 0.769 + CHECK_EQ(staging_ring_mb(0.76, 40 * GB, 1, true, true), 1200); // nothing known: no devices - CHECK_EQ(staging_ring_mb(0.0, 0.0, 0, false), 400); + CHECK_EQ(staging_ring_mb(0.0, 0.0, 0, false, true), 400); + // a build that is not HIP keeps main's rule everywhere: 16 MB from 1/1.3, the streamed ring below it (no small band, no 0.82) + CHECK_EQ(staging_ring_mb(0.77, 4 * 31 * GB, 4, false, false), 16); + CHECK_EQ(staging_ring_mb(0.60, 4 * 31 * GB, 4, false, false), 1200); + CHECK_EQ(staging_ring_mb(0.80, 4 * 31 * GB, 4, false, false), 16); + CHECK_EQ(staging_ring_mb(0.06, 10 * GB, 1, false, false), 640); + CHECK_EQ(staging_ring_mb(0.30, 12 * GB, 1, true, false), 768); } // prompt chunk: prefill_chunk_default(own_default, gpu_share, gguf_copy, file_experts, hip, min_vram, big=8192, multi_tp=false). What `strata launch` runs on one card // passes neither --tp nor --threads, but the engine's default tp is 2, so own_default is false there; a launch with several cards passes --tp 1. From bb62a048b89aa86c55530cf715a7989376791cc5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:35:15 +0100 Subject: [PATCH 070/177] updater: a failed test start keeps the runtime records, not only the engine log tail (#3654) The sandbox of a test start was deleted at once, so the PID records that show why a start failed were lost; only the last 64 KiB of the engine log stayed. A failed start now also keeps run.json (without keys), the host, child and ready JSON records of the runtime (tokens cut to their first 8 characters) and the host and server logs in .updates/logs/test-start--failed. The last three failed starts are kept. Best effort, never hides the failure. Tests: tests/terminal/test_updater.py (FailedStartRecords). --- strata_control/updater.py | 53 ++++++++++++++++++++++++++++++ tests/terminal/test_updater.py | 59 ++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) diff --git a/strata_control/updater.py b/strata_control/updater.py index d5a7f7eb..30f226ac 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -792,6 +792,55 @@ def _keep_log(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> Non pass +_RECORD_LIMIT = 65536 # bytes read from any one kept file +_RECORDS_KEPT = 3 # failed test starts whose records stay in .updates/logs + + +def _scrub(value, key: str = ""): + """A kept JSON record without anything that could authorise a request: keys that name a token or a key keep only their first + characters (enough to see that two records agree), the API key is dropped.""" + if isinstance(value, dict): + return {k: _scrub(v, str(k)) for k, v in value.items()} + if isinstance(value, list): + return [_scrub(v, key) for v in value] + low = key.lower() + if isinstance(value, str) and value and ("api_key" in low or low in ("key", "authorization")): + return "" + if isinstance(value, str) and ("token" in low or "secret" in low or low.endswith("_key")): + return value[:8] + "...(rest removed)" + return value + + +def _keep_records(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> None: + """A failed test start keeps what the sandbox knew, because the sandbox is deleted right after (#3654): the run config the test used + (without keys), the host, child and ready records of the runtime (their PIDs show a mismatch), and the host and server logs, next to the + engine log in ``.updates/logs/test-start--failed``. The last few failed starts are kept. Best effort: it never hides the failure.""" + try: + target = updates_dir(ctx.components) / "logs" / f"test-start-{component.version}-failed" + shutil.rmtree(target, ignore_errors=True) + target.mkdir(parents=True) + wanted = [sandbox / "run.json", sandbox / "engine.log"] + wanted += sorted((sandbox / "runtime").glob("*.json")) + sorted((sandbox / "runtime").glob("*.log")) + for source in wanted: + try: + if not source.is_file(): + continue + data = source.read_bytes()[-_RECORD_LIMIT:] + if source.suffix == ".json": + try: + data = (json.dumps(_scrub(json.loads(data.decode("utf-8-sig"))), indent=1) + "\n").encode("utf-8") + except ValueError: + pass # not JSON after all: kept as it is + (target / source.name).write_bytes(data) + except OSError: + continue + folders = sorted((d for d in target.parent.glob("test-start-*-failed") if d.is_dir()), key=lambda d: d.stat().st_mtime) + for old in folders[:-_RECORDS_KEPT]: + shutil.rmtree(old, ignore_errors=True) + except OSError: + pass + + def _warn_if_deep(ctx: Context, folder: Path, longest_inside: int) -> None: """Tell the person, in plain words, when the engine will sit too deep for Windows' ordinary path limit and long paths are off. The install continues: Strata's own file work uses extended paths; only the engine's own loading may not.""" @@ -916,14 +965,18 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con started = {**started, **runtime.verify(name, timeout=min(ctx.test_timeout, 600), load=True)} if not started.get("ok") or started.get("state") != "ready" or started.get("generation_ready") is not True: _keep_log(sandbox, component, ctx) + _keep_records(sandbox, component, ctx) raise _test_start_failure(component, started, ctx, _log_tail(sandbox, component)) _keep_log(sandbox, component, ctx) return {"mode": "full", "model": cfg.get("model_name") or source.stem, "state": started["state"], "generation_ready": True, "detail": "started, answered a one-token probe, stopped"} except TestStartFailed: _keep_log(sandbox, component, ctx) + _keep_records(sandbox, component, ctx) raise except Exception as exc: # noqa: BLE001 + _keep_log(sandbox, component, ctx) + _keep_records(sandbox, component, ctx) raise TestStartFailed(component.version, f"{type(exc).__name__}: {exc}") from None finally: try: diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 4969a34d..267506a4 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -799,5 +799,64 @@ class AnotherCardFamilyNote(unittest.TestCase): self.assertEqual(report["note"], "This build of Strata is for AMD RX 7000 cards. This computer has an AMD RX 9000 card (gfx1201). Ask for the RX 9000 build.") +class FailedStartRecords(LazyModel): + """#3654: a failed test start used to leave only the last 64 KiB of the engine log, because the sandbox that held the host, child and + ready records was deleted at once. The records are kept (without tokens or keys) next to the log.""" + + def failing_start(self): + def start(name, **kw): + runtime_dir = Path(os.environ["STRATA_RUNTIME_DIR"]) # the sandbox's, set by default_test_start + runtime_dir.mkdir(parents=True, exist_ok=True) + (runtime_dir / f"{name}.json").write_text(json.dumps({"pid": 4321, "token": "a1b2c3d4" * 8, "state": "starting"}), encoding="utf-8") + (runtime_dir / f"{name}-{'a1b2c3d4' * 8}.child.json").write_text(json.dumps({"host_token": "a1b2c3d4" * 8, "child_pid": 111}), encoding="utf-8") + (runtime_dir / f"{name}-9f.ready.json").write_text(json.dumps({"pid": 222, "api_key": "sekret-key"}), encoding="utf-8") + (runtime_dir / f"{name}.server.log").write_text("server: model loaded\nserver: pid 222\n", encoding="utf-8") + (runtime_dir / f"{name}.host.log").write_text("", encoding="utf-8") + return {"ok": False, "state": "starting", "error": "startup_wait_expired", "phase": "ready_file_not_matched"} + return start + + def test_the_runtime_records_of_a_failed_start_are_kept_without_tokens_or_keys(self): + from strata_control import runtime + self.install_current() + folder = fx.build_package(self.root / "lazy", "0.1.46", key=self.key) + stage = self.root / "stage" + (stage / "engine").mkdir(parents=True) + shutil.copytree(folder, stage / "engine" / folder.name) + component = ec.read_manifest(stage / "engine" / folder.name) + self.config.write_text(json.dumps({**json.loads(self.config.read_text()), "api_key": "sekret-key"}), encoding="utf-8") + with mock.patch.object(runtime, "start", side_effect=self.failing_start()), mock.patch.object(runtime, "stop", return_value={}): + with self.assertRaises(updater.TestStartFailed): + updater.default_test_start(stage, component, self.ctx()) + kept = updater.updates_dir(self.components) / "logs" / f"test-start-{component.version}-failed" + names = sorted(p.name for p in kept.iterdir()) + self.assertIn("run.json", names) + self.assertTrue(any(n.endswith(".child.json") for n in names), names) + self.assertTrue(any(n.endswith(".ready.json") for n in names), names) + self.assertIn("updtest.server.log", names) + text = "".join(p.read_text(encoding="utf-8") for p in kept.iterdir()) + self.assertNotIn("sekret-key", text) + self.assertNotIn("a1b2c3d4a1b2c3d4", text, "no full token is kept") + self.assertIn('"child_pid": 111', text) # the PIDs that show a mismatch are + self.assertIn("server: pid 222", text) + self.assertFalse((self.components / ".updates").exists() and any(p.name.startswith("t-") for p in (self.components / ".updates").rglob("*") if p.is_dir()), + "the sandbox itself is still removed") + + def test_only_the_last_few_failed_starts_are_kept(self): + logs = updater.updates_dir(self.components) / "logs" + for i in range(5): + folder = logs / f"test-start-0.1.4{i}-failed" + folder.mkdir(parents=True) + (folder / "run.json").write_text("{}", encoding="utf-8") + os.utime(folder, (1_700_000_000 + i, 1_700_000_000 + i)) + from types import SimpleNamespace + sandbox = self.root / "sandbox" + sandbox.mkdir() + (sandbox / "run.json").write_text("{}", encoding="utf-8") + updater._keep_records(sandbox, SimpleNamespace(version="0.1.49"), self.ctx()) + left = sorted(p.name for p in logs.glob("test-start-*-failed")) + self.assertEqual(len(left), 3, left) + self.assertIn("test-start-0.1.49-failed", left) + + if __name__ == "__main__": unittest.main() From 164619c5a84f6fb2a8a11012e764f7a907f213e2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:36:12 +0100 Subject: [PATCH 071/177] DeepSeek: the 4 x R9700 share-based defaults and the drafter cut apply when every device is RDNA4 (gfx1200/gfx1201), not to every HIP build (Impl::rdna4) --- src/dsv41/ds4_experts_rule.hpp | 4 +-- src/dsv41/ds4_model.cu | 51 ++++++++++++++++--------------- tests/dsv41/experts_rule_test.cpp | 4 +-- 3 files changed, 31 insertions(+), 28 deletions(-) diff --git a/src/dsv41/ds4_experts_rule.hpp b/src/dsv41/ds4_experts_rule.hpp index 746822ea..140b3df4 100644 --- a/src/dsv41/ds4_experts_rule.hpp +++ b/src/dsv41/ds4_experts_rule.hpp @@ -47,7 +47,7 @@ inline int prefill_chunk_default(bool own_default, double gpu_share, bool gguf_c // `strata launch` writes for 4 or more AMD cards), share 0.86: 1024 370 against 214 tok/s at 8192; and with the engine's own default tp // (2, pairs of cards, nothing written), where the rule used to fall through to 2048/8192: 2.25 bpw, --dspark auto, ids 5705e1164a, 8K // warm prompts 1024 -> 1247 ppts against 690 at 8192, decode unchanged. So a multi-card tp run takes it too. One card with the default - // tp, `--threads on` (it stalled at the first 8K prompt in the 4-card runs) and a build that is not HIP keep their old defaults: not measured with 1024. + // tp, `--threads on` (it stalled at the first 8K prompt in the 4-card runs) and a system that is not RDNA4 keep their old defaults: not measured with 1024. // An explicit --prefill-chunk N wins over all of this (the call site takes the rule only when none was given). if ((own_default || multi_tp) && gpu_share >= 0.5) return 1024; if (gguf_copy && !hip && min_vram_bytes >= kChunk4096MinVram) return 4096; @@ -108,7 +108,7 @@ inline int attn_slab_rows(int env, int chunk, int base, double spare_bytes, doub // summed room, 64 MB a GB, 400..1200 MB. Measured on Strix Halo only (400 -> 1200: the queue 3,200 -> 8,087 experts, 4K prompt 27.3 // -> 21.3 s, decode unchanged); a discrete card in this band is not measured and takes the same, VRAM-bounded, rule. // A unified-memory GPU never takes the small ring (its datapoint is the 1200 MB one): it keeps the 16 MB "fit" rule at 1/1.3. -// `hip`: the 0.5..0.82 band and the 0.82 threshold are the 4 x R9700 measurements, so only a HIP build takes them; any other build keeps main's +// `hip`: the 0.5..0.82 band and the 0.82 threshold are the 4 x R9700 measurements, so only an RDNA4 system (every device a gfx1200 or gfx1201; the parameter is named hip) takes them; any other build keeps main's // rule there (16 MB from 1/1.3, the streamed ring below it) until a CUDA multi-card rig is measured. inline int staging_ring_mb(double share, double room_bytes, int n_dev, bool integrated, bool hip) { const double GB = 1e9; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index d35398e2..e36ed767 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -78,8 +78,7 @@ namespace gg = strata::ds4::gguf; namespace { -// The DeepSeek engine's share-based defaults (small chunk, whole-chunk slab, small ring, pinned copy) are the 4 x R9700 measurements: only a HIP -// build takes them. +// A HIP build (the share-based defaults below are gated on the devices being RDNA4, Impl::rdna4()). #if defined(__HIP_PLATFORM_AMD__) || defined(__HIPCC__) constexpr bool kHipBuild = true; #else @@ -819,7 +818,25 @@ struct Model::Impl { std::vector groups; std::vector> workers; // threads mode: one per device bool par = false; // threads mode (the windows: decode) - mutable int all_gfx12 = -1; // gpus_are_gfx12(): -1 not asked yet + mutable int all_gfx12 = -1; // rdna4(): -1 not asked yet + // Every GPU the engine uses is a gfx1200 / gfx1201 (RDNA4: R9700, RX 9000) in a HIP build. The DeepSeek engine's share-based defaults (the small + // chunk for multi-card tp runs, the whole-chunk slab, the small staging ring, the pinned copy at share >= 0.5) and the drafter's cumulative cut are + // the 4 x R9700 measurements, so only RDNA4 takes them until another AMD part is tested (Strix Halo next). + bool rdna4() const { + if (all_gfx12 < 0) { + bool yes = false; +#if defined(STRATA_USE_HIP) + yes = !devs.empty(); + for (const auto& d : devs) { + cudaDeviceProp prop{}; + yes = yes && cudaGetDeviceProperties(&prop, d.id) == cudaSuccess && + (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0); + } +#endif + all_gfx12 = yes ? 1 : 0; + } + return all_gfx12 == 1; + } bool prompt_par = false; // the prompt path's chunks (a thread a GPU), as --tp / --threads asked unsigned win_seq = 0; // the windows the threads ran (the hand-offs' seq) // the chunked prompt path (threads mode): chunk tokens a pass, runs shorter than chunk_min in windows @@ -2040,7 +2057,7 @@ struct Model::Impl { // most (4 x R9700: 8192 214, 1024 370) the small one wins; with the experts copied into RAM (--mmap-experts off) 4096 beats 8192 by 7-9% // (H100 32 GiB: 2048 502, 4096 538, 8192 495). A GGUF pack always has file_experts set (copied only by --mmap-experts off). const bool own_default = !(par || o.tp > 1); // (a run with tp 1 and no --threads: `strata launch` writes --tp 1 for 4+ AMD cards, --tp 2 for 2-3 and nothing for one card = the engine's tp 2) - const bool multi_tp = kHipBuild && !own_default && !o.threads && devs.size() >= 2; // (the 4-card default-tp run the 1024 chunk was also measured on; an explicit --prefill-chunk below wins over the rule) + const bool multi_tp = rdna4() && !own_default && !o.threads && devs.size() >= 2; // (the 4-card default-tp run the 1024 chunk was also measured on; an explicit --prefill-chunk below wins over the rule) const bool gguf_copy = pk.gguf && (o.mmap_experts == 0 || (store_gb() <= 0.0 && auto_copy_all)); uint64_t vmin_bytes = ~0ull; for (const Dev& dv : devs) vmin_bytes = std::min(vmin_bytes, (uint64_t) dv.total); @@ -2983,7 +3000,7 @@ struct Model::Impl { cudaDeviceProp ip{}; if (cudaGetDeviceProperties(&ip, d.id) == cudaSuccess && ip.integrated != 0) unified = true; } - const size_t mb = (size_t) strata::ds4::staging_ring_mb(exp_b > 0 ? share : 0.0, room, (int) devs.size(), unified, kHipBuild); + const size_t mb = (size_t) strata::ds4::staging_ring_mb(exp_b > 0 ? share : 0.0, room, (int) devs.size(), unified, rdna4()); if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, room / 1e9, other_b / 1e9, (int) mb); @@ -3043,11 +3060,11 @@ struct Model::Impl { const int base = c.A; // one rule (ds4_experts_rule.hpp: attn_slab_rows): the chunk's whole slab (<= 1024 rows) where the cards hold half the // experts or more (4 x R9700, +9% prompt), up to 2048 rows where the VRAM is spare, the base otherwise - c.A = strata::ds4::attn_slab_rows(env, chunk, base, spare, bpr, kHipBuild ? share : 0.0); + c.A = strata::ds4::attn_slab_rows(env, chunk, base, spare, bpr, rdna4() ? share : 0.0); if (env < 0 && c.A > base) { slab_auto_grew_ = true; if (di == 0 && o.verbose) { - if (kHipBuild && share >= 0.5) + if (rdna4() && share >= 0.5) std::fprintf(stderr, "ds4: attention slab %d rows (automatic: the cards hold %.0f%% of the experts; DS4_ATTN_SLAB=0 keeps %d)\n", c.A, share * 100.0, base); else @@ -4599,10 +4616,10 @@ struct Model::Impl { // DS4_COPY_PIN_RO=1: cudaHostRegisterReadOnly (the GPU only reads it). // 0.2.7: DS4_COPY_PIN unset = ON when EITHER condition measured reliable holds: (a) the whole arena is on explicit 2 MB pages (a pin of a // THP arena registers 4 KB pages and the DMA rate was erratic on the 12 GB cell: 11.9 s one prompt, 30.4 s the next), or (b) the - // cards hold at least half the routed experts in a HIP build (4 x R9700: the pin was reliable in 4/4 runs there, see above). =0 is the off + // cards hold at least half the routed experts on RDNA4 (4 x R9700: the pin was reliable in 4/4 runs there, see above). =0 is the off // switch, =1 pins any arena. const char* cp = std::getenv("DS4_COPY_PIN"); - const bool pin_copies = cp != nullptr ? std::atoi(cp) != 0 : ((arena_all_huge || (kHipBuild && gpu_expert_share() >= 0.5)) && !ram_chunks.empty()); + const bool pin_copies = cp != nullptr ? std::atoi(cp) != 0 : ((arena_all_huge || (rdna4() && gpu_expert_share() >= 0.5)) && !ram_chunks.empty()); if (pin_copies) { const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; const double tr = now_ms(); @@ -9672,21 +9689,7 @@ void Model::set_images(std::vector images) { p_->imgs = std::move(images); } int Model::draft_block() const { return p_->g.n_mtp > 0 ? p_->g.d_block : 0; } -bool Model::gpus_are_gfx12() const { - if (p_->all_gfx12 < 0) { - bool yes = false; -#if defined(STRATA_USE_HIP) - yes = !p_->devs.empty(); - for (const auto& d : p_->devs) { - cudaDeviceProp prop{}; - yes = yes && cudaGetDeviceProperties(&prop, d.id) == cudaSuccess && - (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0); - } -#endif - p_->all_gfx12 = yes ? 1 : 0; - } - return p_->all_gfx12 == 1; -} +bool Model::gpus_are_gfx12() const { return p_->rdna4(); } bool Model::draft(int y, std::vector& d, std::vector& c, std::string& err, float t, float tp, int tk, float mp, uint64_t seed, uint64_t counter) { return p_->draft(y, d, c, err, t, tp, tk, mp, seed, counter); diff --git a/tests/dsv41/experts_rule_test.cpp b/tests/dsv41/experts_rule_test.cpp index fdaf50fe..1f9bfee7 100644 --- a/tests/dsv41/experts_rule_test.cpp +++ b/tests/dsv41/experts_rule_test.cpp @@ -134,7 +134,7 @@ int main() { CHECK_EQ(staging_ring_mb(0.76, 40 * GB, 1, true, true), 1200); // nothing known: no devices CHECK_EQ(staging_ring_mb(0.0, 0.0, 0, false, true), 400); - // a build that is not HIP keeps main's rule everywhere: 16 MB from 1/1.3, the streamed ring below it (no small band, no 0.82) + // a system that is not RDNA4 keeps main's rule everywhere: 16 MB from 1/1.3, the streamed ring below it (no small band, no 0.82) CHECK_EQ(staging_ring_mb(0.77, 4 * 31 * GB, 4, false, false), 16); CHECK_EQ(staging_ring_mb(0.60, 4 * 31 * GB, 4, false, false), 1200); CHECK_EQ(staging_ring_mb(0.80, 4 * 31 * GB, 4, false, false), 16); @@ -174,7 +174,7 @@ int main() { CHECK_EQ(prefill_chunk_default(true, 0.86, false, true, true, 32 * GiB), 1024); CHECK_EQ(prefill_chunk_default(true, 0.50, false, true, true, 32 * GiB), 1024); CHECK_EQ(prefill_chunk_default(true, 0.49, false, true, true, 32 * GiB), 8192); - // a multi-card tp run (own_default false, multi_tp: 2+ cards, no --threads on; the engine's default tp 2, or --tp 2 from the launcher) takes + // a multi-card tp run (own_default false, multi_tp: RDNA4, 2+ cards, no --threads on; the engine's default tp 2, or --tp 2 from the launcher) takes // the small chunk too: the 4 x R9700 default-tp datapoint (8K warm 1247 ppts at 1024 against 690) CHECK_EQ(prefill_chunk_default(false, 0.86, false, true, true, 32 * GiB, 8192, true), 1024); CHECK_EQ(prefill_chunk_default(false, 0.50, false, true, true, 32 * GiB, 8192, true), 1024); From e6f598c0a2a0b11a1336aa03eca722a5a94572ae Mon Sep 17 00:00:00 2001 From: Norm <304706238+Buddychek@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:36:43 +0100 Subject: [PATCH 072/177] docs: STRATA_VCVARS, /metrics/prometheus behind the API key, and the Monitor's prompt speed (#3244) Three 0.1.42 changes no page told. Ported by hand from PR #3244 by Buddychek (the PR conflicted with the rewritten pages), each sentence checked against the code: /metrics/prometheus needs the API key like /metrics (serve/server.py _authorized), the prompt-speed row is (prompt_tokens - reused) / prompt_ms (apps/host/server/monitor-dashboard.mjs), STRATA_VCVARS is read by setup.find_vcvars. The compiler text now says Visual Studio 2022 (2019 is refused since 0.2.5, #3566) and went to docs/SOURCE_INSTALL.md. --- SECURITY.md | 5 +++-- docs/DETAILS.md | 4 +++- docs/SOURCE_INSTALL.md | 7 +++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 8bd61c84..8afbf44c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,8 +23,9 @@ this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAIL - **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 + that shows the model's state, requests or answers (`/status`, `/metrics`, `/metrics/prometheus`, `/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 diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 43538ddc..9ccf7685 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -292,7 +292,9 @@ files, read time; `routing prefetch`: how many file reads had been warmed). The `GET /metrics` lists `ram_blobs`, `file_blobs`, `file_mb`, `drafts_offered` and `drafts_accepted` per recent request, with `totals` since the start. `hit_rate` is the VRAM share of the experts looked up; experts the GPU reads over PCIe (`--pcie-frac`) are not in it, so a higher `--pcie-frac` raises it even when decoding gets slower. `pcie_share` is their -share of all routed experts. The Monitor tab shows both. +share of all routed experts. The Monitor tab shows both. The request list in the Monitor tab also shows the prompt's own speed: what the cache already held is not read +again, so it is the fresh tokens (`prompt_tokens` minus `reused`) over the prompt time (`prompt_ms`), and a request that read no +new token shows no number. Profiling: start the server with `STRATA_DECODE_TIMING=1` (and `STRATA_VERIFY_PROFILE=1` for the GPU side). After each request the engine log has a `strata decode timing:` line and a `strata decode GPU stages (ms/window):` line. The GPU profile slows diff --git a/docs/SOURCE_INSTALL.md b/docs/SOURCE_INSTALL.md index 1c0d7ec0..1db38150 100644 --- a/docs/SOURCE_INSTALL.md +++ b/docs/SOURCE_INSTALL.md @@ -34,6 +34,13 @@ In PowerShell, prefix the wrapper with `.\`, for example `.\START-HERE.bat`. `SETUP.bat` opens setup again to add a model or change settings. The wrapper can reuse an existing install; first-start and later load times depend on the pack, disk, RAM and backend. A model can take several minutes to load. +When no ready-made engine fits the PC, setup compiles one. That needs the Visual Studio 2022 Build Tools with the C++ workload; +Visual Studio 2019 is too old (the sources are C++20). With a CUDA toolkit, CUDA 13.0 to 13.2 accept Visual Studio 2022 only, and +Visual Studio 2026 works from CUDA 13.3. The CPU image encoder alone (no CUDA toolkit on the PC) builds with MSVC and takes any +Visual Studio that has the C++ tools. If setup cannot find an install it could use, name the file before running it, for example +`set STRATA_VCVARS=C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat`. Setup uses that file +only if it exists; a wrong path is answered as no build tools at all. + ## From source: Linux Clone or extract the source, enter its folder, then run: From f06bfc30e75926a911e7eb2574b9445222058f1a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:37:19 +0100 Subject: [PATCH 073/177] docs/TROUBLESHOOTING.md: the Windows AMD driver-reset entry is back The 0.2.5 rewrite of the page dropped the 'Windows AMD: the driver resets' entry (v0.2.4.2 had it), although setup.py still tells a Windows gfx12 card owner to read it and tools/test_setup_amd.py (TdrPointer) checks for it, so that test failed on main. Restored from v0.2.4.2 with the log and config locations worded for a source checkout. --- docs/TROUBLESHOOTING.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 1c5035cb..f55fba05 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -116,6 +116,40 @@ Check system logs for an out-of-memory kill. Also check `ulimit -R`: a desktop-s kill even when memory is available. The engine prints a warning for that condition; see the [detailed troubleshooting table](DETAILS.md#troubleshooting) before changing system limits. +**Windows AMD: the driver resets (VIDEO_ENGINE_TIMEOUT_DETECTED / screen flicker / the engine dies mid-answer).** +Windows gives a GPU about 2 seconds to answer; when a graphics card does not, it resets the driver (a TDR): the screen +flickers, the engine dies, and the Event Viewer shows `VIDEO_ENGINE_TIMEOUT_DETECTED` (#613, with #579 and #541 on +Linux). Strata 0.1.39 and newer say "the GPU stopped responding" in the log. It was seen with KV streaming on +(`--kv-resident 32768`, which setup turns on from 64K context) while reading a long prompt on a gfx1201 card. Try these +in order, one at a time, and tell us what changed: +1. **Send us the evidence.** The last ~80 lines of the engine log (`strata-.log` in the Strata folder of a source checkout; the server window + shows the same lines), your AMD driver version (AMD Software > System), your card and Windows version, the Strata + version, and the exact steps (context size, how long the prompt was, which app sent it). If Windows wrote a + dump, the newest `.dmp` in `C:\Windows\LiveKernelReports\WATCHDOG` (or `C:\Windows\Minidump`) helps; it holds no + chats, only the driver state. +2. **Find the step that hangs:** add `"STRATA_PF_STEP_SYNC": "1"` to the `"env"` block of the model's run config (`strata-.json` + in a source checkout) and restart. The prompt path then waits for the GPU after each step and logs any step over 250 ms, so the log names + the step. It is slower; use it to diagnose, then take it out. +3. **`"STRATA_KV_HOST_DMA": "1"`** in the same `"env"` block: no GPU kernel writes the RAM copy of the K/V during a + prompt, it is copied by DMA instead. Same answers. +4. **No KV streaming:** run setup again and pick 32K context (or remove `--kv-resident` and its number from + `"args"` in the JSON, with a context that fits the VRAM). +5. **A smaller prompt chunk:** change `--prefill` in `"args"` (for example `--prefill 512`): each GPU launch then does + less work between two checks by Windows. Prompts are read more slowly. +6. **Optional, your decision: give Windows more time (`TdrDelay`).** The default is 2 seconds. In the registry, + `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers`, a DWORD `TdrDelay` of `10` (seconds) + lets a long GPU job finish before Windows resets the driver; restart the PC. It hides the symptom and does not fix + a GPU that has really hung, and a hung GPU then freezes the screen for those 10 seconds. Strata changes no Windows + setting itself; to undo it, delete the value. +7. **Driver:** use the newest AMD Software release for your card (Adrenalin, not a Windows Update driver) and restart + after installing. If it started after a driver update, tell us both versions; going back one version is a fair + test. + +**Large pinned host allocations fail on ROCm although RAM is free.** +See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. + +**"verify: timed out at layer N" or "no progress for 60 s" on AMD (Linux), mostly with `--mmap-experts`.** + **A hand-edited engine option disappears.** The run config tracks explicit options in `user_args` and the generated baseline in `args_written`. Prefer the app's Expert settings or Terminal `--set` for supported overrides. Context, KV, picture reading and drafting are From 5b14fe23f7ea171ba473fec3c567f8c78b3af671 Mon Sep 17 00:00:00 2001 From: Norm <304706238+Buddychek@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:38:42 +0100 Subject: [PATCH 074/177] tests: three suite gaps a live PC showed (#3236) test_iq_pack imports without llama.cpp's gguf-py and skips the classes that build GGUF fixtures with a named reason; the MCP discovery tests use a free port, not whatever Strata serves on 8080; the six conversation-cache tests add the repo root to sys.path so they run from the repo root as the suite does. Ported from PR #3236 by Buddychek (tests only, no shipped code). --- tools/test_conversation_cache_disabled.py | 2 ++ tools/test_conversation_cache_growth.py | 2 ++ tools/test_conversation_cache_http_smoke.py | 2 ++ tools/test_conversation_cache_isolation.py | 2 ++ tools/test_conversation_cache_parity.py | 2 ++ tools/test_conversation_cache_soak.py | 2 ++ tools/test_iq_pack.py | 30 ++++++++++++++++++--- tools/test_strata_mcp.py | 4 +++ 8 files changed, 42 insertions(+), 4 deletions(-) diff --git a/tools/test_conversation_cache_disabled.py b/tools/test_conversation_cache_disabled.py index d389ac9f..59c3e685 100644 --- a/tools/test_conversation_cache_disabled.py +++ b/tools/test_conversation_cache_disabled.py @@ -8,6 +8,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_disabled import NAMES, SETTINGS, STATE_KEYS, common_args, state_hashes, verify diff --git a/tools/test_conversation_cache_growth.py b/tools/test_conversation_cache_growth.py index 36423449..f89f2be8 100644 --- a/tools/test_conversation_cache_growth.py +++ b/tools/test_conversation_cache_growth.py @@ -8,6 +8,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_growth import NAMES, SECRET, SETTINGS, STATE_KEYS, verify diff --git a/tools/test_conversation_cache_http_smoke.py b/tools/test_conversation_cache_http_smoke.py index fd0a79d2..50211a87 100644 --- a/tools/test_conversation_cache_http_smoke.py +++ b/tools/test_conversation_cache_http_smoke.py @@ -9,6 +9,8 @@ import tempfile import unittest from unittest.mock import Mock +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_http_smoke import run diff --git a/tools/test_conversation_cache_isolation.py b/tools/test_conversation_cache_isolation.py index 7205d4d4..d87e9287 100644 --- a/tools/test_conversation_cache_isolation.py +++ b/tools/test_conversation_cache_isolation.py @@ -7,6 +7,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_isolation import STATE_KEYS, fixtures, verify from tools.gguf_reader import GGUFFile diff --git a/tools/test_conversation_cache_parity.py b/tools/test_conversation_cache_parity.py index 3f950ebd..b9a79013 100644 --- a/tools/test_conversation_cache_parity.py +++ b/tools/test_conversation_cache_parity.py @@ -6,6 +6,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_parity import STATE_KEYS, engine_args, pressure_budget_hint, verify_admission, verify_exchange, verify_pressure, verify_results diff --git a/tools/test_conversation_cache_soak.py b/tools/test_conversation_cache_soak.py index 7d815890..7ac12a6d 100644 --- a/tools/test_conversation_cache_soak.py +++ b/tools/test_conversation_cache_soak.py @@ -6,6 +6,8 @@ import sys import tempfile import unittest +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # runnable as tools/test_x.py from the repo root too + from tools.conversation_cache_soak import STATE_KEYS, answer_text, verify diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 0e0f5e8b..f1faeabe 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -14,9 +14,25 @@ import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) # runnable from the repo root too from _paths import add_gguf_py -add_gguf_py() -from gguf import GGUFWriter, GGMLQuantizationType as Q, quants -import iq_pack +import iq_pack # needs numpy + gguf_reader only, not gguf-py: import it unguarded + +try: + add_gguf_py() # llama.cpp's gguf-py: setup.py clones it; gguf_py() exits when absent + from gguf import GGUFWriter, GGMLQuantizationType as Q, quants +except SystemExit: + GGUF_PY = None +else: + GGUF_PY = "found" + + +def require_gguf_py(test): + """setUpClass for the classes that build GGUF fixtures: skip (not fail) on a checkout without llama.cpp.""" + @classmethod + def setUpClass(cls): + if GGUF_PY is None: + raise unittest.SkipTest("llama.cpp's gguf-py not found: run setup.py (it clones llama.cpp into " + "third_party/) or set STRATA_GGUF_PY") + return setUpClass def write_gguf(path, tensors, split=None, arch=True): @@ -37,6 +53,7 @@ def write_gguf(path, tensors, split=None, arch=True): class CompatibilityTests(unittest.TestCase): + setUpClass = require_gguf_py(unittest.TestCase) def test_bf16_halfway_rounds_to_even(self): values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32) got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16) @@ -253,6 +270,8 @@ class ConversionTests(unittest.TestCase): """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" + setUpClass = require_gguf_py(unittest.TestCase) + def test_exact_f32_to_bf16_by_default(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000) # BF16 values held as F32 @@ -362,8 +381,9 @@ def expert(seed, shape): return np.random.default_rng(seed).standard_normal((N_EXPERT, *shape)).astype(np.float32) -def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=Q.Q8_0, seed=0): +def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=None, seed=0): """Writes the 4 shards; returns their paths.""" + gate1 = Q.Q8_0 if gate1 is None else gate1 # not a default arg: the module imports without gguf-py gu, dn = (32, 32), (32, 32) router = [(f"blk.{l}.ffn_gate_inp.weight", np.full((N_EXPERT, 32), 0.5, np.float32), Q.F32) for l in (0, 1)] l0 = [(f"blk.0.ffn_{r}_exps.weight", expert(seed + 10 + i, gu if r != "down" else dn), Q.Q8_0) @@ -406,6 +426,7 @@ def expected_experts(model): class SplitArtifactTests(unittest.TestCase): + setUpClass = require_gguf_py(unittest.TestCase) def test_four_shards_and_a_layer_split_per_role(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) @@ -689,6 +710,7 @@ class HadamardTests(unittest.TestCase): class NativeExpertsV5Tests(unittest.TestCase): """The v5 mark (Hadamard-folded experts) rewrites only the tables the packer writes, v3 and v4.""" + setUpClass = require_gguf_py(unittest.TestCase) # test_packer_refuses_before_writing builds GGUF fixtures ROWS = "0 145 146 0 100 1 2 3\n1 145 146 100 100 4 5 6\n" def table(self, version, tail="(n_expert 2, total 200)"): diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 0fdb78bc..fab2199f 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -164,8 +164,12 @@ class FakeRoot(unittest.TestCase): self.strata.disk_free = lambda p: 1000.0 self.tools = M.Tools(self.strata) self.extra = [] + # the tests must never see a Strata server that happens to run on the real default port on this PC + self._default_port = M.DEFAULT_PORT + M.DEFAULT_PORT = free_port() def tearDown(self): + M.DEFAULT_PORT = self._default_port for p in self.extra: if p.poll() is None: p.kill() From a0fc88abd646a81f1669d37c47548772296be3f4 Mon Sep 17 00:00:00 2001 From: Patrick Schaub <11846736+pschaub@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:40:01 +0100 Subject: [PATCH 075/177] serve: timings on /v1/responses (#3291) The final response.completed / response.incomplete event and a non-streaming /v1/responses reply now carry the same top-level timings object that /v1/chat/completions has. The server already put timings in the done dict; the Responses assembler dropped them. Tests: UsageAndStatus.test_responses (stream and non-stream). Unset timings leave the event unchanged; response.failed has none. --- docs/DETAILS.md | 3 +++ serve/responses.py | 13 +++++++++++-- serve/test_server.py | 13 +++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index f60429bf..61dfb584 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -707,6 +707,9 @@ endpoints are refused with an error that says so. | `text.format` | `json_schema` and `json_object` use the JSON formats above (checked, not constrained) | | `client_metadata["x-codex-turn-metadata"]` thread-title request | Opt-in `"codex_thread_titles": true`: answered without the engine as `{"title": ""}` so the conversation keeps the prompt cache | +The final event (`response.completed` or `response.incomplete`) and a non-streaming reply carry the same top-level `timings` object as +`/v1/chat/completions`. + The thinking comes back as a `reasoning` output item with `reasoning_text` content. The model writes no summaries, so `summary` is empty. With `"include": ["reasoning.encrypted_content"]` the item also carries an opaque string (base64, not encrypted). Send reasoning items back with the conversation, as Codex does, so the prompt matches and the cache is reused. Streaming diff --git a/serve/responses.py b/serve/responses.py index 8b7241b9..53c4fb54 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -662,10 +662,17 @@ class Assembler: if length: self.response["status"] = "incomplete" self.response["incomplete_details"] = {"reason": "max_output_tokens"} - return out + [self.event("response.incomplete", response=self.snapshot())] + return out + [self._with_timings(self.event("response.incomplete", response=self.snapshot()), done)] self.response["status"] = "completed" self.response["completed_at"] = int(time.time()) - return out + [self.event("response.completed", response=self.snapshot())] + return out + [self._with_timings(self.event("response.completed", response=self.snapshot()), done)] + + @staticmethod + def _with_timings(event: dict, done: dict) -> dict: + """Top-level `timings` on the final event, as /v1/chat/completions has them (#107).""" + if done.get("timings"): + event["timings"] = done["timings"] + return event def failed(self, message: str, code: str = "server_error") -> dict: """response.failed: an error after the stream started (the HTTP status is already sent).""" @@ -683,4 +690,6 @@ def collect(events) -> dict: for e in events: if e is not None: last = e + if last.get("timings"): # as on a whole /v1/chat/completions reply (#107) + return {**last["response"], "timings": last["timings"]} return last["response"] diff --git a/serve/test_server.py b/serve/test_server.py index 3e60dee4..935414f9 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3808,6 +3808,19 @@ class UsageAndStatus(unittest.TestCase): self.assertEqual(last["usage"]["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) self.assertEqual(last["timings"]["cache_n"], ClockedEngine.REUSED) + def test_responses(self): + # /v1/responses carries the same top-level timings as /v1/chat/completions + body = {"model": "x", "max_output_tokens": 20, "input": "hi"} + status, raw = self.request("/v1/responses", body) + self.assertEqual(status, 200) + r = json.loads(raw) + self.assertEqual(r["timings"]["cache_n"], ClockedEngine.REUSED) + self.assertEqual(r["timings"]["predicted_n"], r["usage"]["output_tokens"]) + status, raw = self.request("/v1/responses", {**body, "stream": True}) + last = [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")][-1] + self.assertIn(last["type"], ("response.completed", "response.incomplete")) + self.assertAlmostEqual(last["timings"]["predicted_per_second"], 50.0, delta=0.1) # 20 ms a token + def test_anthropic(self): u = self.chat("/v1/messages")["usage"] self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) From fb966cff37e9ce80b09ff58d73f4779bc9db136d Mon Sep 17 00:00:00 2001 From: Tsury <4947581+Tsury@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:40:30 +0100 Subject: [PATCH 076/177] pack_gguf: accept older DeepSeek GGUF metadata names (#3955) Older converters write the Engram scalars as engram.key_length and engram.pad_id, and omit the sparse-attention geometry. The packer now reads the old names only when the canonical engram.head_dim and engram.pad_token_id are absent, and a new --config-json option fills the omitted geometry from the source model's config.json. A value that disagrees with metadata already in the GGUF stops the pack with a clear message. The weights are never rewritten and a set that already has the canonical names packs exactly as before. Tests: LegacyModelMetadata (2 new, 5 in the file) in tests/terminal/test_pack_gguf_engram.py. Not covered: the author reports the older Q2_K set still needs dense Q2/Q3 and Engram Q2_K tensor support in the engine; this does not add it. --- tests/terminal/test_pack_gguf_engram.py | 46 +++++++++++++++++++++++++ tools/dsv41/pack_gguf.py | 32 ++++++++++++++++- 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/tests/terminal/test_pack_gguf_engram.py b/tests/terminal/test_pack_gguf_engram.py index 17848fa2..448d1c97 100644 --- a/tests/terminal/test_pack_gguf_engram.py +++ b/tests/terminal/test_pack_gguf_engram.py @@ -56,5 +56,51 @@ class EngramHeader(unittest.TestCase): self.assertFalse(PG.is_engram_file(PG.Gguf(tiny_gguf(Path(d) / "m.gguf", "deepseek41")))) +class LegacyModelMetadata(unittest.TestCase): + def test_legacy_engram_names_write_the_same_hash_table(self): + common = { + "general.architecture": "deepseek41", + "deepseek41.engram.max_ngram_size": 2, + "deepseek41.engram.head_count": 1, + "deepseek41.engram.token_map": [0, 1, 2], + "deepseek41.engram.multipliers": [3, 5], + "deepseek41.engram.primes": [7], + "deepseek41.engram.offsets": [0], + } + legacy = {**common, "deepseek41.engram.layer_ids": [1], + "deepseek41.engram.key_length": 256, "deepseek41.engram.pad_id": 2} + current = {**common, "deepseek41.engram.layers": [1], + "deepseek41.engram.head_dim": 256, "deepseek41.engram.pad_token_id": 2, + "deepseek41.engram.key_length": 999, "deepseek41.engram.pad_id": 999} + PG.int_tensors_to_engram([], legacy) + PG.int_tensors_to_engram([], current) + with tempfile.TemporaryDirectory() as d: + a, b = Path(d) / "legacy.bin", Path(d) / "current.bin" + PG.write_engram(a, legacy, 3) + PG.write_engram(b, current, 3) + self.assertEqual(a.read_bytes(), b.read_bytes()) + self.assertEqual(struct.unpack("<4s6i", a.read_bytes()[:28]), + (b"DSE1", 3, 1, 2, 1, 256, 2)) + + def test_source_config_restores_omitted_sparse_geometry(self): + kv = {"general.architecture": "deepseek41", "deepseek41.block_count": 40, + "deepseek41.embedding_length": 5120, "deepseek41.expert_count": 384} + cfg = {"text_config": {"num_hidden_layers": 40, "hidden_size": 5120, + "n_routed_experts": 384, "kv_source_layer_ids": [2, 8, 14, 20], + "index_source_layer_ids": [2, 8, 14, 20, 24, 28, 32, 36], + "candidate_source_layer_id": 20, "candidate_topk_blocks": 2048, + "candidate_block_size": 8}} + PG.apply_source_config(kv, cfg) + geometry = PG.geometry(kv, 129280) + self.assertEqual(geometry["kv_source_layer_ids"], [2, 8, 14, 20]) + self.assertEqual(geometry["index_source_layer_ids"], [2, 8, 14, 20, 24, 28, 32, 36]) + self.assertEqual(geometry["candidate_source_layer_id"], 20) + self.assertEqual(geometry["candidate_topk_blocks"], 2048) + self.assertEqual(geometry["candidate_block_size"], 8) + cfg["text_config"]["candidate_block_size"] = 16 + with self.assertRaisesRegex(SystemExit, "candidate_block_size"): + PG.apply_source_config(kv, cfg) + + if __name__ == "__main__": unittest.main() diff --git a/tools/dsv41/pack_gguf.py b/tools/dsv41/pack_gguf.py index b56838f5..4a44d1cc 100644 --- a/tools/dsv41/pack_gguf.py +++ b/tools/dsv41/pack_gguf.py @@ -20,6 +20,9 @@ from there when it is present. Nor a vision tower: vision_pack.py makes it from (--vision: another folder), and the pack takes it and its geometry (vision., image_token_id) from there when it is present; without it the engine reads text only. +For older GGUF converters that omit sparse-attention geometry, pass --config-json /path/to/the/source/model/config.json. +Existing metadata must agree with that configuration; the weights are never rewritten. + A quant that leaves the two Engram tables out (v1.1.16's Maya-S; Maya's quants hold them since) takes them from a set of GGUF files that holds them, beside it: --engram, else ../Engram/ (unsloth's MXFP8 shard of them, where setups before v1.1.17 put it) when it is whole. @@ -253,6 +256,29 @@ def ple_to_engram(kv: dict): kv["%s.engram.%s" % (a, k)] = v +def apply_source_config(kv: dict, config: dict): + """Fill sparse-attention geometry omitted by older converters from the model's own config.json.""" + a = kv["general.architecture"] + text = config.get("text_config", config) + fields = { + "embedding_length": "hidden_size", "block_count": "num_hidden_layers", + "expert_count": "n_routed_experts", "attention.compress_ratios": "compress_ratios", + "attention.kv_source_layers": "kv_source_layer_ids", + "attention.indexer.source_layers": "index_source_layer_ids", + "attention.indexer.candidate_source_layer": "candidate_source_layer_id", + "attention.indexer.candidate_top_k_blocks": "candidate_topk_blocks", + "attention.indexer.candidate_block_size": "candidate_block_size", + } + for name, source in fields.items(): + if source not in text: + continue + keys = ["%s.%s" % (a, k) for k in (name, *ALIASES.get(name, ()))] + for key in keys: + if key in kv and kv[key] != text[source]: + raise SystemExit("source config %s disagrees with GGUF %s" % (source, key)) + kv.setdefault(keys[0], text[source]) + + def int_tensors_to_engram(gs, kv: dict): """The IST-DAS sets carry the Engram's hash parameters as integer tensors of the first shard (engram_token_map I32, engram_primes / engram_offsets / engram_multipliers I64, one row a layer) instead of metadata: read them into the @@ -276,7 +302,8 @@ def int_tensors_to_engram(gs, kv: dict): # the IST-DAS spelling of the Engram's scalar keys -> the dotted ones this pack reads for dotted, theirs in (("engram.layers", "engram.layer_ids"), ("engram.max_ngram_size", "engram_max_ngram_size"), ("engram.head_count", "engram_n_heads"), ("engram.head_dim", "engram_head_dim"), - ("engram.pad_token_id", "engram_pad_token_id")): + ("engram.pad_token_id", "engram_pad_token_id"), + ("engram.head_dim", "engram.key_length"), ("engram.pad_token_id", "engram.pad_id")): if "%s.%s" % (a, dotted) not in kv and "%s.%s" % (a, theirs) in kv: kv["%s.%s" % (a, dotted)] = kv["%s.%s" % (a, theirs)] @@ -413,6 +440,7 @@ def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--model", required=True, help="the directory of the GGUF's shards") ap.add_argument("--out", help="default: /maya-ds4") + ap.add_argument("--config-json", help="the exact source model config.json, to fill sparse-attention geometry omitted by older GGUF converters") ap.add_argument("--vision", help="vision_pack.py's folder (default: /../vision; taken when it is there)") ap.add_argument("--dspark-gguf", help="unsloth's DSpark drafter GGUF (dspark-*-Q8_0.gguf, architecture dflash): its three " "blocks become mtp.0-2 beside the trunk's tensors (default: the first dspark-*.gguf " @@ -461,6 +489,8 @@ def main() -> int: if kv is None: arch = next((g.kv.get("general.architecture") for g in gs), None) raise SystemExit("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model, arch)) + if a.config_json: + apply_source_config(kv, json.loads(pathlib.Path(a.config_json).expanduser().read_text())) split = int(kv.get("split.count", 1)) if split != len(shards): counts = sorted({m.group(1) for m in (re.search(r"-of-(\d{5})\.gguf$", p.name) for p in shards) if m}) From 54d9363c972cd3e4178ccc6408a13b5b42f8246f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:41:09 +0100 Subject: [PATCH 077/177] CUDA Plan opt-ins become defaults where measured: STRATA_GR_V3 on a discrete 12.0 card above 13 GiB, STRATA_PROMPT_ATTN_IMMA on CUDA sm_80+ (env =0 turns each off); DeepSeek Faster mode (5 experts) by default on 2+ RDNA4 cards that hold half the experts; the route-prior/GR_V3/IMMA rules are pure functions with tests; gr_parity and fused_gr_bench pin STRATA_GR_V3=0 for their bitwise contract --- include/strata/core/sm120_series.hpp | 23 +++++++++++++++ src/core/arch_defaults_test.cpp | 42 ++++++++++++++++++++++++++++ src/core/verify.cpp | 2 +- src/dsv41/ds4_experts_rule.hpp | 7 +++-- src/dsv41/ds4_model.cu | 6 ++-- src/kernels/cuda/fused_gr.cu | 34 ++++++++++++++++++++-- src/kernels/cuda/qsa_prompt_attn.cu | 11 ++++++-- src/kernels/fused_gr_bench.cpp | 6 ++++ src/kernels/gr_parity.cpp | 6 ++++ tests/dsv41/experts_rule_test.cpp | 9 ++++++ 10 files changed, 135 insertions(+), 11 deletions(-) diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index 9059d312..b1cc1192 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -42,4 +42,27 @@ inline bool is_sm120(int major, int minor) { return cc_major_of(major) == 12 && /// the default of a bitwise switch of the set: on for a 12.0 card unless STRATA_SM120_PERF=0 inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) && sm120_series(); } +// ---- 0.2.7 defaults of the CUDA speed work (pure rules; the engine reads the device and calls these; tests in arch_defaults_test) +// `hip`: a HIP build, where a gfx1200 / gfx1201 reports compute capability 12.0 as well and none of these is measured or wanted. +// `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory. +constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0 + +/// STRATA_ROUTE_PRIOR when the user set nothing: 2.0 (residency-biased routing, changes which experts run; owner-approved for 12 GB cards) on a +/// discrete CUDA card of 13 GiB or less, 0 everywhere else. Measured on an RTX 3060 12 GB only. +inline float route_prior_default(bool hip, bool integrated, double total_bytes) { + return !hip && !integrated && total_bytes > 0.0 && total_bytes / 1073741824.0 <= kSmallCardGiB ? 2.0f : 0.0f; +} + +/// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability +/// 12.0 card (STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB, CUDA builds only. Measured: RTX PRO 5000 72 GB +1.2% decode clean, +/// -3.0% / -5.9% on 2x RTX A4000 (sm_86), +1.0% / -3.4% on an RTX 3060 (sm_86): so not those; a 12 GB sm_120 card is unmeasured. +inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes) { + return !hip && !integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB; +} + +/// STRATA_PROMPT_ATTN_IMMA (the prompt attention on int8 tensor cores, another summation order) when the user set nothing: ON for every CUDA card of +/// compute capability 8.0 or newer (the int8 m16n8k32 MMA), not Turing / Volta / Pascal, not HIP. `cc` = 10 * major + minor as the engine +/// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt. +inline bool prompt_attn_imma_default(bool hip, int cc) { return !hip && cc >= 80; } + } // namespace strata diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index 459fdaa4..9723b2b7 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -1,6 +1,7 @@ // src/core/arch_defaults_test.cpp - the per-architecture default table (no GPU needed). #include "strata/core/arch_defaults.hpp" #include "strata/core/gfx12_platform_defaults.hpp" +#include "strata/core/sm120_series.hpp" #include #include @@ -226,5 +227,46 @@ int main() { unset("STRATA_UMA_REGISTER"); // both platforms: no Windows guard on the iGPU set (the owner wants it there too; untested on Windows is only said in the log) std::printf(fails ? "arch_defaults_test: %d FAILED\n" : "arch_defaults_test: OK\n", fails); + // ---- 0.2.7 CUDA defaults (sm120_series.hpp): which cards get which, and which never do + { + const double GiB = 1073741824.0; + using namespace strata; + // residency-biased routing: 2.0 on a discrete CUDA card of 13 GiB or less, nothing else + CHECK(route_prior_default(false, false, 11.9 * GiB) == 2.0f); // RTX 3060 / 5070 12 GB + CHECK(route_prior_default(false, false, 12.0 * GiB) == 2.0f); + CHECK(route_prior_default(false, false, 8.0 * GiB) == 2.0f); // an 8 GB card + CHECK(route_prior_default(false, false, 13.0 * GiB) == 2.0f); // the boundary is inclusive + CHECK(route_prior_default(false, false, 13.5 * GiB) == 0.0f); + CHECK(route_prior_default(false, false, 15.7 * GiB) == 0.0f); // 16 GB card: z440's A4000, P100 + CHECK(route_prior_default(false, false, 72.0 * GiB) == 0.0f); // RTX PRO 5000 + CHECK(route_prior_default(true, false, 12.0 * GiB) == 0.0f); // a HIP build: a 12 GB RX 6700 XT / 7700 XT + CHECK(route_prior_default(true, true, 12.0 * GiB) == 0.0f); // Strix Halo with a small carve-out + CHECK(route_prior_default(false, true, 8.0 * GiB) == 0.0f); // an integrated GPU on CUDA (Jetson-like) + CHECK(route_prior_default(false, false, 0.0) == 0.0f); // unknown memory + // the stream-split hyper-connection read: a discrete 12.0 card above 13 GiB (RTX PRO 5000 72 GB, RTX 5090 32 GB), nothing else + CHECK(gr_v3_default(false, 12, 0, false, 72.0 * GiB)); + CHECK(gr_v3_default(false, 12, 0, false, 31.4 * GiB)); // RTX 5090 + CHECK(!gr_v3_default(false, 12, 0, false, 11.9 * GiB)); // RTX 5070 12 GB: streams most experts, unmeasured + CHECK(gr_v3_default(false, 12, 0, false, 15.6 * GiB)); // a 16 GB sm_120 card (RTX 5060 Ti / 5070 Ti): above 13 GiB, on (unmeasured size, same arch) + CHECK(!gr_v3_default(false, 8, 6, false, 15.7 * GiB)); // 2x RTX A4000 (sm_86): measured -3.0% / -5.9% + CHECK(!gr_v3_default(false, 8, 6, false, 72.0 * GiB)); // any sm_86 + CHECK(!gr_v3_default(false, 8, 9, false, 24.0 * GiB)); // sm_89 + CHECK(!gr_v3_default(false, 12, 1, false, 128.0 * GiB)); // sm_121 (DGX Spark class): not 12.0 + CHECK(!gr_v3_default(false, 12, 0, true, 128.0 * GiB)); // integrated + CHECK(!gr_v3_default(true, 12, 0, false, 32.0 * GiB)); // a HIP build: gfx1201 reports 12.0 too + CHECK(!gr_v3_default(false, 6, 0, false, 16.0 * GiB)); // P100 + } + { + using namespace strata; + // the prompt attention on int8 tensor cores: every CUDA card from sm_80 on, not Turing / Volta / Pascal, not HIP + CHECK(prompt_attn_imma_default(false, 120)); // RTX PRO 5000 / RTX 50: measured +1.6-1.8% + CHECK(prompt_attn_imma_default(false, 86)); // 2x RTX A4000 / RTX 3060: measured +1.1-1.3% + CHECK(prompt_attn_imma_default(false, 80)); + CHECK(prompt_attn_imma_default(false, 89)); + CHECK(!prompt_attn_imma_default(false, 75)); // Turing (also a forced STRATA_QSA_WARP=1 card) + CHECK(!prompt_attn_imma_default(false, 70)); // Volta + CHECK(!prompt_attn_imma_default(false, 60)); // Pascal (P100) + CHECK(!prompt_attn_imma_default(true, 120)); // HIP + } return fails ? 1 : 0; } diff --git a/src/core/verify.cpp b/src/core/verify.cpp index b9d4eede..f99dc9e8 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -225,7 +225,7 @@ inline float g_route_prior() { cudaDeviceProp p; const bool ok = cudaGetDeviceProperties(&p, dev) == cudaSuccess; if (!ok) cudaGetLastError(); - per_dev[dev] = 1.0f + (ok && !p.integrated && (double) p.totalGlobalMem / 1073741824.0 <= 13.0 ? 2.0f : 0.0f); + per_dev[dev] = 1.0f + (ok ? strata::route_prior_default(false, p.integrated != 0, (double) p.totalGlobalMem) : 0.0f); } return per_dev[dev] - 1.0f; #endif diff --git a/src/dsv41/ds4_experts_rule.hpp b/src/dsv41/ds4_experts_rule.hpp index 140b3df4..ae872def 100644 --- a/src/dsv41/ds4_experts_rule.hpp +++ b/src/dsv41/ds4_experts_rule.hpp @@ -18,10 +18,13 @@ constexpr int kFasterModeExperts = 5; // requested: --experts (-1: not given, the rule decides); vram_bytes: the total memory of the cards the engine uses; // model_k: the experts a word takes in the model; integrated: a GPU that shares the PC's RAM (Strix Halo: part of the experts live only on // the SSD, each expert dropped is less read - measured 5 against 6 on a Radeon 8065S: decode +11..13%, prompts +5..7%). The result is in 1 .. model_k. -inline int experts_per_word(int requested, uint64_t vram_bytes, int model_k, bool integrated = false) { +// multi_rdna4: two or more RDNA4 cards (gfx1200 / gfx1201: R9700, RX 9000) that together hold at least half of the routed experts - the 4 x R9700 box +// the Marlin stream measured: 5 against 6 experts, 2.25 bpw, 8K prompt 1339 -> 1419 ppts (+6%) and decode 78.1 -> 81.2 tok/s (+4%), reference KL +// 0.10987 against 0.10833 and top-1 87.59% against 87.53% (the gate is 0.006). Faster mode there too, by default. +inline int experts_per_word(int requested, uint64_t vram_bytes, int model_k, bool integrated = false, bool multi_rdna4 = false) { if (model_k <= 1) return model_k; int n = requested; - if (n < 1) n = integrated || (vram_bytes != 0 && vram_bytes <= kFasterModeVramMax) ? kFasterModeExperts : model_k; + if (n < 1) n = integrated || multi_rdna4 || (vram_bytes != 0 && vram_bytes <= kFasterModeVramMax) ? kFasterModeExperts : model_k; if (n > model_k) n = model_k; return n < 1 ? 1 : n; } diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index e36ed767..9c359644 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2132,11 +2132,13 @@ struct Model::Impl { cudaDeviceProp ip{}; if (cudaGetDeviceProperties(&ip, dv.id) == cudaSuccess && ip.integrated) integrated = true; } - const int n = experts_test_override(experts_per_word(o.experts, vram_all, l.k_exp, integrated), l.k_exp); + // two or more RDNA4 cards holding at least half of the experts (the 4 x R9700 class): Faster by default too + const bool multi_rdna4 = rdna4() && devs.size() >= 2 && gpu_expert_share() >= 0.5; + const int n = experts_test_override(experts_per_word(o.experts, vram_all, l.k_exp, integrated, multi_rdna4), l.k_exp); experts_used = n; if (n < l.k_exp) std::fprintf(stderr, "ds4: experts per word: %d (%s; full quality: --experts %d)\n", n, - o.experts >= 1 ? "as asked" : "faster mode", l.k_exp); + o.experts >= 1 ? "as asked" : multi_rdna4 ? "faster mode: the cards hold most of the experts" : "faster mode", l.k_exp); else if (o.experts >= 1) std::fprintf(stderr, "ds4: experts per word: %d (full quality)\n", n); } diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 73a9089b..ad1fcbd3 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -2302,6 +2302,32 @@ int g_gr_fast = -1; #endif void fused_gr_set_fast(int on) { g_gr_fast = on; } +// STRATA_GR_V3: the stream-split hyper-connection read (gr_down_v3_kernel / gr_up_v3_kernel). Another summation order than the default +// read (~1e-7; a greedy tie can flip, so the answers are not byte-identical to 0.2.6's). 0.2.7: ON by default on a compute capability 12.0 +// card (RTX 50 / RTX PRO Blackwell: sm120_series.hpp, STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB of memory, discrete; +// measured on the RTX PRO 5000 72 GB with every expert resident: code decode 245.1 -> 248.1 tok/s (+1.2%, identical tokens), a story prompt +// +6.4% (tokens changed, not a claim), held-out document prompt +4.3%, with STRATA_PROMPT_ATTN_IMMA=1 +1.5% decode / +1.6-1.8% prompt together, +// 5 pairs. NOT a default elsewhere: it measured -3.0% / -5.9% on 2x RTX A4000 (sm_86) and +1.0% / -3.4% on an RTX 3060 (sm_86), and a 12 GB +// sm_120 card (RTX 5070: streams most experts, the read is a small share of its window) is unmeasured. STRATA_GR_V3=0 / 1 forces it off / on +// on any card; never in a HIP build (gfx12 reports compute capability 12.0 too). Decided per card, first asked in fused_gr_check (before any +// graph capture). +static bool gr_v3_default_on(int dev) { +#if defined(__HIPCC__) + (void) dev; + return false; +#else + static int per_dev[64]; // 0 unknown, 1 no, 2 yes + if (dev < 0 || dev >= 64) return false; + if (!per_dev[dev]) { + cudaDeviceProp p; + const bool ok = cudaGetDeviceProperties(&p, dev) == cudaSuccess; + if (!ok) cudaGetLastError(); + per_dev[dev] = ok && strata::gr_v3_default(false, p.major, p.minor, p.integrated != 0, (double) p.totalGlobalMem) ? 2 : 1; + } + return per_dev[dev] == 2; +#endif +} + bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, int stamp_i0) { if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { @@ -2337,12 +2363,13 @@ bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi } return q8; } - // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in) - static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); + // the two-kernel read above (another summation order): STRATA_GR_V3=0 / 1, unset = gr_v3_default_on (a 12.0 card with > 13 GiB) + static const int v3_env = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit int dev3 = 0; + cudaGetDevice(&dev3); + const bool v3 = v3_env >= 0 ? v3_env == 1 : gr_v3_default_on(dev3); if (v3) { - cudaGetDevice(&dev3); if (dev3 >= 0 && dev3 < 64 && split3[dev3] == 0) { int optin = 0; cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev3); @@ -2653,6 +2680,7 @@ int fused_gr_variant() { void fused_gr_check() { int dev = 0; cudaGetDevice(&dev); + (void) gr_v3_default_on(dev); // decided here, before any graph capture asks if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; const int want = env_variant(); if (want == kHcPlain) { diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 3bdc4ffc..f2b2d0a0 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1,5 +1,6 @@ // src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. #include "strata/core/emulate.hpp" +#include "strata/core/sm120_series.hpp" #include "strata/core/sm75_series.hpp" #include "strata/core/geometry.hpp" #include "strata/core/gfx12_platform_defaults.hpp" @@ -2418,12 +2419,16 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 if (pf_env == 1 || (pf_env < 0 && t75 && strata::sm75_series())) return launch<1, true>(q, pools, ids, steps, cap, s, attn, n_q, st); return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st); } - // STRATA_PROMPT_ATTN_IMMA=1 (opt-in, sm_80+): both products on INT8 tensor cores (prompt_attn_i8v3_kernel) + // STRATA_PROMPT_ATTN_IMMA (sm_80+): both products on INT8 tensor cores (prompt_attn_i8v3_kernel). ON by default since 0.2.7 on every + // card that has them (Ampere and newer, CUDA builds; not Turing, Volta or Pascal, which have no int8 m16n8k32 MMA this kernel needs): + // +1.6% / +1.8% prompt at 8K / 16K on the RTX PRO 5000 (sm_120) and +1.1% / +1.3% at 8K / 16K on 2x RTX A4000 (sm_86), decode unchanged, + // 5 pairs each; another summation order (~1e-7), so a near-tie can flip a prompt's first token. Sm_80, 8.9, 9.0 and the datacentre + // Blackwells run the same kernel unmeasured. STRATA_PROMPT_ATTN_IMMA=0 is the off switch (the v2 i8 kernel of 0.2.6), =1 as the default. if (g_pa_imma < 0) { const char* v = std::getenv("STRATA_PROMPT_ATTN_IMMA"); - g_pa_imma = v != nullptr && v[0] == '1' ? 1 : 0; + g_pa_imma = v == nullptr ? 2 : (v[0] == '1' ? 1 : 0); // 2: the default (on where the kernel can run) } - if (g_pa_imma == 1 && !turing) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st); + if (!turing && (g_pa_imma == 1 || (g_pa_imma == 2 && strata::prompt_attn_imma_default(false, 80)))) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st); return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st); } if (!pools.k_pool || !pools.v_pool) return false; diff --git a/src/kernels/fused_gr_bench.cpp b/src/kernels/fused_gr_bench.cpp index 0ac95eaf..677696cf 100644 --- a/src/kernels/fused_gr_bench.cpp +++ b/src/kernels/fused_gr_bench.cpp @@ -55,6 +55,12 @@ static std::vector q8_0_of_bf16(const std::vector& w, size_t } int main(int argc, char** argv) { + // the bench's contract is the default kernels' bitwise hashes; the split read (a default on a 12.0 card since 0.2.7) is another summation order +#if defined(_WIN32) + if (std::getenv("STRATA_GR_V3") == nullptr) _putenv_s("STRATA_GR_V3", "0"); +#else + if (std::getenv("STRATA_GR_V3") == nullptr) setenv("STRATA_GR_V3", "0", 1); +#endif setvbuf(stdout, nullptr, _IONBF, 0); const int iters = argc > 1 ? std::atoi(argv[1]) : 500; const int t_lo = argc > 2 ? std::atoi(argv[2]) : 1, t_hi = argc > 3 ? std::atoi(argv[3]) : 6; diff --git a/src/kernels/gr_parity.cpp b/src/kernels/gr_parity.cpp index 34d7510b..22da807b 100644 --- a/src/kernels/gr_parity.cpp +++ b/src/kernels/gr_parity.cpp @@ -480,6 +480,12 @@ int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const ui } // namespace int main(int argc, char** argv) { + // this test compares the default kernels bit for bit; the split read (a default on a 12.0 card since 0.2.7) is STRATA_GR_V3=1 below +#if defined(_WIN32) + if (std::getenv("STRATA_GR_V3") == nullptr) _putenv_s("STRATA_GR_V3", "0"); +#else + if (std::getenv("STRATA_GR_V3") == nullptr) setenv("STRATA_GR_V3", "0", 1); +#endif bool selftest = false; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--selftest") selftest = true; diff --git a/tests/dsv41/experts_rule_test.cpp b/tests/dsv41/experts_rule_test.cpp index 1f9bfee7..6fb5a1d8 100644 --- a/tests/dsv41/experts_rule_test.cpp +++ b/tests/dsv41/experts_rule_test.cpp @@ -38,6 +38,15 @@ int main() { CHECK_EQ(experts_per_word(-1, 24 * GiB, 6, false), 6); // a discrete 24 GB card CHECK_EQ(experts_per_word(-1, 12 * GiB, 6, false), 5); // a discrete 12 GB card CHECK_EQ(experts_per_word(6, 91 * GiB, 6, true), 6); // --experts 6 wins on the unified-memory GPU too + // two or more RDNA4 cards that hold at least half of the experts (4 x R9700, 128 GiB in all): faster mode by default (the 5th argument) + CHECK_EQ(experts_per_word(-1, 4 * 32 * GiB, 6, false, true), 5); + CHECK_EQ(experts_per_word(-1, 3 * 32 * GiB, 6, false, true), 5); + CHECK_EQ(experts_per_word(-1, 4 * 32 * GiB, 6, false, false), 6); // the same cards when they hold under half (or are not RDNA4): the model's 6 + CHECK_EQ(experts_per_word(6, 4 * 32 * GiB, 6, false, true), 6); // --experts 6 (the app's / Terminal's "Full quality") wins + CHECK_EQ(experts_per_word(4, 4 * 32 * GiB, 6, false, true), 4); // so does any other --experts N + CHECK_EQ(experts_per_word(5, 4 * 32 * GiB, 6, false, false), 5); + CHECK_EQ(experts_per_word(-1, 4 * 32 * GiB, 1, false, true), 1); // a model of one expert a word has nothing to drop + CHECK_EQ(experts_test_override(experts_per_word(-1, 4 * 32 * GiB, 6, false, true), 6), 5); CHECK_EQ(experts_per_word(-1, 91 * GiB, 4, true), 4); // never raised // unknown memory (0): the model's count, never a silent cut CHECK_EQ(experts_per_word(-1, 0, 6), 6); From 9e3fd0f73a4a21be5c2885b43a51765ca3445ed2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:41:17 +0100 Subject: [PATCH 078/177] App: the DeepSeek card names the free disk the set needs, and the version line says "{N} GB RAM + VRAM, plus about {disk} GB of disk" The "This computer" card said only "Fits fully in memory." for DeepSeek, with no word of the ~265 GB of disk. For a DeepSeek version it now says "Needs about {N} GB of free disk space. What does not fit in memory is read from your SSD." (the spill line stays beside it when part of the model is read from the SSD), and the selected version's line reads "{N} GB RAM + VRAM, plus about {disk} GB of disk". {disk} is not hard-coded: the catalog (tools/strata_mcp.py) gives each set its `disk_gb`, the set's whole download (model files, n-gram table, drafter, metadata) plus the pack and room to work (dsv41_fit.DISK_HEADROOM_GB), so 2.00 and 2.25 differ. Same card and row markup, no design change; every other model keeps its card. Both sentences are fx80 and fx81 in the eight fix catalogs. The Terminal's DeepSeek description makes no "fits fully in memory" claim (its lines already state the download and the free disk), so it is unchanged. --- apps/host/src/components/NativeModels.tsx | 2 +- apps/host/src/components/PcFitCard.tsx | 5 +- apps/host/src/components/VersionPicker.tsx | 2 +- apps/host/src/lib/native.ts | 2 +- apps/host/src/locales/fix-de.json | 4 +- apps/host/src/locales/fix-en.json | 4 +- apps/host/src/locales/fix-es.json | 4 +- apps/host/src/locales/fix-ja.json | 4 +- apps/host/src/locales/fix-ko.json | 4 +- apps/host/src/locales/fix-pt.json | 4 +- apps/host/src/locales/fix-ru.json | 4 +- apps/host/src/locales/fix-zh.json | 4 +- apps/host/tests/deepseek-card.test.mjs | 72 ++++++++++++++++++++++ tools/strata_mcp.py | 9 +++ tools/test_setup_dsv41.py | 16 +++++ 15 files changed, 127 insertions(+), 13 deletions(-) create mode 100644 apps/host/tests/deepseek-card.test.mjs diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 1ea22472..0e267e6b 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -209,7 +209,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(expert && IMAGE_GENERATION_VISIBLE ? <>
{tr("Image generation ")}{tr("Optional")} { }}/>
: null)} {tr(expert ?

{tr("Expert settings")}

{tr(tunedNow ?

{tr("Showing the values of your tuning '{0}'.", [tunedNow.name])}

: null)}
: null)}
- + !pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")})}

{tr(plan?.drafting?.needed ?

{tr("Choosing DFlash2 also downloads its drafter: about {0} GB, once. If it does not fit in graphics memory, the model uses the MTP instead.", [plan.drafting.gb])}

: null)}{tr(installed?.ready ?

{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}

: null)}{tr(plan?.plan?.disk_short ? : null)}{tr(installed?.ready ?

{tr("Any currently loaded native models will be unloaded first.")}

: <>

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

)}{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index 17ca134b..62a5e2a1 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -15,7 +15,7 @@ function Meter({ label, total, use }: { label: string; total: number; use: numbe * "This computer": the graphics memory and RAM, and what the chosen version would take of each. One plain line says whether it fits * or how much would be read from the SSD (the n-gram table, which always sits on the SSD, is not counted). */ -export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null }) { +export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = null }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null; diskGb?: number | null }) { const freeVram = Math.max(0, vramGb - (inUse?.vramGb ?? 0)), freeRam = ramGb ? Math.max(0, ramGb - (inUse?.ramGb ?? 0)) : 0; return

{tr("This computer")}

@@ -23,6 +23,7 @@ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null }: { gpuNa {tr(fit?.known && vramGb > 0 ? : null)} {tr(fit?.known && ramGb ? : null)} {tr(inUse ?

{tr("Models that stay loaded use about {0} GB of RAM and {1} GB of this card’s memory.", [inUse.ramGb, inUse.vramGb])}

: null)} - {tr(fit?.known ?

{tr(fit.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit.spillGb)])}

: null)} + {tr(diskGb ?

{tr("Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", [Math.round(diskGb)])}

: null)} + {tr(fit?.known && (diskGb ? fit.spillGb >= 1 : true) ?

{tr(fit.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit.spillGb)])}

: null)}
; } diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index dd5fbd00..5a078316 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -68,7 +68,7 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG return <> {tr(open ? setOpen(false)}> diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index e6e64bbf..adab6e92 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -3,7 +3,7 @@ import { api } from './client'; import type { Hardware, RuntimeModels } from './types'; export interface GpuChoiceOption {key:string;cards:number[];label:string;verdict:'fits'|'tight'|'spills'|'unknown';words:string;notes:string[];recommended:boolean} export interface GpuChoice {options:GpuChoiceOption[];recommended:string|null;ignored:{name?:string;why_ignored:string}[];cards:number} -export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** DeepSeek-V4.1-Flash and the like: several big files and an engine of their own. */multi_file?:boolean} +export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** DeepSeek-V4.1-Flash and the like: several big files and an engine of their own. */multi_file?:boolean;/** DeepSeek: the free disk the set needs (its download plus the pack and room to work), from the set itself. */disk_gb?:number} export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]} export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean;forModel?:string} export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record|null;progress?:Record|null} diff --git a/apps/host/src/locales/fix-de.json b/apps/host/src/locales/fix-de.json index f378e020..c29c0281 100644 --- a/apps/host/src/locales/fix-de.json +++ b/apps/host/src/locales/fix-de.json @@ -77,5 +77,7 @@ "fx76": "Ein (empfohlen)", "fx77": "Das ist ein sehr großes Modell. Der Download umfasst {0} GB und braucht etwa so viel freien Speicherplatz. Es läuft auf NVIDIA-RTX-Karten der Serien 30, 40 und 50, auf einer Radeon AI PRO R9700 (Linux) oder auf einem Ryzen-AI-Max-/Strix-Halo-PC (Windows); wie schnell es ist, hängt von Speicher und Grafikkarte ab (die Zeile darunter sagt, was auf diesem Computer zu erwarten ist). Was nicht in den Speicher passt, wird von deiner SSD gelesen, deshalb zählt eine NVMe-SSD.", "fx78": "Noch nicht getestet. Ein so langer Kontext nimmt dem Modell Grafikspeicher weg, und lange Prompts werden langsam gelesen.", - "fx79": "Aus (empfohlen)" + "fx79": "Aus (empfohlen)", + "fx80": "Braucht etwa {0} GB freien Speicherplatz. Was nicht in den Speicher passt, wird von Ihrer SSD gelesen.", + "fx81": "{0} RAM + VRAM, dazu etwa {1} GB Speicherplatz" } diff --git a/apps/host/src/locales/fix-en.json b/apps/host/src/locales/fix-en.json index efe52962..332f7041 100644 --- a/apps/host/src/locales/fix-en.json +++ b/apps/host/src/locales/fix-en.json @@ -77,5 +77,7 @@ "fx76": "On (recommended)", "fx77": "This is a very large model. The download is {0} GB and it needs about as much free disk space. It runs on NVIDIA RTX 30, 40 and 50 cards, on a Radeon AI PRO R9700 (Linux) or on a Ryzen AI Max / Strix Halo PC (Windows); how fast it is depends on the memory and card (the line below says what to expect on this computer). What does not fit in memory is read from your SSD, so an NVMe drive matters.", "fx78": "Not tested yet. A context this long takes graphics memory from the model and reads long prompts slowly.", - "fx79": "Off (recommended)" + "fx79": "Off (recommended)", + "fx80": "Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", + "fx81": "{0} RAM + VRAM, plus about {1} GB of disk" } diff --git a/apps/host/src/locales/fix-es.json b/apps/host/src/locales/fix-es.json index 211c1988..d2bef534 100644 --- a/apps/host/src/locales/fix-es.json +++ b/apps/host/src/locales/fix-es.json @@ -77,5 +77,7 @@ "fx76": "Activado (recomendado)", "fx77": "Es un modelo muy grande. La descarga es de {0} GB y necesita casi el mismo espacio libre en disco. Funciona con tarjetas NVIDIA RTX de las series 30, 40 y 50, con una Radeon AI PRO R9700 (Linux) o en un PC con Ryzen AI Max / Strix Halo (Windows); su velocidad depende de la memoria y de la tarjeta (la línea de abajo indica qué esperar en este equipo). Lo que no cabe en memoria se lee de tu SSD, así que importa que sea NVMe.", "fx78": "Aún sin probar. Un contexto tan largo le quita memoria gráfica al modelo y lee los prompts largos con lentitud.", - "fx79": "Desactivado (recomendado)" + "fx79": "Desactivado (recomendado)", + "fx80": "Necesita unos {0} GB de espacio libre en disco. Lo que no cabe en memoria se lee de tu SSD.", + "fx81": "{0} de RAM + VRAM, más unos {1} GB de disco" } diff --git a/apps/host/src/locales/fix-ja.json b/apps/host/src/locales/fix-ja.json index 2b888a77..28931624 100644 --- a/apps/host/src/locales/fix-ja.json +++ b/apps/host/src/locales/fix-ja.json @@ -77,5 +77,7 @@ "fx76": "オン(推奨)", "fx77": "とても大きなモデルです。ダウンロードは {0} GB で、ほぼ同じ大きさの空き容量が必要です。NVIDIA RTX 30・40・50 シリーズ、Radeon AI PRO R9700(Linux)、または Ryzen AI Max / Strix Halo の PC(Windows)で動きます。速さはメモリとカードによって変わります(この PC での目安は下の行に表示されます)。メモリに入らない分は SSD から読むため、NVMe ドライブが重要です。", "fx78": "まだテストされていません。これほど長いコンテキストは、モデルが使うグラフィックスメモリを消費し、長いプロンプトの読み込みも遅くなります。", - "fx79": "オフ(推奨)" + "fx79": "オフ(推奨)", + "fx80": "約 {0} GB の空きディスク容量が必要です。メモリに入らない分は SSD から読み込みます。", + "fx81": "RAM + VRAM {0}、ほかにディスク約 {1} GB" } diff --git a/apps/host/src/locales/fix-ko.json b/apps/host/src/locales/fix-ko.json index befec99d..f92b8526 100644 --- a/apps/host/src/locales/fix-ko.json +++ b/apps/host/src/locales/fix-ko.json @@ -77,5 +77,7 @@ "fx76": "켬(권장)", "fx77": "매우 큰 모델입니다. 다운로드는 {0}GB이고, 거의 같은 크기의 여유 디스크 공간이 필요합니다. NVIDIA RTX 30·40·50 시리즈 카드, Radeon AI PRO R9700(Linux), 또는 Ryzen AI Max / Strix Halo PC(Windows)에서 실행됩니다. 속도는 메모리와 카드에 따라 달라집니다(아래 줄에 이 컴퓨터에서 기대할 수 있는 속도가 표시됩니다). 메모리에 들어가지 않는 부분은 SSD에서 읽으므로 NVMe 드라이브가 중요합니다.", "fx78": "아직 테스트하지 않았습니다. 이렇게 긴 컨텍스트는 모델이 쓸 그래픽 메모리를 차지하고, 긴 프롬프트를 느리게 읽습니다.", - "fx79": "끔(권장)" + "fx79": "끔(권장)", + "fx80": "약 {0}GB의 여유 디스크 공간이 필요합니다. 메모리에 들어가지 않는 부분은 SSD에서 읽습니다.", + "fx81": "RAM + VRAM {0}, 디스크 약 {1}GB 추가" } diff --git a/apps/host/src/locales/fix-pt.json b/apps/host/src/locales/fix-pt.json index 3accb7ef..eacbe231 100644 --- a/apps/host/src/locales/fix-pt.json +++ b/apps/host/src/locales/fix-pt.json @@ -77,5 +77,7 @@ "fx76": "Ativado (recomendado)", "fx77": "Este é um modelo muito grande. O download tem {0} GB e precisa de quase o mesmo espaço livre em disco. Ele roda em placas NVIDIA RTX das séries 30, 40 e 50, em uma Radeon AI PRO R9700 (Linux) ou em um PC com Ryzen AI Max / Strix Halo (Windows); a velocidade depende da memória e da placa (a linha abaixo diz o que esperar neste computador). O que não cabe na memória é lido do seu SSD, então um NVMe faz diferença.", "fx78": "Ainda não testado. Um contexto tão longo tira memória gráfica do modelo e lê prompts longos devagar.", - "fx79": "Desativado (recomendado)" + "fx79": "Desativado (recomendado)", + "fx80": "Precisa de cerca de {0} GB de espaço livre em disco. O que não cabe na memória é lido do seu SSD.", + "fx81": "{0} de RAM + VRAM, mais cerca de {1} GB de disco" } diff --git a/apps/host/src/locales/fix-ru.json b/apps/host/src/locales/fix-ru.json index d2147327..5af178cf 100644 --- a/apps/host/src/locales/fix-ru.json +++ b/apps/host/src/locales/fix-ru.json @@ -77,5 +77,7 @@ "fx76": "Вкл. (рекомендуется)", "fx77": "Это очень большая модель. Загрузка — {0} ГБ, и нужно почти столько же свободного места на диске. Она работает на видеокартах NVIDIA RTX серий 30, 40 и 50, на Radeon AI PRO R9700 (Linux) или на ПК с Ryzen AI Max / Strix Halo (Windows); скорость зависит от памяти и видеокарты (строка ниже подскажет, чего ждать на этом компьютере). То, что не помещается в память, читается с вашего SSD, поэтому важен накопитель NVMe.", "fx78": "Ещё не проверено. Такой длинный контекст отнимает у модели видеопамять, а длинные запросы читаются медленно.", - "fx79": "Выкл. (рекомендуется)" + "fx79": "Выкл. (рекомендуется)", + "fx80": "Нужно около {0} ГБ свободного места на диске. То, что не помещается в память, читается с вашего SSD.", + "fx81": "{0} RAM + VRAM, плюс около {1} ГБ на диске" } diff --git a/apps/host/src/locales/fix-zh.json b/apps/host/src/locales/fix-zh.json index 48b64cd1..6f6117a2 100644 --- a/apps/host/src/locales/fix-zh.json +++ b/apps/host/src/locales/fix-zh.json @@ -77,5 +77,7 @@ "fx76": "开启(推荐)", "fx77": "这是一个非常大的模型。下载大小为 {0} GB,需要差不多同样大小的可用磁盘空间。它可在 NVIDIA RTX 30、40 和 50 系列显卡、Radeon AI PRO R9700(Linux)或 Ryzen AI Max / Strix Halo 电脑(Windows)上运行;速度取决于内存和显卡(下面一行会说明在这台电脑上的预期)。内存放不下的部分会从你的 SSD 读取,所以 NVMe 硬盘很重要。", "fx78": "尚未测试。这么长的上下文会占用本该给模型使用的显存,读取长提示词也会很慢。", - "fx79": "关闭(推荐)" + "fx79": "关闭(推荐)", + "fx80": "大约需要 {0} GB 可用磁盘空间。内存放不下的部分会从你的 SSD 读取。", + "fx81": "{0} 内存 + 显存,另需约 {1} GB 磁盘空间" } diff --git a/apps/host/tests/deepseek-card.test.mjs b/apps/host/tests/deepseek-card.test.mjs new file mode 100644 index 00000000..58b51a7e --- /dev/null +++ b/apps/host/tests/deepseek-card.test.mjs @@ -0,0 +1,72 @@ +// The DeepSeek model card in the Models screen names the free disk the set needs (from the set itself: 2.00 and 2.25 differ), in the existing card markup, +// and the version line says "{N} GB RAM + VRAM, plus about {disk} GB of disk". Other models keep their card. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; +import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const read = rel => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8').replace(/\r\n/g, '\n'); +const stdin = { contents: "import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { PcFitCard } from './src/components/PcFitCard'; export { setTranslationLanguage } from './src/lib/i18n'; export const render = props => renderToStaticMarkup(createElement(PcFitCard, props));", resolveDir: fileURLToPath(new URL('..', import.meta.url)), loader: 'ts' }; +const built = await build({ stdin, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json', '.tsx': 'tsx' }, jsx: 'automatic', logLevel: 'silent', banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" } }); +const dir = mkdtempSync(join(tmpdir(), 'strata-card-test-')); +writeFileSync(join(dir, 'card.mjs'), built.outputFiles[0].text); // a file, not a data: URL: the bundled react-dom/server needs require() +const { render, setTranslationLanguage } = await import(pathToFileURL(join(dir, 'card.mjs')).href); +rmSync(dir, { recursive: true, force: true }); +const fit = (spillGb, known = true) => ({ memoryGb: 250, vramUseGb: 10, ramUseGb: 240, spillGb, known }); +const card = props => render({ gpuName: 'RTX 5070', ramGb: 64, vramGb: 12, ...props }); + +test('a DeepSeek card with no spill says what it needs on the disk, not just "Fits fully in memory"', () => { + setTranslationLanguage('en'); + const html = card({ fit: fit(0), diskGb: 262.8 }); + assert.match(html, /Needs about 263 GB of free disk space\. What does not fit in memory is read from your SSD\./); + assert.doesNotMatch(html, /Fits fully in memory/); + assert.match(html, /class="pc-note"/, 'the existing note markup'); +}); + +test('the disk comes from the set: 2.00 and 2.25 say different figures', () => { + setTranslationLanguage('en'); + assert.match(card({ fit: fit(0), diskGb: 262.8 }), /about 263 GB/); + assert.match(card({ fit: fit(0), diskGb: 279.8 }), /about 280 GB/); +}); + +test('a DeepSeek card that does spill keeps its spill line beside the disk line', () => { + setTranslationLanguage('en'); + const html = card({ fit: fit(120), diskGb: 262.8 }); + assert.match(html, /Needs about 263 GB of free disk space/); + assert.match(html, /About 120 GB will be read from the SSD, so answers can be a little slower\./); +}); + +test('every other model keeps its card as it was', () => { + setTranslationLanguage('en'); + assert.match(card({ fit: fit(0) }), /Fits fully in memory\./); + assert.match(card({ fit: fit(0), diskGb: null }), /Fits fully in memory\./); + assert.doesNotMatch(card({ fit: fit(0) }), /free disk space/); + assert.match(card({ fit: fit(30) }), /About 30 GB will be read from the SSD/); +}); + +test('the words are in all eight languages with the same slots', () => { + const en = JSON.parse(read('../src/locales/fix-en.json')); + const ids = Object.keys(en).filter(k => /^Needs about \{0\} GB of free disk space|^\{0\} RAM \+ VRAM, plus about \{1\} GB of disk$/.test(en[k])); + assert.equal(ids.length, 2); + for (const lang of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']) { + const cat = JSON.parse(read(`../src/locales/fix-${lang}.json`)); + for (const id of ids) { + assert.ok(cat[id] && cat[id] !== en[id], `${lang} ${id} is translated`); + assert.deepEqual((cat[id].match(/\{\d+\}/g) ?? []).sort(), (en[id].match(/\{\d+\}/g) ?? []).sort(), `${lang} ${id} slots`); + } + } + setTranslationLanguage('de'); + assert.match(card({ fit: fit(0), diskGb: 262.8 }), /Braucht etwa 263 GB freien Speicherplatz/); + setTranslationLanguage('en'); +}); + +test('the Models screen passes the set\'s disk to the card, and the version line states it for DeepSeek only', () => { + const screen = read('../src/components/NativeModels.tsx'); + assert.match(screen, /]*diskGb=\{selectedSize\?\.multi_file \? selectedSize\.disk_gb \?\? selectedSize\.download_gb : null\}/); + const picker = read('../src/components/VersionPicker.tsx'); + assert.match(picker, /tr\("\{0\} RAM \+ VRAM, plus about \{1\} GB of disk", \[gb\(fit\.memoryGb\), Math\.round\(selected\.disk_gb\)\]\)/); + assert.match(picker, /: fit \? `\$\{gb\(fit\.memoryGb\)\} RAM \+ VRAM` : ''/, 'every other model keeps its line'); +}); diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 5a5eb2fe..37db14da 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1268,6 +1268,9 @@ class Strata: # RAM + VRAM the weights need together, WITHOUT the n-gram table (that stays on the SSD): Gyro states it # (mem_total), for the rest the experts plus ~1 GB for the dense part (Swift IQ2_XS: 35.5 + 1 = 36.5) "mem_total": bool(d.get("mem_total")), "multi_file": bool(own and own.get("multi_file")), + # DeepSeek only: the free disk the set needs, from the set itself (the download: model files, n-gram table, drafter and + # metadata, plus the pack folder and room to work, strata_control/dsv41_fit.DISK_HEADROOM_GB): 2.00 and 2.25 differ + "disk_gb": self.dsv41_disk_gb(d) if own and own.get("multi_file") else None, # the first engine that reads this size's files (setup.py "engine"); the app says "needs a newer engine" # with the update step when the installed one is older. None: any engine that setup accepts. "engine_min": ".".join(map(str, d["engine"])) if d.get("engine") else None, @@ -1283,6 +1286,12 @@ class Strata: "sizes": sizes}) return out + @staticmethod + def dsv41_disk_gb(d: dict) -> float: + """The free disk a DeepSeek set needs: its whole download plus the pack and room to work (the card text says "about").""" + from strata_control import dsv41_fit + return round(float(d["download_gb"]) + dsv41_fit.DISK_HEADROOM_GB, 1) + def dsv41_plan(self, hw, disk_free=None, only=None, model=None) -> dict: """strata_control/dsv41_fit.plan for this computer; `only`: the card numbers a launch names (else every card that counts).""" from strata_control import dsv41_fit diff --git a/tools/test_setup_dsv41.py b/tools/test_setup_dsv41.py index cc8af0af..e2c49380 100644 --- a/tools/test_setup_dsv41.py +++ b/tools/test_setup_dsv41.py @@ -315,6 +315,22 @@ class Catalog(unittest.TestCase): small = next(f for f in s.model_table({"ram_gb": 32.0, "gpus": []}) if f["family"] == "deepseek41") self.assertTrue(all(x["on_this_pc"].startswith("does not fit") for x in small["sizes"])) # no card + def test_each_set_states_the_free_disk_it_needs_from_the_set_itself(self): + """The app's DeepSeek card says "Needs about N GB of free disk space": N is the set's whole download plus the pack and room to work, per set.""" + import strata_mcp as M + s = M.Strata(ROOT) + table = s.model_table({"ram_gb": 251.0, "gpus": [{**c, "usable": True} for c in FOUR], "engine_vendor": "amd"}) + fam = next(f for f in table if f["family"] == "deepseek41") + for size in fam["sizes"]: + self.assertEqual(size["disk_gb"], round(size["download_gb"] + dsv41_fit.DISK_HEADROOM_GB, 1), size["model"]) + by = {x["model"]: x["disk_gb"] for x in fam["sizes"]} + self.assertNotEqual(by["IST-DAS-2.00bpw"], by["IST-DAS-2.25bpw"], "2.00 and 2.25 do not need the same disk") + self.assertGreater(by["IST-DAS-2.25bpw"], by["IST-DAS-2.00bpw"]) + self.assertGreater(by["IST-DAS-2.00bpw"], by["IST-DAS-1.75bpw"]) + for f in table: + if f["family"] != "deepseek41": + self.assertTrue(all(x["disk_gb"] is None for x in f["sizes"]), f["family"]) + def test_the_install_plan(self): import strata_mcp as M s = M.Strata(ROOT) From 2ac3482144e98330b59331d17b83f9d56d550312 Mon Sep 17 00:00:00 2001 From: l33tm4st3r <26746186+l33tm4st3r@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:41:53 +0100 Subject: [PATCH 079/177] bench: the standard report names an AMD card and its ROCm runtime when only amd-smi exists (#3519) ROCm 7 and newer ship amd-smi and no rocm-smi, and the amdgpu product_name is empty on gfx1201, so a Radeon AI PRO R9700 run was filed under 'unknown' with 'runtime: not measured'. bench_facts reads the market name from amd-smi static --asic, the VRAM from the amdgpu sysfs file of the PCI address amd-smi list reports, the ROCm version from the install (or amd-smi -h), and keeps the probe's card name when the server only says 'AMD Radeon'. Ported from PR #3519 by l33tm4st3r with its tests and the BENCHMARK_PROTOCOL.md text. Changed while porting: the amd-smi branch also took macOS (os.name is posix there), which would have hidden the Apple chip; it now skips darwin, and a test keeps the chip. --- docs/BENCHMARK_PROTOCOL.md | 7 +- strata_cli/bench_facts.py | 67 ++++++++++- tests/terminal/test_bench_facts_amd.py | 157 +++++++++++++++++++++++++ 3 files changed, 227 insertions(+), 4 deletions(-) create mode 100644 tests/terminal/test_bench_facts_amd.py diff --git a/docs/BENCHMARK_PROTOCOL.md b/docs/BENCHMARK_PROTOCOL.md index 29e9e9eb..949f9d8f 100644 --- a/docs/BENCHMARK_PROTOCOL.md +++ b/docs/BENCHMARK_PROTOCOL.md @@ -329,7 +329,12 @@ An install with neither has no commit, and the run is `nonconforming`. `engine_v from `/props` (`build_info`), or `/v1/status` when `/props` has none. `build_kind` is `source` when the folder has a `.git`, otherwise `release`. The runner cannot read build options from a server; pass `--build-options` for a source build. The drivers and the CUDA version come from `nvidia-smi` (or `rocm-smi`, or the Windows display -driver key), read on the machine that runs the engine. +driver key), read on the machine that runs the engine. ROCm 7 and newer ship `amd-smi` and no `rocm-smi`: the card's +name is that tool's `static --asic` market name, its memory is the amdgpu sysfs file of the PCI address `amd-smi list` +reports, and the `rocm` runtime entry is the version file inside the ROCm install (`amd-smi -h` prints the same +version). Where the kernel builds amdgpu in there is no driver version to read, and `gpu-driver` stays null with a +reason. When the server can only name a vendor, because the amdgpu `product_name` is empty on some cards, the card the +local probe named is kept instead. Except for typed objects, arrays, numbers and booleans identified above, identity and descriptive fields are strings (or null with a reason where unavailable). Empty configuration objects mean no relevant options; diff --git a/strata_cli/bench_facts.py b/strata_cli/bench_facts.py index 309223bf..026b5c49 100644 --- a/strata_cli/bench_facts.py +++ b/strata_cli/bench_facts.py @@ -1,12 +1,13 @@ """What a standard benchmark report says about the machine, the build, the model and the settings (docs/BENCHMARK_PROTOCOL.md). -Every probe is best effort and local: it reads the inference host's own tools (nvidia-smi, rocm-smi, PowerShell, /proc, sysctl) and the +Every probe is best effort and local: it reads the inference host's own tools (nvidia-smi, rocm-smi, amd-smi, PowerShell, /proc, sysctl) and the server's answers. A fact that cannot be read becomes `None` with a reason in `Why`, never a guess. Nothing here changes the machine. """ from __future__ import annotations import getpass +import glob import hashlib import json import os @@ -193,6 +194,37 @@ def other_gpus() -> tuple[list[dict], str | None]: driver = next((c.get("driver") for c in found if c.get("driver")), None) except Exception: # noqa: BLE001 - a report without the card's name is still a report pass + elif os.name != "nt" and sys.platform != "darwin": # (a Mac has no AMD card to ask for; its chip is read below) + # ROCm 7 and newer ship amd-smi and no rocm-smi (verified on ROCm 10.1). Different grammar: `static --asic` + # gives the marketing name, `static --driver` the kernel driver's version, and the PCI address only comes + # from `amd-smi list`; the VRAM size is the amdgpu driver's sysfs file for that address. + def amd_json(args): + try: + return json.loads(run_cmd(["amd-smi", "static"] + args + ["--json"]).strip() or "{}").get("gpu_data") or [] + except (ValueError, OSError): + return [] + try: + bdf = {e.get("gpu"): (e.get("bdf") or "") for e in json.loads(run_cmd(["amd-smi", "list", "--json"]).strip() or "[]")} + except (ValueError, OSError): + bdf = {} + drv = {e.get("gpu"): ((e.get("driver") or {}).get("version") or "") for e in amd_json(["--driver"])} + for i, e in enumerate(amd_json(["--asic"])): + name = ((e.get("asic") or {}).get("market_name") or "").strip() + if not name: + continue + d = drv.get(e.get("gpu"), "") + driver = driver or (d if d.upper() not in ("", "N/A") else None) + vram = None + for dev in glob.glob("/sys/class/drm/card[0-9]*/device"): + try: + if bdf.get(e.get("gpu")) and os.path.basename(os.path.realpath(dev)).lower() == bdf[e["gpu"]].lower(): + with open(os.path.join(dev, "mem_info_vram_total"), encoding="utf-8") as f: + total = f.read().strip() + vram = int(total) if total.isdigit() else None + except OSError: + pass + cards.append({"device_index": i, "name": name, "memory_bytes": vram, "memory_kind": "dedicated", + "power_limit_w": None}) elif sys.platform == "darwin": chip = cpu_name() if chip: @@ -201,6 +233,25 @@ def other_gpus() -> tuple[list[dict], str | None]: return cards, driver +def rocm_version() -> str | None: + """ROCm's own version, which `rocm-smi --showdriverversion` used to report with the driver. ROCm 10 has no + `rocm-smi` and no `/opt/rocm/.info/`: its version file sits under `/core/.info/version`, and + `amd-smi -h` prints the same version.""" + for base in [os.environ.get("ROCM_PATH", ""), "/opt/rocm"]: + if not base: + continue + for sub in (".info/version", "core/.info/version"): + try: + with open(os.path.join(base, sub), encoding="utf-8") as f: + found = f.read().strip() + if found: + return found + except OSError: + pass + match = re.search(r"ROCm version:\s*([\d.]+)", run_cmd(["amd-smi", "-h"])) + return match.group(1) if match else None + + def lsblk_disk(data: dict) -> list[dict] | None: """The first physical disk in `lsblk -J -s` output. `-s` lists the parents of a device as nested children: an LVM volume is lvm -> partition -> disk, two levels down, so the walk goes all the way down.""" @@ -277,7 +328,12 @@ def hardware(why: Why, *, selected: list[int], served_gpu: str | None, model_dir named = [c for c in cards if c["name"] == served_gpu] cards = named[:1] or cards[:1] served = [n for n in (served_gpu or "").split(" + ") if n and n != "?"] - if served and cards and not all(n in {c["name"] for c in cards} for n in served): + # the amdgpu driver's product_name is empty on some cards (gfx1201 among them), so the server falls back to a bare + # "AMD Radeon": that names the vendor, not the card, and the local probe's marketing name is the one to keep + stub = re.compile(r"(?i)^(amd radeon|advanced micro devices(,? inc\.?)?|nvidia( corporation)?|intel" + r"( corporation)?)( graphics)?$") + if served and cards and not all(stub.match(n) for n in served) \ + and not all(n in {c["name"] for c in cards} for n in served): # the server reads cards the local tools do not list (another vendor's, or a different numbering) cards = [{"device_index": i, "name": n, "memory_bytes": None, "memory_kind": "dedicated", "power_limit_w": None} for i, n in enumerate(served)] @@ -308,7 +364,10 @@ def hardware(why: Why, *, selected: list[int], served_gpu: str | None, model_dir if not declared_background: why.add(pointer("hardware", "background_workloads"), "the runner does not inspect other programs; none were declared with --background") - return block, {"driver": driver, "cuda": cuda} + # an AMD card on Linux runs on ROCm, which the report names as the runtime; on ROCm 7 and newer that version no + # longer comes from rocm-smi, but from the install itself + rocm = rocm_version() if (sys.platform.startswith("linux") and cards and not cuda) else None + return block, {"driver": driver, "cuda": cuda, "rocm": rocm} # ------------------------------------------------------------------------------------------------------------ software @@ -364,6 +423,8 @@ def software(why: Why, machine: dict, *, engine_version: str | None, build_optio runtime.append({"name": "cuda-driver-supports", "version": machine["cuda"]}) elif machine.get("cuda"): runtime.append({"name": "cuda", "version": machine["cuda"]}) + if machine.get("rocm") and not any(r.get("name") == "rocm" for r in runtime): + runtime.append({"name": "rocm", "version": machine["rocm"]}) if sys.platform == "darwin": runtime.append({"name": "metal", "version": platform.mac_ver()[0] or platform.release()}) drivers = [{"name": "gpu-driver", "version": machine["driver"]}] if machine.get("driver") else [] diff --git a/tests/terminal/test_bench_facts_amd.py b/tests/terminal/test_bench_facts_amd.py new file mode 100644 index 00000000..353f432f --- /dev/null +++ b/tests/terminal/test_bench_facts_amd.py @@ -0,0 +1,157 @@ +"""ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, and the amdgpu driver's `product_name` is empty on gfx1201, so a +report from a Radeon wrote the vendor as the card ("AMD Radeon", `...-standard-unknown-...`) and `runtime: not +measured`. The strings below are the real output of `amd-smi static --asic --json`, `static --driver --json`, +`list --json` and `-h` on one AI PRO R9700 (gfx1201) with ROCm 10.1, trimmed to the fields the probe reads.""" +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from unittest import mock + +from strata_cli import bench_facts as bf + +ASIC = {"gpu_data": [{"gpu": 0, "asic": {"market_name": "AMD Radeon AI PRO R9700", "target_graphics_version": "gfx1201"}}, + {"gpu": 1, "asic": {"market_name": "AMD Radeon Graphics", "target_graphics_version": "gfx1036"}}]} +DRIVER = {"gpu_data": [{"gpu": 0, "driver": {"name": "amdgpu", "version": "N/A", + "os_kernel_version": "7.3.0-rc6-2-cachyos-rc"}}]} +LIST = [{"gpu": 0, "bdf": "0000:03:00.0", "node_id": 1}, {"gpu": 1, "bdf": "0000:7c:00.0", "node_id": 2}] +HELP = "AMD System Management Interface | Version: 27.1.0+7da43026 | ROCm version: 10.1.0 |" +BDF_TO_TOTAL = {"0000:03:00.0": "34208743424", "0000:7c:00.0": "805306368"} + + +def run_cmd(cmd: list[str], timeout: float = 15) -> str: + """ROCm 10.1 answers, with `rocm-smi` missing entirely.""" + if cmd[:1] == ["rocm-smi"]: + return "" + if cmd[:3] == ["amd-smi", "list", "--json"]: + return json.dumps(LIST) + if cmd[:2] == ["amd-smi", "static"]: + return json.dumps(DRIVER if "--driver" in cmd else ASIC) + if cmd == ["amd-smi", "-h"]: + return HELP + return "" + + +@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch") +class AmdSmiProbe(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + # /sys/class/drm/cardN/device is a symlink whose target's last component is the PCI address; the probe matches + # that address against `amd-smi list`, so the fake tree repeats the shape instead of the path + devices = [] + for card, bdf in (("card1", "0000:03:00.0"), ("card2", "0000:7c:00.0")): + pci = os.path.join(self.tmp.name, "pci", bdf) + os.makedirs(pci) + with open(os.path.join(pci, "mem_info_vram_total"), "w", encoding="utf-8") as f: + f.write(BDF_TO_TOTAL[bdf] + "\n") + link = os.path.join(self.tmp.name, "drm", card, "device") + os.makedirs(os.path.dirname(link)) + os.symlink(pci, link) + devices.append(link) + self.globs = mock.patch.object(bf.glob, "glob", lambda pattern: devices) + self.globs.start() + self.addCleanup(self.globs.stop) + self.cmds = mock.patch.object(bf, "run_cmd", run_cmd) + self.cmds.start() + self.addCleanup(self.cmds.stop) + + def test_names_both_cards_with_their_vram(self): + cards, driver = bf.other_gpus() + self.assertEqual([c["name"] for c in cards], ["AMD Radeon AI PRO R9700", "AMD Radeon Graphics"]) + self.assertEqual([c["memory_bytes"] for c in cards], [34208743424, 805306368]) + self.assertEqual([c["device_index"] for c in cards], [0, 1]) + + def test_a_stub_driver_version_stays_unmeasured(self): + # `amd-smi static --driver` says N/A when amdgpu is built into the kernel: that is not a version, so the report + # must keep saying it did not measure one instead of writing "N/A" + _, driver = bf.other_gpus() + self.assertIsNone(driver) + + def test_an_asic_without_a_market_name_is_skipped(self): + blank = {"gpu_data": [{"gpu": 0, "asic": {"market_name": ""}}, + {"gpu": 1, "asic": {"market_name": "AMD Radeon AI PRO R9700"}}]} + with mock.patch.object(bf, "run_cmd", lambda cmd, timeout=15: json.dumps(blank) if "static" in cmd else ""): + cards, _ = bf.other_gpus() + self.assertEqual([c["name"] for c in cards], ["AMD Radeon AI PRO R9700"]) + + def test_rocm_version_comes_from_the_install(self): + base = os.path.join(self.tmp.name, "rocm") + os.makedirs(os.path.join(base, "core", ".info")) + with open(os.path.join(base, "core", ".info", "version"), "w", encoding="utf-8") as f: + f.write("10.1.0\n") + with mock.patch.object(bf.os, "environ", {"ROCM_PATH": base}): + self.assertEqual(bf.rocm_version(), "10.1.0") + + def test_rocm_version_falls_back_to_the_help_text(self): + real_open = open + + def refuse(path, *args, **kwargs): + if "/opt/rocm" in str(path): + raise OSError("no ROCm install here") + return real_open(path, *args, **kwargs) + + env = {k: v for k, v in os.environ.items() if k != "ROCM_PATH"} + with mock.patch.object(bf.os, "environ", env), mock.patch("builtins.open", side_effect=refuse): + self.assertEqual(bf.rocm_version(), "10.1.0") + + +@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch") +class ServedName(unittest.TestCase): + """The server's `gpu` string is the driver's product_name, empty on gfx1201, so it degrades to the vendor. That + must not overwrite the card the local probe named, while a card only the server can see still wins.""" + + def cards(self): + return [{"device_index": 0, "name": "AMD Radeon AI PRO R9700", "memory_bytes": 34208743424, + "memory_kind": "dedicated", "power_limit_w": None}] + + def hardware(self, served_gpu): + with mock.patch.object(bf, "nvidia_gpus", lambda: ([], None, None)), \ + mock.patch.object(bf, "other_gpus", lambda: (self.cards(), None)): + block, machine = bf.hardware(bf.Why(), selected=[], served_gpu=served_gpu, model_dir=None, + declared_background=[]) + return block, machine + + def test_a_vendor_only_name_does_not_replace_the_card(self): + block, machine = self.hardware("AMD Radeon") + self.assertEqual([c["name"] for c in block["gpus"]], ["AMD Radeon AI PRO R9700"]) + self.assertEqual(block["gpus"][0]["memory_bytes"], 34208743424) + + def test_a_card_only_the_server_lists_still_wins(self): + block, _ = self.hardware("AMD Radeon RX 7900 XTX") + self.assertEqual([c["name"] for c in block["gpus"]], ["AMD Radeon RX 7900 XTX"]) + self.assertIsNone(block["gpus"][0]["memory_bytes"]) + + def test_the_rocm_runtime_reaches_the_report(self): + why = bf.Why() + with mock.patch.object(bf, "nvidia_gpus", lambda: ([], None, None)), \ + mock.patch.object(bf, "other_gpus", lambda: (self.cards(), None)), \ + mock.patch.object(bf, "rocm_version", lambda: "10.1.0"): + _, machine = bf.hardware(why, selected=[], served_gpu="AMD Radeon", model_dir=None, + declared_background=[]) + software = bf.software(why, dict(machine), engine_version="0.1.46.2", build_options=None) + self.assertEqual(machine["rocm"], "10.1.0") + self.assertIn({"name": "rocm", "version": "10.1.0"}, software["runtime"]) + + +class MacStillReadsItsChip(unittest.TestCase): + """The amd-smi branch is for Linux; a Mac (os.name is posix there too) still takes its card from the chip name.""" + + def test_a_mac_is_not_sent_down_the_amd_smi_branch(self): + calls = [] + + def run(cmd, timeout=15): + calls.append(cmd[0]) + return "" + + with mock.patch.object(bf.os, "name", "posix"), mock.patch.object(bf.sys, "platform", "darwin"), mock.patch.object(bf, "run_cmd", run), mock.patch.object(bf, "cpu_name", lambda: "Apple M5 Max"), mock.patch.object(bf, "ram_bytes", lambda: 137438953472): + cards, driver = bf.other_gpus() + self.assertEqual([c["name"] for c in cards], ["Apple M5 Max"]) + self.assertEqual(cards[0]["memory_kind"], "shared") + self.assertNotIn("amd-smi", calls) + + +if __name__ == "__main__": + unittest.main() From 6a6d58ad03890a19abc4adc0961fa0e1b87dd32b Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:43:32 +0100 Subject: [PATCH 080/177] iq_kernels: GP100 decode down projection staged in shared memory, opt-in STRATA_DOWN_WS=1 (#3867) Problem: on a GP100 die (cc 6.0, no dp4a, no tensor cores) the verify window's routed down projection for the native packs' IQ4_NL and Q2_0 rows (n_ff 640) is latency bound. native_down_multi_kernel reads each weight as 2-byte loads, one item at a time, straight from global memory. Change: native_down_ws_kernel copies a block's rows (IQ4_NL 32, Q2_0 64, 11,520 bytes) into shared memory with 16-byte loads, then runs the same row dots on the copy: same sub-warp, lane, items, float expressions and order. Only the integer sum inside an item changes form (vmad byte selectors, prmt table lookups), the same int8 x int8 products, so every output is native_down_multi_kernel's (expert mode 0) bit for bit. Gating: compiled only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (not HIP, not Metal). At run time only with STRATA_DOWN_WS=1 on a device of compute capability exactly 6.0, IQ4_NL / Q2_0 down rows at n_ff 640, and not with STRATA_OLD_IQ_MMVQ or STRATA_NO_SUB16_GU. Unset, the only change on the default path is one cached boolean test per native_expert_grouped call. docs/OLDER_GPUS.md lists the switch. The contributor's microbench numbers (one PH402 die, Swift 1.5 IQ3_S, one-token window: IQ4_NL 72.6 us mode 8 and 54.5 us mode 0 become 42.3 us; Q2_0 53.5 / 65.4 us become 38.6 us) were measured on a four-GP100 rig, not here. Tests: compile-only on sm_60 (CUDA 12.9) on P1004. The contributor's bitwise check (native_expert_bench hash against modes 0 and 8) is not run here: it needs a GP100 GPU run and the model's layers. The gate script is phaseA-tests/gh027/gates/3867-down-ws.sh. Not covered: no end-to-end measurement on a single P100 (16 GB cannot hold the 47 GB pack resident). --- docs/OLDER_GPUS.md | 10 +- src/kernels/cuda/iq_kernels.cu | 315 +++++++++++++++++++++++++++++++++ 2 files changed, 323 insertions(+), 2 deletions(-) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 92c26f9c..1ddd99a6 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -129,7 +129,7 @@ in [DETAILS.md](DETAILS.md#rtx-30-series-sm_86-and-tesla-p100-sm_60-bitwise-deco ## Pascal GP100: a Q8_0 decode kernel (opt-in) GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projections read their weights at 40-80 GB/s of about -730, decoding K- and i-quant blocks one int at a time. Two opt-in changes, both measured on a PH402 only: +730, decoding K- and i-quant blocks one int at a time. Three opt-in changes, all measured on a PH402 only: - **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp per row, 16-byte weight loads, activations copied once per workgroup into shared memory, @@ -141,8 +141,14 @@ GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projectio - **`STRATA_IQ_STAGE_TABLES=1`** stages IQ3_XXS and IQ3_S codebooks in shared memory in the grouped expert kernels. Bitwise the same output. Interleaved A/Bs on a Tesla P100 showed no end-to-end change, so it is off by default. On an RTX 3090 Ti, forced on, the same layers took 3-13% longer. +- **`STRATA_DOWN_WS=1`** (compute capability 6.0 only, CUDA build with `STRATA_EXPERIMENTAL_SM60`): the verify window's IQ4_NL / Q2_0 + expert down rows (n_ff 640) take `native_down_ws_kernel`. It stages a block's rows in shared memory with 16-byte loads and then + runs expert mode 0's row dots on them, so the output is bit for bit mode 0's (and mode 8's, which equals it). The author's numbers + on one PH402 die, Swift 1.5 IQ3_S, one-token window: IQ4_NL 72.6 us (mode 8, the cc 6.0 default) and 54.5 us (mode 0) become + 42.3 us; Q2_0 53.5 / 65.4 us become 38.6 us. It replaces the down step in either expert mode. Not measured end to end on a + single card here. -Neither change is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default +None of these changes is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default application clock is 759 MHz and a layer split leaves each die idle most of a window, so lock the clocks (`nvidia-smi -i -ac 715,1050` as administrator). And a second engine pinned to the same logical CPUs halves this one's decode; keep two engines on different logical CPUs. diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index d2f2e34e..9cb6894f 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -4167,6 +4167,314 @@ void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, c else if (g_no_sub16_gu) native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); else native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); } +// ---------------------------------------------------------------- STRATA_DOWN_WS: the decode down projection, staged +// (opt-in, default off; cc 6.0 only). native_down_multi_kernel's IQ4_NL (K 40, n_ff 640) and Q2_0 (K 20) rows read each +// weight as 2-byte loads, an item at a time, straight from global memory, and a block (32 / 16 rows) waits on that. +// Here a block copies its rows (IQ4_NL 32, Q2_0 64: 11,520 bytes) into shared memory with 16-byte loads - one round +// trip, all in flight - reads the plan words before the group test and the entries' destination rows before the weights +// land, and then runs the production row dots on the copy: the same 8 / 16-lane sub-warp, lane t, items, float +// expressions and order (row_dot_40_sub8 / row_dot_20_sub16: s += item t (+ t + 32), s16, s8, s24, the __fadd_rn's, +// xor 4..1 / 8..1, * sd). Two integer-only changes inside an item: the dp4a emulation's byte products are taken from +// the table lookup's bytes with vmad byte selectors (no interleaving byte_perm), and IQ4_NL's lookup uses raw prmt +// selectors (bit 3, sign replicate, only touches the bytes the low/high merge drops; lhsi's nibbles are 0..7, so no +// 0x7777 masks). An item's int32 sum is the sum of the same int8 x int8 products, so every output is bit for bit +// native_down_multi_kernel's (memcmp equal on all 48 layers of the Swift 1.5 IQ3_S pack, all 512 experts, 1-6 +// entries a group and T = 1..4 plans; native_expert_bench checks it against mode 0 and mode 8 by output hash). +#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \ + !defined(STRATA_GPU_METAL) +#define STRATA_DOWN_WS_BUILT 1 // the CUDA build with STRATA_EXPERIMENTAL_SM60 only +#else +#define STRATA_DOWN_WS_BUILT 0 +#endif +#if STRATA_DOWN_WS_BUILT +#define STRATA_DWS_VMAD(r, a, sa, b, sb) asm("vmad.s32.s32.s32 %0, %1.b" #sa ", %2.b" #sb ", %0;" : "+r"(r) : "r"(a), "r"(b)) + +__device__ __forceinline__ uint32_t dws_prmt(uint32_t a, uint32_t b, uint32_t c) { + uint32_t d; + asm("prmt.b32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); + return d; +} + +// get_int_from_table_16(q4, kvalues_iq4nl) before its 0x6420 / 0x7531 interleave: t0 = T(v0) T(v16) T(v1) T(v17), +// t1 = T(v2) T(v18) T(v3) T(v19). low = prmt(T0..7, q) is right for codes < 8, high = prmt(T8..15, q ^ 0x8..) for +// codes >= 8, and the merge with lhsi (nibbles 0..7) takes exactly those bytes - the same bytes as __byte_perm's masked +// selectors give. +__device__ __forceinline__ void dws_iq4_tab(uint32_t q4, int& t0, int& t1) { + const uint32_t* table32 = (const uint32_t*) kvalues_iq4nl; + const uint32_t lhsi = 0x32103210u | ((q4 & 0x88888888u) >> 1); + const uint32_t qx = q4 ^ 0x88888888u; + t0 = (int) dws_prmt(dws_prmt(table32[0], table32[1], q4), dws_prmt(table32[2], table32[3], qx), lhsi); + t1 = (int) dws_prmt(dws_prmt(table32[0], table32[1], q4 >> 16), dws_prmt(table32[2], table32[3], qx >> 16), lhsi >> 16); +} + +struct DwsIq4W { int t0[2], t1[2]; float dw; }; + +__device__ __forceinline__ DwsIq4W dws_iq4_load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; + DwsIq4W r; +#pragma unroll + for (int l = 0; l < 2; ++l) dws_iq4_tab((uint32_t) get_int_b2(bq4->qs, iqs + l), r.t0[l], r.t1[l]); + r.dw = __half2float(bq4->d); + return r; +} + +// = Split<20>::apply(Split<20>::load(...)): x_l = (t0.b0 t0.b2 t1.b0 t1.b2) . q8[l], y_l = (t0.b1 t0.b3 t1.b1 t1.b3) . q8[l + 4] +__device__ __forceinline__ float dws_iq4_apply(const DwsIq4W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int* q8 = (const int*) bq8_1->qs + iqs; + int sumi = 0; +#pragma unroll + for (int l = 0; l < 2; ++l) { + const int A = q8[l + 0], B = q8[l + 4]; + STRATA_DWS_VMAD(sumi, r.t0[l], 0, A, 0); + STRATA_DWS_VMAD(sumi, r.t0[l], 2, A, 1); + STRATA_DWS_VMAD(sumi, r.t1[l], 0, A, 2); + STRATA_DWS_VMAD(sumi, r.t1[l], 2, A, 3); + STRATA_DWS_VMAD(sumi, r.t0[l], 1, B, 0); + STRATA_DWS_VMAD(sumi, r.t0[l], 3, B, 1); + STRATA_DWS_VMAD(sumi, r.t1[l], 1, B, 2); + STRATA_DWS_VMAD(sumi, r.t1[l], 3, B, 3); + } + const float d = r.dw * __low2float(bq8_1->ds); + return d * sumi; +} + +// row_dot_40_sub8<20, NC, true> (t < 8: its k loop is k = t, t + 32), the five items' words loaded first +template +__device__ __forceinline__ void dws_row40(const uint8_t* row, const block_q8_1* x, int t, float (&s)[NC]) { + const int k0 = t, k1 = t + 32, k2 = t + 16, k3 = t + 8, k4 = t + 24; + const DwsIq4W w0 = dws_iq4_load(row, k0 / 2, 2 * (k0 % 2)); + const DwsIq4W w1 = dws_iq4_load(row, k1 / 2, 2 * (k1 % 2)); + const DwsIq4W w2 = dws_iq4_load(row, k2 / 2, 2 * (k2 % 2)); + const DwsIq4W w3 = dws_iq4_load(row, k3 / 2, 2 * (k3 % 2)); + const DwsIq4W w4 = dws_iq4_load(row, k4 / 2, 2 * (k4 % 2)); +#pragma unroll + for (int c = 0; c < NC; ++c) { + const block_q8_1* xc = x + 20 * c; + s[c] = 0.0f; + s[c] += dws_iq4_apply(w0, xc + k0 / 2, 2 * (k0 % 2)); + s[c] += dws_iq4_apply(w1, xc + k1 / 2, 2 * (k1 % 2)); + { + float s16 = 0.0f; + s16 += dws_iq4_apply(w2, xc + k2 / 2, 2 * (k2 % 2)); + s[c] = __fadd_rn(s[c], s16); + } + float s8 = 0.0f; + s8 += dws_iq4_apply(w3, xc + k3 / 2, 2 * (k3 % 2)); + { + float s24 = 0.0f; + s24 += dws_iq4_apply(w4, xc + k4 / 2, 2 * (k4 % 2)); + s[c] = __fadd_rn(s[c], __fadd_rn(s8, s24)); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) { +#pragma unroll + for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// Split<42>::load before its 0x5140 / 0x7362 interleave (qx = qe.b0 qo.b0 qe.b1 qo.b1, qy = qe.b2 qo.b2 qe.b3 qo.b3) +struct DwsQ2W { int qe[4], qo[4]; float d2; }; + +__device__ __forceinline__ DwsQ2W dws_q2_load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx; + DwsQ2W r; + r.d2 = bq2_0->d; + const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int q = qs[j]; + r.qe[j] = __byte_perm(0x020100FF, 0x020100FF, q >> 0); + r.qo[j] = __byte_perm(0x020100FF, 0x020100FF, q >> 2); + } + return r; +} + +// = Split<42>::apply, the 32 products summed in two int32 chains +__device__ __forceinline__ float dws_q2_apply(const DwsQ2W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const block_q8_1* bq8_1_chunk = bq8_1 + iqs; + int a[2] = { 0, 0 }; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0); + const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1); + int& x = a[j & 1]; + STRATA_DWS_VMAD(x, u, 0, r.qe[j], 0); + STRATA_DWS_VMAD(x, u, 1, r.qo[j], 0); + STRATA_DWS_VMAD(x, u, 2, r.qe[j], 1); + STRATA_DWS_VMAD(x, u, 3, r.qo[j], 1); + STRATA_DWS_VMAD(x, v, 0, r.qe[j], 2); + STRATA_DWS_VMAD(x, v, 1, r.qo[j], 2); + STRATA_DWS_VMAD(x, v, 2, r.qe[j], 3); + STRATA_DWS_VMAD(x, v, 3, r.qo[j], 3); + } + const int sumi = a[0] + a[1]; + const float d8 = __low2float(bq8_1_chunk->ds); + return r.d2 * d8 * sumi; +} + +// row_dot_20_sub16<42, NC, true> +template +__device__ __forceinline__ void dws_row20(const uint8_t* row, const block_q8_1* x, int t, float (&s)[NC]) { + const DwsQ2W w = dws_q2_load(row, t / 2, t % 2); +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = 0.0f; + s[c] += dws_q2_apply(w, x + 20 * c + (t / 2) * 2, t % 2); + } + float s16[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; + if (t < 4) { + const int k = t + 16; + const DwsQ2W w2 = dws_q2_load(row, k / 2, k % 2); +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] += dws_q2_apply(w2, x + 20 * c + (k / 2) * 2, k % 2); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = __fadd_rn(s[c], s16[c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// NC entries of one row; every lane of the sub-warp holds the same sum (butterfly), lane c stores entry c +template +__device__ __forceinline__ void dws_rows(const uint8_t* wr, const block_q8_1* s_hq, int t, float sd, float* __restrict__ out, + const int (&dst)[NC], int64_t n_embd, int r) { + float s[NC]; + if constexpr (TD == 20) dws_row40(wr, s_hq, t, s); + else dws_row20(wr, s_hq, t, s); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (t == c) out[(size_t) dst[c] * n_embd + r] = s[c] * sd; +} + +// grid (n_embd / RB, gy), 256 threads: RB = 32 IQ4_NL rows (one pass of 8-lane rows) or 64 Q2_0 rows (four passes of +// 16-lane rows); entries NCMAX at a time (1: a T = 1 window, every group one entry; 4: as GRP_NC) +template +__global__ void __launch_bounds__(256, 4) native_down_ws_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + constexpr int LPR = TD == 20 ? 8 : 16, RPP = 256 / LPR, P = TD == 20 ? 1 : 4, RB = RPP * P; + constexpr int DROW = TD == 20 ? 360 : 180, WB = RB * DROW, NV = (WB / 16 + 255) / 256; + static_assert(WB % 16 == 0, "16-byte copies"); + STRATA_SHARED_ALIGN16_U32(s_w, WB / 4); + STRATA_SHARED_ALIGN16_U32(s_hq_buf, NCMAX * 20 * 9); + const int tid = threadIdx.x, t = tid % LPR, sub = tid / LPR; + const int r0 = blockIdx.x * RB; + const int nrow = min(RB, (int) L.n_embd - r0); + const block_q8_1* s_hq = reinterpret_cast(s_hq_buf); + // the plan words of this block row's first group before the test (gridDim.y <= cap_groups: in bounds) + int g = blockIdx.y; + unsigned long long gpu = grp_ptr[g]; + int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int ng = *n_groups; + for (; g < ng; g += gridDim.y) { // the group stride, as native_down_multi_kernel + if (g != (int) blockIdx.y) { + __syncthreads(); + gpu = grp_ptr[g]; + e0 = grp_start[g]; + e1 = grp_start[g + 1]; + } + const uint8_t* gp = (const uint8_t*) gpu + L.down_off + (size_t) r0 * DROW; + const float sd = L.tail_off ? ((const float*) (gpu + L.tail_off))[2] : 1.0f; + int dst[NCMAX]; +#pragma unroll + for (int c = 0; c < NCMAX; ++c) dst[c] = ent_dst[min(e0 + c, e1 - 1)]; + const int nbytes = nrow * DROW; + if ((((uintptr_t) gp) & 15) == 0 && (nbytes & 15) == 0) { + const uint4* src = reinterpret_cast(gp); + uint4* dw = reinterpret_cast(s_w); + uint4 v[NV]; +#pragma unroll + for (int k = 0; k < NV; ++k) + if (tid + 256 * k < (nbytes >> 4)) v[k] = __ldg(src + tid + 256 * k); +#pragma unroll + for (int k = 0; k < NV; ++k) + if (tid + 256 * k < (nbytes >> 4)) dw[tid + 256 * k] = v[k]; + } else { + const uint16_t* s2 = reinterpret_cast(gp); + uint16_t* d2 = reinterpret_cast(s_w); + for (int i = tid; i < (nbytes >> 1); i += 256) d2[i] = s2[i]; + } + for (int e = e0; e < e1; e += NCMAX) { + const int n = min(NCMAX, e1 - e); + if (e != e0) { + __syncthreads(); +#pragma unroll + for (int c = 0; c < NCMAX; ++c) dst[c] = ent_dst[min(e + c, e1 - 1)]; + } + const uint32_t* src = reinterpret_cast(hq + (size_t) e * 20); + for (int i = tid; i < n * 180; i += 256) s_hq_buf[i] = src[i]; + __syncthreads(); +#pragma unroll + for (int p = 0; p < P; ++p) { + const int rl = p * RPP + sub; + if (rl >= nrow) continue; + const uint8_t* wr = reinterpret_cast(s_w) + rl * DROW; + const int r = r0 + rl; + if constexpr (NCMAX == 1) { + const int d1[1] = { dst[0] }; + dws_rows(wr, s_hq, t, sd, out, d1, L.n_embd, r); + } else { + static_assert(NCMAX == 4, "NCMAX 1 or 4"); + if (n == 1) { + const int d1[1] = { dst[0] }; + dws_rows(wr, s_hq, t, sd, out, d1, L.n_embd, r); + } else if (n == 2) { + const int d2[2] = { dst[0], dst[1] }; + dws_rows(wr, s_hq, t, sd, out, d2, L.n_embd, r); + } else if (n == 3) { + const int d3[3] = { dst[0], dst[1], dst[2] }; + dws_rows(wr, s_hq, t, sd, out, d3, L.n_embd, r); + } else { + const int d4[4] = { dst[0], dst[1], dst[2], dst[3] }; + dws_rows(wr, s_hq, t, sd, out, d4, L.n_embd, r); + } + } + } + } + } +} +#undef STRATA_DWS_VMAD + +// STRATA_DOWN_WS=1 on a compute capability 6.0 device: the IQ4_NL / Q2_0 down rows at n_ff 640 take +// native_down_ws_kernel (whatever the expert mode: it is bitwise mode 0's, and mode 8's matches mode 0) +bool down_ws_on(const NativeExpertLayout& L) { + static const bool env = env_on("STRATA_DOWN_WS"); + if (!env || g_old_kernels || g_no_sub16_gu || L.n_ff != 640 || (L.d_type != 20 && L.d_type != 42)) return false; + static int per_dev[64]; // 0 unknown, 1 no, 2 yes + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; + if (!per_dev[dev]) { + int major = 0, minor = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + per_dev[dev] = major == 6 && minor == 0 ? 2 : 1; + } + return per_dev[dev] == 2; +} + +void launch_down_ws(const NativeExpertLayout& L, int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, float* out) { + const int rb = L.d_type == 20 ? 32 : 64; + const dim3 grid((unsigned) ((L.n_embd + rb - 1) / rb), (unsigned) gy); + const bool one = cap_groups <= 10; // a T = 1 window: ten groups of one entry + if (L.d_type == 20) { + if (one) native_down_ws_kernel<20, 1><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else native_down_ws_kernel<20, 4><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + } else { + if (one) native_down_ws_kernel<42, 1><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else native_down_ws_kernel<42, 4><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + } +} +#endif // STRATA_DOWN_WS_BUILT + } // namespace @@ -5255,6 +5563,13 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 || L.d_type == 40 || tq_sub8 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8; const int tq_ch = tq_sub8 ? tq_row_chunks() : 1; // the staged trellis down kernel takes this many 32-row chunks a block const dim3 gd((unsigned) (((L.n_embd + d_rows - 1) / d_rows + tq_ch - 1) / tq_ch), (unsigned) gy); +#if STRATA_DOWN_WS_BUILT + if (down_ws_on(L)) { // STRATA_DOWN_WS=1 (cc 6.0): the staged down rows, bitwise native_down_multi_kernel's + launch_down_ws(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, out); + check("native_expert_grouped/down ws"); + return; + } +#endif #if STRATA_EXP_LAYOUTS const int em0d = sm75_down_em(em0, cap_groups); int dev_d = 0; From 41188ec73495638b88afb604a8c284f78138400c Mon Sep 17 00:00:00 2001 From: Dzmitry Senchankau <11807229+dsenchankau@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:43:46 +0100 Subject: [PATCH 081/177] calibrate: an engine that dies mid-measurement drops only its candidate (#3317) #1337 made a failed engine start in a later calibration step a candidate that loses. An engine that started and then exited during its own rate measurement still failed the whole run. measure_candidate() now treats both the same: the candidate is dropped and recorded in report["failed_starts"], the earlier results stay. It is used for the CPU worker step, the adaptive expert tier step and the AMD shared-expert fork. An operator cancel (CalibrationCancelled) is still raised. The first start (steps 1 to 3) still fails the run. src/core/verify.cpp: when adapt_gate_wait times out after 20 s, the message now says which layer was reached (atomic and copy signal), that the copy stream is not drained by the release, and dumps the STRATA_VERIFY_TRACE breadcrumbs when that is on. Diagnostics only, #2188 stays open. The watchdog label is set only once a wait actually starts, so a gate that is already open costs nothing extra (changed from the PR, which set it on every call). Tests: tools/test_calibrate.py 33 tests OK (3 new death tests). Not covered: engine compile of verify.cpp is checked in the build step. --- src/core/verify.cpp | 20 ++++++++++- tools/calibrate.py | 76 ++++++++++++++++++++++------------------- tools/test_calibrate.py | 44 +++++++++++++++++++++--- 3 files changed, 99 insertions(+), 41 deletions(-) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index b82181c2..c8b9aa14 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -2809,12 +2809,30 @@ void Verifier::accumulate_profile_inner(const unsigned long long* stamps) { bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) { const Clock::time_point t0 = Clock::now(); uint32_t spins = 0; + bool announced = false; // the watchdog's label is set only once the wait really starts: no cost when the copies landed while (adapt_gate_->reached() < layer) { + if (!announced) { + progress_at("verify window: waiting for the adaptive tier's copies of layer", layer); + announced = true; + } _mm_pause(); if ((++spins & 1023u) != 0) continue; if (Clock::now() - t0 > std::chrono::seconds(20)) { + // the release drains the window's own streams, never the tier's copy stream: say so, and hand out the + // gate's words and this window's GPU breadcrumbs (STRATA_VERIFY_TRACE) - the last landed layer is the + // exact place the stream stopped, which the released window's error line alone never told (#2188's class) + const int32_t reach = adapt_gate_->reached(), land = adapt_gate_->landed.load(); + const int32_t hl = adapt_gate_->hland != nullptr ? *adapt_gate_->hland : -2; + if (g_trace) trace_ev("GATE-TIMEOUT", -1, layer, reach); + std::fprintf(stderr, "strata verify: the adaptive gate waited %lld ms for layer %d: reached %d " + "(atomic %d, copy signal %d) - the tier's copy stream was not drained by the release\n", + (long long) ms_since(t0), (int) layer, (int) reach, (int) land, (int) hl); + if (g_trace) trace_dump(stderr); err = "verify: the adaptive tier's copies for layer " + std::to_string(layer) + " never landed" + - released_note(release_gpu_waits(5000)); + released_note(release_gpu_waits(5000)) + + " (the copy stream itself is not drained: reached " + std::to_string(reach) + " of " + + std::to_string(layer) + ", STRATA_VERIFY_TRACE=1 prints where the stream stopped)"; + std::fflush(stderr); return false; } } diff --git a/tools/calibrate.py b/tools/calibrate.py index 182c5a4d..5fbe48f4 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -361,7 +361,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke settings["--pcie-frac"] = f"{chosen[0]:.2f}" settings["--spec-min-p"] = f"{chosen[1]:.2f}" base_rate = statistics.median(confirm[chosen]) if confirm.get(chosen) else None - # 4. fewer CPU workers (a restart each), with the chosen settings + # 4. fewer CPU workers (a restart each), with the chosen settings. #1337's rule covers a death during a + # measurement too: an engine that exits mid-rate is that candidate losing; the measurements so far stay. if d_workers and len(worker_candidates(d_workers, extra_workers)) > 1: tuned = with_arg(with_arg(base_args, "--pcie-frac", f"{chosen[0]:.2f}"), "--spec-min-p", f"{chosen[1]:.2f}") by_workers = {} @@ -370,18 +371,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke for index, w in enumerate(workers, 1): _check_cancel(cancel_event) say(f" Measuring with {w} CPU workers (restarts the engine) ...") - e = restart(start_engine, with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)), f"{w} workers", - say, report) - if e is None: - _progress(progress, "cpu_workers", index, len(workers)) - continue - try: - sw = Session(e, ids_list, cancel_event) - sw.warm_up(1) - by_workers[w] = [sw.rate(), sw.rate()] - say(f" {w} workers: {statistics.median(by_workers[w]):.1f} tok/s") - finally: - close(e) + measure_candidate(start_engine, with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)), + f"{w} workers", say, report, by_workers, w, ids_list, cancel_event=cancel_event) _progress(progress, "cpu_workers", index, len(workers)) report["workers"] = {str(k): v for k, v in by_workers.items()} w_best = pick(by_workers, d_workers) if by_workers else d_workers @@ -392,7 +383,9 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke base_rate = statistics.median(by_workers[d_workers]) else: _progress(progress, "cpu_workers", 1, 1) - # 5. the adaptive expert tier (a restart each), with everything chosen so far + # 5. the adaptive expert tier (a restart each), with everything chosen so far. A candidate whose engine dies + # during its own measurement is dropped like a failed start (#1337); the other candidates and every earlier + # result survive. tuned = apply(base_args, settings) by_adapt = {} _progress(progress, "expert_tier", 0, len(ADAPT_CANDIDATES)) @@ -403,17 +396,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke for flag, v in zip(ADAPT_FLAGS, cand or (None,) * len(ADAPT_FLAGS)): args = with_arg(args, flag, v) say(f" Measuring the expert tier {'(the engine default)' if cand is None else 'every ' + cand[0] + ', ' + cand[1] + ' swaps, decay ' + cand[2]} (restarts the engine) ...") - e = restart(start_engine, args, "the expert tier " + key, say, report) - if e is None: - _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES)) - continue - try: - sa = Session(e, ids_list, cancel_event) - sa.warm_up(1) - by_adapt[key] = [sa.rate(max_new=TIER_MAX_NEW), sa.rate(max_new=TIER_MAX_NEW)] - say(f" {statistics.median(by_adapt[key]):.1f} tok/s") - finally: - close(e) + measure_candidate(start_engine, args, "the expert tier " + key, say, report, by_adapt, key, ids_list, + TIER_MAX_NEW, cancel_event=cancel_event) _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES)) a_best = pick(by_adapt, "default") if by_adapt else "default" report["adapt"] = by_adapt @@ -433,16 +417,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke _check_cancel(cancel_event) say(f" Measuring the shared expert {'on its own stream' if v == '1' else 'on the main stream (the AMD default)'}" " (restarts the engine) ...") - e = restart(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report) - if e is None: - continue - try: - sf = Session(e, ids_list, cancel_event) - sf.warm_up(1) - by_fork[v] = [sf.rate(), sf.rate()] - say(f" {statistics.median(by_fork[v]):.1f} tok/s") - finally: - close(e) + measure_candidate(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report, + by_fork, v, ids_list, cancel_event=cancel_event) report["sh_stream"] = by_fork if pick(by_fork, "0") == "1": env[SH_STREAM] = "1" @@ -455,6 +431,10 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke return {"settings": settings, "env": env, "report": report} +def first_line(exc: Exception) -> str: + return str(exc).strip().splitlines()[0][:300] if str(exc).strip() else type(exc).__name__ + + def restart(start_engine, args, what, say, report): """#1337: a later step's engine start that fails is a candidate that loses, not a failed run: what the earlier steps measured (and the settings they chose) must survive it. Returns the engine, or None after saying why and @@ -463,12 +443,36 @@ def restart(start_engine, args, what, say, report): try: return start_engine(args) except Exception as e: # noqa: BLE001 - whatever the start raised (RuntimeError, EngineDied, OSError ...) - why = str(e).strip().splitlines()[0][:300] if str(e).strip() else type(e).__name__ + why = first_line(e) say(f" the engine did not start for {what}: {why} - this candidate is dropped, the earlier results are kept") report.setdefault("failed_starts", {})[what] = why return None +def measure_candidate(start_engine, args, what, say, report, by: dict, key, ids_list, max_new: int | None = None, + cancel_event=None): + """One restart-and-measure candidate (#1337): a start that fails and an engine that exits mid-measurement are + both that candidate losing - `by[key]` gets its two rates, or report["failed_starts"] its reason. Everything + measured earlier and the other candidates survive. An operator cancel is not a candidate death: it raises.""" + e = restart(start_engine, args, what, say, report) + if e is None: + return + try: + s = Session(e, ids_list, cancel_event) + s.warm_up(1) + by[key] = [s.rate(max_new=max_new), s.rate(max_new=max_new)] + say(f" {what}: {statistics.median(by[key]):.1f} tok/s") + except CalibrationCancelled: + raise + except Exception as exc: # noqa: BLE001 - the engine died mid-measurement: this candidate loses (#1337) + why = first_line(exc) + say(f" the engine died while measuring {what}: {why} - this candidate is dropped, " + "the earlier results are kept") + report.setdefault("failed_starts", {})[what] = why + finally: + close(e) + + def close(eng): proc = getattr(eng, "proc", None) if proc is None: diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index 97e33597..7ffe1fb6 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -21,9 +21,10 @@ import calibrate as CAL # noqa: E402 class FakeEngine: - """Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`.""" + """Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`. + `dies`: setting values whose engine exits during its first generation (the #267 class, mid-measurement).""" - def __init__(self, args, speed, info_workers=6, starts=None, adapt=None, read=None, reads=None): + def __init__(self, args, speed, info_workers=6, starts=None, adapt=None, read=None, reads=None, dies=()): self.args = list(args) self.read, self.reads = read, reads # prompt read speed = read(prefill_pipe); the values it read with self.adapt_bonus = (adapt or {}).get(CAL.arg_value(args, "--adapt-swaps"), 1.0) @@ -33,10 +34,16 @@ class FakeEngine: self.speed = speed self.last = {} self.proc = None + self.dies = CAL.arg_value(args, "--adapt-swaps") in dies or CAL.arg_value(args, "--pool-workers") in dies + self.dead = False if starts is not None: starts.append(list(args)) def generate(self, ids, max_new, sampling, cancel): + if self.dies and not self.dead: + self.dead = True + raise RuntimeError("the engine exited: ERR verify: the adaptive tier's copies for layer 47 never landed" + " (the copy stream itself is not drained); restart the engine") tune = sampling.get("strata_tune") or {} rate = self.speed(tune.get("pcie_frac", 0.55), tune.get("spec_min_p", self.info["spec_min_p"]), self.workers) rate *= self.adapt_bonus @@ -54,9 +61,10 @@ BASE = ["--pack", "p", "--spec", "4", "--spec-min-p", "0.5", "--max-context", "8 class Calibrate(unittest.TestCase): - def run_with(self, speed, workers=6, base=BASE, adapt=None, read=None, reads=None): + def run_with(self, speed, workers=6, base=BASE, adapt=None, read=None, reads=None, dies=()): starts = [] - res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts, adapt, read, reads), + res = CAL.measure(base, [[1, 2, 3]] * 3, + lambda a: FakeEngine(a, speed, workers, starts, adapt, read, reads, dies), say=lambda *_: None, long_prompt=lambda i, n: [1] * n) return res, starts @@ -233,6 +241,22 @@ class Calibrate(unittest.TestCase): self.assertEqual(CAL.arg_value(a, "--adapt-swaps"), "160") self.assertIsNone(CAL.arg_value(CAL.apply(a, {}), "--adapt-swaps")) # an old calibration's tier goes + def test_engine_death_during_tier_measurement_drops_only_that_candidate(self): + # the 160-swap candidate's engine dies during its own measurement (the adaptive gate's #267 livelock): + # that candidate loses, 80 (10% faster) is still chosen, and the run returns with the earlier results + res, _ = self.run_with(lambda f, p, w: 50.0, adapt={"80": 1.10}, dies=("160",)) + self.assertEqual(res["settings"].get("--adapt-swaps"), "80") + self.assertEqual(list(res["report"]["adapt"]), ["default", "1/80/0.97"]) + self.assertIn("the expert tier 1/160/0.97", res["report"]["failed_starts"]) + + def test_engine_death_during_a_worker_measurement_keeps_the_run(self): + # 4 workers' engine dies mid-measurement: 3 and 2 are still measured, the default count stays, the tier runs + res, _ = self.run_with(lambda f, p, w: 50.0, workers=6, dies=("4",)) + self.assertNotIn("--pool-workers", res["settings"]) + self.assertEqual(sorted(int(k.split()[0]) for k in res["report"]["workers"]), [2, 3, 6]) + self.assertIn("4 workers", res["report"]["failed_starts"]) + self.assertEqual(list(res["report"]["adapt"]), ["default", "1/80/0.97", "1/160/0.97"]) + def test_old_calibration_is_the_baseline_reset(self): # a config tuned earlier: the measurement starts from the product defaults, not from those values base = CAL.apply(BASE, {"--pcie-frac": "0.20", "--pool-workers": "3", "--spec-min-p": "0.70"}) @@ -277,6 +301,18 @@ class Calibrate(unittest.TestCase): self.assertEqual(res["env"], {}) self.assertIn(f"{CAL.SH_STREAM}=1", res["report"]["failed_starts"]) + def test_engine_death_during_a_fork_measurement_keeps_the_run(self): + # the forked engine exits mid-measurement (#267's class): that candidate loses, the run returns + def start(args, env=None): + e = FakeEngine(args, lambda f, p, w: 50.0, 6) + if (env or {}).get(CAL.SH_STREAM) == "1": + e.dies = True + return e + res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None, hip=True) + self.assertEqual(res["env"], {}) + self.assertEqual(list(res["report"]["sh_stream"]), ["0"]) + self.assertIn(f"{CAL.SH_STREAM}=1", res["report"]["failed_starts"]) + def test_apply_env(self): old = {"STRATA_ROCBLAS_TUNING": "tools/hip", CAL.SH_STREAM: "1"} self.assertEqual(CAL.apply_env(old, {}), {"STRATA_ROCBLAS_TUNING": "tools/hip"}) # an older choice goes From f213f78baec8c5b64b7662c4a8a2daee62f5c51a Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:43:53 +0100 Subject: [PATCH 082/177] mtp: the drafter's Q8_0 draft head and projections on the Pascal GEMV, opt-in STRATA_MTP_Q8_SM60=1 (#3751) Problem: with STRATA_Q8_SM60=1 the main model's Q8_0 matrices run on the GP100 Q8_0 kernel, but the MTP drafter's own Q8_0 draft head and projections kept the generic kernels. Change: with STRATA_MTP_Q8_SM60=1 (on top of STRATA_Q8_SM60=1) the drafter packs its Q8_0 projections as packed copies, as the main model does (the prompt path's draft_kv still reads the GGUF layout, so a copy is kept), and packs the draft head's subset in place when every column count fits the kernel's shared-memory planes and the data is 16-byte aligned (otherwise a packed copy). The in-place pack writes the GGUF blocks back if the device write fails. Release unregisters the entry without a cudaFree when the data was packed in place. New native_q8_0_sm60_pack_quiet and native_q8_0_sm60_pack_in_place; HIP returns false; metal/src/engine/stubs_0145.cpp gets matching stubs that answer "nothing packed". Replies do not depend on the drafts (they are verified); only the draft rounding changes, because the Pascal kernel sums in another order. Default path: mtp_q8_sm60() is false unless the env is set, so the packing calls are skipped. The destructor now walks the tensor list once at teardown, not in a hot loop. The SYCL tree has its own sycl/src/core/mtp.cpp, so it is not touched. Tests: compile-only on sm_60 (CUDA 12.9) on P1004. Model gate (identical replies with the flag on and off, decode speed on a P100) is written down in phaseA-tests/gh027/gates/3751-mtp-q8-sm60.sh. Not covered: no GPU run here; the contributor measured +4.4% on four GP100 dies with all experts resident, one run per arm, not on a single streamed P100. --- include/strata/kernels/native_mmvq.hpp | 9 ++++- metal/src/engine/stubs_0145.cpp | 3 ++ src/core/mtp.cpp | 48 +++++++++++++++++++++- src/kernels/cuda/native_mmvq.cu | 56 +++++++++++++++++++++++--- 4 files changed, 108 insertions(+), 8 deletions(-) diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index ce11095c..c809e74e 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -110,8 +110,15 @@ void native_q8_0_packed_register(const void* gguf_weights, const void* packed, i void native_q8_0_packed_unregister(const void* gguf_weights); /// STRATA_Q8_SM60=1 (opt-in, Pascal GP100): every Q8_0 dense matrix is packed as above whatever its shape, and the /// Q8_0 decode GEMVs run a kernel written for compute capability 6.0 (q8_sm60.cuh; not bitwise the exact kernels). -/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release. +/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release; +/// native_q8_0_sm60_pack_quiet is the same with no line for a success (the caller sums several up). bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what); +bool native_q8_0_sm60_pack_quiet(const void* weights, int n_in, int n_out, const char* what); +/// The same for a matrix that nothing but native_mmvq reads (the MTP drafter's draft head subset): where every column +/// count takes the Pascal kernel and the planes stay 16-byte aligned, they replace the GGUF blocks in the matrix's own +/// allocation (the same byte count, staged through the host: no second copy); otherwise a packed copy as +/// native_q8_0_sm60_pack makes. Either way native_q8_0_sm60_release must run before the caller frees the matrix. +bool native_q8_0_sm60_pack_in_place(void* weights, int n_in, int n_out, const char* what); void native_q8_0_sm60_release(const void* weights); /// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh / diff --git a/metal/src/engine/stubs_0145.cpp b/metal/src/engine/stubs_0145.cpp index 0c1976f6..351665ec 100644 --- a/metal/src/engine/stubs_0145.cpp +++ b/metal/src/engine/stubs_0145.cpp @@ -147,5 +147,8 @@ namespace strata::kernels { bool gemm_iq_f16_grouped(int p0, void const* p1, uns // STRATA_Q8_SM60 (Pascal GP100, opt-in): a no-op on Metal; NativeHead::load()/unload() call these for a Q8_0 head, so they must exist and answer "nothing packed". namespace strata::kernels { bool native_q8_0_sm60_pack(void const* p0, int p1, int p2, char const* p3) { return false; } } namespace strata::kernels { void native_q8_0_sm60_release(void const* p0) { } } +// the MTP drafter's STRATA_MTP_Q8_SM60 packing (mtp.cpp): nothing packed on Metal +namespace strata::kernels { bool native_q8_0_sm60_pack_quiet(void const* p0, int p1, int p2, char const* p3) { return false; } } +namespace strata::kernels { bool native_q8_0_sm60_pack_in_place(void* p0, int p1, int p2, char const* p3) { return false; } } // only reached with pf_wmma (off on Metal) namespace strata::prefill { void swiglu_split_f16(float const* p0, unsigned short* p1, long long p2, int p3, bool p4, void* p5) { } } diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 292a5d2b..99ad68f2 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -78,6 +78,16 @@ bool mtp_catchup_all() { }(); return on; } +// STRATA_MTP_Q8_SM60=1 (opt-in, with STRATA_Q8_SM60=1): the drafter's own Q8_0 matrices (the draft head's subset, +// the projections) run on the Pascal GEMV too (the drafts differ in rounding only: the Pascal kernel sums in another +// order; the replies do not depend on the drafts) +bool mtp_q8_sm60() { + static const bool on = [] { + const char* v = std::getenv("STRATA_MTP_Q8_SM60"); + return v != nullptr && v[0] == '1'; + }(); + return on; +} constexpr int GGML_Q8_0 = 8; constexpr int GGML_Q4_0 = 2; using Clock = std::chrono::steady_clock; @@ -154,12 +164,20 @@ MtpDrafter::~MtpDrafter() { if (side_) cudaStreamDestroy(side_); if (sh_fork_) cudaEventDestroy(sh_fork_); if (sh_join_) cudaEventDestroy(sh_join_); - if (owns_weights_ && dense_) cudaFree(dense_); + if (owns_weights_ && dense_) { + for (const auto& t : tensors_) // the STRATA_MTP_Q8_SM60 registrations first (a no-op for the rest) + if (t.kind == "q8_0") strata::kernels::native_q8_0_sm60_release(dense_ + t.off); + cudaFree(dense_); + } if (owns_weights_ && experts_) cudaFree(experts_); if (state_arena_) cudaFree(state_arena_); if (arena_) cudaFree(arena_); if (head_logits_) cudaFree(head_logits_); - if (owns_draft_head_ && dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); } + if (owns_draft_head_ && dhead_) { + strata::kernels::native_q6_k_unpack(dhead_); + strata::kernels::native_q8_0_sm60_release(dhead_); + cudaFree(dhead_); + } if (owns_draft_head_ && dvocab_) cudaFree(dvocab_); if (ev_chain_) cudaEventDestroy(ev_chain_); for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e); @@ -335,6 +353,26 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session "self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"}; for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; } + // STRATA_MTP_Q8_SM60=1: the projections on the Pascal GEMV (--batch's shared drafters read the same pointers), as + // packed copies like the main model's: the prompt path's draft_kv reads four of them in the GGUF layout (MMQ); + // --mtp-q4 reads its Q4_0 copies instead + if (shared == nullptr && dense4_ == nullptr && mtp_q8_sm60()) { + int packed = 0; + uint64_t packed_bytes = 0; + for (const char* n : required) + for (const auto& t : tensors_) + if (t.name == n && t.kind == "q8_0" && + strata::kernels::native_q8_0_sm60_pack_quiet(dense_ + t.off, (int) t.cols, (int) t.rows, + ("MTP " + t.name).c_str())) { + ++packed; + packed_bytes += t.bytes; // a copy is the same 34 bytes per 32 values + } + vram_ += packed_bytes; + if (packed > 0) + std::fprintf(stderr, "strata mtp: %d of %zu projections on the Pascal Q8_0 GEMV (STRATA_MTP_Q8_SM60=1, %.1f " + "MiB more VRAM)\n", packed, sizeof(required) / sizeof(required[0]), + (double) packed_bytes / 1048576.0); + } // ---- the layer's own K/V (dense attention: no indexer state is read) const strata::kernels::QsaShapes s = shapes_of(g); @@ -742,6 +780,12 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1 strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_, "MTP draft head"); + // STRATA_MTP_Q8_SM60=1: the subset on the Pascal GEMV like the main head, but packed in place - nothing but + // record_rest's native_mmvq reads it (the prompt path never does), and a copy would cost its size again + if (dhead_type_ == GGML_Q8_0 && owns_draft_head_ && mtp_q8_sm60() && row_bytes == g_->n_embd / 32 * 34 && + strata::kernels::native_q8_0_sm60_pack_in_place(dhead_, (int) g_->n_embd, (int) n_dvocab_, + "MTP draft head")) + std::fprintf(stderr, "strata mtp: the draft head on the Pascal Q8_0 GEMV (STRATA_MTP_Q8_SM60=1)\n"); } } if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 05f9b42d..afaec6cb 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -2243,15 +2243,25 @@ bool native_q8_0_packed_eligible(int n_in, int n_out) { } namespace { -std::unordered_map& q8_sm60_owned() { // packed copies made here (the head), freed by release +// packed copies made here (the head), freed by release; null: packed in place (release only unregisters it) +std::unordered_map& q8_sm60_owned() { static std::unordered_map owned; return owned; } +bool q8_sm60_pack_impl(const void* weights, int n_in, int n_out, const char* what, bool quiet); } // namespace bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what) { + return q8_sm60_pack_impl(weights, n_in, n_out, what, false); +} +bool native_q8_0_sm60_pack_quiet(const void* weights, int n_in, int n_out, const char* what) { + return q8_sm60_pack_impl(weights, n_in, n_out, what, true); +} + +namespace { +bool q8_sm60_pack_impl(const void* weights, int n_in, int n_out, const char* what, bool quiet) { #if defined(__HIPCC__) - (void) weights; (void) n_in; (void) n_out; (void) what; + (void) weights; (void) n_in; (void) n_out; (void) what; (void) quiet; return false; #else if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false; @@ -2276,18 +2286,20 @@ bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* } q8_packed_registry()[weights] = Q8Packed{qs, d, n_in, n_out}; q8_sm60_owned()[weights] = packed; - std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in, - double(bytes) / 1048576.0); + if (!quiet) + std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in, + double(bytes) / 1048576.0); return true; #endif } +} // namespace void native_q8_0_sm60_release(const void* weights) { auto& owned = q8_sm60_owned(); const auto it = owned.find(weights); if (it == owned.end()) return; q8_packed_registry().erase(weights); - cudaFree(it->second); + if (it->second) cudaFree(it->second); owned.erase(it); } @@ -2313,6 +2325,40 @@ void native_q8_0_packed_register(const void* gguf_weights, const void* packed, i void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); } +bool native_q8_0_sm60_pack_in_place(void* weights, int n_in, int n_out, const char* what) { +#if defined(__HIPCC__) + (void) weights; (void) n_in; (void) n_out; (void) what; + return false; +#else + if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false; + if (q8_packed_registry().count(weights)) return true; + // The GGUF blocks are gone afterwards, so only where q8_packed_mmvq can never fall back to the GGUF-layout kernels + // (every column count fits the kernel's shared-memory planes) and its 16-byte weight loads stay aligned + if (q8sm60::smem_bytes(MAX_NCOLS, n_in) > q8sm60::MAX_SMEM || reinterpret_cast(weights) % 16 != 0) + return native_q8_0_sm60_pack(weights, n_in, n_out, what); + const std::size_t bytes = std::size_t(n_in / 32) * std::size_t(n_out) * 34; // both layouts: 34 bytes per 32 + std::vector blocks(bytes), planes(bytes); + if (cudaMemcpy(blocks.data(), weights, bytes, cudaMemcpyDeviceToHost) != cudaSuccess) { + cudaGetLastError(); + std::fprintf(stderr, "strata q8 sm60: reading the %s failed; it keeps the GGUF layout\n", what); + return false; + } + native_q8_0_pack_host(blocks.data(), planes.data(), n_in, n_out); + if (cudaMemcpy(weights, planes.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) { + cudaGetLastError(); + // a partial write leaves neither layout: put the blocks back + const bool restored = cudaMemcpy(weights, blocks.data(), bytes, cudaMemcpyHostToDevice) == cudaSuccess; + cudaGetLastError(); + std::fprintf(stderr, "strata q8 sm60: writing the packed %s failed; %s\n", what, + restored ? "it keeps the GGUF layout" : "its GGUF blocks could not be restored either"); + return false; + } + native_q8_0_packed_register(weights, weights, n_in, n_out); + q8_sm60_owned()[weights] = nullptr; + return true; // the caller says what it packed +#endif +} + bool native_q6_k_packed_enabled() { static const bool enabled = [] { const char* v = std::getenv("STRATA_Q6_PACKED"); From 407f659763412d5b0e6e4f91db1f12db867f1731 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:45:02 +0100 Subject: [PATCH 083/177] docs: GR_V3 and PROMPT_ATTN_IMMA defaults in DETAILS.md and the 0.2.7 release-notes draft --- docs/DETAILS.md | 3 ++- docs/release-notes-0.2.7.md | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index afd8290a..e5c23659 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -919,7 +919,8 @@ measured. "Exact" means the 10-prompt and 4K/20K identity gate with the switch o | `STRATA_B6_MMVQ_ROWS=1` | Exact multi-column MMVQ reusing the activation fragment across rows | Exact; on by default on sm_86 and sm_60 | | `STRATA_QSA_SPLIT_ATTN=1` | Decode attention split across blocks on the int8 mma path (sm_80+, int8 KV) | Rounding level | | `STRATA_HC_UPMIX=1` | Hyper-connection up projection and `gr_mix_r` in one kernel (sm_80+) | Exact | -| `STRATA_PROMPT_ATTN_IMMA=1` | Int8-KV prompt attention on INT8 tensor cores | Rounding level | +| `STRATA_PROMPT_ATTN_IMMA` | Int8-KV prompt attention on INT8 tensor cores | Rounding level. On by default since 0.2.7 on NVIDIA Ampere and newer (+1.1% to +1.8% prompt at 8K/16K on an RTX PRO 5000 and 2x RTX A4000); `=0` brings the 0.2.6 kernel back. | +| `STRATA_GR_V3` | The hyper-connection read split over two kernels | Rounding level. On by default since 0.2.7 on a discrete compute capability 12.0 card (RTX 50, RTX PRO Blackwell) with more than 13 GiB (RTX PRO 5000: +1.2% decode with identical tokens); slower on sm_86, so off there. `=0` / `=1` forces it off / on. | | `STRATA_HC_REQ8=1` | Hyper-connection projections as int8 plus a scale per 32 (more expert-cache slots) | Rounding level | | `STRATA_QUANT_GATHER=1`, `STRATA_PREFILL_GROUP_GATHER=0` | Per-row gather for the MoE input quantization; the short-prompt grouped gather off | No gain measured; keep the defaults | diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 8166d70d..de029522 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -16,6 +16,14 @@ - Off switch: `STRATA_GR_UP_WIDE=0`. `STRATA_SM120_PERF=0` still turns off the whole Blackwell set. - Other cards are untouched: the old kernel runs everywhere else. +- **Two more kernel switches are on by default where they were measured.** Both sum in another order (about 1e-7), so a + tie between two near-equal words can flip and a reply can differ from 0.2.6 here and there. + - The prompt attention on int8 tensor cores (NVIDIA Ampere and newer): **+1.6% / +1.8% prompt at 8K / 16K on the RTX PRO 5000 + and +1.1% / +1.3% on 2x RTX A4000**, decode unchanged, five pairs each. Off switch: `STRATA_PROMPT_ATTN_IMMA=0`. + - The hyper-connection read split over two kernels (a discrete RTX 50 / RTX PRO Blackwell card with more than 13 GiB): **+1.2% + decode on the RTX PRO 5000 with identical tokens**, about +1.5% together with the switch above. On 2x RTX A4000 and the + RTX 3060 it was slower, so those cards keep the old read. Off switch: `STRATA_GR_V3=0`. + ## What is faster if your PC is set up for it These need no engine change; they are settings. Each was measured on the same boxes. From 9c2d35d978e290f9919415c740bf5d25cc4c3e2e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:45:04 +0100 Subject: [PATCH 084/177] serve: /v1/responses accepts max_output_tokens of 0 and -1 (#4036) The Responses validator still refused anything below 1 after the chat path made max_tokens of -1 and 0 mean no cap (documented in docs/DETAILS.md). It now accepts -1 and 0 as no cap; values below -1, floats, booleans and strings stay a 400. Nothing else changes: the server already passes max_output_tokens or 0 to prepare(), which gives the answer the room left in the context. Tests: OverHttp.test_max_output_tokens_zero_and_minus_one_mean_no_cap (stream and non-stream, status completed) and test_max_output_tokens_bad_values_are_400. The first fails without the change. serve/test_responses.py 43 tests OK. --- docs/DETAILS.md | 2 +- serve/responses.py | 6 ++++-- serve/test_responses.py | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 61dfb584..0ed983c3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -703,7 +703,7 @@ endpoints are refused with an error that says so. | `tools` | `function`, `namespace` and `custom` tools. Hosted tools (`web_search`, `file_search`, ...) are left out because the model cannot run them | | `tool_choice` | `"none"` hides the tools; anything else lets the model choose (it cannot be forced) | | `reasoning.effort` | `none`/`minimal`, `low`, `medium`, `high`/`xhigh`; without it the config's `reasoning_effort`, else the model's default | -| `max_output_tokens` | The output cap, thinking included. Running out ends the response `incomplete` | +| `max_output_tokens` | The output cap, thinking included. Running out ends the response `incomplete`. `0` and `-1` (or leaving it out) mean no cap, as for `max_tokens`; anything below `-1` is a 400 | | `text.format` | `json_schema` and `json_object` use the JSON formats above (checked, not constrained) | | `client_metadata["x-codex-turn-metadata"]` thread-title request | Opt-in `"codex_thread_titles": true`: answered without the engine as `{"title": ""}` so the conversation keeps the prompt cache | diff --git a/serve/responses.py b/serve/responses.py index 53c4fb54..a5b97bce 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -443,8 +443,10 @@ def check_request(req: dict) -> None: raise ResponsesError("stored prompt templates are not supported: send instructions and input", "prompt", "unsupported_parameter") n = req.get("max_output_tokens") - if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < 1): - raise ResponsesError("max_output_tokens must be a positive whole number", "max_output_tokens") + # -1 and 0 mean no cap, as max_tokens does on the chat path (docs/DETAILS.md); anything lower is a mistake + if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < -1): + raise ResponsesError("max_output_tokens must be a whole number, 1 or more, or -1 or 0 for no cap", + "max_output_tokens") reasoning = req.get("reasoning") if reasoning is not None and not isinstance(reasoning, dict): raise ResponsesError("reasoning must be an object", "reasoning") diff --git a/serve/test_responses.py b/serve/test_responses.py index d6c4e857..866582c3 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -389,6 +389,21 @@ class OverHttp(Server): code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": 5, "stream": True}) self.assertEqual(events[-1]["type"], "response.incomplete") + def test_max_output_tokens_zero_and_minus_one_mean_no_cap(self): + # #4036: the documented "no cap" values; the answer is complete, not cut at the cap + for n in (0, -1): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n}) + self.assertEqual((code, r["status"]), (200, "completed"), (n, r)) + self.assertIsNone(r["incomplete_details"]) + code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": n, "stream": True}) + self.assertEqual((code, events[-1]["type"]), (200, "response.completed"), n) + + def test_max_output_tokens_bad_values_are_400(self): + for n in (-2, -100, 1.5, True, "5"): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n}) + self.assertEqual(code, 400, (n, r)) + self.assertEqual(r["error"]["param"], "max_output_tokens", n) + def test_effort_none_does_not_think(self): self.engine.scripts = [self.tok.encode("Hello.<|im_end|>", parse_special=True)] self.engine.script = self.engine.scripts[0] From 01e404c1402346d55322faecb28177035294cfaf Mon Sep 17 00:00:00 2001 From: hotschmoe <24309845+hotschmoe@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:46:05 +0100 Subject: [PATCH 085/177] serve: an idle batch slot's decoded conversation is parked before an admission overwrites it (#2526) A batch slot holds the reply it decoded. The main session was parked with the conversation's prompt only (the admission's copy), so when the next admission or a yielding read overwrote the slot, the reply lived nowhere: the conversation's next turn found its prompt-read state and read the whole reply again (the author measured 255 of a 256-token reply re-read on four 200K chats over two slots). What changed: - park_current is split into park_source (one budget / RAM-admission / snapshot path) and two callers: park_current (the main session, output line and byte accounting as before) and the new park_slot (an idle slot's ids, checkpoints, sessions and draft K/V). The ParkSource passes what a park captures; the main session's retained K/V (#1503 take_reuse_for) is taken only for the main session, never for a slot. - park_slot runs before copy_to_slot at a slot admission and before a BYIELD read overwrites a slot. It does nothing when the live main session or a parked conversation already holds that state (ConversationCache::holds / conversation_covers, new, with unit tests), for a slot with pictures, or without --batch-mtp when the drafter is on. - When a slot is admitted into the main session its checkpoints come along (the shorter ones too), so the chain keeps its branch points and the parked copies a turn back are superseded (#342) instead of taking an entry each. - Same refactor in sycl/src/program/generate.cpp. Changed from the PR: parking is an optimization like a checkpoint (#3350). The PR ended the request (ERR) or the batch (batch_fatal) when park_slot's snapshot failed; here a failed snapshot, a failed device sync and a host allocation that runs out are logged, the slot is overwritten as before and the request goes on. The slot's extra checkpoints that come along at an admission are copied under a bad_alloc guard (the one the request continues from is copied as before). Tests: conversation_cache_test (new holds() cases and the four-conversation replay at policy level) and conversation_split_failure_test. Not covered: no model run (the batch path itself needs one); the gate is written down. --- include/strata/core/conversation_cache.hpp | 31 ++++ src/core/conversation_cache_test.cpp | 104 ++++++++++++ src/program/generate.cpp | 181 +++++++++++++++++---- sycl/src/program/generate.cpp | 140 +++++++++++++--- 4 files changed, 399 insertions(+), 57 deletions(-) diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 973b2593..b977ac49 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -187,6 +187,24 @@ struct SavedConversation { } }; +/// `c` holds the state `ids` (with `images`) describes, or a continuation of it: its tokens start with `ids` and +/// its pictures below ids.size() are exactly `images`. What an idle batch slot holds is then parked already (or +/// a longer continuation is), so the slot need not park it again before an admission overwrites it. +template +bool conversation_covers(const ConversationCheckpoint& c, const std::vector& ids, + const std::vector& images) { + const size_t n = ids.size(); + if (n == 0 || c.ids.size() < n) return false; + for (size_t i = 0; i < n; ++i) + if ((int64_t) c.ids[i] != (int64_t) ids[i]) return false; + size_t j = 0; + for (const auto& image : c.imgs) { + if (image.start >= (int64_t) n) continue; + if (j == images.size() || !(images[j++] == image)) return false; + } + return j == images.size(); +} + template int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector& prompt, const std::vector& images) { @@ -285,6 +303,19 @@ public: return best; } + /// A parked conversation holds this state already (its live tokens or one of its checkpoints start with `ids`, + /// same pictures, same steering): see conversation_covers. Read-only; no LRU effect. + template + bool holds(const std::vector& ids, const std::vector& images, bool cvec) const { + for (const auto& e : entries_) { + if (e.cvec != cvec) continue; + if (conversation_covers(e.live, ids, images)) return true; + for (const auto& c : e.checkpoints) + if (conversation_covers(c, ids, images)) return true; + } + return false; + } + SavedConversation take(size_t index) { SavedConversation out = std::move(entries_.at(index)); bytes_ -= out.bytes(); diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp index 8c1e61c3..242e3760 100644 --- a/src/core/conversation_cache_test.cpp +++ b/src/core/conversation_cache_test.cpp @@ -253,6 +253,110 @@ int main() { const auto s = cache.best(with(history, {40}), {}, true); check(s.tokens == (int64_t) history.size() - 2, "SUB resumes from its last turn boundary"); } + { + // holds(): what an idle batch slot holds is parked already (or a continuation of it is) + auto s = image({1, 2, 3, 4, 5}); + ConversationCheckpoint cp; + cp.ids = {1, 2, 3}; + s.checkpoints.push_back(cp); + ConversationCache cache(4096, 4); + cache.put(std::move(s)); + check(cache.holds(std::vector{1, 2, 3, 4, 5}, {}, true), "the parked live state itself"); + check(cache.holds(std::vector{1, 2, 3, 4}, {}, true), "a prefix of the parked live state"); + check(cache.holds(std::vector{1, 2}, {}, true), "a prefix of a parked checkpoint"); + check(!cache.holds(std::vector{1, 2, 3, 4, 5, 6}, {}, true), "a longer state is not held"); + check(!cache.holds(std::vector{1, 2, 9}, {}, true), "a diverging state is not held"); + check(!cache.holds(std::vector{}, {}, true), "an empty state is never held"); + check(!cache.holds(std::vector{1, 2, 3}, {}, false), "steering mode is isolated"); + check(!cache.holds(std::vector{1, 2, 3}, {{1, 77}}, true), "a slot with pictures is not held by a text image"); + auto p = image({1, 2, 3, 4}); + p.live.imgs = {{1, 77}, {3, 78}}; + cache.put(std::move(p)); + check(cache.holds(std::vector{1, 2, 3}, {{1, 77}}, true), "pictures below the state must match"); + check(!cache.holds(std::vector{1, 2, 3, 4}, {{1, 77}}, true), "a picture inside the state that the slot lacks"); + } + { + // The 2026-10-14 four-conversation measurement replayed at policy level: two batch slots, four parked + // entries, conversations A..D. Each has a prompt P (8 tokens; the read's periodic checkpoint at 4), a first + // reply R1 (3 tokens; the slot holds P + 2 of them), the next turn as the client renders it (P + R1 + end + + // header: 14 tokens, the read's turn checkpoint at 12), a second reply R2 (4 tokens; the slot holds 17) and + // a third turn (21 tokens). The engine parks the MAIN session (the prompt as read, plus the admission's + // token) whenever another conversation displaces it; the replies are decoded in the slots. Measured: + // A's third turn found 199584 of 199839 held tokens (its prompt-read state), B found nothing. + // slot_parks: an idle slot parks what it holds before an admission overwrites it + // checks_back: a slot that gives "all it holds" back to the main session gives its checkpoints with it, + // so the chain still supersedes (#342) the parked copies a turn back + auto replay = [&](bool slot_parks, bool checks_back) { + std::vector> full(4); + for (int c = 0; c < 4; ++c) { + for (int32_t t = 1; t <= 8; ++t) full[(size_t) c].push_back(c * 100 + t); + for (int32_t t : {21, 22, 23, 9, 31, 32, 41, 42, 43, 44, 9, 51, 52}) full[(size_t) c].push_back(c * 100 + t); + } + auto st = [&](int c, size_t n) { return std::vector(full[(size_t) c].begin(), full[(size_t) c].begin() + (std::ptrdiff_t) n); }; + auto cp = [&](int c, size_t n) { ConversationCheckpoint k; k.ids = st(c, n); return k; }; + auto park = [&](ConversationCache& cache, int c, size_t n, const std::vector& cks) { + SavedConversation s = image({}); + s.live.ids = st(c, n); + for (size_t k : cks) s.checkpoints.push_back(cp(c, k)); + check(cache.put(std::move(s)), "the replay's parks all fit the budget"); + }; + auto restore = [&](ConversationCache& cache, int c, size_t prompt) -> int64_t { + const auto m = cache.best(st(c, prompt), {}, true); + if (m.tokens > 0) cache.take(m.index); + return m.tokens; + }; + // the main chain after a slot gave "all it holds" back: its checkpoints, or none + auto back = [&](const std::vector& slot_cks) { return checks_back ? slot_cks : std::vector{}; }; + auto slot_park = [&](ConversationCache& cache, int c, size_t n, const std::vector& cks) { + if (slot_parks && !cache.holds(st(c, n), {}, true)) park(cache, c, n, cks); + }; + enum { A, B, C, D }; + ConversationCache cache(1 << 20, 4); + // initial-AB: B solo then admitted (its prompt + the first token parked when A's request came), A + // admitted directly, then alone: solo again from its slot (A's prompt-read state parked first) + park(cache, B, 9, {4}); + park(cache, A, 8, {4}); + std::vector chain_a = back({4}); // slot 1 gave back A's 10 tokens + // resident1-AB: B's request displaces A's solo state; B's slot gives back 10; B admitted with the turn + // checkpoint; A's request restores A's solo state from RAM and is admitted beside B + park(cache, A, 12, chain_a); + std::vector chain_b = back({4}); + chain_b.push_back(12); + // (a request takes its parked conversation before it parks the one it displaces) + check(restore(cache, A, 14) == 12, "A's second turn resumes from its parked solo state"); + park(cache, B, 15, chain_b); + chain_a.push_back(12); + // both decode: slot 0 holds B's 17, slot 1 holds A's 17 + // initial-CD: C's request displaces A's main state; D admitted into slot 0 (B's reply), C into slot 1 + park(cache, A, 14, chain_a); + slot_park(cache, B, 17, {12}); + park(cache, D, 9, {4}); + slot_park(cache, A, 17, {12}); + park(cache, C, 8, {4}); // C alone: solo again from its slot + std::vector chain_c = back({4}); + // resident1-CD: C continues from the main session (no park), D's request displaces it (slot 1 held C's + // own earlier state: covered, no slot park), D's slot gives back 10 (covered as well) + chain_c.push_back(12); + park(cache, C, 15, chain_c); + std::vector chain_d = back({4}); + chain_d.push_back(12); + // both decode: slot 0 holds D's 17, slot 1 holds C's 17 + // exchange1-AB: A's request takes A's parked state, displaces D's main state, is admitted into slot 1 + // (C's reply); B's request displaces A's state + const int64_t a_found = restore(cache, A, 21); + park(cache, D, 14, chain_d); + slot_park(cache, C, 17, {12}); + park(cache, A, 22, {12, 20}); + const int64_t b_found = restore(cache, B, 21); + return std::pair(a_found, b_found); + }; + const auto baseline = replay(false, false); + check(baseline.first == 14 && baseline.second == 0, "baseline: A returns to its prompt-read state, B to nothing (as measured)"); + const auto parks_only = replay(true, false); + check(parks_only.first == 17 && parks_only.second == 0, "slot parks alone: A whole, B's copy evicted by a stale initial image"); + const auto both = replay(true, true); + check(both.first == 17 && both.second == 17, "slot parks + checkpoints back: both return whole"); + } { // what is NOT superseded: another conversation sharing only the root, an entry without checkpoints, the // other steering mode, a branch whose deepest checkpoint the new chain does not hold diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 75d404ac..29172c9b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -9600,10 +9600,23 @@ int main(int argc, char** argv) { id.config = *config_fp; return true; }; + // What a park captures: the main session's conversation (park_current) or an idle batch slot's (park_slot: + // the reply it decoded, before an admission overwrites it). One budget / admission / snapshot path for both. + struct ParkSource { + const std::vector& ids; + const std::vector& imgs; + std::vector& checks; ///< moved apart into stage parts for the capture, put back after + bool cvec; + strata::core::SessionState& session; ///< stage 0's + std::vector stage_sessions; ///< the later stages', in stage order (stages[k]->dev) + const strata::core::QsaState* draft0; ///< the draft layer's K/V saved with stage 0's image (or none) + const strata::core::QsaState* draft_last; ///< ... with the last stage's image (a split: the drafter's GPU) + bool with_reuse; ///< the retained K/V describes this source (the main session's) + std::string what; ///< the log's words after the token count ("", " from slot 1") + }; // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. - auto park_current_body = [&](size_t held) -> bool { - if (!conversations.enabled() || !live_ok || live.empty()) return true; + auto park_source = [&](const ParkSource& src, size_t held) -> bool { // #2049: parking copies the outgoing conversation's running checkpoints and K/V into host memory, which // is a silent stretch of the "request" stage; when the OS has paged that memory out it takes minutes. // Named, so a stall report says "parking"; its copies beat (conversation_copy.hpp), so the watchdog @@ -9616,15 +9629,15 @@ int main(int argc, char** argv) { // switch-time decision, so a client's small side requests would otherwise park themselves and, once the // cache is full, evict the long conversation they were interleaved with (oldest first) - the reuse it // wanted. Returning true is the same non-error skip the byte-budget and RAM-floor paths below take. - if (!conversations.wants((int64_t) live.size())) { + if (!conversations.wants((int64_t) src.ids.size())) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%zu tokens, below the %lld " "minimum; parked=%zu)\n", - live.size(), (long long) o.conversation_cache_min_tokens, conversations.size()); + src.ids.size(), (long long) o.conversation_cache_min_tokens, conversations.size()); return true; } // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold // nothing the outgoing chain does not, apart from the tail this conversation rewrote) - if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached)) + if (const size_t dropped = conversations.drop_superseded(src.ids, src.imgs, src.checks, src.cvec)) std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this " "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size()); // A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per @@ -9633,17 +9646,21 @@ int main(int argc, char** argv) { const size_t n_st = stages.size(); // the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is // saved with that stage's image, under its device; stage 0's image holds none - const strata::core::QsaState* draft0 = (n_st > 0 && !mtp_first) || !use_mtp ? nullptr : &mtp.kv_state(); // no --mtp: no draft K/V (snapshots accept null) - auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return use_mtp && !mtp_first && k + 1 == n_st ? &mtp.kv_state() : nullptr; }; + const strata::core::QsaState* draft0 = src.draft0; // no --mtp: no draft K/V (snapshots accept null) + auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? src.draft_last : nullptr; }; + std::vector& checks = src.checks; strata::core::ConversationCheckpointSplit cs; if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); // #752: two-phase; a bad_alloc leaves `checks` whole struct MergeBack { strata::core::ConversationCheckpointSplit& cs; std::vector& checks; bool on; ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } } merge_back{cs, checks, n_st > 0}; - const strata::core::ConversationView view{live, live_imgs, n_st > 0 ? cs.stage0 : checks, cvec_cached}; - const int64_t retained_n = conversations.retained_tokens(); - auto reuse = conversations.take_reuse_for(live); // never another conversation's K/V + const strata::core::ConversationView view{src.ids, src.imgs, n_st > 0 ? cs.stage0 : checks, src.cvec}; + const int64_t retained_n = src.with_reuse ? conversations.retained_tokens() : 0; + // a batch slot's image carries no retained K/V (it describes the main session's conversation), and the + // main session's stays retained for its own park + auto reuse = src.with_reuse ? conversations.take_reuse_for(src.ids) // never another conversation's K/V + : strata::core::ConversationKvReuse{}; if (retained_n > 0 && reuse.unchanged_tokens < retained_n) std::fprintf(stderr, "strata serve: conversation cache: retained K/V reused for %lld of its %lld tokens " "(the rest is not this conversation's)\n", (long long) reuse.unchanged_tokens, @@ -9656,9 +9673,9 @@ int main(int argc, char** argv) { for (size_t k = 0; k < n_st; ++k) { auto& st = stages[k]; const strata::core::OnDevice on(st->dev); - const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; + const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec}; size_t b = 0; - if (!strata::core::conversation_snapshot_bytes(view_k, st->ss, g, draft_of(k), b, err)) { + if (!strata::core::conversation_snapshot_bytes(view_k, *src.stage_sessions[k], g, draft_of(k), b, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n", st->dev, err.c_str()); err.clear(); @@ -9666,8 +9683,8 @@ int main(int argc, char** argv) { } if (!stage_reuse[k].kv.empty()) { size_t r = 0; - if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, st->ss, g, draft_of(k), - r, err)) { + if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, *src.stage_sessions[k], g, + draft_of(k), r, err)) { b = r; stage_retained += stage_reuse[k].bytes(); } else { @@ -9678,14 +9695,14 @@ int main(int argc, char** argv) { stage_estimate += b; } size_t estimate = 0; - if (!strata::core::conversation_snapshot_bytes(view, ss, g, draft0, estimate, err)) { + if (!strata::core::conversation_snapshot_bytes(view, src.session, g, draft0, estimate, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. return true; } const size_t fresh_estimate = estimate; if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes( - reuse, view, ss, g, draft0, estimate, err)) { + reuse, view, src.session, g, draft0, estimate, err)) { reuse = {}; estimate = fresh_estimate; err.clear(); @@ -9739,15 +9756,15 @@ int main(int argc, char** argv) { (long long) o.conversation_cache_min_free_mib); strata::core::SavedConversation image; size_t reused_bytes = 0; - if (!strata::core::conversation_snapshot_save(image, view, ss, g, draft0, err, + if (!strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err, std::move(reuse), &reused_bytes)) return false; for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V) auto& st = stages[k]; const strata::core::OnDevice on(st->dev); if (cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; return false; } - const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; + const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec}; strata::core::SavedConversation part; - if (!strata::core::conversation_snapshot_save(part, view_k, st->ss, g, draft_of(k), err, + if (!strata::core::conversation_snapshot_save(part, view_k, *src.stage_sessions[k], g, draft_of(k), err, std::move(stage_reuse[k]), &reused_bytes)) return false; image.stage_images.push_back(std::move(part)); @@ -9761,8 +9778,8 @@ int main(int argc, char** argv) { } const size_t snapshot_bytes = image.bytes(); const bool stored = conversations.put(std::move(image), held); - std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", - stored ? "parked" : "skipped", live.size(), + std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens%s in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", + stored ? "parked" : "skipped", src.ids.size(), src.what.c_str(), std::chrono::duration(Clock::now() - t0).count(), conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); } catch (const std::bad_alloc&) { @@ -9772,6 +9789,15 @@ int main(int argc, char** argv) { } return true; }; + auto park_current_body = [&](size_t held) -> bool { + if (!conversations.enabled() || !live_ok || live.empty()) return true; + const size_t n_st = stages.size(); + ParkSource src{live, live_imgs, checks, cvec_cached, ss, {}, + (n_st > 0 && !mtp_first) || !use_mtp ? nullptr : &mtp.kv_state(), + use_mtp && !mtp_first && n_st > 0 ? &mtp.kv_state() : nullptr, true, ""}; + for (auto& st : stages) src.stage_sessions.push_back(&st->ss); + return park_source(src, held); + }; // #752: the whole park (the checkpoint split included) is under one try, so a host OOM skips parking instead of // ending the server auto park_current = [&](size_t held) -> bool { @@ -11686,6 +11712,60 @@ int main(int argc, char** argv) { return true; }; auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; }; + // What an idle slot holds (the conversation it decoded last: its sessions, its draft K/V and its checkpoints) + // goes to the parked conversations before an admission overwrites it. The main session was parked with that + // conversation's prompt only (the admission's copy), so the reply the slot decoded lives nowhere else: without + // this, the conversation's next turn finds its prompt-read state and reads the whole reply again (measured on + // four 200K chats over two slots: 255 of a 256-token reply re-read, and a chat whose copies the cache had + // evicted meanwhile read from token 0). Nothing to do when the live main session or a parked conversation + // already holds that state (or a continuation of it). + // Parking is an optimization like a checkpoint (#3350): a skip and a failed snapshot (a host or device + // allocation that ran out) are logged and the slot is overwritten as before. Nothing here ends the request + // or the engine. + auto park_slot = [&](int b) { + BSlot& sl = bs[(size_t) b]; + if (!conversations.enabled() || sl.active || !sl.cached || sl.img || sl.ids.empty()) return; + auto prefix_of = [&](const std::vector& whole) { + return whole.size() >= sl.ids.size() && std::equal(sl.ids.begin(), sl.ids.end(), whole.begin()); + }; + const bool in_main = live_ok && cvec_cached == sl.cvec && prefix_of(live) && + imgs_below(live_imgs, (int64_t) sl.ids.size()).empty(); + if (in_main || conversations.holds(sl.ids, {}, sl.cvec)) return; + if (use_mtp && !batch_mtp) { // no draft K/V of its own: an image without it would not restore beside the drafter + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (its %zu tokens " + "have no per-slot draft K/V without --batch-mtp)\n", b, sl.ids.size()); + return; + } + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (device sync " + "failed)\n", b); + return; + } + std::string why; + if (batch_mtp && !slot_mtp[(size_t) b]->idle(why)) { + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n", + b, why.c_str()); + return; + } + const size_t n_st = stages.size(); + static const std::vector no_imgs; + ParkSource src{sl.ids, no_imgs, sl.checks, sl.cvec, *bslot_ss[0][(size_t) b], {}, + (n_st > 0 && !mtp_first) || !batch_mtp ? nullptr : &slot_mtp[(size_t) b]->kv_state(), + batch_mtp && !mtp_first && n_st > 0 ? &slot_mtp[(size_t) b]->kv_state() : nullptr, false, + " from slot " + std::to_string(b)}; + for (size_t k = 1; k < bslot_ss.size(); ++k) src.stage_sessions.push_back(bslot_ss[k][(size_t) b].get()); + try { + if (park_source(src, 0)) return; + // the snapshot failed (the copy's own memory, as in #3350): the slot is not touched, so go on without + // the image; a non-sticky allocation error is cleared, a sticky one comes back from the next call + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n", + b, err.empty() ? "the snapshot failed" : err.c_str()); + err.clear(); + (void) checkpoint_failure_is_survivable(); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking slot %d\n", b); + } + }; // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, // so it keeps the conversation it holds auto batch_step = [&]() -> bool { @@ -12967,25 +13047,54 @@ int main(int argc, char** argv) { resume_plan = bs[(size_t) slot_source].partial_plan; resume_plan_at = slot_tokens; resume_plan_end = resume_plan.to; - for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) checks.push_back(c); bs[(size_t) slot_source].partial = false; bs[(size_t) slot_source].partial_plan = {}; } - if (slot_ck != nullptr) { - live = slot_ck->ids; - if (slot_ckpt_move_env() && admit_slot == slot_source) { - // STRATA_SLOT_CKPT_MOVE: the slot this request continues in drops its checkpoints at the - // admission, so this one moves (and moves on into the slot then: moved_in) - std::vector& sc = bs[(size_t) slot_source].checks; - const auto it = sc.begin() + (slot_ck - sc.data()); - checks.push_back(std::move(*it)); - sc.erase(it); - slot_ck = &checks.back(); - moved_in = (int64_t) slot_ck->ids.size(); + // the slot's checkpoints come along (the one continued from, and any shorter one: prefixes of what + // was copied back, their K/V cells with it), so the chain keeps its branch points and the parked + // copies of this conversation a turn back - whose deepest checkpoint the chain holds again - go + // as superseded (#342) instead of taking a parked entry each until the cache evicts another chat. + // STRATA_SLOT_CKPT_MOVE: the slot this request continues in drops its checkpoints at the + // admission, so they move (the one continued from moves on into the slot then: moved_in) + const bool move_cks = slot_ckpt_move_env() && admit_slot == slot_source; + const int64_t ck_len = slot_ck != nullptr ? (int64_t) slot_ck->ids.size() : -1; + std::vector& sc = bs[(size_t) slot_source].checks; + // the one continued from first, exactly as before this change (its copy is the one the request needs) + const ConvCheckpoint* first = slot_ck; + if (first != nullptr) { + if (move_cks) { + checks.push_back(std::move(sc[(size_t) (first - sc.data())])); + sc.erase(sc.begin() + (first - sc.data())); + first = nullptr; // gone from the slot } else { - checks.push_back(*slot_ck); // the main session's chain has it now + checks.push_back(*first); } - checks.back().used = ++check_clock; + } + // then the shorter ones: an optimization, so a host allocation that fails skips them + try { + for (auto it = sc.begin(); it != sc.end();) { + if ((int64_t) it->ids.size() > slot_tokens || &*it == first) { + ++it; + } else if (move_cks) { + checks.push_back(std::move(*it)); + it = sc.erase(it); + } else { + checks.push_back(*it); + ++it; + } + } + } catch (const std::bad_alloc&) { + std::fprintf(stderr, "strata batch: slot %d: its shorter checkpoints were not all copied (out of " + "memory); the rest are skipped\n", slot_source); + } + if (slot_ck != nullptr) { + for (ConvCheckpoint& c : checks) // the main session's chain has it now + if ((int64_t) c.ids.size() == ck_len) { + live = c.ids; + c.used = ++check_clock; + slot_ck = &c; + } + if (move_cks) moved_in = ck_len; } else { live = bs[(size_t) slot_source].ids; } @@ -13684,6 +13793,7 @@ int main(int argc, char** argv) { std::string ye; const auto ty = Clock::now(); std::vector pre(ids.begin(), ids.begin() + q); + if (can) park_slot(ys); // the conversation the slot holds, before this read overwrites it if (can && copy_to_slot(ys, pre, ye)) { BSlot& sl = bs[(size_t) ys]; sl = BSlot{}; @@ -15603,6 +15713,7 @@ int main(int argc, char** argv) { bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 && (int64_t) live.size() == p; const auto tc0 = Clock::now(); + if (cont) park_slot(admit_slot); // the conversation the slot holds, before this one overwrites it if (cont && !copy_to_slot(admit_slot, live, err)) { std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str()); bs[(size_t) admit_slot].cached = false; // its sessions may be half written diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index a3852930..893e7d6b 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -7685,13 +7685,26 @@ int main(int argc, char **argv) try { id.config = *config_fp; return true; }; + // What a park captures: the main session's conversation (park_current) or an idle batch slot's (park_slot: + // the reply it decoded, before an admission overwrites it). One budget / admission / snapshot path for both. + struct ParkSource { + const std::vector& ids; + const std::vector& imgs; + std::vector& checks; ///< moved apart into stage parts for the capture, put back after + bool cvec; + strata::core::SessionState& session; ///< stage 0's + std::vector stage_sessions; ///< the later stages', in stage order (stages[k]->dev) + const strata::core::QsaState* draft0; ///< the draft layer's K/V saved with stage 0's image (or none) + const strata::core::QsaState* draft_last; ///< ... with the last stage's image (a split: the drafter's GPU) + bool with_reuse; ///< the retained K/V describes this source (the main session's) + std::string what; ///< the log's words after the token count ("", " from slot 1") + }; // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. - auto park_current_body = [&](size_t held) -> bool { - if (!conversations.enabled() || !live_ok || live.empty()) return true; + auto park_source = [&](const ParkSource& src, size_t held) -> bool { // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold // nothing the outgoing chain does not, apart from the tail this conversation rewrote) - if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached)) + if (const size_t dropped = conversations.drop_superseded(src.ids, src.imgs, src.checks, src.cvec)) std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this " "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size()); // A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per @@ -7700,17 +7713,21 @@ int main(int argc, char **argv) try { const size_t n_st = stages.size(); // the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is // saved with that stage's image, under its device; stage 0's image holds none - const strata::core::QsaState* draft0 = n_st > 0 || !use_mtp ? nullptr : &mtp.kv_state(); // no --mtp: no draft K/V (snapshots accept null) - auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return use_mtp && k + 1 == n_st ? &mtp.kv_state() : nullptr; }; + const strata::core::QsaState* draft0 = src.draft0; // no --mtp: no draft K/V (snapshots accept null) + auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? src.draft_last : nullptr; }; + std::vector& checks = src.checks; strata::core::ConversationCheckpointSplit cs; if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); // #752: two-phase; a bad_alloc leaves `checks` whole struct MergeBack { strata::core::ConversationCheckpointSplit& cs; std::vector& checks; bool on; ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } } merge_back{cs, checks, n_st > 0}; - const strata::core::ConversationView view{live, live_imgs, n_st > 0 ? cs.stage0 : checks, cvec_cached}; - const int64_t retained_n = conversations.retained_tokens(); - auto reuse = conversations.take_reuse_for(live); // never another conversation's K/V + const strata::core::ConversationView view{src.ids, src.imgs, n_st > 0 ? cs.stage0 : checks, src.cvec}; + const int64_t retained_n = src.with_reuse ? conversations.retained_tokens() : 0; + // a batch slot's image carries no retained K/V (it describes the main session's conversation), and the + // main session's stays retained for its own park + auto reuse = src.with_reuse ? conversations.take_reuse_for(src.ids) // never another conversation's K/V + : strata::core::ConversationKvReuse{}; if (retained_n > 0 && reuse.unchanged_tokens < retained_n) std::fprintf(stderr, "strata serve: conversation cache: retained K/V reused for %lld of its %lld tokens " "(the rest is not this conversation's)\n", (long long) reuse.unchanged_tokens, @@ -7723,9 +7740,9 @@ int main(int argc, char **argv) try { for (size_t k = 0; k < n_st; ++k) { auto& st = stages[k]; const strata::core::OnDevice on(st->dev); - const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; + const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec}; size_t b = 0; - if (!strata::core::conversation_snapshot_bytes(view_k, st->ss, g, draft_of(k), b, err)) { + if (!strata::core::conversation_snapshot_bytes(view_k, *src.stage_sessions[k], g, draft_of(k), b, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n", st->dev, err.c_str()); err.clear(); @@ -7733,8 +7750,8 @@ int main(int argc, char **argv) try { } if (!stage_reuse[k].kv.empty()) { size_t r = 0; - if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, st->ss, g, draft_of(k), - r, err)) { + if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, *src.stage_sessions[k], g, + draft_of(k), r, err)) { b = r; stage_retained += stage_reuse[k].bytes(); } else { @@ -7745,14 +7762,14 @@ int main(int argc, char **argv) try { stage_estimate += b; } size_t estimate = 0; - if (!strata::core::conversation_snapshot_bytes(view, ss, g, draft0, estimate, err)) { + if (!strata::core::conversation_snapshot_bytes(view, src.session, g, draft0, estimate, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. return true; } const size_t fresh_estimate = estimate; if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes( - reuse, view, ss, g, draft0, estimate, err)) { + reuse, view, src.session, g, draft0, estimate, err)) { reuse = {}; estimate = fresh_estimate; err.clear(); @@ -7782,7 +7799,7 @@ int main(int argc, char **argv) try { } strata::core::SavedConversation image; size_t reused_bytes = 0; - if (!strata::core::conversation_snapshot_save(image, view, ss, g, draft0, err, + if (!strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err, std::move(reuse), &reused_bytes)) return false; for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V) auto& st = stages[k]; @@ -7791,9 +7808,9 @@ int main(int argc, char **argv) try { .queues_wait_and_throw()) != 0) { err = "stage sync failed"; return false; } - const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; + const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec}; strata::core::SavedConversation part; - if (!strata::core::conversation_snapshot_save(part, view_k, st->ss, g, draft_of(k), err, + if (!strata::core::conversation_snapshot_save(part, view_k, *src.stage_sessions[k], g, draft_of(k), err, std::move(stage_reuse[k]), &reused_bytes)) return false; image.stage_images.push_back(std::move(part)); @@ -7804,8 +7821,8 @@ int main(int argc, char **argv) try { } const size_t snapshot_bytes = image.bytes(); const bool stored = conversations.put(std::move(image), held); - std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", - stored ? "parked" : "skipped", live.size(), + std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens%s in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", + stored ? "parked" : "skipped", src.ids.size(), src.what.c_str(), std::chrono::duration(Clock::now() - t0).count(), conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); } catch (const std::bad_alloc&) { @@ -7815,6 +7832,15 @@ int main(int argc, char **argv) try { } return true; }; + auto park_current_body = [&](size_t held) -> bool { + if (!conversations.enabled() || !live_ok || live.empty()) return true; + const size_t n_st = stages.size(); + ParkSource src{live, live_imgs, checks, cvec_cached, ss, {}, + n_st > 0 || !use_mtp ? nullptr : &mtp.kv_state(), + use_mtp && n_st > 0 ? &mtp.kv_state() : nullptr, true, ""}; + for (auto& st : stages) src.stage_sessions.push_back(&st->ss); + return park_source(src, held); + }; // #752: the whole park (the checkpoint split included) is under one try, so a host OOM skips parking instead of // ending the server auto park_current = [&](size_t held) -> bool { @@ -9155,6 +9181,65 @@ int main(int argc, char **argv) try { std::exit(1); } }; + // What an idle slot holds (the conversation it decoded last: its sessions, its draft K/V and its checkpoints) + // goes to the parked conversations before an admission overwrites it. The main session was parked with that + // conversation's prompt only (the admission's copy), so the reply the slot decoded lives nowhere else: without + // this, the conversation's next turn finds its prompt-read state and reads the whole reply again (measured on + // four 200K chats over two slots: 255 of a 256-token reply re-read, and a chat whose copies the cache had + // evicted meanwhile read from token 0). Nothing to do when the live main session or a parked conversation + // already holds that state (or a continuation of it). + // Parking is an optimization like a checkpoint (#3350): a skip and a failed snapshot (a host or device + // allocation that ran out) are logged and the slot is overwritten as before. Nothing here ends the request + // or the engine. + auto park_slot = [&](int b) { + BSlot& sl = bs[(size_t) b]; + if (!conversations.enabled() || sl.active || !sl.cached || sl.img || sl.ids.empty()) return; + auto prefix_of = [&](const std::vector& whole) { + return whole.size() >= sl.ids.size() && std::equal(sl.ids.begin(), sl.ids.end(), whole.begin()); + }; + const bool in_main = live_ok && cvec_cached == sl.cvec && prefix_of(live) && + imgs_below(live_imgs, (int64_t) sl.ids.size()).empty(); + if (in_main || conversations.holds(sl.ids, {}, sl.cvec)) return; + if (use_mtp && !batch_mtp) { // no draft K/V of its own: an image without it would not restore beside the drafter + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (its %zu tokens " + "have no per-slot draft K/V without --batch-mtp)\n", b, sl.ids.size()); + return; + } + try { + if (DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()) != 0) { + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (device " + "sync failed)\n", b); + return; + } + } catch (sycl::exception const& exc) { + std::cerr << exc.what() << "Exception caught at file:" << __FILE__ << ", line:" << __LINE__ << std::endl; + std::exit(1); + } + std::string why; + if (batch_mtp && !slot_mtp[(size_t) b]->idle(why)) { + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n", + b, why.c_str()); + return; + } + const size_t n_st = stages.size(); + static const std::vector no_imgs; + ParkSource src{sl.ids, no_imgs, sl.checks, sl.cvec, *bslot_ss[0][(size_t) b], {}, + n_st > 0 || !batch_mtp ? nullptr : &slot_mtp[(size_t) b]->kv_state(), + batch_mtp && n_st > 0 ? &slot_mtp[(size_t) b]->kv_state() : nullptr, false, + " from slot " + std::to_string(b)}; + for (size_t k = 1; k < bslot_ss.size(); ++k) src.stage_sessions.push_back(bslot_ss[k][(size_t) b].get()); + try { + if (park_source(src, 0)) return; + // the snapshot failed (the copy's own memory, as in #3350): the slot is not touched, so go on without + // the image + std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n", + b, err.empty() ? "the snapshot failed" : err.c_str()); + err.clear(); + (void) checkpoint_failure_is_survivable(); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking slot %d\n", b); + } + }; // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, // so it keeps the conversation it holds auto batch_step = [&]() -> bool { @@ -10024,13 +10109,22 @@ int main(int argc, char **argv) try { // checkpoints as if it had not stopped if (slot_ck == nullptr && bs[(size_t) slot_source].partial && admit_slot == slot_source) { resumed_from0 = bs[(size_t) slot_source].partial_from0; - for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) checks.push_back(c); bs[(size_t) slot_source].partial = false; } + // the slot's checkpoints come along (the one continued from, and any shorter one: prefixes of what + // was copied back, their K/V cells with it), so the chain keeps its branch points and the parked + // copies of this conversation a turn back - whose deepest checkpoint the chain holds again - go + // as superseded (#342) instead of taking a parked entry each until the cache evicts another chat + try { // an optimization: a host allocation that fails skips the rest + for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) + if ((int64_t) c.ids.size() <= slot_tokens) checks.push_back(c); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, "strata batch: slot %d: its checkpoints were not all copied (out of memory); the rest are skipped\n", slot_source); + } if (slot_ck != nullptr) { live = slot_ck->ids; - checks.push_back(*slot_ck); // the main session's chain has it now - checks.back().used = ++check_clock; + for (ConvCheckpoint& c : checks) // the main session's chain has it now + if (c.ids.size() == slot_ck->ids.size()) c.used = ++check_clock; } else { live = bs[(size_t) slot_source].ids; } @@ -10554,6 +10648,7 @@ int main(int argc, char **argv) try { std::string ye; const auto ty = Clock::now(); std::vector pre(ids.begin(), ids.begin() + q); + if (can) park_slot(ys); // the conversation the slot holds, before this read overwrites it if (can && copy_to_slot(ys, pre, ye)) { BSlot& sl = bs[(size_t) ys]; sl = BSlot{}; @@ -11865,6 +11960,7 @@ int main(int argc, char **argv) try { bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 && (int64_t) live.size() == p; const auto tc0 = Clock::now(); + if (cont) park_slot(admit_slot); // the conversation the slot holds, before this one overwrites it if (cont && !copy_to_slot(admit_slot, live, err)) { std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str()); bs[(size_t) admit_slot].cached = false; // its sessions may be half written From c471588f3ec289d292ae2b330ea3efc7c1239265 Mon Sep 17 00:00:00 2001 From: l33tm4st3r <26746186+l33tm4st3r@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:46:33 +0100 Subject: [PATCH 086/177] bench: tools/strata_bench.py (BENCH.bat, bench.sh) names an AMD card on ROCm 7+ too (#3630) The quick speed check has its own GPU probe, separate from strata_cli/bench_facts.py, and tried nvidia-smi then rocm-smi only. On a Radeon with amd-smi alone it wrote the server's vendor stub and 'GPU driver: not read'. The same amd-smi probe as #3519 is added in the shape this file uses, and a bare vendor name from the server no longer replaces a card the probe named. Ported from PR #3630 by l33tm4st3r. The three new tests are POSIX-only (symlinks, /sys); run on z440 (Linux, Python 3.12): OK. tools/test_strata_bench.py on Windows: OK. --- tests/terminal/test_bench_community_amd.py | 90 ++++++++++++++++++++++ tools/strata_bench.py | 37 +++++++++ 2 files changed, 127 insertions(+) create mode 100644 tests/terminal/test_bench_community_amd.py diff --git a/tests/terminal/test_bench_community_amd.py b/tests/terminal/test_bench_community_amd.py new file mode 100644 index 00000000..2aa53068 --- /dev/null +++ b/tests/terminal/test_bench_community_amd.py @@ -0,0 +1,90 @@ +"""`bench.sh` (tools/strata_bench.py) has its own GPU probe, so the ROCm 7+ fix in strata_cli/bench_facts.py did not +reach it: with no `rocm-smi` on the box it wrote the server's vendor stub as the card ("AMD Radeon", +`...-community-unknown-...`) and `GPU driver: not read`. The strings below are the real answers of `amd-smi static +--asic --json`, `static --driver --json` and `list --json` on one AI PRO R9700 (gfx1201) plus a Ryzen iGPU, with ROCm +10.1, trimmed to the fields the probe reads.""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from tools import strata_bench as sb + +ASIC = {"gpu_data": [{"gpu": 0, "asic": {"market_name": "AMD Radeon AI PRO R9700", "target_graphics_version": "gfx1201"}}, + {"gpu": 1, "asic": {"market_name": "AMD Radeon Graphics", "target_graphics_version": "gfx1036"}}]} +DRIVER = {"gpu_data": [{"gpu": 0, "driver": {"name": "amdgpu", "version": "N/A", + "os_kernel_version": "7.3.0-rc6-2-cachyos-rc"}}, + {"gpu": 1, "driver": {"name": "amdgpu", "version": "6.16.4"}}]} +LIST = [{"gpu": 0, "bdf": "0000:03:00.0", "node_id": 1}, {"gpu": 1, "bdf": "0000:7c:00.0", "node_id": 2}] +BDF_TO_TOTAL = {"0000:03:00.0": "34208743424", "0000:7c:00.0": "805306368"} + + +def run_cmd(cmd: list[str], timeout: float = 15) -> str: + """ROCm 10.1 answers, with `rocm-smi` missing entirely.""" + if cmd[:1] == ["rocm-smi"] or cmd[:1] == ["nvidia-smi"]: + return "" + if cmd[:3] == ["amd-smi", "list", "--json"]: + return json.dumps(LIST) + if cmd[:2] == ["amd-smi", "static"]: + return json.dumps(DRIVER if "--driver" in cmd else ASIC) + return "" + + +@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch") +class AmdSmiProbe(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + # /sys/class/drm/cardN/device is a symlink whose target ends in the PCI address; the fake tree repeats the + # shape, and the probe matches that address against `amd-smi list` + root = Path(self.tmp.name) + drm = root / "drm" + for card, bdf in (("card1", "0000:03:00.0"), ("card2", "0000:7c:00.0")): + real = root / "devices" / bdf + real.mkdir(parents=True) + (real / "mem_info_vram_total").write_text(BDF_TO_TOTAL[bdf], encoding="utf-8") + drm.mkdir(parents=True, exist_ok=True) + (drm / card).mkdir(exist_ok=True) + os.symlink(real, drm / card / "device") + self.drm = str(drm) + real_path = Path + + class DrmPath(real_path): + def __new__(cls, *a, **kw): + return real_path(self.drm) if a == ("/sys/class/drm",) else real_path(*a, **kw) + + self.drm_patch = mock.patch.object(sb, "Path", DrmPath) + self.drm_patch.start() + self.addCleanup(self.drm_patch.stop) + self.cmd_patch = mock.patch.object(sb, "run_cmd", run_cmd) + self.cmd_patch.start() + self.addCleanup(self.cmd_patch.stop) + + def test_the_probe_names_both_cards(self): + info = sb.gpu_info_local() + self.assertEqual([g["name"] for g in info["gpus"]], ["AMD Radeon AI PRO R9700", "AMD Radeon Graphics"]) + self.assertEqual([g["vram_mib"] for g in info["gpus"]], [34208743424 >> 20, 805306368 >> 20]) + self.assertEqual([g["driver"] for g in info["gpus"]], [None, "6.16.4"]) + self.assertEqual(info.get("rocm_driver"), "6.16.4") + + def test_the_folder_names_the_card_it_used(self): + # the suite reports the card the engine runs on: the words gpu_slug drops are the vendor ones only + self.assertEqual(sb.gpu_slug({"gpu": ["AMD Radeon AI PRO R9700"]}), "ai-pro-r9700") + + def test_the_vendor_stub_does_not_replace_the_card(self): + metrics = {"hardware_static": {"gpu_name": "AMD Radeon", "cpu_name": "AMD Ryzen 9 9950X3D", + "cores": 16, "threads": 32}, "engine": {}} + with mock.patch.object(sb, "try_json", lambda base, path, key="", timeout=20: metrics if path == "/metrics" else {}): + m = sb.collect_machine("http://127.0.0.1:1", "", None) + self.assertEqual(m["gpu"], ["AMD Radeon AI PRO R9700"]) + self.assertEqual(m["gpu_vram_mib"], 34208743424 >> 20) + self.assertEqual(m["gpu_driver"], None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/strata_bench.py b/tools/strata_bench.py index be0e39cf..36d919e7 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -502,6 +502,39 @@ def gpu_info_local() -> dict: m2 = re.search(r"Driver version:\s*(\S+)", v) if m2: info["rocm_driver"] = m2.group(1) + if not info["gpus"] and os.name != "nt": + # ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, so a Radeon wrote the server's vendor stub ("AMD + # Radeon", `...-community-unknown-...`) and `GPU driver: not read`. `static --asic` gives the marketing + # name, `static --driver` the kernel driver's version, the PCI address only comes from `amd-smi list` and + # the VRAM size is the amdgpu driver's sysfs file for that address (same probe as strata_cli/bench_facts.py). + def amd_json(args): + try: + return json.loads(run_cmd(["amd-smi", "static"] + args + ["--json"]).strip() or "{}").get("gpu_data") or [] + except ValueError: # noqa: BLE001 - a report without the card's name is a report + return [] + try: + bdf = {e.get("gpu"): (e.get("bdf") or "") for e in json.loads(run_cmd(["amd-smi", "list", "--json"]).strip() or "[]")} + except ValueError: + bdf = {} + drv = {e.get("gpu"): ((e.get("driver") or {}).get("version") or "") for e in amd_json(["--driver"])} + cards = [] + for e in amd_json(["--asic"]): + name = ((e.get("asic") or {}).get("market_name") or "").strip() + if not name: + continue + d = drv.get(e.get("gpu"), "") + d = d if d.upper() not in ("", "N/A") else None + if d: + info["rocm_driver"] = info.get("rocm_driver") or d + vram = None + for dev in Path("/sys/class/drm").glob("card[0-9]*/device"): + try: + if bdf.get(e.get("gpu")) and os.path.basename(os.path.realpath(dev)).lower() == bdf[e["gpu"]].lower(): + vram = int((dev / "mem_info_vram_total").read_text(encoding="utf-8").strip()) >> 20 + except (OSError, ValueError): + pass + cards.append({"name": name, "vram_mib": vram, "driver": d}) + info["gpus"] = cards if not info["gpus"] and os.name == "nt": # #1587: Windows with only an AMD card has neither nvidia-smi nor rocm-smi; the display class in the registry # names the card, its VRAM and its driver (the run was labelled "CPU only" before) @@ -624,6 +657,10 @@ def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = # engine runs on another vendor's card (an Intel Arc beside a GeForce): the server's names are the right ones, and # so is its VRAM total - the PC's NVIDIA cards were not used. served = [n for n in (static.get("gpu_name") or "").split(" + ") if n and n != "?"] + # the engine's own stub when the driver names no card is the vendor alone ("AMD Radeon"), not a card name: + # taking it as one would throw away the real name amd-smi read (same guard as strata_cli/bench_facts.py) + served = [n for n in served if not re.fullmatch(r"(?i)\s*(nvidia|amd|intel|advanced micro devices)" + r"([ -](geforce|radeon|graphics|arc))?\s*", n)] if served and not all(n in {g["name"] for g in local["gpus"]} for n in served): gpu_names, used = served, [] local = {**local, "cuda": None} # the PC's CUDA belongs to cards the engine did not use From 2251053b427c4b2476914d32438f8b1220038113 Mon Sep 17 00:00:00 2001 From: SanghunYun <45596437+SanghunYun@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:46:55 +0100 Subject: [PATCH 087/177] serve: the serial decode timing line shows the adaptive waits in its sum (#1864) With STRATA_DECODE_TIMING=1 the serial line listed `verify + commit/emit + draft` after `ms/window =`, while the adaptive wait before verify and the join after the draft were timed but printed after the sum, so the named parts did not add up to ms/window. The serial line now reads `adapt wait + verify + commit/emit + draft + adapt join + other`, where `other` is the decode time minus the named parts (not a timed step). The pipelined decode keeps its old line, byte for byte, and nothing is printed with the timing off or with no windows. Diagnostic only: no decode path changes. docs/DETAILS.md: a short paragraph on the new line (the hunk was rebased by hand onto the current file). Tests: compiles on CUDA (the format string was counted against its 22 arguments); no parser in the repo reads `ms/window = verify`. Not covered: no run of the line itself (it needs a decode). --- docs/DETAILS.md | 6 ++++++ src/program/generate.cpp | 37 +++++++++++++++++++++++++++---------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index f60429bf..15f377c7 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -300,6 +300,12 @@ decoding a little: use it to compare, not to measure speed. `STRATA_LOOKAHEAD_ST prediction every 100 windows and costs CPU. `tools/replay_cache_policy.py` replays a `--dump-routing` trace through the adaptive tier's swap policy offline. +In the serial serve loop the timing line lists the wall-time parts in the order they run: `adapt wait + verify + +commit/emit + draft + adapt join + other`. `other` is the decode time minus the named parts, not a step of its own. +The times are host wall times, averaged over every decode window, and the bracketed parts of verify are already inside +verify. The pipelined decode keeps the older line (`ms/window = verify ...`) and batch slots are not covered, so a script +that reads this line must accept `ms/window = adapt wait` for a serial run. + ### Draft layer | Option | Effect | diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 29172c9b..5decbae3 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -15530,16 +15530,33 @@ int main(int argc, char** argv) { if (dec_timing && dec_windows > 0) { const DecSnap d1 = dec_snap(); const double w = (double) dec_windows, L = (double) g.n_layers; - std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " - "verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f " - "CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts " - "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f; adapt wait %.2f join %.2f, %.1f swaps/window\n", - (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_run / w, - (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w, - (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, - (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L), - (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L), - dt_adapt_wait / w, dt_adapt_join / w, (double) ((ajob ? a_swapped : adapt_nswaps) - dt_sw0) / w); + if (!pl_ran) { + const double dt_other = decode_ms - dt_adapt_wait - dt_run - dt_commit - dt_draft - dt_adapt_join; + std::fprintf(stderr, + "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " + "adapt wait %.2f + verify %.2f (GPU-reach wait %.2f + per-layer host %.2f " + "[plan %.2f actq %.2f jobs %.2f CPU %.2f] + stage %.2f) + commit/emit %.2f + " + "draft %.2f + adapt join %.2f + other %.2f; per layer-window: CPU experts " + "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f; %.1f swaps/window\n", + (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_adapt_wait / w, + dt_run / w, (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, + (d1.plan - ds0.plan) / w, (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, + (d1.run - ds0.run) / w, (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, + dt_adapt_join / w, dt_other / w, (d1.misses - ds0.misses) / (w * L), + (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), + (d1.pcie - ds0.pcie) / (w * L), (double) ((ajob ? a_swapped : adapt_nswaps) - dt_sw0) / w); + } else { // Keep the pipeline's existing timing format. + std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " + "verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f " + "CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts " + "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f; adapt wait %.2f join %.2f, %.1f swaps/window\n", + (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_run / w, + (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w, + (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, + (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L), + (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L), + dt_adapt_wait / w, dt_adapt_join / w, (double) ((ajob ? a_swapped : adapt_nswaps) - dt_sw0) / w); + } if (aov) std::fprintf(stderr, "strata decode adapt overlap: %lld windows took swaps still landing, a layer waited %.2f ms in all so far\n", (long long) aov_flips, ver.ms_gate); From 2cc6ea169b9175e0405f5b775bb4007802fb1be1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:47:07 +0100 Subject: [PATCH 088/177] serve: opt-in LaTeX-safe JSON recovery for structured output (#2893) A json_object or json_schema answer that holds LaTeX such as \alpha is rejected (502) because \a, \g and the like are not JSON escapes. New opt-in: "repair_latex_escapes": true in response_format (and in text.format on /v1/responses). Only after the strict parse failed, the server doubles each backslash that does not start a valid JSON escape and parses once more with the same duplicate-key and NaN rules, then checks the schema as before, and prints one log line. Without the option, and for any answer that parses on the first try, nothing changes. Escapes that are valid JSON (\b \f \n \r \t \/ \" \ and a well-formed \uXXXX) are left alone, because they cannot be told from LaTeX: a \beta next to a \alpha comes back with a backspace. Truncated output, arrays, NaN and duplicate keys still fail. Tests: three new tests in serve/test_structured.py (default still 502, opt-in 200 and stream, failures stay failures, helper cases, Responses format passthrough). serve/test_structured.py 13 tests OK. --- docs/DETAILS.md | 6 ++++- serve/responses.py | 5 ++-- serve/structured.py | 54 +++++++++++++++++++++++++++++++++++++++- serve/test_structured.py | 35 ++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 4 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 0ed983c3..0f16b8be 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -492,7 +492,11 @@ applies at the next start. Network, key, MCP and program keys are not editable t decoding, with one generation per request. `jsonschema` is used when installed (`python -m pip install "jsonschema>=4.23,<5"`); without it the answer is only checked to be one JSON object. Malformed output returns **502** with `error.code: structured_output_failed`, an invalid schema **400**. JSON formats combined with tools or MCP are refused. - Streaming buffers the answer and emits content only after validation. + Streaming buffers the answer and emits content only after validation. Math answers often hold LaTeX such as `\alpha`, which is + not a valid JSON escape. Add `"repair_latex_escapes": true` to the `response_format` (or to `text.format` on `/v1/responses`) and, + only after the strict parse failed, the server doubles the backslashes that are not valid escapes and checks the answer again. + Valid output is never touched. `\b`, `\f`, `\n`, `\r`, `\t` and `\uXXXX` are valid JSON, so they stay: a `\beta` beside a `\alpha` + comes back with a backspace. Off by default. - `logit_bias` and token/bias pair lists work on CUDA and HIP engines without continuous batching ([LOGIT_BIAS.md](LOGIT_BIAS.md)). - Stop strings (`stop`, `stop_sequences`), `temperature`, `top_p`, `top_k`, `min_p` and `seed` are honored per request. `top_k` keeps at most 64 candidates. Penalties (`presence_penalty`, `frequency_penalty`, `repetition_penalty`, diff --git a/serve/responses.py b/serve/responses.py index a5b97bce..d5ea4cd0 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -420,11 +420,12 @@ def text_format(req: dict): kind = fmt.get("type") if kind in (None, "text"): return None + extra = {"repair_latex_escapes": True} if fmt.get("repair_latex_escapes") is True else {} # #2893, opt-in if kind == "json_object": - return {"type": "json_object"} + return {"type": "json_object", **extra} if kind == "json_schema": spec = {k: fmt[k] for k in ("name", "schema", "strict", "description") if k in fmt} - return {"type": "json_schema", "json_schema": spec} + return {"type": "json_schema", "json_schema": spec, **extra} raise ResponsesError("text.format.type must be text, json_object or json_schema", "text.format.type") diff --git a/serve/structured.py b/serve/structured.py index 9bed5348..99ecf1c8 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -28,6 +28,46 @@ class _ObjectError: message = "the answer is not a JSON object" +class _Repairing: + """A validator that also tells validated_json to retry once, after a strict parse failed, with the backslashes that + are not valid JSON escapes doubled (response_format "repair_latex_escapes": true, #2893).""" + repair_escapes = True + + def __init__(self, inner): + self.inner = inner + + def iter_errors(self, value): + return self.inner.iter_errors(value) + + +_HEX = "0123456789abcdefABCDEF" + + +def repair_latex_escapes(text: str) -> str: + r"""Double every backslash that does not start a valid JSON escape, so \alpha and \gamma read as text. + The valid escapes (\b \f \n \r \t \/ \" and a well-formed \uXXXX) stay as they are: a model cannot be told + from LaTeX there, so a \beta next to a \alpha comes back with a backspace. Pairs of backslashes are skipped.""" + out = [] + i, n = 0, len(text) + while i < n: + ch = text[i] + if ch != "\\": + out.append(ch) + i += 1 + continue + nxt = text[i + 1] if i + 1 < n else "" + if nxt in ("\\", '"', "/", "b", "f", "n", "r", "t"): + out.append(ch + nxt) + i += 2 + elif nxt == "u" and len(text) >= i + 6 and all(c in _HEX for c in text[i + 2:i + 6]): + out.append(text[i:i + 6]) + i += 6 + else: + out.append("\\\\") + i += 1 + return "".join(out) + + _jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed _jsonschema_lock = threading.Lock() @@ -140,6 +180,8 @@ def prepare_format(response_format, messages, with_tools=False): # /v1/responses (#782): the schema is for the final answer; a turn that calls a tool is not an answer directive += ("\nThis applies only to your final answer. To use a tool, call it as usual; the JSON object is " "what you write once you are done with the tools.") + if response_format.get("repair_latex_escapes") is True: + validator = _Repairing(validator) messages = [dict(message) for message in messages] if messages and messages[0].get("role") == "system": content = messages[0].get("content") or "" @@ -207,7 +249,17 @@ def validated_json(text, validator, finish): value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) except (ValueError, TypeError) as exc: - raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + value = None + if getattr(validator, "repair_escapes", False): # opt-in (#2893); only after the strict parse failed + try: + value = json.loads(repair_latex_escapes(_extract_json(text)), object_pairs_hook=pairs, + parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + print("[strata] structured output: repaired backslashes that were not valid JSON escapes", flush=True) + except (ValueError, TypeError): + value = None + if value is None: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc try: error = next(validator.iter_errors(value), None) except Exception as exc: diff --git a/serve/test_structured.py b/serve/test_structured.py index 6b66cf8b..f0e2c74a 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -112,6 +112,41 @@ class Structured(unittest.TestCase): # Plain text callers retain normal streaming, without a JSON validation gate. self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + def test_latex_escape_repair_is_opt_in_and_only_after_a_strict_failure(self): + # #2893: \alpha is not a JSON escape. Off by default: still a 502. On: one retry after the strict parse failed. + bad = r'{"answer":"the angle \alpha and \gamma_0"}' + self.assertEqual(self.chat(bad, response_format={"type": "json_object"})[0], 502) + self.assertEqual(self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": False})[0], 502) + code, reply = self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": True}) + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), + {"answer": "the angle \\alpha and \\gamma_0"}) + # streaming asks for the same check before any content leaves + _, raw = self.chat(bad, stream=True, response_format={"type": "json_object", "repair_latex_escapes": True}) + self.assertIn(r"\\alpha", raw) + # the repair does not hide what is wrong with the answer itself + fmt = {"type": "json_object", "repair_latex_escapes": True} + for script in ('[]', r'{"x":NaN}', r'{"a":"\alpha","a":2}', 'no json at all', r'{"x":"\alpha'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502, script) + self.assertEqual(self.chat(r'{"answer":"\alpha"}', response_format=fmt, max_tokens=5)[0], 502) + + def test_latex_escape_repair_helper(self): + fix = structured.repair_latex_escapes + self.assertEqual(fix(r'{"a":"\alpha \gamma_0"}'), r'{"a":"\\alpha \\gamma_0"}') + for same in (r'{"a":"x\ny\t\"q\" \\ \/ \u00e9"}', '{"a": 1}', ''): + self.assertEqual(fix(same), same) + self.assertEqual(fix(r'{"a":"\u12"}'), r'{"a":"\\u12"}') # \u without four hex digits + self.assertEqual(fix(r'{"a":"\\alpha"}'), r'{"a":"\\alpha"}') # an escaped backslash is skipped as a pair + self.assertEqual(fix("\\"), "\\\\") # a lone trailing backslash + # \b is a valid escape: untouched, so it parses (as a backspace), as it does without the option + self.assertEqual(json.loads(fix(r'{"a":"\beta \alpha"}'))["a"], "\beta \\alpha") + + def test_the_repair_option_reaches_the_responses_format(self): + from serve.responses import text_format + self.assertEqual(text_format({"text": {"format": {"type": "json_object", "repair_latex_escapes": True}}}), + {"type": "json_object", "repair_latex_escapes": True}) + self.assertEqual(text_format({"text": {"format": {"type": "json_object"}}}), {"type": "json_object"}) + def test_rejected_schema_does_not_load_the_engine_or_retry(self): with mock.patch.object(self.svc, "load") as load: code, _ = self.chat(response_format={"type": "json_schema"}) From a332cc95dbc2a9398860e468a94d758729d25750 Mon Sep 17 00:00:00 2001 From: Jakub Luwierski <91573380+j-luwierski@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:47:46 +0100 Subject: [PATCH 089/177] setup: an explicit --rope-scale must be finite and at least 1 (#3393) resolve_rope accepted nan, inf, zero and values below 1 and handed them to the engine. It now stops with a message that names --rope-scale and the valid range, before any configuration is written; valid factors and the automatic scaling are unchanged. Ported from PR #3393 by j-luwierski (follow-up to #2950) with its tests; the --help text gets the range. --- setup.py | 8 +++++--- tools/test_setup_rope.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index f994d32e..ab6dad1b 100644 --- a/setup.py +++ b/setup.py @@ -7427,7 +7427,7 @@ def derived_factor(ctx: int, trained: int = 262144) -> float: def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. - An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even + An explicit --rope-scaling/--rope-scale always wins - a valid user-supplied factor is kept verbatim even when a reduction changed the context. Past the trained range an omitted method defaults to yarn - llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the magnitude correction keeps the attention temperature - and an omitted factor is derived from the @@ -7436,6 +7436,8 @@ def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): past the trained range (the setup will not configure a run it knows is out of spec) rather than silently overridden. """ + if scale is not None and (not math.isfinite(scale) or scale < 1.0): + raise ValueError("--rope-scale must be a finite value >= 1, e.g. --rope-scale 4") if ctx <= trained: if scale is not None and scaling in (None, "none"): raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " @@ -8640,8 +8642,8 @@ def main() -> int: "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " "picks yarn; 'none' is refused for such a context") ap.add_argument("--rope-scale", type=float, - help="the extension factor (default: the final context over the trained 262144, at least 1 - " - "1.5 for 384K, 2 for 512K, 1 inside the trained range)") + help="the extension factor, finite and >= 1 (default: the final context over the trained " + "262144, at least 1 - 1.5 for 384K, 2 for 512K, 1 inside the trained range)") ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4", "fp16"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " "precise) k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell) or fp16 (16-bit, twice the memory of int8)") diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py index 85b47f98..743fd045 100644 --- a/tools/test_setup_rope.py +++ b/tools/test_setup_rope.py @@ -35,6 +35,21 @@ class DerivedFactor(unittest.TestCase): class ResolveRope(unittest.TestCase): + def test_invalid_explicit_factors_are_rejected(self): + for ctx in (131072, 262144, 1048576): + for method in (None, "none", "linear", "yarn"): + for scale in (float("nan"), float("inf"), float("-inf"), -1.0, 0.0, 0.5): + with self.subTest(ctx=ctx, method=method, scale=scale): + with self.assertRaisesRegex(ValueError, r"--rope-scale.*finite.*>= 1"): + setup.resolve_rope(ctx, method, scale) + + def test_valid_explicit_factors_remain_verbatim(self): + for ctx in (131072, 262144, 1048576): + for method in ("linear", "yarn"): + for scale in (1.0, 1.5, 4.0): + with self.subTest(ctx=ctx, method=method, scale=scale): + self.assertEqual(setup.resolve_rope(ctx, method, scale), (method, scale)) + # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) def test_omitted_384k_gets_yarn_and_1_5(self): self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) From 3100ca05ed1a4bc1dc23f70764220edcb2e6a248 Mon Sep 17 00:00:00 2001 From: Xiaomi2008 <6199045+Xiaomi2008@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:47:52 +0100 Subject: [PATCH 090/177] expert cache: STRATA_VRAM_FREE=device reads the whole card's free VRAM through NVML, Windows + NVIDIA, opt-in (#1911) Under WDDM cudaMemGetInfo answers for the calling process: memory another process holds on the card (the image encoder, a browser, another engine) is not in its free figure. The reporter measured, on an RTX 5090, 30,994 MiB free from CUDA where NVML read 24,348 with 6 GiB held elsewhere, so --expert-cache auto sized the cache too large and shrank it by guesses. device_free_bytes() now takes min(CUDA's figure, NVML's figure for the whole card) when STRATA_VRAM_FREE=device is set. nvml.dll is loaded from the system directory at first use (LoadLibraryExW with LOAD_LIBRARY_SEARCH_SYSTEM32), the card is matched by its PCI bus id, and a missing nvml.dll, a missing export or a failed nvmlInit leaves CUDA's figure with one line on stderr. The serve check of "VRAM free with everything loaded" uses the same function. The value can only get smaller, so the switch can only shrink the expert cache. Unset (the default), nothing changes: the NVML code is compiled only for _WIN32 and not for HIP, Metal or the no-VMM build, and the env variable is read once. The serve check's min() is the same value elsewhere (on a unified-memory system device_free_bytes() is never below cudaMemGetInfo's figure). Added to the PR: the NVML block is also left out of a SYCL build (SYCL_LANGUAGE_VERSION), whose CUDA names are a compatibility layer. docs/DETAILS.md: one row in the measured-and-left-off table instead of the PR's long paragraph. Tests: builds on Linux CUDA (the Windows-only block is skipped), SYCL (P1006) and on Windows MSVC (owner PC build of the final tree). Not covered: no run with a model; the Windows gate is written down. --- docs/DETAILS.md | 1 + include/strata/core/expert_cache.hpp | 4 +- src/core/expert_cache.cpp | 78 ++++++++++++++++++++++++++++ src/program/generate.cpp | 2 + 4 files changed, 84 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 15f377c7..a53ede74 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1287,6 +1287,7 @@ with `--batch 2` at 262,144 context saw 538 MiB at the free line become 395 MiB | `STRATA_SPEC_COUPLED` / `STRATA_SPEC_PROB` (0.1.40.2) | RTX 3060 IQ3_XXS, 200-token answers, 10 pairs | Median tok/s at temperature 0.3 / 0.7 / 1.0: default 42.4 / 43.2 / 43.3, coupled 40.6 / 42.4 / 43.3, rejection sampling 41.0 / 42.6 / 42.6 | | `STRATA_STAGER_SLEEP=1` | Ryzen 9 7940HS laptop, RTX 4070, IQ3_S, 64K (issue #1101) | Prompts of 5,914 and 22,305 tokens read 5-6% slower; whole-machine CPU use 77-90% -> 21-25%. An RTX 5070 read an 8K Q2_0 prompt 1.2% faster with spinning | | Stager threads for a GGUF read in place | Big-RAM box, 124K-token Q8 prompt | 57 -> 350-410 tok/s with the 4-thread RAM profile instead of the 32-thread SSD profile (#1353) | +| `STRATA_VRAM_FREE=device` (Windows, NVIDIA, #1911) | RTX 5090 (WDDM), Core i7-13700K, 64 GB, 128K context, image encoder loaded, `--expert-cache auto` | The switch reads the free VRAM of the whole card through NVML: with 6 GiB held by another process CUDA still read 30,994 MiB free where NVML read 24,348. Default starts ended with 336 to 602 MiB free (0.1.42, three starts) and 93 MiB to 10 GiB (0.1.40.3 and 0.1.41, six starts); with the switch and `--vram-reserve-mib 1500` 973 to 1,392 MiB free over seven starts and 1,107 to 1,288 over three on 0.1.42. A run that filled the card to 0 MiB free decoded 80-115 tok/s where the same text ran at 205-230 with 900 MiB or more free. The cache can only get smaller. Not measured: AMD cards and Linux (the switch is compiled for Windows CUDA builds only). | ### Threads, sockets and sessions diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 9685aa4d..3f66f5ca 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -75,7 +75,9 @@ bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_e /// Free device memory for the expert cache. On a unified memory system - one memory for the CPU and the GPU, such as /// the DGX Spark (GB10); CUDA reports it as cudaDevAttrIntegrated - cudaMemGetInfo counts only MemFree, not the page cache - which, with the experts read from the GGUF in place, is mostly those /// files' clean pages and gives way to a device allocation. There the figure is MemAvailable less 6 GiB for the OS -/// and the engine's host side (STRATA_UMA_HEADROOM_GIB). Elsewhere it is cudaMemGetInfo's. +/// and the engine's host side (STRATA_UMA_HEADROOM_GIB). Elsewhere it is cudaMemGetInfo's. On Windows with an NVIDIA +/// card STRATA_VRAM_FREE=device (opt-in) takes the smaller of that and NVML's figure for the whole card: under WDDM +/// cudaMemGetInfo does not count what other processes hold. It can only make the figure smaller. size_t device_free_bytes(); /// One piece of an expert blob that lives contiguously in a source's own memory: `n` bytes at `p`, to land `at` bytes into the blob. diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index bd98ad71..f499378c 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -22,8 +22,65 @@ #include #include +// (not in a SYCL build: its CUDA names are a compatibility layer without the PCI ids NVML is matched by) +#if defined(_WIN32) && !defined(STRATA_EC_NO_VMM) && !defined(SYCL_LANGUAGE_VERSION) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#define STRATA_EC_NVML_FREE 1 +#endif + namespace strata::core { +#if defined(STRATA_EC_NVML_FREE) +namespace { + +// STRATA_VRAM_FREE=device (opt-in, Windows + NVIDIA). Under WDDM cudaMemGetInfo answers for THIS process: memory +// another process holds on the card (the image encoder, a browser, another engine) is not in its free figure. +// Measured on an RTX 5090, driver 610.88: with 6 GiB written by another process, cudaMemGetInfo in a second process +// still read 30,994 MiB free where NVML read 24,348. NVML (nvml.dll, installed with every driver) counts the whole +// card. The library is loaded from the system directory only, at first use; false when it cannot answer. +bool nvml_device_free(size_t& out) { + struct Memory { unsigned long long total, free, used; }; + typedef int (*InitFn)(void); + typedef int (*ByBusFn)(const char*, void**); + typedef int (*MemFn)(void*, Memory*); + struct Lib { + ByBusFn by_bus = nullptr; + MemFn mem = nullptr; + Lib() { + HMODULE h = LoadLibraryExW(L"nvml.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (h == nullptr) return; + const auto init = (InitFn) (void*) GetProcAddress(h, "nvmlInit_v2"); + const auto bus = (ByBusFn) (void*) GetProcAddress(h, "nvmlDeviceGetHandleByPciBusId_v2"); + const auto m = (MemFn) (void*) GetProcAddress(h, "nvmlDeviceGetMemoryInfo"); + if (init == nullptr || bus == nullptr || m == nullptr || init() != 0) return; + by_bus = bus; + mem = m; + } + }; + static const Lib lib; + if (lib.mem == nullptr) return false; + int dev = 0; + cudaDeviceProp prop{}; + if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess) return false; + char bus[32]; + std::snprintf(bus, sizeof bus, "%08X:%02X:%02X.0", (unsigned) prop.pciDomainID, (unsigned) prop.pciBusID, + (unsigned) prop.pciDeviceID); + void* handle = nullptr; + Memory m{}; + if (lib.by_bus(bus, &handle) != 0 || lib.mem(handle, &m) != 0) return false; + out = (size_t) m.free; + return true; +} + +} // namespace +#endif + // See the header. NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same: // not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim. Swap is not counted here (unlike // NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one. @@ -67,6 +124,27 @@ size_t device_free_bytes() { if (avail > head && avail - head > free_b) free_b = (size_t) (avail - head); } } +#endif +#if defined(STRATA_EC_NVML_FREE) + static const bool device_wide = [] { + const char* v = std::getenv("STRATA_VRAM_FREE"); + return v != nullptr && std::strcmp(v, "device") == 0; + }(); + if (device_wide) { + size_t nvml_b = 0; + const bool got = nvml_device_free(nvml_b); + static std::atomic said{false}; + if (!said.exchange(true)) { + if (got) + std::fprintf(stderr, "strata generate: STRATA_VRAM_FREE=device: free VRAM is read for the whole card " + "(NVML: %lld MiB now; CUDA's figure for this process alone: %lld MiB)\n", + (long long) (nvml_b >> 20), (long long) (free_b >> 20)); + else + std::fprintf(stderr, "strata generate: STRATA_VRAM_FREE=device: NVML did not answer (nvml.dll); free " + "VRAM stays CUDA's figure for this process\n"); + } + if (got) free_b = std::min(free_b, nvml_b); + } #endif return free_b; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5decbae3..77efc070 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11194,6 +11194,8 @@ int main(int argc, char** argv) { // and a page-in while the verify graph spins on a host flag stalls the request for good size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); + // STRATA_VRAM_FREE=device: the whole card's figure when it is the smaller one (the same value otherwise) + free_b = std::min(free_b, strata::core::device_free_bytes()); // below ~256 MiB a later allocation (a first-used window's buffers, the desktop, another program) can make // the driver page GPU memory, and a verify graph spinning on a host flag then never finishes const int64_t free_mib = (int64_t) (free_b >> 20); From 96b6068c32adc0967cbcc8210b544aaee9cf735e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:48:09 +0100 Subject: [PATCH 091/177] Fix the follow-up of #4014 (a variable name already used in Chat.tsx) and two of my tests (#3254 iterator, #3656 raw paths) --- apps/host/src/screens/Chat.tsx | 6 +++--- tests/terminal/test_launch_own_log.py | 4 ++-- tests/terminal/test_procs.py | 6 ++++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 3fbc90d3..46075fab 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -215,7 +215,7 @@ export function ChatScreen() { const pinned = useRef(true); /** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */ const readerInput = useRef(0); - const messageCount = useRef(0); + const seenMessages = useRef(0); /** * Scrolls to the newest message and stays there. * @@ -273,8 +273,8 @@ export function ChatScreen() { // The reader's own scrolling decides (#4014): a wheel notch is about 100 px and used to land inside a 120 px band that pulled // the view back on every token. `pinned` is set by the scroller's wheel, touch, key and scroll handlers below. const count = session?.messages.length ?? 0; - const sent = count > messageCount.current && session?.messages.at(-1)?.role === 'user'; - messageCount.current = count; + const sent = count > seenMessages.current && session?.messages.at(-1)?.role === 'user'; + seenMessages.current = count; // Sending a message always brings the reader to it, as it did before; only the answer's growth waits for the reader. if (pinned.current || sent) scrollToLatest(); diff --git a/tests/terminal/test_launch_own_log.py b/tests/terminal/test_launch_own_log.py index 73210ec7..85eb1f99 100644 --- a/tests/terminal/test_launch_own_log.py +++ b/tests/terminal/test_launch_own_log.py @@ -17,12 +17,12 @@ def derive(base): class OwnLog(unittest.TestCase): def test_the_setup_log_name_is_replaced_by_the_launch_log(self): - for name in ("M:/Strata/strata-iq3_xxs.log", "/home/me/strata/strata-q2_0.log", "M:\Strata\strata-iq3_s.log"): + for name in ("M:/Strata/strata-iq3_xxs.log", "/home/me/strata/strata-q2_0.log", r"M:\Strata\strata-iq3_s.log"): self.assertEqual(derive({"exe": "e", "args": [], "log": name})["log"], "C:/launch/q2_0.engine.log", name) self.assertEqual(derive({"exe": "e", "args": []})["log"], "C:/launch/q2_0.engine.log") def test_a_log_path_the_person_chose_is_kept(self): - for name in ("M:/logs/history.log", "/var/log/strata/engine.log", "D:\notes\iq3.txt"): + for name in ("M:/logs/history.log", "/var/log/strata/engine.log", r"D:\notes\iq3.txt"): self.assertEqual(derive({"exe": "e", "args": [], "log": name})["log"], name, name) self.assertEqual(runner.own_log_path({"log": "M:/Strata/strata-iq3_xxs.log"}), None) self.assertEqual(runner.own_log_path({"log": ""}), None) diff --git a/tests/terminal/test_procs.py b/tests/terminal/test_procs.py index c71ce742..2891ee5c 100644 --- a/tests/terminal/test_procs.py +++ b/tests/terminal/test_procs.py @@ -180,9 +180,11 @@ class SubreaperOrphans(unittest.TestCase): def test_ending_waits_on_the_start_token_not_on_an_empty_command_line(self): record = {"pid": 4242, "token": "t1", "cmd": ["engine", "--serve"]} - tokens = iter(["t1", "t1", None]) # still exiting twice, then gone + answers = ["t1", "t1"] # still exiting twice, then gone + def token(pid): + return answers.pop(0) if answers else None with mock.patch.object(procs, "WINDOWS", False), mock.patch.object(procs, "is_same", side_effect=[True, False, False]) as same, \ - mock.patch.object(procs, "_signal_verified"), mock.patch.object(procs, "start_token", side_effect=lambda pid: next(tokens)), \ + mock.patch.object(procs, "_signal_verified"), mock.patch.object(procs, "start_token", side_effect=token), \ mock.patch.object(procs, "drop_record"), mock.patch.object(procs.time, "sleep"): self.assertEqual(procs.end_one(record, grace=5), "ended") self.assertGreaterEqual(same.call_count, 1) From 560cc9fbbc4272a1d5be73118972572a1dae6216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnter?= <24978919+ai-bits@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:48:14 +0100 Subject: [PATCH 092/177] setup: --gguf-dir files for Qwen3.6 no longer need a .done mark made by setup (#3606) install_own_path treated a file as present only when .done existed, and that mark is written by setup's own download or by verify_sha256, which a file from another tool (LM Studio) never reached: setup said it was missing and asked for the full download size in free disk. With --gguf-dir an existing file and its mmproj go to verify_sha256(own=True), which checks size and SHA-256, leaves a mismatching file alone and writes the mark. A file that is not in the folder is still reported missing. Ported from PR #3606 by ai-bits with its two tests. --- setup.py | 8 +++++--- tools/test_setup_qwen36.py | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index ab6dad1b..d72ba3e3 100644 --- a/setup.py +++ b/setup.py @@ -7757,7 +7757,9 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte gguf = folder / fam["file"].format(q=model) size = fam["sha256"][gguf.name][0] part = gguf.with_name(gguf.name + ".part") - left = 0 if gguf.exists() and done(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 + def have(p: Path) -> bool: # --gguf-dir: the person's own file has no finish mark; verify_sha256 checks and writes it + return p.exists() and (done(p) or bool(a.gguf_dir)) + left = 0 if have(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 if left and free_gb(folder) < left: fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive")) if left and free_gb(folder) < left + 1: @@ -7781,7 +7783,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}") step(5, f"downloading {fam['title']} {model}") - if gguf.exists() and done(gguf): + if have(gguf): ok(f"{gguf.name} already downloaded") else: if a.gguf_dir: @@ -7791,7 +7793,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte ok(f"model file: {gguf}") mmproj = folder / fam["mmproj"] if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked - if mmproj.exists() and done(mmproj): + if have(mmproj): ok(f"{mmproj.name} already downloaded") else: if a.gguf_dir: diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py index 0baef2e9..b71cab23 100644 --- a/tools/test_setup_qwen36.py +++ b/tools/test_setup_qwen36.py @@ -151,6 +151,25 @@ class InstallOwnPath(unittest.TestCase): self.assertEqual(Path(self.cfg["exe"]).parent, self.root / "engine") self.assertIn(("config", "strata-qwen36-ud-q4_k_xl.json"), self.calls) + def test_gguf_dir_takes_the_persons_own_files_that_have_no_finish_mark(self): + folder = self.root / "own" + folder.mkdir() + for name in ("Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", "mmproj-F16.gguf"): + (folder / name).write_text("x") # no .done: verify_sha256 checks the file and marks it + with mock.patch.object(setup, "free_gb", lambda p: 1.0): # nothing to download: no disk needed + rc, out = self.install(model="UD-Q4_K_XL", vision="cpu", gguf_dir=str(folder)) + self.assertEqual(rc, 0, out) + self.assertEqual([c for c in self.calls if c[0] == "get"], []) + self.assertIn(("sha", "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"), self.calls) + self.assertIn(("sha", "mmproj-F16.gguf"), self.calls) + + def test_gguf_dir_without_the_file_still_says_it_is_missing(self): + folder = self.root / "empty" + folder.mkdir() + rc, out = self.install(model="UD-Q4_K_XL", vision="no", gguf_dir=str(folder)) + self.assertEqual(rc, 1) + self.assertIn("is missing", out) + def test_default_size_follows_the_ram(self): rc, out = self.install(ram=64.0) self.assertEqual(rc, 0, out) From a1d2fd7ed1792410af20431da4bc71290060a72a Mon Sep 17 00:00:00 2001 From: Keyan Hu <177766066+KeyanHu-git@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:48:49 +0100 Subject: [PATCH 093/177] setup: use the published size when the download length probes fail (#2287) When HEAD and the one-byte range probe both gave no length, download() took an early EOF as a finished file even though the repository pin (or ModelScope's published size) names the size. The published size now stands in for the length, so the existing resume, retry and parallel code publishes the file only after it has all its bytes; a size that disagrees with the pin is still refused before the transfer and the SHA-256 check is unchanged. Ported from PR #2287 by KeyanHu-git with its tests (tools/test_setup_download_length.py). --- setup.py | 4 +- tools/test_setup_download_length.py | 109 ++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 tools/test_setup_download_length.py diff --git a/setup.py b/setup.py index d72ba3e3..7f3193a9 100644 --- a/setup.py +++ b/setup.py @@ -2885,12 +2885,14 @@ def download(url, dst: Path, what=None): time.sleep(5) if not total: total = range_total(url) + meta = ms_meta(*ms) if ms is not None else None + if not total: # published size also governs partial-file completion + total = pin[0] if pin else (meta[0] if meta else 0) if pin and total and total != pin[0]: # not the pinned file: stop before the download, not after fail(f"{what or dst.name} is {total:,} bytes on {url.split('/')[2]}, not the pinned {pin[0]:,}", "update Strata (the file there has changed since this version pinned it)") label = what or dst.name conns = dl_connections() - meta = ms_meta(*ms) if ms is not None else None fixed = pin if pin else (meta if meta is not None and meta[1] else None) again = (lambda: repair_download(url, dst, total, label, conns)) if total >= DL_MIN_PARALLEL and conns > 1 else None if dst.exists() and total and dst.stat().st_size == total: # finished by an older setup (no mark yet), or stopped before the check diff --git a/tools/test_setup_download_length.py b/tools/test_setup_download_length.py new file mode 100644 index 00000000..2ad726b6 --- /dev/null +++ b/tools/test_setup_download_length.py @@ -0,0 +1,109 @@ +"""Published size drives resume when HEAD and the range probe have no length.""" +import contextlib +import hashlib +import io +import tempfile +import unittest +from pathlib import Path +from unittest import mock +from tools.test_setup_download import DATA, Server, small_pieces, setup + + +class PublishedDownloadLength(unittest.TestCase): + def run_download(self, metadata, persistent=False, digest=True, parallel=False): + def faults(path, start, end, nth): + if (start, end) == (0, 0) and (not parallel or nth == 1): + return 'status', 405 + if start == 0 and nth == 1: + return 'cut', 262144 + if persistent: + return 'cut', 0 + + with Server(length=False, faults=faults, delay=0) as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + published = (len(DATA), hashlib.sha256(DATA).hexdigest() if digest else '') + with contextlib.ExitStack() as stack: + stack.enter_context(small_pieces(DL_MIN_PARALLEL=0 if parallel else len(DATA) + 1)) + stack.enter_context(contextlib.redirect_stdout(io.StringIO())) + stack.enter_context(mock.patch.object(setup, 'file_pin', return_value=None if metadata else published)) + stack.enter_context(mock.patch.object(setup, 'model_source', return_value='modelscope' if metadata else 'huggingface')) + stack.enter_context(mock.patch.object(setup, 'ms_file', return_value=('repo', 'model.gguf'))) + stack.enter_context(mock.patch.object(setup, 'ms_url', return_value=server.url)) + stack.enter_context(mock.patch.object(setup, 'reachable', return_value=True)) + meta = stack.enter_context(mock.patch.object(setup, 'ms_meta', return_value=published)) + if persistent: + with self.assertRaises(SystemExit): + setup.download(server.url, dst) + self.assertFalse(dst.exists()) + self.assertFalse(dst.with_name(dst.name + '.done').exists()) + self.assertEqual(dst.with_name(dst.name + '.part').read_bytes(), DATA[:262144]) + else: + setup.download(server.url, dst) + self.assertEqual(dst.read_bytes(), DATA) + self.assertTrue(dst.with_name(dst.name + '.done').exists()) + if parallel: + self.assertTrue(any(start > 0 and end < len(DATA) - 1 for start, end in server.gets)) + else: + self.assertIn((262144, len(DATA) - 1), server.gets) + self.assertEqual(meta.call_count, 1 if metadata else 0) + + def test_pin_size_recovers_clean_early_eof(self): + self.run_download(metadata=False) + + def test_modelscope_metadata_size_recovers_clean_early_eof(self): + self.run_download(metadata=True) + + def test_exhausted_transfer_keeps_resumable_partial(self): + self.run_download(metadata=False, persistent=True) + + def test_metadata_size_without_hash_still_recovers(self): + self.run_download(metadata=True, digest=False) + + def test_published_size_also_drives_parallel_download(self): + self.run_download(metadata=False, parallel=True) + + def test_complete_partial_is_published_without_downloading_again(self): + def faults(path, start, end, nth): + return ('status', 405) if (start, end) == (0, 0) else None + + with Server(length=False, faults=faults) as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + dst.with_name(dst.name + '.part').write_bytes(DATA) + published = (len(DATA), hashlib.sha256(DATA).hexdigest()) + with small_pieces(DL_MIN_PARALLEL=len(DATA) + 1), \ + mock.patch.object(setup, 'file_pin', return_value=published), \ + contextlib.redirect_stdout(io.StringIO()): + setup.download(server.url, dst) + self.assertEqual(dst.read_bytes(), DATA) + self.assertIn(published[1], dst.with_name(dst.name + '.done').read_text()) + self.assertEqual(server.gets, [(0, 0)]) + heads = server.heads + setup.download(server.url, dst) + self.assertEqual(server.heads, heads) + self.assertEqual(server.gets, [(0, 0)]) + + def test_transport_size_conflict_is_still_refused_before_transfer(self): + with Server() as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + with small_pieces(), mock.patch.object(setup, 'file_pin', return_value=(len(DATA) + 1, '0' * 64)), \ + contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + setup.download(server.url, dst) + self.assertEqual(server.gets, []) + self.assertEqual(list(Path(tmp).iterdir()), []) + + def test_fallback_size_does_not_bypass_hash_verification(self): + def faults(path, start, end, nth): + return ('status', 405) if (start, end) == (0, 0) else None + + with Server(length=False, faults=faults) as server, tempfile.TemporaryDirectory() as tmp: + dst = Path(tmp) / 'model.gguf' + with small_pieces(DL_MIN_PARALLEL=len(DATA) + 1), \ + mock.patch.object(setup, 'file_pin', return_value=(len(DATA), '0' * 64)), \ + contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + setup.download(server.url, dst) + self.assertFalse(dst.exists()) + self.assertFalse(dst.with_name(dst.name + '.done').exists()) + + +if __name__ == '__main__': + unittest.main() From 61ede87e1bed4f90d67bc3c4a5fad7455ed112b9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:48:59 +0100 Subject: [PATCH 094/177] Maxwell sm_52 floor for the opt-in old-card build (#3218) A reporter built Strata for two Quadro M6000 (sm_52) by lowering two floors and saw about 22 tokens a second with Qwen3.8-Flash-Next IQ1. CMakeLists.txt: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON) now accepts sm_52 and prints a warning for it (Maxwell, one reporter, no native half precision, CUDA 12.x). Without the flag the build still stops at sm_75 as before, and the architectures a build uses are not changed. setup.py: sm60_card() admits a 5.2 card only when the tester sets STRATA_EXPERIMENTAL_SM52=1, because the ready-made CUDA 12 engine holds no sm_52 code and a Maxwell card must not be routed to it by default. With the variable set, setup warns about the Maxwell card instead of refusing. Default: a Maxwell card is "not supported" exactly as before. docs/OLDER_GPUS.md: a Maxwell row and a short section, with the build command and a request for an answer-text check. Tests: tools/test_setup_older_gpus.py (20 tests, new Maxwell cases for default, opt-in and a newer card present). Not covered: no model run, and the answer text on a Maxwell card is unchecked. --- CMakeLists.txt | 11 +++++++++-- docs/OLDER_GPUS.md | 17 +++++++++++++++++ setup.py | 11 ++++++++++- tools/test_setup_older_gpus.py | 15 +++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6356e27b..e18e6161 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -213,9 +213,16 @@ elseif(STRATA_ENABLE_CUDA) "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is " "-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)") endif() - if(_base LESS 60) + if(_base LESS 52) message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build " - "needs compute capability 6.0 (sm_60) or newer") + "needs compute capability 5.2 (sm_52, Maxwell) or newer") + endif() + # Maxwell (sm_52, #3218): one reporter built and ran this on two Quadro M6000 (CUDA 12.x, Qwen3.8-Flash-Next + # IQ1, about 22 t/s). It has no native half-precision arithmetic, so it is slower per byte than Pascal; only + # this opt-in build gets the floor. Warn, do not refuse. + if(_base LESS 60) + message(WARNING "Building for sm_${_base} (Maxwell): community-tested on one reporter's Quadro M6000 only, " + "no native half-precision arithmetic, CUDA 12.x toolkit required (docs/OLDER_GPUS.md).") endif() # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 92c26f9c..88036809 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -21,6 +21,7 @@ unchanged. Numbers are the reporters' own, on one machine each, unless the text | Cards | Compute capability | How it runs | What is different on it | | --- | --- | --- | --- | +| Quadro M6000, GTX 900 series (Maxwell) | 5.2 | a source build with CUDA 12.x | Opt-in, one reporter, [below](#maxwell-sm_52). No native half-precision arithmetic. Not in the ready-made CUDA 12 engine | | Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32; seven scheduling switches on by default ([below](#tesla-p100-sm_60)); opt-in `STRATA_Q8_SM60=1` ([below](#pascal-gp100-a-q8_0-decode-kernel-opt-in)) | | Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there); dense weights dequantized by a wide kernel; expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | | Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores; prompt attention on `mma.m8n8k4`; a leaner attention kernel. See [NVIDIA_V100.md](NVIDIA_V100.md) | @@ -41,6 +42,22 @@ too and cannot hold any of the model. | Radeon PRO V520 / Pro 5600M (RDNA1) | gfx1011 | built by hand: `-DCMAKE_HIP_ARCHITECTURES=gfx1011`; builds with 0 errors, untested on hardware | | Instinct MI50 / MI60, Radeon VII | gfx906 (wave64) | built by hand: `-DSTRATA_HIP_GFX906=ON` | +### Maxwell (sm_52) + +One reporter ran Strata v0.1.44.1 on two Quadro M6000 24 GB (Ubuntu, driver 580) with Qwen3.8-Flash-Next at IQ1 and saw about +22 tokens a second. Nobody has checked the answer text on these cards yet, and Maxwell has no native half-precision arithmetic, +so treat it as a test. The ready-made CUDA 12 engine holds no sm_52 code; build from source with a CUDA 12.x toolkit (CUDA 13 +cannot compile for Maxwell): + +``` +cmake -B build -G Ninja -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52 +cmake --build build -j +``` + +CMake prints a warning for sm_52 and goes on. A release build still needs sm_75 or newer, and without `STRATA_EXPERIMENTAL_SM60=ON` +the build stops as before. For `setup.py` to list a Maxwell card as usable, set `STRATA_EXPERIMENTAL_SM52=1`; setup warns and uses +the CUDA 12 path. If you try it, please post a short chat and one code answer from the card. + ## NVIDIA: the CUDA 12 engine CUDA 13 dropped Pascal and Volta and cannot compile for them. Setup therefore keeps a second engine, built with CUDA 12.9 and diff --git a/setup.py b/setup.py index 55f8941f..de04c597 100644 --- a/setup.py +++ b/setup.py @@ -1548,7 +1548,12 @@ def experimental_sm60() -> bool: def sm60_card(arch) -> bool: - return 60 <= int(arch) <= 70 + """Pascal (6.x) and Volta (7.0) cards; Maxwell 5.2 (#3218) only for a tester who set STRATA_EXPERIMENTAL_SM52=1, + because the ready-made CUDA 12 engine holds no sm_52 code: a Maxwell card is built from source, by that tester.""" + a = int(arch) + if a == 52: + return os.environ.get("STRATA_EXPERIMENTAL_SM52", "").strip() == "1" + return 60 <= a <= 70 def old_gpus_opt_in(found, named=(), cuda=None, other=False): @@ -8881,6 +8886,10 @@ def main() -> int: if OLD_GPUS and a.backend != "hip": warn(f"older NVIDIA GPUs (Pascal / Volta) can be used ({OLD_GPUS}): experimental, through a second engine " "built with CUDA 12 (docs/OLDER_GPUS.md)") + if any(int(g["arch"]) == 52 for g in found): + warn("a Maxwell card (compute capability 5.2) has no fast half-precision path; it was tested by one reporter " + "only, on a source build (-DSTRATA_EXPERIMENTAL_SM60=ON, CUDA 12.x). Check that the answer text reads " + "correctly (docs/OLDER_GPUS.md)") nv_ok = any(gpu_problem(g) is None for g in found) hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) if a.backend is None and nv_ok and amd_ok: diff --git a/tools/test_setup_older_gpus.py b/tools/test_setup_older_gpus.py index d11419e1..f66d121e 100644 --- a/tools/test_setup_older_gpus.py +++ b/tools/test_setup_older_gpus.py @@ -88,6 +88,21 @@ class OptIn(unittest.TestCase): self.assertIn("only kind", setup.old_gpus_opt_in([V100])) self.assertIsNone(setup.old_gpus_opt_in([V100], other=True)) # an AMD card it can use instead self.assertIsNone(setup.old_gpus_opt_in([card(0, "GTX 980", 4.0, "52")])) + # #3218: Maxwell only for a tester who sets STRATA_EXPERIMENTAL_SM52=1 (the default stays unchanged) + m6000 = card(0, "Quadro M6000", 24.0, "52") + self.assertFalse(setup.sm60_card("52")) + self.assertTrue(setup.sm60_card("60") and setup.sm60_card("70") and not setup.sm60_card("75")) + self.assertIn("not supported", setup.gpu_problem(m6000)) + self.assertNotIn("experimental: choose it", setup.gpu_problem(m6000)) + with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM52": "1"}): + self.assertTrue(setup.sm60_card("52")) + self.assertFalse(setup.sm60_card("50")) + self.assertIn("experimental: choose it", setup.gpu_problem(m6000)) + self.assertIn("only kind", setup.old_gpus_opt_in([m6000])) + self.assertIsNone(setup.old_gpus_opt_in([rtx, m6000])) # a newer card keeps winning + self.assertEqual(setup.cuda_choice([52])[0], 12) + with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): + self.assertIsNone(setup.gpu_problem(m6000)) # warned, not refused with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): self.assertEqual(setup.old_gpus_opt_in([rtx, v100]), "STRATA_EXPERIMENTAL_SM60=1") From eba3106c0e31d18a0f48cdff596afb1ffd41673e Mon Sep 17 00:00:00 2001 From: PurrSec <87878066+purrsec@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:50:11 +0100 Subject: [PATCH 095/177] serve: support IPv6 bind addresses (#3212) --host :: failed before the model loaded because Server always opened an IPv4 socket. Server now selects AF_INET6 when the bind address contains a colon; the ready line, the 'from other devices' lines and the browser address bracket an IPv6 address. The bind is still the person's choice and no default changes. Ported from PR #3212 by purrsec with its tests (serve/test_security.py, including a real :: bind). setup.py's --host help and docs/DETAILS.md say :: is all IPv6 interfaces; the README hunks of the PR (they name strata launch --host, not checked) are left out. --- docs/DETAILS.md | 2 ++ serve/server.py | 16 +++++++++++----- serve/test_security.py | 38 +++++++++++++++++++++++++++++++++++++- setup.py | 9 +++++---- 4 files changed, 55 insertions(+), 10 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9ccf7685..27d0fdf3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -544,6 +544,8 @@ tables per token). The scaling is fixed for the whole run, because the KV cache `--host 0.0.0.0 --api-key some-long-secret`, or add `"host": "0.0.0.0"` and `"api_key": "..."` to the config. A key is recommended, not required: without one the server starts and warns that anyone who can reach the port can use the model and its tools. `--no-api-key` (or `"api_key": "none"`) says it is on purpose. The server window prints this PC's addresses. + For IPv6 use `--host ::` (or `"host": "::"`, all IPv6 interfaces) and put the address in brackets in URLs, for example + `http://[2001:db8::7]:8080/v1`. On Windows allow the port in the firewall for private networks: `New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private` (admin PowerShell). diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..8a51e2e9 100644 --- a/serve/server.py +++ b/serve/server.py @@ -7445,6 +7445,11 @@ class Server(ThreadingHTTPServer): # (STRATA_HTTP_BACKLOG overrides it) request_queue_size = max(5, int(os.environ.get("STRATA_HTTP_BACKLOG") or 256)) + def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): + if ":" in server_address[0]: + self.address_family = socket.AF_INET6 + super().__init__(server_address, RequestHandlerClass, bind_and_activate) + def handle_error(self, request, client_address): if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace super().handle_error(request, client_address) @@ -8143,7 +8148,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in "written by setup.py") ap.add_argument("--host", default=None, help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices " - "on your network (set an API key); also \"host\" in the config") + "on your network, :: = all IPv6 interfaces (set an API key); also \"host\" in the config") ap.add_argument("--script-cycle", action="store_true", help="with --script given more than once: repeat the scripts by position instead of advancing " "to the last one and staying there, so extra requests a harness makes (a session title, " @@ -8617,18 +8622,19 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in bound_port = httpd.server_address[1] # --port 0: report the port the OS actually assigned svc.start_idle_unload() svc.start_vision_idle() - here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host + here = "[::1]" if a.host == "::" else "127.0.0.1" if a.host in ("0.0.0.0", "") else f"[{a.host}]" if ":" in a.host else a.host print(f"ready: http://{here}:{bound_port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " f"context {engine.max_context} tokens{', images on' if vision else ''}" f"{', API key required' if svc.api_key else ''})", flush=True) print(f" open http://{here}:{bound_port}/ in a browser to chat; close this window to stop the model", flush=True) if a.host not in ("127.0.0.1", "localhost", "::1"): # issue #26: reachable from other devices - say at which address, and what can still block it - ips = lan_addresses() + ips = [f"[{a.host}]"] if ":" in a.host and a.host != "::" else [] if a.host == "::" else lan_addresses() for ip in ips: print(f" from other devices: http://{ip}:{bound_port}/ (API: http://{ip}:{bound_port}/v1)", flush=True) if not ips: - print(" from other devices: http://:" + str(bound_port) + "/", flush=True) + address = "[]" if a.host == "::" else "" + print(f" from other devices: http://{address}:{bound_port}/", flush=True) if not svc.api_key: print(" WARNING: " + open_server_warning(bound_port, tools=svc.mcp is not None), flush=True) @@ -8642,7 +8648,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in # on its own thread: webbrowser.open waits for the browser launcher, which on Linux can run for as long as # the browser does, and the main thread must be free to take Ctrl+C and SIGTERM (#1872) threading.Thread(target=webbrowser.open, daemon=True, name="strata-open-browser", - args=(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{bound_port}/",)).start() + args=(f"http://{here}:{bound_port}/",)).start() if ready_path is not None or event_sink is not None: ready_host = f"[{here}]" if ":" in here and not here.startswith("[") else here record = {"schema_version": 1, "instance_id": svc.instance_id, "pid": os.getpid(), diff --git a/serve/test_security.py b/serve/test_security.py index 4b00f440..0fb695e7 100644 --- a/serve/test_security.py +++ b/serve/test_security.py @@ -12,12 +12,13 @@ import json import socket import sys import unittest +from http.server import BaseHTTPRequestHandler from pathlib import Path from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 -from serve.server import (ByteTokenizer, MockEngine, Service, allowed_hosts_of, host_allowed, # noqa: E402 +from serve.server import (ByteTokenizer, MockEngine, Server, Service, allowed_hosts_of, host_allowed, # noqa: E402 host_name, host_names_for, origin_allowed, serve) ROOT = Path(__file__).resolve().parents[1] @@ -57,6 +58,41 @@ class HostNames(unittest.TestCase): self.assertNotIn("*", names) +class ListenAddress(unittest.TestCase): + def test_ipv4_address_family(self): + with Server(("127.0.0.1", 0), BaseHTTPRequestHandler, bind_and_activate=False) as s: + self.assertEqual(s.address_family, socket.AF_INET) + + @unittest.skipUnless(socket.has_ipv6, "IPv6 is not available") + def test_ipv6_loopback(self): + for host in ("::1", "2001:db8::7"): + try: + with Server((host, 0), BaseHTTPRequestHandler, bind_and_activate=False) as s: + self.assertEqual(s.address_family, socket.AF_INET6) + except OSError as e: + self.skipTest(f"IPv6 socket is not available: {e}") + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=4096), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + try: + httpd = serve(svc, host="::", port=0) + except OSError as e: + self.skipTest(f"IPv6 loopback is not available: {e}") + try: + self.assertEqual(httpd.address_family, socket.AF_INET6) + c = http.client.HTTPConnection("::1", httpd.server_address[1], timeout=10) + try: + c.request("GET", "/health") + r = c.getresponse() + self.assertEqual(r.status, 200) + r.read() + finally: + c.close() + finally: + httpd.shutdown() + httpd.server_close() + + class HostCheck(unittest.TestCase): def test_accepted(self): for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]", diff --git a/setup.py b/setup.py index 7f3193a9..c32c6db4 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768 at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port 8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, ---host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off +--host 0.0.0.0 --api-key KEY (reach it over IPv4; use --host :: for IPv6), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), --models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM), @@ -8685,9 +8685,10 @@ def main() -> int: "auto, placed from each GPU's free VRAM") ap.add_argument("--no-remote-expert-opt", action="store_true", help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)") - ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " - "devices on your network (issue #26; an --api-key is recommended)") - ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0); several keys: key1,key2") + ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = all IPv4 " + "interfaces, :: = all IPv6 interfaces (issue #26; an --api-key is recommended)") + ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0 or --host ::); " + "several keys: key1,key2") ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, help="do not open the chat page in the browser when the model is ready (for a harness or an app " "that uses the API; remembered for this model, also in run-.bat/.sh)") From a11f8b0aa5445389cbbb0a0292402ee8d31aad4a Mon Sep 17 00:00:00 2001 From: Vop3p <69450118+Vop3p@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:50:44 +0100 Subject: [PATCH 096/177] prefill: opt-in sparse copied events and deduplicated slot waits in the streamed prompt walk (#4005) Under WDDM every cudaEventRecord and cross-stream wait is a submission of its own (the author measured ~80 / ~45 us each on an RX 6900 XT under Windows 11), and the streamed walk paid one record and one wait per expert although a group gathers after one wait on its last copy. Two tester switches, threaded issuer only: - STRATA_PREFILL_COPY_EVENT_EVERY=N (2..64): the copied event is recorded every N-th entry, before the issuer waits and on the last; the compute stream waits on the first recorded entry at or after the one it needs (the copy stream is in order). - STRATA_PREFILL_COPY_WAIT_DEDUPE=1: the copy stream skips its wait on a slot's release event when the previous slot was released by the same event. The same copies into the same slots: the same bytes. Default path (both unset): read line by line. The issuer records copied[slot] and waits on used[used_of[slot]] exactly as before (the counters are bookkeeping, cover() is a no-op). Added to the PR so this holds by construction: wait_copied takes the slot the old code used and, without the sparse switch, waits on copied[slot] at all three consumer sites (the PR derived the slot from the entry number). The record/wait selection is now three pure functions in include/strata/prefill/copy_events.hpp, with a host test (copy_events_test, registered in CMakeLists.txt) that models the issuer and consumer with a full ring and checks that every wait names a live recorded entry at or after the one needed. Tests: copy_events_test passes (z440, g++ -std=c++20). Not yet: a CUDA build of prefill.cpp in this tree (queued), no GPU run. Not covered: the Windows HIP / WDDM speed claim and NVIDIA (the gate is written down). Needs the author's numbers repeated before any default talk. --- CMakeLists.txt | 4 ++ include/strata/prefill/copy_events.hpp | 35 ++++++++++ src/prefill/copy_events_test.cpp | 76 +++++++++++++++++++++ src/prefill/prefill.cpp | 93 ++++++++++++++++++++++++-- 4 files changed, 201 insertions(+), 7 deletions(-) create mode 100644 include/strata/prefill/copy_events.hpp create mode 100644 src/prefill/copy_events_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6356e27b..e1aa9ffe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2338,6 +2338,10 @@ if(STRATA_BUILD_TESTS) 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) + # #4005: which streamed expert copies get a copied event (header-only, CPU) + add_executable(copy_events_test src/prefill/copy_events_test.cpp) + target_include_directories(copy_events_test PRIVATE include) + add_test(NAME copy_events_test COMMAND copy_events_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) diff --git a/include/strata/prefill/copy_events.hpp b/include/strata/prefill/copy_events.hpp new file mode 100644 index 00000000..96f1ea62 --- /dev/null +++ b/include/strata/prefill/copy_events.hpp @@ -0,0 +1,35 @@ +// include/strata/prefill/copy_events.hpp - which streamed expert copies get a "copied" event (#4005). +// +// The streamed prompt walk issues one host-to-device copy per expert entry on the copy stream and the compute stream +// waits for it. By default every entry records its own event (every == 1) and the compute stream waits on the event of +// the entry it needs. STRATA_PREFILL_COPY_EVENT_EVERY=N (tester switch) records every N-th entry only, and the +// compute stream waits on the first recorded entry at or after the one it needs: the copy stream is in order, so that +// event covers it. The two rules are pure functions so a host test can check them without a GPU. +#pragma once + +#include +#include + +namespace strata::prefill { + +/// The value of STRATA_PREFILL_COPY_EVENT_EVERY: 1 (every entry) unless the text is a number above 1; at most 64. +inline int copy_event_every_from(int parsed) { return parsed > 1 ? (parsed < 64 ? parsed : 64) : 1; } + +/// Entry `idx` of `total` records its copied event right after its copy: always with every == 1; else every N-th entry +/// and the last one. +inline bool copy_event_due(size_t idx, size_t total, int every) { + return every <= 1 || (idx + 1) % (size_t) every == 0 || idx + 1 == total; +} + +/// The entry whose recorded event a consumer waits on for entry `k`, when the entries [0, recorded) have had their +/// events decided (`recorded` = 1 + the last recorded entry) and `is_recorded(r)` says whether entry r has one. The +/// first recorded entry at or after k; the last recorded entry (recorded - 1) when none is found, which covers k as +/// well. Precondition: k < recorded. +template +inline size_t copy_event_entry(size_t k, size_t recorded, IsRecorded is_recorded) { + for (size_t r = k; r < recorded; ++r) + if (is_recorded(r)) return r; + return recorded - 1; +} + +} // namespace strata::prefill diff --git a/src/prefill/copy_events_test.cpp b/src/prefill/copy_events_test.cpp new file mode 100644 index 00000000..1ce75e68 --- /dev/null +++ b/src/prefill/copy_events_test.cpp @@ -0,0 +1,76 @@ +// Host test for include/strata/prefill/copy_events.hpp (#4005): the copied-event rules of the streamed prompt walk. +#include "strata/prefill/copy_events.hpp" + +#include +#include +#include + +using namespace strata::prefill; + +static int g_fail = 0; +static void check(bool ok, const char* what) { + if (!ok) { std::printf("FAIL: %s\n", what); ++g_fail; } +} + +int main() { + check(copy_event_every_from(0) == 1 && copy_event_every_from(1) == 1 && copy_event_every_from(-5) == 1, "unset / 0 / 1 / negative: every entry"); + check(copy_event_every_from(2) == 2 && copy_event_every_from(16) == 16 && copy_event_every_from(64) == 64, "2..64 as given"); + check(copy_event_every_from(65) == 64 && copy_event_every_from(100000) == 64, "above 64 is 64"); + + // default: every entry records (the walk then waits on copied[slot], as before the switch) + for (size_t total : {1u, 2u, 7u, 100u}) + for (size_t i = 0; i < total; ++i) check(copy_event_due(i, total, 1), "every == 1 records every entry"); + + // sparse: the walk's issuer/consumer as a model. The issuer records per copy_event_due (and, when it must wait for + // the consumer, the entry before the one it is about to issue); the consumer for entry k waits on + // copy_event_entry(k, recorded, ...). Every wait must name a recorded entry at or after k, and the ring must + // never need an event that a later entry has overwritten. + std::srand(4005); + for (int every : {2, 3, 5, 16, 64}) + for (int ring : {2, 4, 8, 96}) + for (size_t total : {1u, 5u, 33u, 300u}) { + std::vector rec_of((size_t) ring, -1); + size_t recorded = 0, issued = 0, consumed = 0; + long long last_rec = -1; + bool ok = true; + auto record = [&](size_t i) { + if (rec_of[i % (size_t) ring] >= 0 && (size_t) rec_of[i % (size_t) ring] >= consumed) ok = false; // overwrote a live event + rec_of[i % (size_t) ring] = (long long) i; + recorded = i + 1; + last_rec = (long long) i; + }; + auto cover = [&](size_t idx) { if (idx > 0 && last_rec < (long long) idx - 1) record(idx - 1); }; + size_t guard = 0; + while (consumed < total && ok && ++guard < 100000) { + const bool can_issue = issued < total && issued < consumed + (size_t) ring; + const bool can_consume = consumed < issued; + const bool pick_issue = can_issue && (!can_consume || std::rand() % 2); + if (pick_issue) { + const size_t idx = issued; + if (std::rand() % 4 == 0) cover(idx); // the issuer had to wait (ring full or stager) + if (copy_event_due(idx, total, every)) record(idx); + ++issued; + } else if (can_consume) { + if (issued == total || true) { + // a consumer needs recorded > k; when the issuer is blocked it has covered what it issued + if (recorded <= consumed) { + if (issued < total && !(issued < consumed + (size_t) ring)) cover(issued); + if (issued == total) cover(issued); + } + if (recorded <= consumed) { continue; } // would spin until the issuer records + const size_t r = copy_event_entry(consumed, recorded, [&](size_t e) { return rec_of[e % (size_t) ring] == (long long) e; }); + if (r < consumed || r >= recorded || rec_of[r % (size_t) ring] != (long long) r) ok = false; + ++consumed; + } + } else { + break; + } + } + char what[128]; + std::snprintf(what, sizeof what, "sparse every=%d ring=%d total=%zu: every wait names a live recorded entry", every, ring, total); + check(ok && consumed == total, what); + } + + if (g_fail == 0) std::printf("copy_events_test: all checks passed\n"); + return g_fail == 0 ? 0 : 1; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 08b529e6..9e71dd69 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,6 +1,7 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. #include "strata/kernels/fused_gr.hpp" #include "strata/prefill/prefill.hpp" +#include "strata/prefill/copy_events.hpp" #if defined(STRATA_HAVE_DFLASH2) #include "strata/kernels/dflash2.hpp" #endif @@ -3205,13 +3206,54 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri ~IssuerJoin() { if (t->joinable()) { stop->store(true); t->join(); } } } issuer_join{&a_stop, &issuer}; const bool threaded_issue = stream_all && issuer_on; + // Opt-in, the threaded issuer only: under WDDM every cudaEventRecord and cross-stream wait is a + // submission of its own (~80 / ~45 us each on a 6900 XT under Windows 11, ~3 / ~0 us on Linux), and the + // streamed walk paid one record and one wait per expert although a group gathers after ONE wait on its last + // copy and is released by ONE event. STRATA_PREFILL_COPY_EVENT_EVERY=N records the copied event every N-th + // entry (and before the issuer waits, and on the last), and the consumer waits on the first recorded entry at or + // after the one it needs (the copy stream is in order). STRATA_PREFILL_COPY_WAIT_DEDUPE=1 skips the copy + // stream's wait on a slot's release event when the previous slot was released by the same event (one flush). + // The same copies into the same slots: the same bytes. + static const int copy_event_every = [] { + const char* v = std::getenv("STRATA_PREFILL_COPY_EVENT_EVERY"); + return strata::prefill::copy_event_every_from(v ? std::atoi(v) : 1); + }(); + static const bool copy_wait_dedupe = [] { + const char* v = std::getenv("STRATA_PREFILL_COPY_WAIT_DEDUPE"); + return v != nullptr && std::atoi(v) != 0; + }(); + const bool sparse_copied = threaded_issue && copy_event_every > 1; + if (threaded_issue && (sparse_copied || copy_wait_dedupe)) { + static bool said = false; + if (!said) { + said = true; + std::fprintf(stderr, "strata: prompt copies: a copied event every %d streamed experts " + "(STRATA_PREFILL_COPY_EVENT_EVERY), %s (STRATA_PREFILL_COPY_WAIT_DEDUPE)\n", + copy_event_every, copy_wait_dedupe ? "one wait per release event" : "a wait per slot"); + } + } + std::vector> rec_of(sparse_copied ? (size_t) m.ring : 0); // the entry a slot's event marks + for (auto& r : rec_of) r.store(-1, std::memory_order_relaxed); + std::atomic a_rec{0}; // 1 + the last entry whose copied event is recorded + int64_t iss_waits = 0, iss_dedup = 0; if (threaded_issue) { issuer = std::thread([&] { strata::platform::name_this_thread("strata-issue"); strata::aux_cpus::pin_current_thread(); const core::OnDevice od(m.device); + int64_t last_rec = -1; // sparse_copied: the last entry whose copied event is recorded + int prev_rel = -1; // dedupe: the release event the copy stream waited on for the previous entry + auto record = [&](size_t i) { + cudaEventRecord(m.copied[i % (size_t) m.ring], m.copy); + rec_of[i % (size_t) m.ring].store((int64_t) i, std::memory_order_release); + a_rec.store(i + 1, std::memory_order_release); + last_rec = (int64_t) i; + }; + // before the issuer waits: what it issued is covered, so no consumer waits on an entry with no event + auto cover = [&](size_t idx) { if (sparse_copied && idx > 0 && last_rec < (int64_t) idx - 1) record(idx - 1); }; for (size_t idx = 0; idx < seq.size(); ++idx) { while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) { + cover(idx); if (a_stop.load(std::memory_order_acquire)) return; std::this_thread::yield(); } @@ -3219,16 +3261,31 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const int sl = (int) (idx % (size_t) m.ring); const auto th = Clock::now(); const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0); + if (m.stage_live[sl]) { + // from the second round on, both slots were released in this walk: the same event means the same + // flush, and the wait for the previous slot already covers this one + const int rel = m.used_of[sl]; + if (copy_wait_dedupe && idx >= (size_t) m.ring && rel == prev_rel) { + ++iss_dedup; + } else { + cudaStreamWaitEvent(m.copy, m.used[rel], 0); + ++iss_waits; + } + prev_rel = rel; + } else { + prev_rel = -1; + } if (en.job < 0) { cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); ++iss_dma; } else { + cover(idx); // the stager may make the issuer wait const uint8_t* hb = m.stager->wait(en.job); cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy); m.stager->issued_one(en.job, m.copy); } - cudaEventRecord(m.copied[sl], m.copy); + if (!sparse_copied) cudaEventRecord(m.copied[sl], m.copy); + else if (strata::prefill::copy_event_due(idx, seq.size(), copy_event_every)) record(idx); m.stage_live[sl] = true; iss_ms += ms_since(th); ++iss_streamed; @@ -3243,6 +3300,22 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (!threaded_issue) return; while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield(); }; + // the compute stream waits for entry k's copy: on its slot's event (`slot`, as before this switch existed), or + // (sparse_copied) on the first recorded entry at or after it. That event's slot cannot be re-recorded before k + // is given back (the issuer stays a ring ahead). + auto wait_copied = [&](size_t k, size_t slot) { + if (!sparse_copied) { + cudaStreamWaitEvent(m.cs, m.copied[slot], 0); + return; + } + while (a_rec.load(std::memory_order_acquire) <= k) std::this_thread::yield(); + const size_t hi = a_rec.load(std::memory_order_acquire); + // (hi - 1 is always recorded, so the last entry is only the fallback that covers k all the same) + const size_t r = strata::prefill::copy_event_entry(k, hi, [&](size_t e) { + return rec_of[e % (size_t) m.ring].load(std::memory_order_acquire) == (int64_t) e; + }); + cudaStreamWaitEvent(m.cs, m.copied[r % (size_t) m.ring], 0); + }; auto give_back = [&](size_t upto) { if (threaded_issue) a_consumed.store(upto, std::memory_order_release); else issue_until(upto + (size_t) m.ring); @@ -3913,7 +3986,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // one copy stream, in order: the batch's last blob covers the others pt.mark(kPfWaitCopy, cs); wait_issued(k - 1); - cudaStreamWaitEvent(m.cs, m.copied[(k - 1) % (size_t) m.ring], 0); + wait_copied(k - 1, (k - 1) % (size_t) m.ring); } pt.mark(kPfGemmGU, cs); if (fused_nat) { @@ -4699,7 +4772,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. mmq::GatherGroup gg; int gg_slots[MMQ_GROUP]; + size_t gg_ents[MMQ_GROUP]; // the streamed walk: their entries (wait_copied) int gg_nslots = 0; // ring slots gathered by the next flush + size_t cur_entry = 0; // the streamed walk: the entry compute() is given // STRATA_MMQ_DIRECT=1: a resident expert with guard room in its slot is not gathered - the // group's pointer tables give MMQ each expert's own address (group position q), the others are // gathered at compact positions c = 0..ns-1 of the group buffers, as before (same bytes) @@ -4714,7 +4789,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const auto& f = lay.fmt[(size_t) l]; if (gg_nslots > 0) { // the copies land in order: the last one covers the others pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[gg_slots[gg_nslots - 1]], 0); + wait_copied(gg_ents[gg_nslots - 1], (size_t) gg_slots[gg_nslots - 1]); pt.mark(kPfDequant, cs); } // NVFP4: each expert's scales go next to its group slot in the same launch @@ -4765,7 +4840,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (gg_now) { gg.blob[c] = blob_dev; gg.n = c + 1; - if (slot >= 0) gg_slots[gg_nslots++] = slot; + if (slot >= 0) { gg_ents[gg_nslots] = cur_entry; gg_slots[gg_nslots++] = slot; } } else { mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, mmq_db, m.grp_gu + (size_t) c * mmq_gub, @@ -4782,7 +4857,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (gg_now) { gg.blob[q] = blob_dev; gg.n = (int) q + 1; - if (slot >= 0) gg_slots[gg_nslots++] = slot; + if (slot >= 0) { gg_ents[gg_nslots] = cur_entry; gg_slots[gg_nslots++] = slot; } if (!last_of_group) return true; flush(MMQ_TAIL); gg = mmq::GatherGroup{}; @@ -4946,8 +5021,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri wait_issued(k); if (!group_gather) { pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[sl], 0); + wait_copied(k, (size_t) sl); } + cur_entry = k; if (!compute(j, m.stage_dev[sl], sl, -1)) return false; consumed = ++k; if (!group_gather || gg_nslots == 0) give_back(consumed); // its group was gathered @@ -5106,6 +5182,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri stats_.ms_experts_host += iss_ms; stats_.experts_streamed += iss_streamed; stats_.experts_dma += iss_dma; + if (copy_wait_dedupe && pt.on) + std::fprintf(stderr, "strata prefill copies: %lld slot waits, %lld skipped as the same release event\n", + (long long) iss_waits, (long long) iss_dedup); } stats_.tokens += T; core::progress_at("reading the prompt (batched): finishing the chunk from token", p0); From 092c7d1ef45db1deb6a668de7801ed5715c8decd Mon Sep 17 00:00:00 2001 From: i-Vladimir-i <291339861+i-Vladimir-i@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:51:44 +0100 Subject: [PATCH 097/177] serve: return 503 when the elastic image encoder cannot start (#2435) When the elastic image encoder failed to restart, its exception left request preparation and the client got a closed connection. It now goes through the EngineDied path: HTTP 503 with the reason, a later picture tries again, text requests and a later good start are unaffected. An idle encoder stop is logged even when the cache shrink was refused, and a layer split gets a line saying its encoder VRAM has to be kept free with --vram-reserve-mib. Ported from PR #2435 by i-Vladimir-i with its tests (chat, messages and responses, streamed and not, plus a real encoder that exits with code 71 on Linux) and the docs/VRAM_ELASTIC.md text. --- docs/VRAM_ELASTIC.md | 4 +- serve/server.py | 20 ++++- serve/test_vision_elastic.py | 25 +++++- serve/test_vision_elastic_http.py | 140 ++++++++++++++++++++++++++++++ 4 files changed, 183 insertions(+), 6 deletions(-) create mode 100644 serve/test_vision_elastic_http.py diff --git a/docs/VRAM_ELASTIC.md b/docs/VRAM_ELASTIC.md index 64ea795e..94945094 100644 --- a/docs/VRAM_ELASTIC.md +++ b/docs/VRAM_ELASTIC.md @@ -113,7 +113,9 @@ and starts the encoder with the model, as before) the GPU encoder is not started - **A picture's turn** (the same FIFO turn an encode always takes): if the encoder is not running, the engine's `VRAM` command first keeps `"elastic_mib"` (default 2048) free on top of the reserve - the last `POST /v1/vram`, or 0 when none was made - and then the encoder starts. If the cache cannot shrink (the resident low-RAM mode, an engine - without `--vram-elastic`) it starts anyway, as a non-elastic encoder would, and the log says why. + without `--vram-elastic`, a layer split) it starts anyway, as a non-elastic encoder would, and the log says why; on a + layer split the server says at start that the encoder's VRAM has to be kept free with `--vram-reserve-mib`. An + encoder that fails to start (out of VRAM) ends the request with a `503`; the next picture tries again. - **Idle** for `"elastic_idle_s"` (default 120) without a picture: a thread stops the encoder between requests and sends `VRAM` with that reserve again, so the cache grows back to the size it had (0, not the start's reserve: that would leave it a segment or more smaller). diff --git a/serve/server.py b/serve/server.py index 8a51e2e9..adf9f552 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4202,7 +4202,10 @@ class Service: if self.vision_held: time.sleep(0.2) # the driver's free-VRAM counter shows the cache's release a moment later free0, t0 = self.free_vram_mib(), time.time() - v.restart() + try: + v.restart() + except Exception as e: # a 503 as for a non-elastic encoder at a load, not a dropped connection + raise EngineDied(f"the image encoder failed to start: {e}") from e free1 = self.free_vram_mib() took = f", {free0 - free1} MiB of VRAM" if free0 is not None and free1 is not None else "" print(f"[strata] images: the image encoder started in {time.time() - t0:.1f} s{took}", flush=True) @@ -4220,11 +4223,14 @@ class Service: return "busy" try: v.unload() + back = "" if self.vision_held and hasattr(self.engine, "vram") and self.loaded(): out = self.engine.vram(self._engine_reserve()) - print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture; " - f"the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " - f"{out.get('expert_cache_full_mib')} MiB)", flush=True) + back = (f"; the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " + f"{out.get('expert_cache_full_mib')} MiB)") + # also when the cache never made room (a layer split, an engine without --vram-elastic): the stop happened + print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture{back}", + flush=True) self.vision_held = False return "down" finally: @@ -8377,6 +8383,12 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the ' "encoder its VRAM): the encoder starts with the model instead", flush=True) vcfg["elastic"] = False + elif vcfg.get("elastic") is True and layer_split_of(cfg): + # the engine turns --vram-elastic off on a layer split (a cache per GPU): the encoder still starts + # with the first picture and stops when idle, but its VRAM has to be free already + print('[strata] images: on a layer split the expert cache cannot make room for the image encoder (the ' + 'engine turns --vram-elastic off); keep its VRAM free with "--vram-reserve-mib" on the ' + "encoder's GPU, or the first picture may not get it", flush=True) vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=vision_env(cfg, env), lazy=lazy) print("model unloaded; the first request loads it ..." if lazy else diff --git a/serve/test_vision_elastic.py b/serve/test_vision_elastic.py index b8516b1a..fa16426c 100644 --- a/serve/test_vision_elastic.py +++ b/serve/test_vision_elastic.py @@ -2,13 +2,15 @@ expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts it on its own.""" +import contextlib +import io import tempfile import time import unittest from pathlib import Path from serve.frontend import ChatTemplate -from serve.server import ByteTokenizer, Service, Vision +from serve.server import ByteTokenizer, EngineDied, Service, Vision from serve.test_vram import VramEngine ROOT = Path(__file__).resolve().parents[1] @@ -99,6 +101,27 @@ class Elastic(unittest.TestCase): self.assertEqual(self.svc._vision_idle_down(), "down") self.assertEqual(self.engine.calls, [2048]) # the refused shrink only: nothing to give back + def test_an_encoder_that_fails_to_start_is_a_503_not_a_dropped_connection(self): + def fail(): + raise RuntimeError("the vision encoder did not start: cudaMalloc failed: out of memory") + self.vision.restart = fail + with self.assertRaises(EngineDied) as e: # the handlers answer EngineDied with a 503 + self.picture() + self.assertIn("the image encoder failed to start", str(e.exception)) + self.svc.last_image_at = 0 + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertEqual(self.engine.calls, [2048, 0]) # the share made for it goes back + + def test_the_stop_is_logged_when_the_cache_never_made_room(self): + self.engine.elastic = False # a layer split: the engine refuses --vram-elastic + self.picture() + self.svc.last_image_at = 0 + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertIn("the image encoder stopped after 60 s without a picture", out.getvalue()) + self.assertNotIn("expert cache", out.getvalue()) + def test_the_load_never_starts_an_elastic_encoder(self): self.assertFalse(self.svc._vision_down()) self.svc.vision = ElasticVision(tempfile.mkdtemp(), elastic=False) diff --git a/serve/test_vision_elastic_http.py b/serve/test_vision_elastic_http.py new file mode 100644 index 00000000..78b6df73 --- /dev/null +++ b/serve/test_vision_elastic_http.py @@ -0,0 +1,140 @@ +"""Elastic encoder failures reach clients, can be retried, and do not prevent recovery.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest +import urllib.error +import urllib.request + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, Service, Vision, serve +from serve.test_vision_elastic import ElasticVision +from serve.test_vram import VramEngine + + +class EncoderFailureHTTP(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + tok = ByteTokenizer() + self.engine = VramEngine(tok) + self.engine.loaded = True + self.engine.elastic = False # as on a layer split: the cache cannot make room + self.vision = ElasticVision(tmp.name) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'), + vision=self.vision) + httpd = serve(self.svc, port=0) + self.addCleanup(httpd.server_close) + self.addCleanup(httpd.shutdown) + self.addCleanup(self.drop_embeddings) + self.base = f'http://127.0.0.1:{httpd.server_address[1]}' + self.attempts = 0 + self.original_restart = self.vision.restart + + def drop_embeddings(self): + path = getattr(getattr(self.svc, 'embeddings', None), 'path', None) + if path is not None: + path.unlink(missing_ok=True) + + def post(self, path, body): + req = urllib.request.Request(self.base + path, json.dumps(body).encode(), + {'Content-Type': 'application/json'}) + return urllib.request.urlopen(req, timeout=10) + + @staticmethod + def chat_picture(): + return {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,eA=='}}]}]} + + def fail_with(self, error_type): + def fail(): + self.attempts += 1 + raise error_type('synthetic encoder startup failure') + self.vision.restart = fail + + def assert_503(self, path, body): + with self.assertRaises(urllib.error.HTTPError) as got: + self.post(path, body) + with got.exception as response: + self.assertEqual(response.code, 503) + payload = json.load(response) + self.assertIn('synthetic encoder startup failure', payload['error']['message']) + + def test_start_failure_and_retry_on_all_three_apis(self): + cases = [ + ('/v1/chat/completions', self.chat_picture()), + ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}), + ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [ + {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}), + ] + for error_type in (RuntimeError, OSError): + self.fail_with(error_type) + for path, body in cases: + for stream in (False, True): + for retry in range(2): + with self.subTest(error=error_type.__name__, path=path, stream=stream, retry=retry): + before = self.attempts + self.assert_503(path, {**body, 'stream': stream}) + self.assertEqual(self.attempts, before + 1) + + def test_text_requests_and_image_recovery_after_a_failed_start(self): + self.fail_with(RuntimeError) + text = {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]} + with self.post('/v1/chat/completions', text) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.attempts, 0) + self.assert_503('/v1/chat/completions', self.chat_picture()) + self.assertEqual(self.attempts, 1) + self.vision.restart = self.original_restart + with self.post('/v1/chat/completions', self.chat_picture()) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.vision.starts, 1) + with self.post('/v1/chat/completions', text) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.vision.starts, 1) + + @unittest.skipUnless(sys.platform.startswith('linux'), 'child reaping is checked through /proc') + def test_real_encoder_failure_retries_and_reaps_each_child(self): + with tempfile.TemporaryDirectory() as directory: + started = Path(directory) / 'started-pids' + executable = Path(directory) / 'encoder-exits' + executable.write_text( + '#!' + sys.executable + '\nimport os\n' + 'with open(' + repr(str(started)) + ', "a") as output:\n' + ' output.write(str(os.getpid()) + "\\n")\n' + 'raise SystemExit(71)\n') + executable.chmod(0o700) + vision = Vision({'exe': str(executable), 'mmproj': 'unused', 'model': 'unused', + 'elastic': True}, lazy=True) + self.addCleanup(vision.unload) + self.svc.vision = vision + cases = [ + ('/v1/chat/completions', self.chat_picture()), + ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}), + ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [ + {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}), + ] + for path, body in cases: + for stream in (False, True): + for retry in range(2): + with self.subTest(path=path, stream=stream, retry=retry): + previous = started.read_text().splitlines() if started.exists() else [] + with self.assertRaises(urllib.error.HTTPError) as got: + self.post(path, {**body, 'stream': stream}) + with got.exception as response: + self.assertEqual(response.code, 503) + self.assertIn('the image encoder failed to start', json.load(response)['error']['message']) + children = started.read_text().splitlines() + self.assertEqual(len(children), len(previous) + 1) + self.assertFalse(vision.alive()) + self.assertFalse(Path('/proc', children[-1]).exists()) + + +if __name__ == '__main__': + unittest.main() From bdecbffc6bef0e9399aeee39b9ae2ddc6b85f164 Mon Sep 17 00:00:00 2001 From: rodi4eg <160655730+rodi4eg@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:46:20 +0100 Subject: [PATCH 098/177] native_mmvq: sm_89 (Ada) MMVQ-IL table from the cells two cards agree on (#3453) Problem: an Ada card took the shared MMVQ-IL table, which has no Q3_K row, so Q3_K shapes ran the plain kernel and the other types used a table measured on sm_86 and sm_120. Change: kIlRows_89 (2-4 columns) and kIl1Rows_89 (one column) are registered for compute capability 8.9. The 2-4 column table keeps only the cells where the RTX 4070 run (rodi4eg) and the RTX 4080 run (kzhv) gave the same rows count and sets the rest to 0, the plain kernel; the 4070 and 4080 disagree in 13 of 15 cells of the unmerged tables. The one-column row is Q3_K only, which both cards gave. The issue's 5-8 column table is not taken: the 4080's changed in 10-14 of 20 entries between two runs of the same card, so there is no kIlRows58_89. The bench output files of the PR are not ported. Every choice in a table is bitwise native_mmvq's output (kernel row split only), so answers do not change; this is speed only. No end-to-end decode change was seen on a 4090 or a 4080 in the issue, so the gain is the microbenchmark's. This does change which kernel an sm_89 card runs by default, so the model gate (identity on sm_89) is written down in phaseA-tests/gh027/gates/3453-sm89-il.sh. Tests: mmvq_il_parity (registered in CMakeLists.txt) now checks sm_89's table against the two source runs (check_tables) instead of expecting the shared table, and still checks bitwise parity of every case and rows choice on the GPU it runs on (sm_86 on z440). docs/MMVQ_IL_TABLE.md updated. Not covered: no sm_89 card here, so the table speed is the contributors' numbers, not ours. Co-authored-by: kzhv <22279674+kzhv@users.noreply.github.com> --- docs/MMVQ_IL_TABLE.md | 9 +++++---- src/kernels/cuda/native_mmvq.cu | 24 +++++++++++++++++++++--- src/kernels/mmvq_il_parity.cpp | 33 +++++++++++++++++++++++++-------- 3 files changed, 51 insertions(+), 15 deletions(-) diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index 1f3bae10..c4929625 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -15,18 +15,19 @@ Which table a card gets: |---|---| | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | -| sm_89 (Ada) and every other sm_80+ card | `kIlRowsShared` too. Nobody has measured sm_89 yet (we have no such card). | +| sm_89 (Ada) | `kIlRows_89`: the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card, so it is not taken until it reproduces. No end-to-end decode change was seen on a 4090 or a 4080 (issue 3453), so this is a microbenchmark gain only. | +| every other sm_80+ card | `kIlRowsShared` | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | -## Measuring sm_89 (or any other card) +## Measuring a card that has no table yet 1. Build with tests: `cmake -S . -B build -DSTRATA_BUILD_TESTS=ON` and `cmake --build build --target mmvq_il_parity`. 2. Close everything else on the GPU, then run `build/mmvq_il_parity --bench --emit-table` (a few minutes). It first checks bit-for-bit parity of every shape and every rows choice (it must end with `mmvq_il_parity: OK`), prints a `BENCH` line per shape and token count, and last a ready-to-paste block, one line per type. -3. Post the whole output on the issue. A maintainer pastes the block as `kIlRows_89[]` and adds - `{89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)}` to `kIlArch`. +3. Post the whole output on the issue. A maintainer pastes the block as `kIlRows_[]` and adds + `{, kIlRows_, sizeof(kIlRows_) / sizeof(IlRows)}` to `kIlArch`. 4. To try a table without rebuilding, set `STRATA_MMVQ_IL_ROWS="type:ncols:r0,r1,r2,r3,r4;..."`, for example `STRATA_MMVQ_IL_ROWS="23:3:0,0,2,4,4;12:2:0,1,1,1,1"` (the five numbers are the row classes below 2048, 4096, 8192, 12288 and above; each is 0, 1, 2 or 4). Then A/B the decode: same flags, `STRATA_MMVQ_IL_ROWS` set or unset, 10 diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index afaec6cb..c4b11942 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -3037,10 +3037,9 @@ constexpr IlRows kIlRowsShared[] = { // sm_86 + sm_120, and the fallback for e {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}}, // Q6_K }; // Per-architecture tables (P10). A card whose compute capability (major * 10 + minor) is listed here uses its own table; -// every other sm_80+ card uses kIlRowsShared. sm_89 (Ada) has none yet: nobody measured it (we have no such card), so -// it takes the shared table, which sits between the measured sm_86 and sm_120. To add one, run +// every other sm_80+ card uses kIlRowsShared. sm_89 (Ada) has its own table (kIlRows_89, below). To add one, run // `mmvq_il_parity --bench --emit-table` on the card (docs/MMVQ_IL_TABLE.md), paste the printed block as a -// `constexpr IlRows kIlRows_89[]` and add {89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)} below. Each choice +// `constexpr IlRows kIlRows_[]` and add {, kIlRows_, sizeof(kIlRows_) / sizeof(IlRows)} below. Each choice // is bitwise the same output, so a table is only speed. Without a rebuild: STRATA_MMVQ_IL_ROWS (see il_env_rows). // Volta (sm_70): read off mmvq_il_parity --bench on a V100-SXM2-32GB (two runs, mean), the same rule - per cell the // rows count whose every measured shape takes at least 3% off native_mmvq's time (e.g. the Q5_K head at 3 columns @@ -3091,6 +3090,19 @@ constexpr IlRows kIlRows_120[] = { {14, {{0, 0, 2, 1, 1}, {0, 0, 4, 2, 4}, {0, 2, 2, 2, 2}}}, // Q6_K {11, {{0, 1, 2, 2, 2}, {0, 2, 4, 2, 2}, {0, 2, 2, 2, 2}}}, // Q3_K }; +// Ada (sm_89): the cells where two cards agree. mmvq_il_parity --bench --emit-table was run on an RTX 4070 (46 SMs, +// #3453) and on an RTX 4080 (48 SMs, same issue); a cell is kept only where both runs give the same rows count, else 0 +// (the plain kernel), so a card that disagrees never gets a split it did not measure. The 5-8 column table of that +// issue is not taken: the 4080 reproduced the 2-4 column table byte for byte in four runs, and the 5-8 column table +// changed in 10-14 of 20 entries between runs. Bitwise equal to native_mmvq, so the table is only speed. +// mmvq_il_parity's check_tables rebuilds the table from the two source runs and compares. +constexpr IlRows kIlRows_89[] = { + {23, {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}}, // IQ4_XS + {12, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}}, // Q4_K + {13, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}, {0, 0, 1, 0, 0}}}, // Q5_K + {14, {{0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}}}, // Q6_K + {11, {{0, 0, 1, 0, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}, // Q3_K +}; // Turing (sm_75): read off mmvq_il_parity --bench --emit-table on an RTX 2080 Ti 22 GB (SM 1650 MHz), the same 3% rule. // The plain multi-column kernels are bound by dp4a throughput on Turing from 2 columns on (IQ4_XS 2560x10240 at 4 // columns 81.1 -> 37.4 us, the Q5_K head 1671 -> 1045 us); bitwise equal to native_mmvq. No one-column table here: @@ -3124,6 +3136,10 @@ struct Il1Rows { int type; uint8_t r[5]; }; constexpr Il1Rows kIl1Rows_86[] = { {11, {0, 1, 1, 1, 1}}, // Q3_K: 2560x10240 60 -> 43 us, 6144x2560 30 -> 26 us on the A4000 }; +// Ada (sm_89): the RTX 4070 and the RTX 4080 runs gave the same one-column row (only Q3_K takes the interleaved kernel) +constexpr Il1Rows kIl1Rows_89[] = { + {11, {0, 0, 1, 1, 1}}, // Q3_K +}; // Tesla P40 (sm_61), the same three runs: IQ4_XS 2560x10240 102 -> 58 us, the Q5_K head 1754 -> 1507 us constexpr Il1Rows kIl1Rows_61[] = { {23, {2, 2, 4, 4, 4}}, // IQ4_XS @@ -3134,6 +3150,7 @@ struct Il1Arch { int cc; const Il1Rows* t; size_t n; }; constexpr Il1Arch kIl1Arch[] = { {61, kIl1Rows_61, sizeof(kIl1Rows_61) / sizeof(Il1Rows)}, {86, kIl1Rows_86, sizeof(kIl1Rows_86) / sizeof(Il1Rows)}, + {89, kIl1Rows_89, sizeof(kIl1Rows_89) / sizeof(Il1Rows)}, // Ada: the RTX 4070 and 4080 agree }; bool il_env_on(const char* name) { const char* v = std::getenv(name); @@ -3148,6 +3165,7 @@ constexpr IlArch kIlArch[] = { {75, kIlRows_75, sizeof(kIlRows_75) / sizeof(IlRows)}, // Turing: measured on an RTX 2080 Ti {70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)}, // Volta: PR 1401, measured on a V100-SXM2 {86, kIlRows_86, sizeof(kIlRows_86) / sizeof(IlRows)}, // 143-dense: RTX A4000 with the real shapes (Q3_K added) + {89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)}, // Ada: the cells where an RTX 4070 and an RTX 4080 agree // 147-verify: RTX PRO 5000 Blackwell (110 SMs). Only 12.0 cards with 80+ SMs (il_cc's 1201) take it: the shared table // was measured on an RTX 5070 (48 SMs) and stays that card's {1201, kIlRows_120, sizeof(kIlRows_120) / sizeof(IlRows)}, diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 9e78015a..05225d9f 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -260,21 +260,33 @@ void emit_table() { } // the per-architecture lookup, no GPU needed for its answers +// The two Ada runs sm_89's table was merged from (mmvq_il_parity --bench --emit-table, issue 3453): by type IQ4_XS, Q4_K, +// Q5_K, Q6_K, Q3_K, then 2/3/4 columns, then the five n_out classes. +const int kAda4070[5][3][5] = { + {{0, 0, 0, 1, 0}, {1, 1, 1, 1, 1}, {2, 2, 1, 1, 1}}, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}}, + {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {1, 2, 1, 2, 2}}, {{0, 0, 0, 0, 0}, {0, 0, 1, 2, 2}, {0, 1, 4, 1, 1}}, + {{1, 1, 1, 2, 1}, {1, 1, 1, 1, 1}, {2, 1, 1, 1, 1}}}; +const int kAda4080[5][3][5] = { + {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}}, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}, + {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}, {0, 0, 1, 1, 1}}, {{0, 0, 0, 1, 0}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}, + {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}; int check_tables() { int bad = 0; for (int type : {23, 12, 13, 14, 11}) for (int nc = 2; nc <= 4; ++nc) for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) { const int a = native_mmvq_il_rows_for(86, type, nc, n_out); - // sm_89 has no table of its own: it answers the shared table (what sm_86 answered before its own - // 143-dense table, which differs only in Q3_K, a type the shared table does not use); sm_120 has its own - // since 147-verify - const int b = native_mmvq_il_rows_for(89, type, nc, n_out); - if ((type != 11 && b != a) || (type == 11 && b != 0)) { - ++bad; - std::printf("FAIL table: sm_89 differs from sm_86 at type %d ncols %d n_out %d\n", type, nc, n_out); - } if (a != 0 && a != 1 && a != 2 && a != 4) { ++bad; std::printf("FAIL table: rows %d\n", a); } + // sm_89 (#3453): the cells where an RTX 4070 and an RTX 4080 gave the same rows count, else 0 + const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; + const int ti = type == 23 ? 0 : type == 12 ? 1 : type == 13 ? 2 : type == 14 ? 3 : 4; + const int b = native_mmvq_il_rows_for(89, type, nc, n_out); + const int want = kAda4070[ti][nc - 2][cls] == kAda4080[ti][nc - 2][cls] ? kAda4070[ti][nc - 2][cls] : 0; + if (b != want) { + ++bad; + std::printf("FAIL table: sm_89 is %d, the 4070/4080 agreement says %d at type %d ncols %d n_out %d\n", b, want, + type, nc, n_out); + } } // Volta has its own table (PR 1401): Q6_K at 2 columns, 2560 rows -> 1 row a warp; the Ampere table says 0 there if (native_mmvq_il_rows_for(70, 14, 2, 2560) != 1 || native_mmvq_il_rows_for(86, 14, 2, 2560) != 0) { @@ -286,6 +298,11 @@ int check_tables() { ++bad; std::printf("FAIL table: the sm_60 table is not the P100's\n"); } + // sm_89 one column: only Q3_K (the 4070 and the 4080 agree); wider than 4: the plain kernels + if (native_mmvq_il_rows_for(89, 11, 1, 2560) != 0 || native_mmvq_il_rows_for(89, 11, 1, 6144) != 1 || native_mmvq_il_rows_for(89, 12, 1, 6144) != 0) { + ++bad; + std::printf("FAIL table: the sm_89 one-column row is not Q3_K only\n"); + } if (native_mmvq_il_rows_for(89, 99, 2, 2560) != 0 || native_mmvq_il_rows_for(89, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(86, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(120, 12, 9, 2560) != 0) { ++bad; From 11237f831f3cc4691369186d3c51e90ac4b59a6d Mon Sep 17 00:00:00 2001 From: Jakub Luwierski <91573380+j-luwierski@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:54:34 +0100 Subject: [PATCH 099/177] serve: Chat Completions tool results keep the order of the calls they answer (#3395) When one assistant message made several tool calls and the client returned the results in another order, the call ids were dropped before the prompt was rendered, so the model saw anonymous results in the wrong order. The ids are now kept while the request is normalized; a run of results is reordered to the call order only when the call ids and result ids are non-empty unique strings with matching sets. Anything else (missing, duplicate, unknown or incomplete ids) keeps the received order, and the ids never reach the template. Ported from PR #3395 by j-luwierski with its seven tests (serve/test_chat_tool_results.py); the hunk was merged by hand beside require_messages. --- serve/frontend.py | 34 +++++++- serve/test_chat_tool_results.py | 133 ++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 serve/test_chat_tool_results.py diff --git a/serve/frontend.py b/serve/frontend.py index a70494f0..5911054e 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -546,6 +546,34 @@ def require_messages(messages: list) -> None: raise ValueError("messages must be a non-empty list: send at least one message") +def _order_chat_tool_results(messages: list[dict]) -> None: + """The template pairs results by position, so restore call order while IDs are still available. + + Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their + received order. IDs are private to this conversion and never reach the template. + """ + i = 0 + while i < len(messages): + if messages[i]["role"] != "tool": + i += 1 + continue + j = i + 1 + while j < len(messages) and messages[j]["role"] == "tool": + j += 1 + prev = messages[i - 1] if i else {} + calls = [c.get("_call_id") for c in prev.get("tool_calls") or []] if prev.get("role") == "assistant" else [] + results = [m.get("_call_id") for m in messages[i:j]] + if len(calls) == len(results) and all(isinstance(cid, str) and cid for cid in calls + results): + if len(set(calls)) == len(calls) and len(set(results)) == len(results) and set(calls) == set(results): + rank = {cid: n for n, cid in enumerate(calls)} + messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]]) + i = j + for message in messages: + message.pop("_call_id", None) + for call in message.get("tool_calls") or []: + call.pop("_call_id", None) + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -558,6 +586,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: content = _check_parts(m.get("content"), f"messages[{i}].content", TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS) out = {"role": role, "content": _parts_of(content) if images else _text_of(content)} + if role == "tool": + out["_call_id"] = m.get("tool_call_id") if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): @@ -566,9 +596,11 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: fn = c.get("function", c) if not isinstance(fn, dict): raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") - calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}}) + calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}, + "_call_id": c.get("id")}) out["tool_calls"] = calls messages.append(out) + _order_chat_tool_results(messages) tools = [t.get("function", t) if t.get("type") == "function" else t for t in _tool_list(req.get("tools"), "function")] or None kwargs = {} diff --git a/serve/test_chat_tool_results.py b/serve/test_chat_tool_results.py new file mode 100644 index 00000000..9c99b2ee --- /dev/null +++ b/serve/test_chat_tool_results.py @@ -0,0 +1,133 @@ +"""Chat Completions tool results must follow call IDs before the template drops them.""" +import copy +import http.client +import json +from pathlib import Path +import unittest + +from serve.frontend import ChatTemplate, openai_to_messages +from serve.server import ByteTokenizer, MockEngine, Service, serve + + +TEMPLATE = ChatTemplate(Path(__file__).with_name("chat_template.jinja")) + + +def history(): + return [ + {"role": "user", "content": "Read a.txt and b.txt."}, + {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_a", "type": "function", "function": { + "name": "read_file", "arguments": '{"path":"a.txt"}'}}, + {"id": "call_b", "type": "function", "function": { + "name": "read_file", "arguments": '{"path":"b.txt"}'}}]}, + {"role": "tool", "tool_call_id": "call_b", "content": "RESULT_FROM_B"}, + {"role": "tool", "tool_call_id": "call_a", "content": "RESULT_FROM_A"}, + ] + + +def normalized(messages): + return openai_to_messages({"messages": messages})[0] + + +def rendered(messages): + return TEMPLATE.render(normalized(messages), enable_thinking=False) + + +class ChatToolResults(unittest.TestCase): + def test_reversed_results_of_the_same_function_follow_call_ids(self): + raw = history() + before = copy.deepcopy(raw) + ordered = raw[:2] + list(reversed(raw[2:])) + self.assertEqual(rendered(raw), rendered(ordered)) + self.assertLess(rendered(raw).index("RESULT_FROM_A"), rendered(raw).index("RESULT_FROM_B")) + self.assertEqual(raw, before) + messages = normalized(raw) + self.assertEqual([m["content"] for m in messages[2:]], ["RESULT_FROM_A", "RESULT_FROM_B"]) + self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:])) + self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"])) + + def test_already_ordered_and_legacy_prompts_are_identical(self): + ordered = history() + ordered[2:] = reversed(ordered[2:]) + legacy = copy.deepcopy(ordered) + for call in legacy[1]["tool_calls"]: + call.pop("id") + for result in legacy[2:]: + result.pop("tool_call_id") + self.assertEqual(normalized(ordered), normalized(legacy)) + self.assertEqual(rendered(ordered), rendered(legacy)) + + def test_ambiguous_or_incomplete_ids_preserve_received_order(self): + for case in ("missing_call", "missing_result", "duplicate_call", "duplicate_result", "unknown", + "list_call", "list_result", "empty_call", "empty_result", "partial"): + raw = history() + if case == "missing_call": + raw[1]["tool_calls"][0].pop("id") + elif case == "missing_result": + raw[2].pop("tool_call_id") + elif case == "duplicate_call": + raw[1]["tool_calls"][1]["id"] = "call_a" + elif case == "duplicate_result": + raw[3]["tool_call_id"] = "call_b" + elif case == "unknown": + raw[2]["tool_call_id"] = "unknown" + elif case == "list_call": + raw[1]["tool_calls"][0]["id"] = [] + elif case == "list_result": + raw[2]["tool_call_id"] = [] + elif case == "empty_call": + raw[1]["tool_calls"][0]["id"] = "" + elif case == "empty_result": + raw[2]["tool_call_id"] = "" + else: + raw.pop() + with self.subTest(case=case): + self.assertEqual([m["content"] for m in normalized(raw)[2:]], + [m["content"] for m in raw[2:]]) + + def test_each_tool_run_is_scoped_to_its_assistant_turn(self): + raw = history() + history() + self.assertEqual([m["content"] for m in normalized(raw) if m["role"] == "tool"], + ["RESULT_FROM_A", "RESULT_FROM_B"] * 2) + raw = history() + raw.insert(2, {"role": "user", "content": "intervening message"}) + self.assertEqual([m["content"] for m in normalized(raw) if m["role"] == "tool"], + ["RESULT_FROM_B", "RESULT_FROM_A"]) + + def test_json_encoded_history_and_calls(self): + raw = history() + raw[1]["tool_calls"] = json.dumps(raw[1]["tool_calls"]) + self.assertEqual(normalized(json.dumps(raw)), normalized(history())) + + def test_multimodal_result_moves_with_its_call(self): + raw = history() + raw[2]["content"] = [{"type": "text", "text": "RESULT_FROM_B"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}] + messages = normalized(raw) + self.assertEqual(messages[2]["content"], "RESULT_FROM_A") + self.assertEqual(messages[3]["content"], [{"type": "text", "text": "RESULT_FROM_B"}, + {"type": "image", "source": "data:image/png;base64,AA=="}]) + + def test_http_engine_receives_the_ordered_prompt(self): + tok = ByteTokenizer() + engine = MockEngine(tok, "ok", max_context=4096) + service = Service(engine, tok, TEMPLATE) + httpd = serve(service, port=0) + connection = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=10) + try: + connection.request("POST", "/v1/chat/completions", json.dumps({ + "messages": history(), "max_tokens": 16, "reasoning_effort": "none"}), + {"Content-Type": "application/json"}) + response = connection.getresponse() + body = response.read() + self.assertEqual(response.status, 200, body) + prompt = tok.decode(engine.last_prompt) + self.assertLess(prompt.index("RESULT_FROM_A"), prompt.index("RESULT_FROM_B")) + finally: + connection.close() + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() From 409f2466ad2a589d8d9af711c960184e3f5de67f Mon Sep 17 00:00:00 2001 From: Keyan Hu <177766066+KeyanHu-git@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:55:57 +0100 Subject: [PATCH 100/177] tools/gguf_reader.py: bound the header reads and report malformed metadata as ValueError (#2288, #1919) A GGUF header with an unknown metadata type or an impossible length raised KeyError or OverflowError inside the reader, and setup, which expects a ValueError, printed a traceback instead of its diagnostic naming the broken shard. Strings, scalars, arrays and tensor dimensions now share one bounded read; counts are checked against the bytes left in the file before anything is constructed; type ids are checked before their values are decoded; nested arrays are reported as unsupported; general.alignment must be a positive multiple of 8. The file name is added once to the message. Ported from PR #2288 by KeyanHu-git with its tests (tools/test_gguf_reader_malformed.py). Checked against the old reader on the 18 GGUF v3 vocabulary files of the pinned llama.cpp: same metadata, tensors and data start. --- tools/gguf_reader.py | 86 +++++++++----- tools/test_gguf_reader_malformed.py | 176 ++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+), 27 deletions(-) create mode 100644 tools/test_gguf_reader_malformed.py diff --git a/tools/gguf_reader.py b/tools/gguf_reader.py index 4da9d2d2..de30d3b9 100644 --- a/tools/gguf_reader.py +++ b/tools/gguf_reader.py @@ -10,6 +10,7 @@ no ggml dependency)"). It parses the header only; tensor data is never read. from __future__ import annotations import dataclasses +import os import pathlib import struct from typing import Any @@ -77,6 +78,10 @@ class TensorInfo: return self.elements // block_elems * block_bytes +_META_FMT = {"u8": "B", "i8": "b", "u16": "H", "i16": "h", "u32": "I", "i32": "i", + "f32": "f", "bool": "?", "u64": "Q", "i64": "q", "f64": "d"} + + class GGUFFile: def __init__(self, path: pathlib.Path): self.path = pathlib.Path(path) @@ -85,55 +90,82 @@ class GGUFFile: self.version = 0 self.alignment = 32 with self.path.open("rb") as fh: - self._parse(fh) + self._size = os.fstat(fh.fileno()).st_size + self._pos = 0 + try: + self._parse(fh) + except ValueError as e: + raise ValueError(f"{self.path.name}: {e}") from None self.data_start = self._data_start # ------------------------------------------------------------------ internals + def _read(self, fh, n: int) -> bytes: + left = self._size - self._pos + if n < 0 or n > left: + raise ValueError(f"header ends early: {n:,} bytes needed at offset {self._pos:,}, {left:,} left") + raw = fh.read(n) + self._pos += len(raw) + if len(raw) != n: + raise ValueError(f"header ends early at offset {self._pos:,}") + return raw + + def _unpack(self, fh, fmt: str) -> tuple: + return struct.unpack(fmt, self._read(fh, struct.calcsize(fmt))) + + def _count(self, fh, count: int, min_bytes: int, what: str) -> int: + if count * min_bytes > self._size - self._pos: + raise ValueError(f"{count:,} {what} cannot fit in the {self._size - self._pos:,} bytes left") + return count + def _parse(self, fh) -> None: - magic = struct.unpack(" str: - (n,) = struct.unpack(" tuple[str, int | None]: + if t not in GGUF_META: + raise ValueError(f"unknown metadata value type {t}") + return GGUF_META[t] def _value(self, fh): - (t,) = struct.unpack(" dict[str, int]: diff --git a/tools/test_gguf_reader_malformed.py b/tools/test_gguf_reader_malformed.py new file mode 100644 index 00000000..98358f02 --- /dev/null +++ b/tools/test_gguf_reader_malformed.py @@ -0,0 +1,176 @@ +"""A malformed GGUF header is refused with a ValueError that names the file, never a KeyError, OverflowError +or struct.error (#1919). Tensor-size support and setup compatibility policy are unchanged. +Over minimal GGUF v3 files written here (no download, no model, no GPU). + + python -m unittest tools.test_gguf_reader_malformed +""" +from __future__ import annotations + +import contextlib +import io +import struct +import sys +import tempfile +import unittest +from unittest import mock +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) +import setup as S # noqa: E402 +from gguf_reader import GGUFFile # noqa: E402 + + +class Stop(Exception): + """setup.fail(), caught instead of exiting.""" + + +def gstr(s: bytes) -> bytes: + return struct.pack(" bytes: + return struct.pack(" bytes: + return gstr(name) + struct.pack(" bytes: + return b + bytes(-len(b) % 32 + data) + + +class MalformedHeader(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.path = Path(self.tmp.name) / "m-00001-of-00002.gguf" + + def tearDown(self): + self.tmp.cleanup() + + def refused(self, raw: bytes) -> str: + self.path.write_bytes(raw) + with self.assertRaises(ValueError) as cm: + GGUFFile(self.path) + self.assertIn(self.path.name, str(cm.exception)) + return str(cm.exception) + + def test_unknown_metadata_value_type(self): + self.refused(pad(header(0, gstr(b"k") + struct.pack(" Date: Mon, 26 Oct 2026 18:56:54 +0100 Subject: [PATCH 101/177] nvfp4 local pack: read the checkpoint with cached sequential reads, not a process-lifetime np.memmap (#3377, #3378) Checkpoint.raw mapped every shard for the life of the process. On Windows each faulted page of the ~64 GB of expert bytes is charged to the process working set, so the pack step looked like a 64 GB RAM demand and was killed by free-RAM watchers on a PC with a model loaded (nothing leaked: it all came back at once). raw() now reads the tensor's byte range into a fresh buffer through one cached file handle per shard; the pages go to the system file cache, which counts as available. The author measured the same bytes, 1.2x faster, flat working set, and a byte-identical pack. raw() is no longer thread-safe (this file uses no threads). Ported from PR #3378 by jerry78424 (the fix for his issue #3377) with its two tests; I ran the tests (13 pass); the full 102 GB pack was not run. --- tools/nvfp4_local_pack.py | 27 +++++++++++++++++----- tools/test_nvfp4_local_pack.py | 41 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/tools/nvfp4_local_pack.py b/tools/nvfp4_local_pack.py index 03f5c884..a9752e4a 100644 --- a/tools/nvfp4_local_pack.py +++ b/tools/nvfp4_local_pack.py @@ -63,7 +63,19 @@ PLE_ROW_BYTES = 90 # 80 B of E2M1 codes + 10 E4M3 block scales, per 160 # --------------------------------------------------------------------------------------------- safetensors access class Checkpoint: - """Header-indexed, memory-mapped access to a checkpoint's safetensors shards (raw bytes, any dtype).""" + """Header-indexed, buffered access to a checkpoint's safetensors shards (raw bytes, any dtype). + + Reads go through a cached file handle into a fresh buffer instead of a process-lifetime np.memmap: + a memmap sweep of the ~64 GB of expert bytes charges every faulted page to the PROCESS WORKING + SET, which Windows (and every free-RAM observer reading GlobalMemoryStatusEx) counts as used + until the OS trims it - the pack step then looks like a ~64 GB RAM demand while its real + committed need is a few GB, and under memory pressure it is the pack run itself that pays + (issue: the silent exit-1 mid-pack failure). + A cached sequential read puts the same pages in the system file cache (standby: counted as + available). The returned array is a fresh WRITABLE buffer - no consumer writes (a mutator would + previously have hit the read-only memmap) - and reads share one handle per shard, so raw() is + not thread-safe, unlike the memmap it replaces. Each shard is read as three ascending streams + (exceptions, weights, CSF-fixed) walked expert-ascending.""" def __init__(self, folder, partial_ok=False): self.dir = pathlib.Path(folder) @@ -76,7 +88,7 @@ class Checkpoint: if not files: raise FileNotFoundError("no .safetensors files in " + str(self.dir)) self.meta: dict[str, tuple[str, str, list[int], int, int]] = {} - self._mm: dict[str, np.memmap] = {} + self._fh: dict[str, "object"] = {} for fn in files: path = self.dir / fn if not path.exists() and partial_ok: @@ -100,9 +112,14 @@ class Checkpoint: def raw(self, name) -> np.ndarray: fn, _, _, a, b = self.meta[name] - if fn not in self._mm: - self._mm[fn] = np.memmap(self.dir / fn, dtype=np.uint8, mode="r") - return self._mm[fn][a:b] + f = self._fh.get(fn) + if f is None: + f = self._fh[fn] = open(self.dir / fn, "rb") + buf = np.empty(b - a, dtype=np.uint8) + f.seek(a) + if f.readinto(buf) != b - a: + raise EOFError("%s: shard %s ended early at %d" % (name, fn, a)) + return buf def array(self, name, np_dtype) -> np.ndarray: return self.raw(name).view(np_dtype).reshape(self.shape(name)) diff --git a/tools/test_nvfp4_local_pack.py b/tools/test_nvfp4_local_pack.py index dd6fbe32..b32c50e1 100644 --- a/tools/test_nvfp4_local_pack.py +++ b/tools/test_nvfp4_local_pack.py @@ -1,5 +1,7 @@ """Tests for tools/nvfp4_local_pack.py: the CSF scale decode, the MXFP8 dequantization, the PLE rows.""" +import json import pathlib +import struct import sys import numpy as np @@ -114,3 +116,42 @@ def test_nvfp4_blocks_layout_by_hand(): # within a 16-block: element j in the low nibble, element j+8 in the high one blk0 = out[0, 4:12] assert [int(b & 15) for b in blk0] == list(range(8)) and [int(b >> 4) for b in blk0] == list(range(8, 16)) + + +def _write_shard(path, tensors): + """tensors: name -> (dtype, shape, uint8 bytes), written safetensors-style (data after the header).""" + hdr, data, off = {}, bytearray(), 0 + for name, (dt, shape, buf) in tensors.items(): + hdr[name] = {"dtype": dt, "shape": shape, "data_offsets": [off, off + len(buf)]} + data += buf + off += len(buf) + hj = json.dumps(hdr).encode("utf-8") + hj += b" " * (-len(hj) % 8) + with open(path, "wb") as f: + f.write(struct.pack(" Date: Mon, 26 Oct 2026 18:57:13 +0100 Subject: [PATCH 102/177] kq_cpu_bench: i-quant pairs no longer crash, and Q2_0 is timed on the CPU pool's path (#3871) make_blob quantized its random test rows with ggml-cpu's type traits from_float, which the i-quants do not have: an IQ3_S pair called a null pointer (an access violation on Windows, SIGSEGV on Linux) before the first timing. It now uses ggml_quantize_chunk, with a flat importance matrix where the type needs one. A Q2_0 gate/up or down is timed as pool.cpp runs it (activations as an ActQ, Strata's own Q2_0 rows, SwiGLU in between) instead of with ggml-cpu's Q2_0 dot, and the pair's header line says so. Other formats are timed as before. Ported from PR #3871 by Licenser. Built on this PC (MSVC, CPU only) and run: iq3_s/q2_0 0.531, iq2_xs/q2_0 0.336 and q2_0/q2_0 0.214 ms per expert per thread (--mb 512, 1 thread). --- src/kernels/cpu/kq_cpu_bench.cpp | 60 ++++++++++++++++++++++++++------ 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/src/kernels/cpu/kq_cpu_bench.cpp b/src/kernels/cpu/kq_cpu_bench.cpp index 0655bc0e..3a2f9b8d 100644 --- a/src/kernels/cpu/kq_cpu_bench.cpp +++ b/src/kernels/cpu/kq_cpu_bench.cpp @@ -53,19 +53,23 @@ std::vector split(const std::string& s) { } // one expert blob in the GGUF form: gate rows, up rows (n_ff x n_embd each), down rows (n_embd x n_ff), from random -// weights quantized by ggml-cpu (valid scales, as a real file has) +// weights quantized by ggml (valid scales, as a real file has). ggml_quantize_chunk, not the CPU traits' from_float: +// ggml-cpu has no from_float for the i-quants (IQ3_S called a null pointer: an access violation on Windows) void make_blob(const cpu::NativeFmt& f, uint8_t* blob, std::mt19937& rng) { std::normal_distribution nd(0.f, 0.02f); std::vector row((size_t) std::max(kH, kFF)); - const auto* tg = ggml_get_type_traits_cpu((ggml_type) f.gu_type); - const auto* td = ggml_get_type_traits_cpu((ggml_type) f.d_type); + const std::vector imatrix((size_t) std::max(kH, kFF), 1.0f); + auto quant = [&](int type, uint8_t* dst, int64_t n) { + ggml_quantize_chunk((ggml_type) type, row.data(), dst, 0, 1, n, + ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr); + }; for (int64_t r = 0; r < 2 * kFF; ++r) { for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng); - tg->from_float(row.data(), blob + (size_t) r * f.gu_row, kH); + quant(f.gu_type, blob + (size_t) r * f.gu_row, kH); } for (int64_t r = 0; r < kH; ++r) { for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng); - td->from_float(row.data(), blob + f.down_off + (size_t) r * f.d_row, kFF); + quant(f.d_type, blob + f.down_off + (size_t) r * f.d_row, kFF); } } @@ -123,16 +127,36 @@ int main(int argc, char** argv) { ha(kMaxT, std::vector(cpu::kNativeHBytes)); const void* act[kMaxT]; const void* hq[kMaxT]; + // a Q2_0 down takes the pool's own path (pool.cpp, run_split_multi_native and drain mode 6): the activation + // as an ActQ (act_quant_any) and Strata's Q2_0 rows (q2_rows_any), not ggml-cpu's Q2_0 dot + const bool q2_down = cpu::q2_native_kernels(f.d_type); + std::vector h2(q2_down ? kMaxT : 0); + const cpu::ActQ* a2[kMaxT] = {}; + // a Q2_0 gate/up the same (pool.cpp mode 5): x as an ActQ, gate and up on q2_rows_any, then SwiGLU + const bool q2_gu = cpu::q2_native_kernels(f.gu_type); + std::vector x2(q2_gu ? kMaxT : 0); + const cpu::ActQ* ax[kMaxT] = {}; for (int t = 0; t < kMaxT; ++t) { std::vector x(kH), h(kFF); for (auto& v : x) v = nd(rng); for (auto& v : h) v = 0.1f * nd(rng); - cpu::native_quant_act(f, x.data(), xa[t].data()); - cpu::native_quant_h(f, h.data(), ha[t].data()); + if (q2_gu) { + cpu::act_quant_any(x.data(), (int) kH, x2[(size_t) t]); + ax[t] = &x2[(size_t) t]; + } else { + cpu::native_quant_act(f, x.data(), xa[t].data()); + } + if (q2_down) { + cpu::act_quant_any(h.data(), (int) kFF, h2[(size_t) t]); + a2[t] = &h2[(size_t) t]; + } else { + cpu::native_quant_h(f, h.data(), ha[t].data()); + } act[t] = xa[t].data(); hq[t] = ha[t].data(); } - std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6); + std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)%s%s\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6, + q2_gu ? ", Q2_0 gate/up" : "", q2_down ? ", Q2_0 down on Strata's rows (the pool's path)" : ""); for (int nt : nts) { for (int T : threads) { if (T < 1) continue; @@ -141,6 +165,11 @@ int main(int argc, char** argv) { std::atomic next{0}; auto work = [&] { std::vector ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH); + std::vector gb(q2_gu ? (size_t) kMaxT * kFF : 0), ub(q2_gu ? (size_t) kMaxT * kFF : 0); + float* gp[kMaxT] = {}; + float* up[kMaxT] = {}; + if (q2_gu) + for (int t = 0; t < kMaxT; ++t) { gp[t] = &gb[(size_t) t * kFF]; up[t] = &ub[(size_t) t * kFF]; } float* ff[kMaxT]; float* out[kMaxT]; for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; } @@ -149,8 +178,19 @@ int main(int argc, char** argv) { const size_t e = next.fetch_add(1); if (e >= E) break; const uint8_t* blob = blobs + e * f.bytes; - cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF); - cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH); + if (q2_gu) { + cpu::q2_rows_any(blob, f.gu_row, (int) (kH / 64), ax, nt, gp, 0, (int) kFF); + cpu::q2_rows_any(blob + f.up_off, f.gu_row, (int) (kH / 64), ax, nt, up, 0, (int) kFF); + for (int t = 0; t < nt; ++t) + for (int64_t r = 0; r < kFF; ++r) + ff[t][r] = (gp[t][r] / (1.f + std::exp(-gp[t][r]))) * up[t][r]; + } else { + cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF); + } + if (q2_down) + cpu::q2_rows_any(blob + f.down_off, f.d_row, (int) (f.n_ff / 64), a2, nt, out, 0, (int) kH); + else + cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH); } volatile float sink = outb[0] + ffb[0]; (void) sink; From 6c09a1929c745b46c235ffb59c80b7323ef9d813 Mon Sep 17 00:00:00 2001 From: stuchapin909 <178119976+stuchapin909@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:57:30 +0100 Subject: [PATCH 103/177] CI: build the Metal engine on macos-26 (#3870, #3824) metal/src/mtl_rt.mm names MTLGPUFamilyMetal4 (macOS 26 SDK) and MTLCompileOptions.mathMode (macOS 15 SDK) behind @available, a run-time check; the names must still exist in the SDK the engine is compiled against, so the metal-link job failed on the macOS 14 SDK on every pull request that touched src/, include/ or metal/. The job now runs on macos-26 (the runner-images repository lists a macos-26 image). Ported from PR #3870 by stuchapin909. A GitHub Actions run cannot be made here: the author ran this workflow on his fork; the first run after the merge proves it. #3824 changes the same line with macos-15 and an Xcode 26.0.1 path pin, and is not taken. --- .github/workflows/metal-build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/metal-build.yml b/.github/workflows/metal-build.yml index 7a69696f..a4f7d997 100644 --- a/.github/workflows/metal-build.yml +++ b/.github/workflows/metal-build.yml @@ -20,7 +20,9 @@ permissions: jobs: metal-link: - runs-on: macos-14 + # the macOS 26 SDK: metal/src/mtl_rt.mm names MTLGPUFamilyMetal4 (and MTLCompileOptions.mathMode, macOS 15) behind @available, + # which is a run-time check; the names must still be in the SDK the engine is compiled against + runs-on: macos-26 timeout-minutes: 45 env: # setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin From e21a1872f7c5543bb00a588717dfc2e186acbf6d Mon Sep 17 00:00:00 2001 From: oscarlius <43489660+oscarlius@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:57:53 +0100 Subject: [PATCH 104/177] docs/BATCHING.md: the cache settings that let a long solo request move into a batch slot without reading its prompt again (#3334) Adds a minimal handoff configuration (--prompt-cache 1, --prompt-cache-every 0, --prompt-cache-root 0, --conversation-cache-mib 0), what each option does, that it costs RAM, that it does not make cold prompts prefill in parallel, and how to look for the handoff in the engine log, /metrics and /v1/status. Ported from PR #3334 by oscarlius (continuing #3035). The four options exist in src/program/generate.cpp and the o.prompt_cache > 0 gate matches the text; the log evidence was not reproduced here (no model run). --- docs/BATCHING.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 6e7b58d3..49abbb6e 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -188,6 +188,40 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`). - A client that disconnects stops its slot (`BSTOP`); the others go on. +### Long prompts that move from solo to a batch slot + +The handoff above needs prompt-cache state. With `--prompt-cache 0`, moving a long request from the solo path into +a slot can read the whole prompt again. This minimal example enables handoff reuse without parking completed +conversations. Set these options in the model config's `args`, keeping the other arguments unchanged: + +``` +"args": [ ..., "--prompt-cache", "1", "--prompt-cache-every", "0", + "--prompt-cache-root", "0", "--conversation-cache-mib", "0" ] +``` + +`--prompt-cache 1` keeps the latest turn-boundary checkpoint so the `GEN` to `BGEN` handoff can reuse the live +prefix. `--prompt-cache-every 0` disables periodic checkpoints and `--prompt-cache-root 0` disables an extra root +checkpoint. The limit is per cache set: a slot can keep its own live state, so it is not one checkpoint shared by +every slot. `--conversation-cache-mib 0` still disables parking independent completed conversations in RAM; it does +not remove the prompt checkpoint or the state held by an active slot. +If conversation parking is already enabled, keep its existing budget instead of setting it to zero: that budget is +independent of the handoff configuration. + +This setting has RAM costs. The checkpoint and every slot's normal context state still consume memory, even with the +conversation cache off. Check the engine's free-memory report and the slot count that it actually accepts before +raising the context length or `"parallel"` value. + +It does not make independent cold prompts prefill in parallel. The server admits them one at a time; a running value +of four can mean four requests are in flight, not four slots decoding together. A slot already decoding may make +progress while the next prompt is read, but long independent prompts can finish before enough admissions overlap to +fill every configured slot. + +After changing the setting, send a long request alone and add a second request while it is decoding. In the engine +log, the first request's `GEN` to `BGEN` transfer should report a large reused prefix and only the new token(s) read. +Then check `/metrics` for the slots that were actually reading or decoding, and `/v1/status` for the effective +serving count. Treat this as handoff evidence only: it does not prove that every configured slot can stay resident or +that cold prompts have concurrent prefill. + ## Reading a prompt beside pipelined groups (experimental, opt-in) With a layer split and `--batch-groups` above 1 a prompt is read in one run: every decoding slot stops until it is From 05c1dabf1aab983d7f0dc06e2b01044ab0d4aceb Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:59:27 +0100 Subject: [PATCH 105/177] docs: the xe expert tier has no SSD fallback under the wrapper default, and a native pack needs --spec 2 or more (#2153, #1796) docs/INTEL.md and docs/INTEL_ARC.md described an SSD expert tier that strata-sycl.sh's default (STRATA_VERIFY_NO_HOST=1) does not have: every expert must be in VRAM or in the pinned RAM mirror, and the engine refuses to start otherwise (sycl/src/program/generate.cpp, 'REFUSED: ... are neither in VRAM nor mirrored'). A native (IQ) pack refuses --spec 0 and 1 (sycl/src/program/generate.cpp and src/program/generate.cpp). Ported by hand from PR #2153 by nekomario28 onto the rewritten pages, each sentence checked against those two messages. The hunk for docs/TROUBLESHOOTING.md is left out: the entry it changed is no longer on that page. --- docs/INTEL.md | 10 +++++++--- docs/INTEL_ARC.md | 3 +++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/INTEL.md b/docs/INTEL.md index 15615039..85b501da 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -127,9 +127,13 @@ the oneAPI runtime image with the serve pipes attached. Paths in the config's `a "sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.05}} ``` -With `--stream-experts` any expert left out of VRAM is read from the SSD and computed on the CPU when routed, so the reserve -matters: on the B70 with Coder IQ1_M a 1,536 MiB reserve left the cache 128 experts short and decode fell to 5-10 tok/s, while -1,024 MiB fits all 12,288 with 2 GB of VRAM free. +A native (IQ) pack takes `--spec` 2 at the smallest: the engine refuses `--spec 0` and `--spec 1` on one (it needs `--native SHARD1`, `--spec T` +with T >= 2 and `--prefill CHUNK`), so speculative decoding cannot be turned off for these packs. + +With `--stream-experts` under `STRATA_VERIFY_NO_HOST=1` (the `strata-sycl.sh` default) there is no SSD expert tier: every expert +must be in VRAM or in the pinned RAM mirror (`STRATA_MIRROR_MIB`), and the engine refuses to start when the two do not cover the model +("REFUSED: N experts are neither in VRAM nor mirrored"). Raise the mirror or lower `--max-context`. So the reserve matters: on the B70 +with Coder IQ1_M 1,024 MiB fits all 12,288 experts with 2 GB of VRAM free. ## Things that matter on this GPU diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 4adf07a3..a38fab0d 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -47,6 +47,9 @@ engine package. Otherwise [build the image yourself](DOCKER.md#build-it-yourself `sudo apt install docker.io git`, then `sudo usermod -aG docker,render $USER` and log in again. - VRAM: the port keeps the experts on the card (`--stream-experts`). A 32 GB card holds the Coder IQ1_M or IQ2_XS. Smaller cards mirror part of the experts in RAM and are slower. + Under the wrapper's `STRATA_VERIFY_NO_HOST=1` there is no SSD expert tier on `xe`: every expert must + be in VRAM or in the pinned RAM mirror (`STRATA_MIRROR_MIB`), and the engine refuses to start when + the two do not cover the model. Size the RAM accordingly, or lower `--max-context`. ## Build with Docker (what `setup --backend sycl` uses) From cea3ed40db9823633083d1b4060d56ad557a3408 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:59:50 +0100 Subject: [PATCH 106/177] serve: a slot's shorter checkpoints come along at a give-back only when they are prefixes of the tokens copied back (#2526) Review fix on the #2526 port. At an admission from a slot the port copies every checkpoint of the slot that is not longer than the copied-back length into the main session's chain. Such a checkpoint is valid there only when its tokens are a prefix of what was copied back (its K/V cells are then the ones the main session holds) and it has no pictures (the main session's pictures are cleared at a give-back). The PR did not check either; a checkpoint left over from a branch the slot no longer holds would sit in the main chain with cells that are not its own. Both trees (CUDA/HIP and SYCL) now test the prefix and the empty picture list per checkpoint. The checkpoint the request continues from is copied as before. Nothing changes when every checkpoint is a prefix, which is the normal case. Tests: compiles on CUDA and SYCL (see the build lines of the branch). Not covered: no model run; the gate is written down. --- src/program/generate.cpp | 9 ++++++++- sycl/src/program/generate.cpp | 6 +++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 77efc070..4ce6a3dc 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -13061,6 +13061,13 @@ int main(int argc, char** argv) { const bool move_cks = slot_ckpt_move_env() && admit_slot == slot_source; const int64_t ck_len = slot_ck != nullptr ? (int64_t) slot_ck->ids.size() : -1; std::vector& sc = bs[(size_t) slot_source].checks; + // a shorter checkpoint comes along only when it is a prefix of the tokens copied back (text only): + // its cells are then the ones the main session holds + const std::vector copied_back = slot_ck != nullptr ? slot_ck->ids : bs[(size_t) slot_source].ids; + auto prefix_of_copied = [&](const ConvCheckpoint& c) { + return c.imgs.empty() && c.ids.size() <= copied_back.size() && + std::equal(c.ids.begin(), c.ids.end(), copied_back.begin()); + }; // the one continued from first, exactly as before this change (its copy is the one the request needs) const ConvCheckpoint* first = slot_ck; if (first != nullptr) { @@ -13075,7 +13082,7 @@ int main(int argc, char** argv) { // then the shorter ones: an optimization, so a host allocation that fails skips them try { for (auto it = sc.begin(); it != sc.end();) { - if ((int64_t) it->ids.size() > slot_tokens || &*it == first) { + if ((int64_t) it->ids.size() > slot_tokens || &*it == first || !prefix_of_copied(*it)) { ++it; } else if (move_cks) { checks.push_back(std::move(*it)); diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 893e7d6b..3e257771 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -10116,8 +10116,12 @@ int main(int argc, char **argv) try { // copies of this conversation a turn back - whose deepest checkpoint the chain holds again - go // as superseded (#342) instead of taking a parked entry each until the cache evicts another chat try { // an optimization: a host allocation that fails skips the rest + // (a shorter checkpoint only when it is a prefix of the tokens copied back, text only) + const std::vector& copied_back = slot_ck != nullptr ? slot_ck->ids : bs[(size_t) slot_source].ids; for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) - if ((int64_t) c.ids.size() <= slot_tokens) checks.push_back(c); + if ((int64_t) c.ids.size() <= slot_tokens && c.imgs.empty() && c.ids.size() <= copied_back.size() && + std::equal(c.ids.begin(), c.ids.end(), copied_back.begin())) + checks.push_back(c); } catch (const std::bad_alloc&) { std::fprintf(stderr, "strata batch: slot %d: its checkpoints were not all copied (out of memory); the rest are skipped\n", slot_source); } From f217b23bd35aacfd611a62b3711c6a932cfdd070 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 18:59:50 +0100 Subject: [PATCH 107/177] prefill: the copy-wait dedupe skips a wait only when both slots were released in the current walk and the ring is longer than one group (#4005) Review fix on the #4005 port. STRATA_PREFILL_COPY_WAIT_DEDUPE=1 skipped the copy stream's wait on a slot's release event when the previous entry had waited on the same event. Two cases break that: - At idx == ring the previous entry (ring - 1) is still in the first round, so its wait was on the event of an earlier walk. The same slot id can be this walk's first flush, which re-records the event after that wait; skipping the wait for slot 0 then lets the next copy overwrite a slot that the flush's gather has not finished reading. - With a ring of one MMQ group (16, the smallest ring) a flush of the whole ring re-records the event right after the previous slot's wait. The rule is now copy_wait_dedupe_ok() in include/strata/prefill/copy_events.hpp: idx > ring, ring > group, same event. copy_events_test models two to three walks with random group sizes and random issuer/consumer interleaving and checks that a refill always waits on a record at or after the flush that released its slot. The same model with the PR's original rule (idx >= ring) finds the stale-event case, so the test can fail. The default path is unchanged (dedupe off). Tests: copy_events_test passes (z440, g++ -std=c++20). Not covered: a GPU run. --- include/strata/prefill/copy_events.hpp | 9 +++ src/prefill/copy_events_test.cpp | 77 ++++++++++++++++++++++++++ src/prefill/prefill.cpp | 9 ++- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/include/strata/prefill/copy_events.hpp b/include/strata/prefill/copy_events.hpp index 96f1ea62..b8e93e40 100644 --- a/include/strata/prefill/copy_events.hpp +++ b/include/strata/prefill/copy_events.hpp @@ -32,4 +32,13 @@ inline size_t copy_event_entry(size_t k, size_t recorded, IsRecorded is_recorded return recorded - 1; } +/// STRATA_PREFILL_COPY_WAIT_DEDUPE: the copy stream may skip its wait on the release event of entry `idx`'s slot (`rel`) +/// when the wait it made for the previous entry was on the same event (`prev_rel`). That holds only when both slots were +/// released in the current walk (idx - 1 >= ring), because the event of an earlier walk can be re-recorded by this walk's +/// first flush, and when the ring is longer than one MMQ group of `group` experts, because a flush of a whole ring would +/// re-record the event right after the previous slot's wait. +inline bool copy_wait_dedupe_ok(size_t idx, int ring, int group, int rel, int prev_rel) { + return ring > group && idx > (size_t) ring && rel == prev_rel; +} + } // namespace strata::prefill diff --git a/src/prefill/copy_events_test.cpp b/src/prefill/copy_events_test.cpp index 1ce75e68..fca467e1 100644 --- a/src/prefill/copy_events_test.cpp +++ b/src/prefill/copy_events_test.cpp @@ -71,6 +71,83 @@ int main() { check(ok && consumed == total, what); } + // copy_wait_dedupe_ok: skipping the copy stream's wait on a slot's release event must never leave a slot's refill + // without a wait on a record at or after the flush that released it. Two walks of random length with random group + // sizes (1..group), the issuer and the consumer interleaved at random. A "record" is a counter tick of the event. + auto simulate = [&](int ring, int group, bool original_rule, unsigned seed) -> bool { + std::srand(seed); + std::vector used_of((size_t) ring); + std::vector rec_time((size_t) ring, 0), last_flush((size_t) ring, 0); + for (int i = 0; i < ring; ++i) used_of[(size_t) i] = i; + long long tick = 0; + for (int walk = 0; walk < 3; ++walk) { + const size_t n = (size_t) ring * (size_t) (2 + std::rand() % 3) + (size_t) (std::rand() % (ring + 1)); + std::vector group_end; // the last entry of each group, in order + for (size_t s = 0; s < n;) { + size_t len = (size_t) (1 + std::rand() % group); + if (s + len > n) len = n - s; + s += len; + group_end.push_back(s - 1); + } + size_t issued = 0, consumed = 0, g = 0; + const int issue_pct = std::vector{50, 90, 99}[(size_t) (std::rand() % 3)]; // how far ahead the issuer runs + int prev_rel = -1; + long long prev_cap = 0; + std::vector live((size_t) ring, walk > 0); // the first walk starts with empty slots + size_t guard = 0; + while (consumed < n && ++guard < 1000000) { + const bool can_issue = issued < n && issued < consumed + (size_t) ring; + const bool can_flush = g < group_end.size() && group_end[g] < issued; + if (can_issue && (!can_flush || std::rand() % 100 < issue_pct)) { + const size_t idx = issued++; + const int sl = (int) (idx % (size_t) ring); + if (live[(size_t) sl]) { + const int rel = used_of[(size_t) sl]; + const bool skip = original_rule ? (idx >= (size_t) ring && rel == prev_rel) + : copy_wait_dedupe_ok(idx, ring, group, rel, prev_rel); + const long long cap = skip ? prev_cap : rec_time[(size_t) rel]; + if (cap < last_flush[(size_t) sl]) return false; // the refill would not wait for its release + prev_cap = cap; + prev_rel = rel; + } else { + prev_rel = -1; + } + live[(size_t) sl] = true; + } else if (can_flush) { + size_t first = consumed; + const size_t last = group_end[g++]; + const int rel = (int) (last % (size_t) ring); + rec_time[(size_t) rel] = ++tick; + for (size_t e = first; e <= last; ++e) { + used_of[e % (size_t) ring] = rel; + last_flush[e % (size_t) ring] = tick; + } + consumed = last + 1; + } else { + return false; // stuck: the model is wrong + } + } + } + return true; + }; + for (int ring : {17, 18, 24, 32, 96, 1024}) + for (unsigned seed = 1; seed <= 300; ++seed) { + char what[96]; + std::snprintf(what, sizeof what, "dedupe never skips a needed wait (ring %d, seed %u)", ring, seed); + if (!simulate(ring, 16, false, seed)) { check(false, what); break; } + } + { + bool rule_ok = true; // the rule refuses a ring that a group can fill + for (size_t idx : {20u, 1000u}) rule_ok = rule_ok && !copy_wait_dedupe_ok(idx, 16, 16, 3, 3); + check(rule_ok, "a ring of one group never dedupes"); + check(!copy_wait_dedupe_ok(32, 32, 16, 3, 3) && copy_wait_dedupe_ok(33, 32, 16, 3, 3), "the first round never dedupes"); + check(!copy_wait_dedupe_ok(40, 32, 16, 3, 4) && !copy_wait_dedupe_ok(40, 32, 16, 3, -1), "different events or none: wait"); + // the control: the PR's first rule (idx >= ring) is caught by this model + bool caught = false; + for (int ring : {17, 18, 20, 24, 32}) for (unsigned seed = 1; seed <= 600 && !caught; ++seed) caught = !simulate(ring, 16, true, seed); + check(caught, "the model finds the stale-event race in the rule 'idx >= ring'"); + } + if (g_fail == 0) std::printf("copy_events_test: all checks passed\n"); return g_fail == 0 ? 0 : 1; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 9e71dd69..8b08b511 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -3262,10 +3262,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const auto th = Clock::now(); const size_t bytes = (size_t) lay0.blob_bytes(en.l); if (m.stage_live[sl]) { - // from the second round on, both slots were released in this walk: the same event means the same - // flush, and the wait for the previous slot already covers this one + // Both this slot and the previous one must have been released in THIS walk (idx - 1 >= ring: the + // previous slot's event of an earlier walk could be re-recorded by this walk's first flush), and + // the ring must be longer than one MMQ group (a flush of a whole ring would re-record the event + // after the previous slot's wait). Then the same event means the same flush, and the wait for + // the previous slot already covers this one. const int rel = m.used_of[sl]; - if (copy_wait_dedupe && idx >= (size_t) m.ring && rel == prev_rel) { + if (copy_wait_dedupe && strata::prefill::copy_wait_dedupe_ok(idx, m.ring, MMQ_GROUP, rel, prev_rel)) { ++iss_dedup; } else { cudaStreamWaitEvent(m.copy, m.used[rel], 0); From 7783b1c18eea95d05478836c0d2f45826bd91b69 Mon Sep 17 00:00:00 2001 From: Norm <304706238+Buddychek@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:00:14 +0100 Subject: [PATCH 108/177] docs: a crashed engine start names itself, and a setup run again keeps the installed size (#3243) Two 0.1.44.1 changes no page told. TROUBLESHOOTING.md gets the start error 'the engine process ended: ...' (serve/server.py start_exit_note: the signal or Windows exit code, and for an illegal instruction the AVX, AVX2, FMA and F16C flags the CPU lacks). SOURCE_INSTALL.md says a setup run again pre-selects the installed size, marked '(installed)', and --yes takes it (setup.py size_tag, installed_size). Written by hand from PR #3243 by Buddychek, whose hunks no longer fit the rewritten pages; each sentence checked against the two functions. --- docs/SOURCE_INSTALL.md | 2 ++ docs/TROUBLESHOOTING.md | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/docs/SOURCE_INSTALL.md b/docs/SOURCE_INSTALL.md index 1db38150..692891de 100644 --- a/docs/SOURCE_INSTALL.md +++ b/docs/SOURCE_INSTALL.md @@ -33,6 +33,8 @@ Choose a pack that fits your machine; Q2_0 is an example, not a universal minimu In PowerShell, prefix the wrapper with `.\`, for example `.\START-HERE.bat`. `SETUP.bat` opens setup again to add a model or change settings. The wrapper can reuse an existing install; first-start and later load times depend on the pack, disk, RAM and backend. A model can take several minutes to load. +Run again over an installed model, setup pre-selects the size that is installed and marks it "(installed)", and `--yes` takes it: a repeat run +does not move the model to the recommended size. When no ready-made engine fits the PC, setup compiles one. That needs the Visual Studio 2022 Build Tools with the C++ workload; Visual Studio 2019 is too old (the sources are C++20). With a CUDA toolkit, CUDA 13.0 to 13.2 accept Visual Studio 2022 only, and diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index f55fba05..37c97734 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -63,6 +63,12 @@ Retry it in the app, or rerun the same `strata launch` command. Completed model- free space and the error message. For an interrupted Terminal installer, rerun the install command. Only a source checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup. +**The engine stops at the start with no line in its log, and the error says `the engine process ended: ...`.** +The error names how the system ended the engine process, because the engine log is silent then: for example `killed by signal 4 (SIGILL, Illegal +instruction)` on Linux and Mac, or `exit code 0xC000001D: illegal instruction` on Windows. An illegal instruction means the engine ran an instruction +the CPU cannot execute; the error lists the AVX, AVX2, FMA and F16C flags the CPU lacks, or says the CPU has them all, which is a bug in the engine. +Report it with the CPU model. + **Startup takes a long time or the computer becomes slow.** Large models need time to check files, prepare packs and fill memory. A first launch can take many minutes; there is no fixed startup time. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a From c0845b7fc513b61f29fd94c1ddbb358c97a83a82 Mon Sep 17 00:00:00 2001 From: JoShMiQueL <26714939+JoShMiQueL@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:01:17 +0100 Subject: [PATCH 109/177] bench: tools/strata_bench.py reads the CUDA UMD version, the storage, the engine's build toolkit and GPU power and PCIe detail (#3250, #2111) The report written by BENCH.bat and bench.sh had fields missing or wrong: nvidia-smi's 'CUDA UMD Version:' (current drivers) was not read, the value was the newest CUDA the driver supports but was labelled like the engine's toolkit, storage always said 'not measured', and Windows 11 showed as Windows 10. Now the report says 'CUDA (driver supports up to): X; engine built for CUDA Y' (BUILD.json beside the engine), names the storage device (Get-PhysicalDisk, system_profiler, lsblk -e 7 to skip snap loop devices), adds a 'GPU detail (after the run, near idle)' line with power limit and draw, PCIe generation and width, pstate and temperature, and recognises Windows 11. The standard report (strata bench run, strata_cli/bench_facts.py) already read the UMD version, storage and power limit; this brings the legacy tool to the same. Ported from PR #3250 by JoShMiQueL with its tests. --- tools/strata_bench.py | 70 ++++++++++++++++++++++++++++++++------ tools/test_strata_bench.py | 48 ++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 10 deletions(-) diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 36d919e7..806273db 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -483,15 +483,26 @@ def cpu_name() -> str | None: def gpu_info_local() -> dict: - out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"]) + out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version,power.limit,power.draw,pcie.link.gen.current,pcie.link.width.current,pstate,temperature.gpu", + "--format=csv,noheader,nounits"]) gpus = [] for line in out.splitlines(): p = [x.strip() for x in line.split(",")] if len(p) >= 3: - gpus.append({"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]}) + g = {"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]} + if len(p) >= 9: + g.update({"power_limit_w": p[3], "power_draw_w": p[4], "pcie": f"gen{p[5]} x{p[6]}", + "pstate": p[7], "temp_c": p[8]}) + gpus.append(g) + if not gpus: + out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"]) + for line in out.splitlines(): + p = [x.strip() for x in line.split(",")] + if len(p) >= 3: + gpus.append({"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]}) info = {"gpus": gpus} head = run_cmd(["nvidia-smi"]) - m = re.search(r"CUDA Version:\s*([\d.]+)", head) + m = re.search(r"CUDA(?: UMD)? Version:\s*([\d.]+)", head) if m: info["cuda"] = m.group(1) if not gpus: @@ -549,6 +560,37 @@ def gpu_info_local() -> dict: return info +def storage_info() -> str | None: + if os.name == "nt": + out = run_cmd(["powershell", "-NoProfile", "-Command", + "Get-PhysicalDisk | Select-Object -First 4 FriendlyName,MediaType,BusType | " + "ForEach-Object { $_.FriendlyName + ' ' + $_.MediaType + '/' + $_.BusType }"]) + names = [x.strip() for x in out.splitlines() if x.strip() and "FriendlyName" not in x] + return "; ".join(names) or None + if sys.platform == "darwin": + out = run_cmd(["system_profiler", "SPNVMeDataType", "SPSerialATADataType"]) + names = re.findall(r"Model:\s*(.+)", out) + if names: + return "; ".join(n.strip() for n in names) + return None + out = run_cmd(["lsblk", "-d", "-o", "NAME,MODEL,TRAN", "-n", "-e", "7"]) # -e 7: skip loop devices (snap mounts) + if out.strip(): + return "; ".join(x.strip() for x in out.splitlines() if x.strip()) or None + return None + + +def engine_build(cfg: dict | None) -> dict | None: + """BUILD.json next to the engine exe: the toolkit/archs it was compiled with, unlike nvidia-smi's driver ceiling.""" + exe = (cfg or {}).get("exe") + if not exe: + return None + try: + b = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return {k: b[k] for k in ("version", "source", "cuda", "rocm", "archs", "ptx", "portable") if b.get(k) is not None} or None + + QUANT = re.compile(r"(?i)(?:^|[-_.])((?:UD-)?(?:IQ\d_[A-Z]+|Q\d_[A-Z0-9_]+|Q\d_K(?:_[A-Z]+)?|IQ\d_?[A-Z]*|BF16|F16|Q\d))(?=[-_.]|$)") SECRET_KEY = re.compile(r"(?i)key|token|secret|password|auth") @@ -672,9 +714,12 @@ def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = n_ctx = n_ctx or (props.get("default_generation_settings") or {}).get("n_ctx") return { "gpu": gpu_names, "gpu_vram_mib": vram_mib, "gpu_driver": (used[0].get("driver") if used else local.get("rocm_driver")), - "cuda": local.get("cuda"), "cpu": static.get("cpu_name") or cpu_name(), "cpu_cores": static.get("cores"), + "gpu_detail": [{k: v for k, v in g.items() if k not in ("name", "vram_mib", "driver")} for g in used] or None, + "cuda": local.get("cuda"), "engine_build": engine_build(cfg), + "cpu": static.get("cpu_name") or cpu_name(), "cpu_cores": static.get("cores"), + "storage": storage_info(), "cpu_threads": static.get("threads") or os.cpu_count(), "ram_gib": total_ram_gib(), - "os": f"{platform.system()} {platform.release()} ({platform.version()})" if os.name == "nt" else f"{platform.system()} {platform.release()}", + "os": f"{platform.system()} {'11' if int(platform.version().split('.')[-1] or 0) >= 22000 else platform.release()} ({platform.version()})" if os.name == "nt" else f"{platform.system()} {platform.release()}", "python": platform.python_version(), "strata_version": project_version(), "strata_commit": git_commit(), "engine_version": (eng.get("version") or status.get("engine") or str(props.get("build_info", "")).replace("Strata ", "") or None), @@ -856,11 +901,16 @@ def render_readme(res: dict) -> str: "## Hardware and software", "", f"- GPU and VRAM: {gpu}, {vram}", f"- CPU: {mc.get('cpu') or 'not read'} ({mc.get('cpu_cores') or '?'} cores, {mc.get('cpu_threads') or '?'} threads); " - f"installed RAM: {mc.get('ram_gib') or '?'} GiB; storage: not measured", - f"- OS: {mc.get('os')}; GPU driver: {mc.get('gpu_driver') or 'not read'}; CUDA: {mc.get('cuda') or 'not read'}", + f"installed RAM: {mc.get('ram_gib') or '?'} GiB; storage: {mc.get('storage') or 'not read'}", + f"- OS: {mc.get('os')}; GPU driver: {mc.get('gpu_driver') or 'not read'}; " + f"CUDA (driver supports up to): {mc.get('cuda') or 'not read'}" + + (f"; engine built for CUDA {(mc.get('engine_build') or {}).get('cuda')}" if (mc.get('engine_build') or {}).get('cuda') else ""), f"- Strata: project {mc.get('strata_version') or '?'}, commit {mc.get('strata_commit') or 'not a git checkout'}; " - f"engine {mc.get('engine_version') or 'not read'}", - "- Background workloads and power limits: not recorded", "", + f"engine {mc.get('engine_version') or 'not read'}"] + for g in (mc.get("gpu_detail") or []): + if g: + L.append("- GPU detail (after the run, near idle): " + ", ".join(f"{k}={v}" for k, v in g.items() if v is not None)) + L += ["- Background workloads: not recorded (GPU power limit/draw read above)", "", "## Model and configuration", "", f"- Model and quantization: {model}", f"- Context: {mc.get('context') or 'not read'} tokens; parallel slots: {mc.get('parallel_slots') or 1}", @@ -909,7 +959,7 @@ def render_readme(res: dict) -> str: L += ["", "Per-request data: `results.json`. Engine log lines from the start: `engine-log-excerpt.txt` (when this run started the server).", "", "## Correctness and limitations", "", "Not measured: this is a speed suite. The conversation uses the model's own replies, so token counts differ a little between runs. " - "Machine details come from the server, `nvidia-smi`/`rocm-smi` and the OS; background load and power limits are not recorded. " + "Machine details come from the server, `nvidia-smi`/`rocm-smi` and the OS; background load is not recorded. " f"Total time of the suite: {res['elapsed_s']:.0f} s.", ""] return "\n".join(L) diff --git a/tools/test_strata_bench.py b/tools/test_strata_bench.py index 80babc65..ec223e59 100644 --- a/tools/test_strata_bench.py +++ b/tools/test_strata_bench.py @@ -322,6 +322,27 @@ class ReportTests(unittest.TestCase): m = B.collect_machine(srv.base, "", {"backend": "sycl"}) self.assertEqual((m["gpu"], m["cuda"]), (["Intel Arc Pro B70"], None)) + def test_the_report_labels_the_driver_s_cuda_and_the_engine_s_build(self): + """#2111: the CUDA line was the driver's ceiling read as the engine's toolkit, and storage said "not measured".""" + srv = FakeStrata() + self.addCleanup(srv.stop) + nv = {"gpus": [{"name": "NVIDIA GeForce RTX 9999", "vram_mib": 16384, "driver": "616.92", + "power_limit_w": "165.00", "power_draw_w": "20.25", "pcie": "gen4 x8", + "pstate": "P3", "temp_c": "45"}], "cuda": "13.4"} + with mock.patch.object(B, "gpu_info_local", return_value=nv), mock.patch.object( + B, "storage_info", return_value="Samsung SSD 990 EVO Plus 2TB SSD/NVMe"), mock.patch.object( + B, "engine_build", return_value={"version": "0.1.43", "cuda": "13.0"}): + with tempfile.TemporaryDirectory() as d: + self.assertEqual(self.run_main(srv, d), 0) + readme = next(Path(d).iterdir()).joinpath("README.md").read_text(encoding="utf-8") + for part in ("CUDA (driver supports up to): 13.4; engine built for CUDA 13.0", + "storage: Samsung SSD 990 EVO Plus 2TB SSD/NVMe", + "GPU detail (after the run, near idle): power_limit_w=165.00, power_draw_w=20.25, " + "pcie=gen4 x8, pstate=P3, temp_c=45", + "Background workloads: not recorded (GPU power limit/draw read above)"): + self.assertIn(part, readme) + self.assertNotIn("storage: not measured", readme) + def test_a_bench_server_never_saves_over_the_users_profile(self): """#2088: --expert-profile-save writes the profile at quit; the bench's own server runs without it.""" cfg = {"args": ["--expert-profile", "p.bin", "--expert-profile-save", "p.bin", "--spec", "4"]} @@ -382,5 +403,32 @@ class ReportTests(unittest.TestCase): self.assertEqual(B.project_version(), "9.8.7") +class MachineDetailTests(unittest.TestCase): + """#2111: what the report reads straight from nvidia-smi on the PC.""" + + ROW = "NVIDIA GeForce RTX 4060 Ti, 16380, 616.92, 165.00, 20.25, 4, 8, P3, 45" + + @staticmethod + def queries(cmd) -> bool: + return any(str(c).startswith("--query-gpu") for c in cmd) + + def test_cuda_header_in_both_forms(self): + """Current drivers print "CUDA UMD Version: 13.4"; the old "CUDA Version:" line still has to be read.""" + for head, want in (("Some header\n\nCUDA UMD Version: 13.4\n", "13.4"), + ("Some header\n\nCUDA Version: 12.6\n", "12.6")): + def fake(cmd, *a, _head=head, **k): + return self.ROW if self.queries(cmd) else _head + with mock.patch.object(B, "run_cmd", side_effect=fake): + info = B.gpu_info_local() + self.assertEqual((info["cuda"], info["gpus"][0]["power_limit_w"]), (want, "165.00")) + + def test_power_pcie_pstate_and_temperature_are_read(self): + with mock.patch.object(B, "run_cmd", + side_effect=lambda cmd, *a, **k: self.ROW if self.queries(cmd) else ""): + g = B.gpu_info_local()["gpus"][0] + self.assertEqual((g["name"], g["vram_mib"], g["driver"]), ("NVIDIA GeForce RTX 4060 Ti", 16380, "616.92")) + self.assertEqual((g["power_limit_w"], g["pcie"], g["pstate"], g["temp_c"]), ("165.00", "gen4 x8", "P3", "45")) + + if __name__ == "__main__": unittest.main() From c966d7ad8988808da5d908ae1891805b51dbfe8c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:01:27 +0100 Subject: [PATCH 110/177] setup: Maxwell gets a warning with the build recipe, not an env switch (#3218) The first #3218 commit made setup.py admit a Maxwell (sm_52) card only when a tester set STRATA_EXPERIMENTAL_SM52=1, and then routed it to the CUDA 12 engine. That engine holds no sm_52 code, and users never set environment variables to get a fix. sm60_card() is back to Pascal and Volta (6.0 to 7.0). A PC whose only NVIDIA cards are Maxwell now gets a warning (maxwell_note) that says no ready-made engine holds code for it, gives the source-build recipe (-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52, CUDA 12.x) and the one reporter's result, and points to docs/OLDER_GPUS.md. The card table line says Maxwell runs only from a source build. A Maxwell card beside a newer card prints nothing new. Naming the card (--gpu, --cuda 12) or any env var does not admit it. The CMake floor from the first commit is unchanged (opt-in build only). Tests: tools.test_setup_older_gpus 23 tests OK (a Maxwell-only PC through setup.main() with and without the old switches installs nothing and prints the recipe; a Maxwell card beside an RTX prints no note). Not covered: no engine was built for sm_52 by this commit; the P1004 compile is recorded in the notes. --- docs/OLDER_GPUS.md | 5 ++-- setup.py | 36 ++++++++++++++++-------- tools/test_setup_older_gpus.py | 51 ++++++++++++++++++++++++++-------- 3 files changed, 68 insertions(+), 24 deletions(-) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 88036809..080d9ee7 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -55,8 +55,9 @@ cmake --build build -j ``` CMake prints a warning for sm_52 and goes on. A release build still needs sm_75 or newer, and without `STRATA_EXPERIMENTAL_SM60=ON` -the build stops as before. For `setup.py` to list a Maxwell card as usable, set `STRATA_EXPERIMENTAL_SM52=1`; setup warns and uses -the CUDA 12 path. If you try it, please post a short chat and one code answer from the card. +the build stops as before. `setup.py` does not install an engine for a Maxwell card, because none of the ready-made engines holds +code for it. On a PC with only Maxwell cards it lists the card as not supported, prints this recipe as a warning and stops. If you +try the build, please post a short chat and one code answer from the card. ## NVIDIA: the CUDA 12 engine diff --git a/setup.py b/setup.py index de04c597..7723eb59 100644 --- a/setup.py +++ b/setup.py @@ -1548,12 +1548,27 @@ def experimental_sm60() -> bool: def sm60_card(arch) -> bool: - """Pascal (6.x) and Volta (7.0) cards; Maxwell 5.2 (#3218) only for a tester who set STRATA_EXPERIMENTAL_SM52=1, - because the ready-made CUDA 12 engine holds no sm_52 code: a Maxwell card is built from source, by that tester.""" - a = int(arch) - if a == 52: - return os.environ.get("STRATA_EXPERIMENTAL_SM52", "").strip() == "1" - return 60 <= a <= 70 + return 60 <= int(arch) <= 70 + + +def maxwell_card(arch) -> bool: + """#3218: Maxwell (5.x). No ready-made engine holds code for it; it is a source build (docs/OLDER_GPUS.md).""" + return 50 <= int(arch) < 60 + + +def maxwell_note(found) -> str: + """#3218: what to tell a PC whose only NVIDIA cards are Maxwell: setup cannot install an engine for it, and a + source build exists. Empty when there is no Maxwell card. A warning with the way forward, never a switch: setup + does not route a Maxwell card to an engine that holds no code for it.""" + cards = [g for g in found if maxwell_card(g["arch"])] + if not cards: + return "" + names = ", ".join(f"GPU {g['index']} ({g['name']})" for g in cards) + return (f"{names}: Maxwell (compute capability {cc(cards[0])}). No ready-made Strata engine holds code for it, so " + "setup cannot install one. One reporter built the engine from source for two Quadro M6000 with a CUDA 12.x " + "toolkit (cmake -B build -G Ninja -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52) and saw about " + "22 tokens a second with a 1-bit Qwen3.8-Flash-Next; nobody has checked the answer text yet. Steps and " + "caveats: docs/OLDER_GPUS.md. A card of the RTX 20 series or newer runs the ready-made engine") def old_gpus_opt_in(found, named=(), cuda=None, other=False): @@ -1622,7 +1637,8 @@ def gpu_problem(g, together=False): if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()): return (f"not supported - older than the RTX 20 series (compute capability {cc(g)}; Strata needs 7.5 or " "newer" + ("; experimental: choose it with --gpu " + str(g["index"]) + " (the CUDA 12 engine, " - "docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else "") + ")") + "docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else + "; Maxwell only runs from a source build, docs/OLDER_GPUS.md" if maxwell_card(g["arch"]) else "") + ")") if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5: return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model " f"needs {SPLIT_MIN_VRAM_GB} GB or more)") @@ -8886,11 +8902,9 @@ def main() -> int: if OLD_GPUS and a.backend != "hip": warn(f"older NVIDIA GPUs (Pascal / Volta) can be used ({OLD_GPUS}): experimental, through a second engine " "built with CUDA 12 (docs/OLDER_GPUS.md)") - if any(int(g["arch"]) == 52 for g in found): - warn("a Maxwell card (compute capability 5.2) has no fast half-precision path; it was tested by one reporter " - "only, on a source build (-DSTRATA_EXPERIMENTAL_SM60=ON, CUDA 12.x). Check that the answer text reads " - "correctly (docs/OLDER_GPUS.md)") nv_ok = any(gpu_problem(g) is None for g in found) + if not nv_ok and not amd_ok and a.backend != "hip" and maxwell_note(found): # #3218: a warning with the way forward + warn(maxwell_note(found)) hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) if a.backend is None and nv_ok and amd_ok: # both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon) diff --git a/tools/test_setup_older_gpus.py b/tools/test_setup_older_gpus.py index f66d121e..99ec6bcf 100644 --- a/tools/test_setup_older_gpus.py +++ b/tools/test_setup_older_gpus.py @@ -88,24 +88,33 @@ class OptIn(unittest.TestCase): self.assertIn("only kind", setup.old_gpus_opt_in([V100])) self.assertIsNone(setup.old_gpus_opt_in([V100], other=True)) # an AMD card it can use instead self.assertIsNone(setup.old_gpus_opt_in([card(0, "GTX 980", 4.0, "52")])) - # #3218: Maxwell only for a tester who sets STRATA_EXPERIMENTAL_SM52=1 (the default stays unchanged) + # #3218: a Maxwell card is never routed to the CUDA 12 engine (it holds no sm_52 code), with or without a switch m6000 = card(0, "Quadro M6000", 24.0, "52") - self.assertFalse(setup.sm60_card("52")) self.assertTrue(setup.sm60_card("60") and setup.sm60_card("70") and not setup.sm60_card("75")) + self.assertFalse(setup.sm60_card("52")) self.assertIn("not supported", setup.gpu_problem(m6000)) + self.assertIn("Maxwell only runs from a source build", setup.gpu_problem(m6000)) self.assertNotIn("experimental: choose it", setup.gpu_problem(m6000)) - with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM52": "1"}): - self.assertTrue(setup.sm60_card("52")) - self.assertFalse(setup.sm60_card("50")) - self.assertIn("experimental: choose it", setup.gpu_problem(m6000)) - self.assertIn("only kind", setup.old_gpus_opt_in([m6000])) - self.assertIsNone(setup.old_gpus_opt_in([rtx, m6000])) # a newer card keeps winning - self.assertEqual(setup.cuda_choice([52])[0], 12) - with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): - self.assertIsNone(setup.gpu_problem(m6000)) # warned, not refused + self.assertIsNone(setup.old_gpus_opt_in([m6000])) + for env in ({"STRATA_EXPERIMENTAL_SM60": "1"}, {"STRATA_EXPERIMENTAL_SM52": "1"}): + with mock.patch.dict(os.environ, env): + self.assertFalse(setup.sm60_card("52")) + self.assertIn("not supported", setup.gpu_problem(m6000)) + self.assertIsNone(setup.old_gpus_opt_in([m6000])) + self.assertIsNone(setup.old_gpus_opt_in([m6000], named=[0], cuda="12")) # naming it does not admit it either with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): self.assertEqual(setup.old_gpus_opt_in([rtx, v100]), "STRATA_EXPERIMENTAL_SM60=1") + def test_maxwell_note_is_a_warning_with_the_recipe(self): + m6000 = card(0, "Quadro M6000", 24.0, "52") + note = setup.maxwell_note([m6000, {**m6000, "index": 1}]) + self.assertIn("GPU 0 (Quadro M6000), GPU 1 (Quadro M6000)", note) + self.assertIn("-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52", note) + self.assertIn("docs/OLDER_GPUS.md", note) + self.assertNotIn("STRATA_EXPERIMENTAL_SM52", note) # no switch the user has to set + self.assertEqual(setup.maxwell_note([V100, P40]), "") + self.assertEqual(setup.maxwell_note([]), "") + def test_named(self): self.assertEqual(setup.named_gpus(None, "0,2"), [0, 2]) self.assertEqual(setup.named_gpus(1, None), [1]) @@ -212,6 +221,26 @@ class Install(unittest.TestCase): self.assertIn("sm_70 is older than CUDA 13 supports", out) self.assertIn("experimental", out) + def test_a_maxwell_pc_is_warned_with_the_recipe_and_gets_no_engine(self): + """#3218: no ready-made engine holds sm_52 code, so none is installed; the way forward is printed, with or + without any switch (a user never has to set one).""" + m6000 = card(0, "Quadro M6000", 24.0, "52") + for env in (None, {"STRATA_EXPERIMENTAL_SM60": "1"}, {"STRATA_EXPERIMENTAL_SM52": "1"}): + with self.subTest(env=env): + code, out, cfg, calls, libs = self.run_setup(95.0, [m6000], argv_for("qwen", "IQ3_XXS"), env) + self.assertNotEqual(code, 0, out[-3000:]) + self.assertEqual((calls, libs), ([], [])) + self.assertIsNone(cfg) + self.assertIn("Maxwell (compute capability 5.2)", out) + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=52", out) + self.assertIn("docs/OLDER_GPUS.md", out) + + def test_a_maxwell_card_beside_a_newer_one_is_not_a_warning(self): + rtx = card(0, "NVIDIA GeForce RTX 3090", 24.0, "86") + code, out, cfg, calls, _ = self.run_setup(95.0, [rtx, card(1, "GTX 980", 4.0, "52")], argv_for("qwen", "IQ3_XXS")) + self.assertEqual((code, calls), (0, [13]), out[-3000:]) + self.assertNotIn("Maxwell (compute capability", out) + def test_a_p40_with_an_older_driver(self): code, out, cfg, calls, _ = self.run_setup(95.0, [P40], argv_for("qwen", "IQ3_XXS")) self.assertEqual(code, 0, out[-3000:]) # driver 535: enough for CUDA 12 From a3b7d9de3fc16d733f804d001650f494ebb4b753 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:01:50 +0100 Subject: [PATCH 111/177] docs/AMD_HIP.md: a hand-built engine has no hipBLASLt tuning table unless it is pointed at one (#4034) The Build section said nothing about it. gemm.cu (create_hipblaslt_state, own_tuning_dir) takes STRATA_HIPBLASLT_TUNING, else the file /tuning/-hipblaslt-.txt, else plain hipBLAS. The report measured 826 against 1,043 tok/s at 8K prompts on a gfx1151 (one run per arm, stated as such) and the log line that tells whether a table was taken. The extra log line the issue suggests for the no-table case is a small engine change and is not part of this commit. --- docs/AMD_HIP.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 2ff7549e..d858002f 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -193,6 +193,13 @@ the card's name, its architecture and the build's list. - CMake fetches the pinned llama.cpp revision. For an offline build, point `STRATA_GGML_DIR` at a checkout of that exact revision. - Linux engine packages: `VARIANT=rx6000 packaging/build_hip_linux.sh`. +- **A hand-built engine has no tuning table.** The packaged engines carry `tuning/-hipblaslt-.txt` beside the binary + ([Ready-made packages](#ready-made-packages) lists which); a build made with plain `cmake` and started + through `serve/server.py` has none, and the prompt GEMMs fall back to plain hipBLAS. On Strix Halo (gfx1151) that read prompts + 20-25% slower in one report (1,043 against 826 tok/s at 8K, hipBLASLt 1.4.1, a single run per arm, not a paired A/B). Point + `STRATA_HIPBLASLT_TUNING` at the file in `tools/hip/` (`gfx1151-hipblaslt-100401.txt` for hipBLASLt 1.4.1), or copy it into a + `tuning/` folder next to the `strata` binary. The start log then has the line `prefill gemm: hipBLASLt tuning enabled (N rows, + gfx1151, version 100401)`; without it, no table was taken. Run the registered checks with: From 2b13a44933e2b48c4a37f4f650332d1d92def47f Mon Sep 17 00:00:00 2001 From: SanghunYun <45596437+SanghunYun@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:02:48 +0100 Subject: [PATCH 112/177] expert source: STRATA_RAM_ADAPT copies the incoming expert out of its stage buffer when it is still there, and moves up to 4 pairs a layer (#3060) STRATA_RAM_ADAPT (opt-in, --serve, one GPU, needs --adapt-every) lets the resident RAM copy follow the conversation: experts the windows keep routing to take the RAM places of unused experts of their layer. Each move re-read the incoming expert from the file and a layer moved one pair per window, although the incoming expert was usually read for the window before and its blob still sits in that read's stage buffer. What changed: - FileExpertSource::replace_resident_staged(layer, in, out): the same move as replace_resident, with the bytes copied out of the finished stage buffer of `in` (no file read). The copy runs under stage_mu_, so claim_stage cannot give the buffer to another blob meanwhile; it needs a non-busy buffer whose key is `in`, and returns false (nothing changed) otherwise, and the pair then goes the old way. The Foresight hold/unhold around the copy is the one install_resident uses. - generate.cpp: a layer pairs up to 4 of its most routed outside experts with up to 4 of its least routed ones in the copy (outgoing count below 0.5, incoming 2 or more), largest difference first. A pair whose incoming expert is staged moves by copy; `n` now caps only the pairs that need a file read. The log line counts the moves and how many came out of a stage buffer (ram_staged()). - docs/DETAILS.md: the RAM_ADAPT bullet in the low-RAM list in plain words and one row of the measured table (the author's numbers: RTX 3060, IQ2_XS and IQ3_XXS, 120 ShareGPT requests, 3 interleaved runs each). Unset (the default) nothing runs: the block is guarded by ram_adapt_n > 0 as before. The weights moved are byte copies of the same blob; which experts sit in RAM changes, as it already does with RAM_ADAPT, so greedy token ids may differ from run to run once it is on. Changed from the PR: the DETAILS.md hunk was rewritten against the current, shorter bullet. Tests: file_expert_source_test (new staged cases; the positive case needs unbuffered load and is skipped without it). Not covered: no model run. Model gate written down: RTX 3060 ShareGPT replay =8 against =1. --- docs/DETAILS.md | 9 +++++-- include/strata/core/expert_source.hpp | 7 +++++- src/core/expert_source.cpp | 27 ++++++++++++++++++++ src/program/generate.cpp | 34 +++++++++++++++++++------- tests/core/file_expert_source_test.cpp | 22 +++++++++++++++++ 5 files changed, 87 insertions(+), 12 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index a53ede74..a6e35c0b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -238,8 +238,12 @@ When the RAM cannot hold them beside the system (the experts plus about 10 GB), - The adaptive tier (`--adapt-every`) keeps following the conversation in the resident mode. `--adapt-async 1` (opt-in, `--serve`) moves the swaps between decode windows on a helper thread. With `--batch` slots it works between their windows too, but not with `--batch-groups` or `--peer-device`. It is not bit-exact from run to run. -- `STRATA_RAM_ADAPT=` (opt-in, `--serve`, one GPU, needs `--adapt-every`): the RAM copy also follows the conversation, - with up to `n` experts swapped per round. +- `STRATA_RAM_ADAPT=` (opt-in, `--serve`, one GPU, needs `--adapt-every`): the RAM copy also follows the conversation. + A layer swaps up to 4 pairs per window: the experts the windows keep routing to (decayed count 2 or more) take the + RAM places of unused experts of the same layer (count below 0.5), largest difference first. The incoming expert was + usually read for the window before; when its blob still sits in that read's stage buffer it is copied from there and + no file read is made. `n` caps only the pairs that need a file read (`=1` is enough in practice). The log counts how + many experts moved and how many came out of a stage buffer. - Several GPUs: setup recommends one GPU in the low-RAM mode and asks. `--gpus 0,1` shares the model across both cards ([MULTI_GPU.md](MULTI_GPU.md#using-it)). `--yes` keeps one GPU. - With a page-locked copy the GPU also takes its share of the misses over PCIe (`--pcie-frac`). `--pcie-frac 0` (or @@ -1230,6 +1234,7 @@ which about doubled prompt speed on the measured card. | 0.2.0 | RTX PRO 5000 emulating a 12 GB card (`--expert-cache 4448`, Q2_0 GGUF in place, cgroup RAM limit), 3 interleaved pairs | Zero-copy, io prefetch and the decode gate vs 0.1.4x: 32 GB RAM decode 1.70 / 2.56 / 2.88x (story / code / doc8k; 34.0 / 28.0 / 21.7 -> 57.6 / 71.7 / 62.6 tok/s), prompts 1.54 / 1.91x; 16 GB decode 1.16 / 1.25 / 1.25x (the gate stays closed), prompts 1.63 / 1.68x. On a real RTX 3060 12 GB (32 GB cgroup) zero-copy alone gave 1.14 / 1.44 / 1.47x decode | | 0.2.1 | RTX 3060 12 GB, IQ3_XXS `experts.bin` pack (43 GB), `--mmap-experts`, cgroup RAM limit, 5 pairs | io prefetch and the gate: 32 GB decode 1.38x / 1.21x / 1.33x (story / code / doc8k), prompts 4K 1.04x, 20K 1.06x. At 16 GB decode +3..8% but the cold 4K prompt 4-6% slower, so it stays off (room 38%) | | 0.1.43 | RTX 3060 12 GB, 32 GB, Linux, IQ2_XS, 20.5 GiB experts in RAM, v0.1.43 as baseline, 47 frozen Korean requests replayed in fresh engines | `STRATA_RAM_ADAPT`: decode 43.26 -> 50.40 tok/s (+16.5%); file-tier demand reads per generated token 14.15 -> 2.67. One machine, one quantization | +| 0.2.1 (#3060) | RTX 3060 12 GB, 32 GB RAM, Linux NVMe, IQ2_XS and IQ3_XXS read in place, 20.5 GiB of experts in RAM, `--adapt-async 1`, `--spec 3`, fresh engine and dropped page cache per run, 3 interleaved runs | `STRATA_RAM_ADAPT` with the stage-buffer copy and `=1` against `=8` before it, 120 ShareGPT requests: IQ2_XS decode 48.71 -> 51.40 tok/s, prompt 137.4 -> 141.5, storage reads 408 -> 308 GB; IQ3_XXS decode 33.07 -> 38.71, prompt 97.8 -> 104.2, reads 1105 -> 717 GB (off: 37.70 and 23.24 tok/s). `standard-v1`: within noise. One machine; the author's numbers, not yet repeated here | | 0.1.45.3 | RTX 3060 12 GB, IQ2_XS, 20 GiB of experts in RAM, cgroup 34 GB, SATA emulated at 450 MB/s, 5 pairs | Prompt-chunk planner `8192 -> 3840`: 4,101 tokens 138.1 vs 138.2 tok/s (one chunk either way); 20,400 tokens 334.0 -> 822.3 tok/s (2.46x, drive read 26.1 -> 2.7 GB, decode after 25.4 -> 42.6); 28,887 tokens 418.8 -> 910.4 (2.17x). With a real NVMe and a 32 GB cap it picks 8192 again | | 2026-10-11 reports | RTX 3090 + Ryzen 5 5600X | `--adapt-async 1` on the arena: x1.07-1.11 decode, 12 of 12 prompts faster ([report](../bench/results/2026-10-11-community-rtx3090-5600x-arena-async/README.md)). `STRATA_PIN_BY_NEED=1`: prompt read +5-7% at 56K-117K tokens ([report](../bench/results/2026-10-11-community-rtx3090-5600x-arena-pin-by-need/README.md)) | | 2026-10-11 report | RTX 5090 / Ryzen 9 9950X, paired 4K three-prompt test | `STRATA_ADAPT_CALLBACK_WARMUP`: 142.82 -> 207.75 tok/s ([report](../bench/results/2026-10-11-rtx-5090-callback-affinity/README.md)) | diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 3ab77dc2..2ca36784 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -819,7 +819,11 @@ public: /// windows, with no adaptive round in flight. A failed read leaves the copy as it was. Not with /// STRATA_EXCHANGE_ROTATE (false, nothing changes). bool replace_resident(int64_t layer, int64_t in, int64_t out); + /// STRATA_RAM_ADAPT: the same move as replace_resident, but `in` is copied out of the finished stage buffer + /// a demand read left it in (no file read). False, nothing changed, when `in` is not staged or still filling. + bool replace_resident_staged(int64_t layer, int64_t in, int64_t out); int64_t ram_adapts() const { return ram_adapts_; } + int64_t ram_staged() const { return ram_staged_; } ///< of ram_adapts(): copied out of a stage buffer // ---- 149-prefetch (STRATA_RAM_ADAPT2): the same promotion, staged. `ram_stage` queues the read of `in` on an I/O thread // (false: already queued, the queue is full, or no compact copy); `ram_install` - called by the decode thread at a window // boundary, when no window reads the RAM copy - puts every read that has landed into `out`'s place, unless the GPU tier @@ -1106,7 +1110,8 @@ private: std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; - int64_t ram_adapts_ = 0; ///< replace_resident: experts moved from the file into the compact copy + int64_t ram_adapts_ = 0; ///< replace_resident(_staged): experts moved into the compact copy + int64_t ram_staged_ = 0; ///< replace_resident_staged: of those, copied out of a stage buffer std::vector ram_adapt_buf_; ///< ...one blob, read here before it replaces another // 149-prefetch: the staged promotions (ram_stage / ram_install) struct RamJob { int64_t layer, in, out; std::vector buf; int state; }; ///< state 0 queued, 1 reading, 2 landed, 3 failed diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index b8ad8fb4..d0ce8bbb 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -4341,6 +4341,33 @@ bool FileExpertSource::replace_resident(int64_t layer, int64_t in, int64_t out) return install_resident(layer, in, out, ram_adapt_buf_.data()); } +bool FileExpertSource::replace_resident_staged(int64_t layer, int64_t in, int64_t out) { + if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_.active() || !staged_.empty() || + layer < 0 || layer >= n_layers_ || in < 0 || out < 0 || in >= n_expert_ || out >= n_expert_ || in == out) + return false; + const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in; + const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out; + if (i_in >= complement_offsets_.size() || i_out >= complement_offsets_.size()) return false; + if (!override_.empty() && (override_[i_in] != nullptr || override_[i_out] != nullptr)) return false; + const uint64_t at = complement_offsets_[i_out], bytes = layer_blob_bytes_[(size_t) layer]; + if (at == kNoComplement || complement_offsets_[i_in] != kNoComplement || at > complement_bytes_ || + bytes > complement_bytes_ - at || bytes > stage_blob_) return false; + ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire); + bool moved = false; + { + // held across the copy: claim_stage cannot hand the buffer to another blob meanwhile + std::lock_guard lk(stage_mu_); + const auto it = stage_of_.find((int64_t) i_in); + if (it == stage_of_.end() || stage_busy_[it->second] || stage_key_[it->second] != (int64_t) i_in) return false; + if (fs != nullptr) fs->hold(layer, (int32_t) out); + std::memcpy((uint8_t*) complement_host_ + (size_t) at, stage_buf_[it->second].get(), (size_t) bytes); + moved = detail::exchange_cache_complement(complement_offsets_, i_out, i_in); + if (fs != nullptr) fs->unhold(layer, (int32_t) out); + } + if (moved) { ++ram_adapts_; ++ram_staged_; } + return moved; +} + // `in`'s bytes (src) into `out`'s place of the compact copy, and the two offsets swapped - the checks again, as the caller // may have read `src` a while ago (149-prefetch: ram_install) bool FileExpertSource::install_resident(int64_t layer, int64_t in, int64_t out, const uint8_t* src) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 4ce6a3dc..a57ea871 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -15344,25 +15344,40 @@ int main(int argc, char** argv) { if (ram_adapt_n > 0 && !first_window && !drive.d.usage.empty() && pending.empty() && (!ajob || astate == AState::Idle) && src.complement_ready() && !multi_gpu && !peer.valid() && !remote_opt && o.batch == 0) { + // up to kRamAdaptPerLayer pairs a layer: the layer's most routed experts outside the copy against its least + // routed ones in it, paired in that order while the outgoing one is still unused constexpr float kRamAdaptRouted = 2.0f, kRamAdaptUnused = 0.5f; + constexpr size_t kRamAdaptPerLayer = 4; struct RamSwap { float gain; int32_t layer, in, out; }; std::vector swaps; + std::vector ins, outs; for (int64_t l = 0; l < g.n_layers; ++l) { const float* u = drive.d.usage.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; - int32_t in = -1, out = -1; + ins.clear(); + outs.clear(); for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { if (r[e] >= 0) continue; // in VRAM: the RAM copy does not hold it - if (src.has_resident(l, e)) { if (out < 0 || u[e] < u[out]) out = e; } - else if (u[e] >= kRamAdaptRouted && (in < 0 || u[e] > u[in])) in = e; + if (src.has_resident(l, e)) outs.push_back(e); + else if (u[e] >= kRamAdaptRouted) ins.push_back(e); } - if (in >= 0 && out >= 0 && u[out] < kRamAdaptUnused) - swaps.push_back({u[in] - u[out], (int32_t) l, in, out}); + const size_t ni = std::min(ins.size(), kRamAdaptPerLayer), no = std::min(outs.size(), kRamAdaptPerLayer); + std::partial_sort(ins.begin(), ins.begin() + (std::ptrdiff_t) ni, ins.end(), + [&](int32_t a, int32_t b) { return u[a] > u[b]; }); + std::partial_sort(outs.begin(), outs.begin() + (std::ptrdiff_t) no, outs.end(), + [&](int32_t a, int32_t b) { return u[a] < u[b]; }); + for (size_t i = 0; i < ni && i < no && u[outs[i]] < kRamAdaptUnused; ++i) + swaps.push_back({u[ins[i]] - u[outs[i]], (int32_t) l, ins[i], outs[i]}); } std::sort(swaps.begin(), swaps.end(), [](const RamSwap& a, const RamSwap& b) { return a.gain > b.gain; }); - if ((int) swaps.size() > ram_adapt_n) swaps.resize((size_t) ram_adapt_n); - for (const RamSwap& x : swaps) src.replace_resident(x.layer, x.in, x.out); + // the incoming expert was usually just read for the window before: a pair whose `in` still sits in that + // read's stage buffer moves with a copy out of it (no file read); n caps only the pairs that need the file read + int file_left = ram_adapt_n; + for (const RamSwap& x : swaps) { + if (src.replace_resident_staged(x.layer, x.in, x.out)) continue; + if (file_left > 0) { --file_left; src.replace_resident(x.layer, x.in, x.out); } + } } if (!adapt_tick(false)) { // --adapt-async: the round in flight moves on a step when it can std::printf("ERR an adaptive refill failed\n"); @@ -15881,8 +15896,9 @@ int main(int argc, char** argv) { (long long) src.ram_staged_reads(), (long long) ram_adapt2.installed, (long long) (src.ram_install_skips() + src.ram_install_gpu()), (long long) src.ram_install_gpu()); if (src.ram_adapts() > 0) // STRATA_RAM_ADAPT, cumulative - std::fprintf(stderr, "strata serve: resident RAM: %lld experts moved in from the file in place of " - "unused ones (STRATA_RAM_ADAPT)\n", (long long) src.ram_adapts()); + std::fprintf(stderr, "strata serve: resident RAM: %lld experts moved in in place of unused ones, %lld of " + "them out of a stage buffer (STRATA_RAM_ADAPT)\n", (long long) src.ram_adapts(), + (long long) src.ram_staged()); if (ajob) // --adapt-async, cumulative (a round may still be in flight: it lands before the next request) std::fprintf(stderr, "strata serve: asynchronous adaptive tier: %lld rounds, %lld experts swapped in, " "%.1f ms per round (start to flip, between windows)", diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index e162664d..d6a274f1 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -979,6 +979,28 @@ void test_replace_resident(bool pin) { require(src.commit_exchanges() == 1 && src.has_resident(0, 3) && holds(3) && !src.has_resident(0, 1), "exchange after replace wrong"); require(src.ram_adapts() == 2, "accounting wrong"); + // a staged incoming blob: RAM {2,3}, VRAM {0,1}, 4 on the file tier + require(!src.replace_resident_staged(0, 4, 3) && src.has_resident(0, 3) && src.ram_adapts() == 2, + "an unstaged expert moved"); + std::string why; + set_env("STRATA_UNBUFFERED_LOAD", "1"); + const bool unbuffered = src.set_unbuffered(0, why); + set_env("STRATA_UNBUFFERED_LOAD", nullptr); + if (unbuffered && src.stages_blobs()) { + require(!src.replace_resident_staged(0, 4, 3) && holds(3), "moved before any demand read"); + require(!src.has_resident(0, 4) && holds(4), "demand read wrong"); // leaves 4 in a stage buffer + require(!src.replace_resident_staged(0, 4, 0) && !src.replace_resident_staged(0, 2, 3), + "invalid staged pair accepted"); + require(src.replace_resident_staged(0, 4, 3) && src.has_resident(0, 4) && !src.has_resident(0, 3), + "staged replacement residency wrong"); + require(src.resident_blob(0, 4) != nullptr && !std::memcmp(src.resident_blob(0, 4), truth[4].data(), bytes), + "staged replacement bytes wrong"); + require(holds(2) && holds(3) && src.ram_adapts() == 3 && src.ram_staged() == 1, + "staged replacement changed another expert"); + std::cout << "replace_resident_staged: pinned=" << pin << " exact_bytes=PASS\n"; + } else { + std::cout << "replace_resident_staged: pinned=" << pin << " unbuffered unavailable here (" << why << "), positive case SKIPPED\n"; + } std::cout << "replace_resident: pinned=" << pin << " exact_bytes=PASS\n"; } From 557aad026554ba3d7005c0518eaae292e9a3af7f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:03:30 +0100 Subject: [PATCH 113/177] hip- is accepted wherever the backend is named (#4013) STRATA_ENGINE_BACKEND=hip-rdna2 worked for strata update (updater.detect_hardware), but strata update --backend hip-rdna2 offered no package and strata launch stopped with "STRATA_ENGINE_BACKEND='hip-rdna2' is not one of cpu, cuda, hip, metal, sycl". engine_component.split_backend reads hip- as the hip family and its package; detect_backend (the start path), detect_hardware and update --backend all use it. Any other name is checked as before. Tests in tests/terminal/test_gfx_selection.py. --- strata_cli/update_cmd.py | 4 ++- strata_control/engine_component.py | 11 +++++++- strata_control/updater.py | 7 ++--- tests/terminal/test_gfx_selection.py | 41 ++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/strata_cli/update_cmd.py b/strata_cli/update_cmd.py index cfe05e4f..196d5eaa 100644 --- a/strata_cli/update_cmd.py +++ b/strata_cli/update_cmd.py @@ -186,7 +186,9 @@ def run(a) -> int: try: hardware = updater.detect_hardware() if a.backend: - hardware["backend"] = a.backend + hardware["backend"], variant = ec.split_backend(a.backend) # --backend hip-rdna2 = the hip family, the rdna2 package (#4013) + if variant: + hardware["variant_wanted"] = variant hardware["backend_source"] = "requested" # the person's own decision: the make guard lets it through lines: list = [] cancel = threading.Event() diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py index c7f60e0b..94f8d0f7 100644 --- a/strata_control/engine_component.py +++ b/strata_control/engine_component.py @@ -436,11 +436,20 @@ def runtime_version() -> str | None: # ----------------------------------------------------------------------------------------------- the GPU +def split_backend(value) -> tuple[str, str]: + """(backend, variant) for a name the person typed: "hip-rdna2" is the hip family and its rdna2 package (the way the feed labels an AMD + package, #4013), "hip" is the family alone, any other name is returned as it is with no variant.""" + name = str(value or "").strip().lower() + if name not in BACKEND_MATRIX and name.startswith("hip-") and len(name) > 4: + return "hip", name[4:] + return name, "" + + def detect_backend(environ=None) -> tuple[str | None, str]: """(backend, how) for this machine: the engine family its GPU needs. Bounded, read-only probes of tools that are already installed; ``STRATA_ENGINE_BACKEND`` overrides (the tests and the support desk use it).""" environ = os.environ if environ is None else environ - forced = environ.get(ENV_BACKEND, "").strip().lower() + forced = split_backend(environ.get(ENV_BACKEND, ""))[0] # "hip-rdna2" starts the hip family (the package choice reads the variant) if forced: if forced not in BACKEND_MATRIX: raise ComponentProblem(f"{ENV_BACKEND}={forced!r} is not one of {', '.join(sorted(BACKEND_MATRIX))}") diff --git a/strata_control/updater.py b/strata_control/updater.py index 30f226ac..995e0c64 100644 --- a/strata_control/updater.py +++ b/strata_control/updater.py @@ -258,11 +258,10 @@ def detect_hardware(environ=None) -> dict: selection treats as "cannot tell", never as a refusal.""" environ = os.environ if environ is None else environ prefer = "" - forced = str(environ.get(ec.ENV_BACKEND, "")).strip().lower() - if forced.startswith("hip-") and forced not in ec.BACKEND_MATRIX: + family, prefer = ec.split_backend(environ.get(ec.ENV_BACKEND, "")) + if prefer: # "hip-rx9070" is how the feed labels a package; accept it as "the hip family, this variant" - prefer = forced[4:] - environ = {**environ, ec.ENV_BACKEND: "hip"} + environ = {**environ, ec.ENV_BACKEND: family} backend, how = ec.detect_backend(environ) hw = {"platform": host_platform(), "backend": backend, "backend_source": how, "runtime": ec.runtime_version(), "nvidia_driver": None, "cuda_archs": [], "gfx": [], "gpu_names": [], "variant_wanted": prefer, diff --git a/tests/terminal/test_gfx_selection.py b/tests/terminal/test_gfx_selection.py index e02ef41f..451ec42f 100644 --- a/tests/terminal/test_gfx_selection.py +++ b/tests/terminal/test_gfx_selection.py @@ -91,5 +91,46 @@ class Detection(unittest.TestCase): self.assertEqual((got["backend"], got["variant_wanted"]), ("hip", "rx9070")) +class FeedStyleBackendName(unittest.TestCase): + """#4013: `hip-` named the AMD package for `strata update` through STRATA_ENGINE_BACKEND only. As `--backend` it offered nothing, + and `strata launch` stopped with "STRATA_ENGINE_BACKEND='hip-rdna2' is not one of cpu, cuda, hip, metal, sycl".""" + + def test_split_backend(self): + self.assertEqual(ec.split_backend("hip-rdna2"), ("hip", "rdna2")) + self.assertEqual(ec.split_backend(" HIP-RX9070 "), ("hip", "rx9070")) + self.assertEqual(ec.split_backend("hip"), ("hip", "")) + self.assertEqual(ec.split_backend("cuda"), ("cuda", "")) + self.assertEqual(ec.split_backend("hip-"), ("hip-", "")) + self.assertEqual(ec.split_backend("cuda-13"), ("cuda-13", "")) # only the AMD family has package names + self.assertEqual(ec.split_backend(None), ("", "")) + + def test_the_engine_start_takes_the_package_name_as_the_hip_family(self): + self.assertEqual(ec.detect_backend({ec.ENV_BACKEND: "hip-rdna2"}), ("hip", "environment")) + with self.assertRaisesRegex(ec.ComponentProblem, "is not one of"): + ec.detect_backend({ec.ENV_BACKEND: "cuda-13"}) + + def test_update_backend_option_takes_it_too(self): + import argparse + from strata_cli import update_cmd + seen = {} + + class Stop(Exception): + pass + + def context(**kw): + seen.update(kw["hardware"]) + raise Stop + + args = argparse.Namespace(components_dir="C:/nowhere", backend="hip-rdna2", output="json", model_config=None, wait=0, force=False, + app_version=None, check=True, feed=None, no_control=True, yes=True, components_command=None) + base = {"platform": WIN, "backend": "hip", "backend_source": "display adapters", "variant_wanted": ""} + with mock.patch.object(updater, "detect_hardware", return_value=dict(base)), mock.patch.object(updater, "Context", context): + try: + update_cmd.run(args) + except Stop: + pass + self.assertEqual((seen.get("backend"), seen.get("variant_wanted"), seen.get("backend_source")), ("hip", "rdna2", "requested")) + + if __name__ == "__main__": unittest.main() From a3bb38ec4511edb999fda6b71fa8c8c3411ba2cb Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:03:48 +0100 Subject: [PATCH 114/177] batch-groups: opt-in adaptive-tier rounds in the pipelined loop, STRATA_PIPE_ADAPT_EVERY (#4010) With --batch-groups above 1 on a layer split the pipelined batch loop never starts a round of the adaptive VRAM tier (the serial batch windows start one every --adapt-every windows). While the slots are busy the tier only moves when they go back to the solo path, so a fresh engine keeps its start-up profile for minutes. STRATA_PIPE_ADAPT_EVERY=N (opt-in; unset, 0 or not a number is off): after N group windows pump starts no new group on the first stage, lets the groups in flight finish, then runs one round as batch_step does between serial windows, adapt() and apply_pending(true), so nothing in flight reads a cache slot while experts swap and the new experts have landed before the next launch. Not while a prompt is read beside the slots (in_prompt_read, its loan of cache slots), not with --adapt-async, not while the last round's copies are in flight, not with the tier off. The rule is two pure functions in include/strata/program/batch_groups.hpp (pipe_adapt_every, pipe_adapt_due) with 12 new cases in batch_groups_test. With the switch set the engine says so once at start and the "strata batch (pipelined ...)" line adds the rounds, the experts swapped in and the time spent. docs/BATCHING.md documents the switch with the author's table (2x RTX 5090, six streams, 309 to 410 rows/s over eight bursts after a fresh start, two engines per setting). Reviewed: unset costs one counter increment per group window and one false check where a group starts, and prints no new line. A due round cannot wait forever: no new group starts, the groups in flight finish, then the round runs. A prompt read sets in_prompt_read before the reader thread starts (including STRATA_PIPED_CONCURRENT) and clears it after the reader joined; the drain after the read runs the round if it is due. Tests: batch_groups_test (the new cases). Not covered and still the author's to show (the PR is a draft): a soak with prompts read beside the slots, a Linux run, another GPU pair, more than two stages, and exactness settings with the switch set. The model gate is written down. --- docs/BATCHING.md | 28 ++++++++++++- include/strata/program/batch_groups.hpp | 30 +++++++++++++ src/program/batch_groups_test.cpp | 39 ++++++++++++++++- src/program/generate.cpp | 56 +++++++++++++++++++++++-- 4 files changed, 148 insertions(+), 5 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 6e7b58d3..ac214105 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -363,7 +363,32 @@ between decoding windows (the prompt may hold a loan of cache slots). The `strat GPU-reach wait and pool time, and how many routed entries the VRAM tier, the PCIe share and the CPU served per window. Swaps move experts between the GPU and the CPU, which round differently, so greedy outputs can differ from run to run; `--adapt-every 1000000` keeps the tier fixed (as in the exactness settings below). The pipelined `--batch-groups` path -does not adapt. +does not adapt by default: its windows count the routing, but no round starts while groups are in flight, so the tier +moves only when the slots go back to the solo path. + +`STRATA_PIPE_ADAPT_EVERY=N` (opt-in; unset or 0 keeps the old behaviour) lets the pipelined path adapt: after N group +windows it starts no new group, lets the groups in flight finish, runs one round as the serial batch loop does (nothing +in flight reads a cache slot, and the swapped-in experts land before the next launch), and goes on. It stands still while +a prompt is read beside the slots, and does nothing with `--adapt-async 1`. The engine says so at start, and the +`strata batch (pipelined ...)` line adds the rounds, the experts swapped in and the time spent. Measured on 2x RTX 5090 +(layer split 25, Swift-Qwen3.8-Flash-Next IQ3_S, `--batch 6 --batch-groups 2`, resident experts, a profile-filled cache, +`--adapt-every 16`), six streams of 1,024 greedy tokens from `tools/serve_load.py`, the engine's rows/s of eight bursts +right after start, two fresh engines per setting: + +| `STRATA_PIPE_ADAPT_EVERY` | bursts 1-8, rows/s | mean | experts swapped before burst 8 | +| --- | --- | ---: | ---: | +| unset (stock 0.2.4.1) | 246, 257, 291, 292, 335, 338, 356, 355 | 309 | 287 | +| unset (this branch) | 249, 242, 297, 296, 333, 336, 372, 362 | 311 | 288 | +| 128 | 363, 415, 414, 420, 420, 411, 415, 420 | 410 | 6,181 | +| 128 | 359, 407, 416, 422, 419, 417, 404, 411 | 407 | 6,294 | +| 32 | 375, 405, 408, 405, 409, 390, 405, 409 | 402 | 5,957 | +| 32 | 384, 414, 404, 402, 401, 412, 406, 401 | 403 | 5,678 | + +Without it the tier swaps 96 experts every burst or two (only when a burst ends) and the engine was still speeding up +after eight bursts; with 128 it reached about 415 rows/s from the second burst, the speed an engine without the switch +showed only after thousands of swaps had come from other traffic. 32 empties the pipeline four times as often and ends a +little lower. One machine, one model and one configuration; not measured on one GPU (no pipelined path there) or with +more than two stages. With `--adapt-async 1` (needs the resident RAM mode) the round does not hold a window up: each batch window moves the round on one step (table changes and uploads on the main thread, the copies on a helper thread and the cards' refill @@ -430,6 +455,7 @@ counter-based draw (Philox(seed, position)). boundary, and not for pictures. - Admissions are one at a time: two new long prompts are read one after the other. - `--batch-groups` needs every stage on its own GPU. A pipelined slot is a conversation cache again (0.1.41): a request left alone in its slot goes back to the solo path with its drafts, as on one GPU. +- The pipelined `--batch-groups` path adapts the VRAM tier only with `STRATA_PIPE_ADAPT_EVERY` (above). - The slot sessions take VRAM (above) and, with KV streaming, pinned RAM. ## Measured diff --git a/include/strata/program/batch_groups.hpp b/include/strata/program/batch_groups.hpp index b1e3f32c..0b80fff1 100644 --- a/include/strata/program/batch_groups.hpp +++ b/include/strata/program/batch_groups.hpp @@ -10,11 +10,41 @@ // the serial windows with the slots' drafts (the 0.1.42/0.1.43 behaviour). A number or `auto` given on the command line // is honoured as before. // +// The pipelined path starts no round of the adaptive VRAM tier on its own (the serial batch windows start one every +// `--adapt-every` windows): opt-in, STRATA_PIPE_ADAPT_EVERY=N lets it run one after every N group windows, once the groups +// in flight have finished (pipe_adapt_every / pipe_adapt_due below). +// // Pure (no GPU, no environment read): generate.cpp passes in what it knows. #pragma once +#include + namespace strata::program::batch_groups { +/// STRATA_PIPE_ADAPT_EVERY's value -> the interval in group windows; 0 (off: the pipelined path adapts nothing, as before) +/// when unset, empty, not a number, 0 or negative. +inline int pipe_adapt_every(const char* value) { + if (value == nullptr) return 0; + const int n = std::atoi(value); + return n > 0 ? n : 0; +} + +/// What the pipelined loop knows when it decides on a round. +struct PipeAdapt { + int every = 0; ///< pipe_adapt_every() + bool tier_on = false; ///< the adaptive tier counts the routing here (it is on and not the whole model) + bool async_tier = false; ///< --adapt-async 1 runs its own rounds + bool prompt_read = false; ///< a prompt is read beside the slots (it may hold a loan of cache slots) + bool swaps_pending = false; ///< the last round's copies have not landed yet + long long windows = 0; ///< group windows completed so far + long long last = 0; ///< `windows` when the last round ran +}; + +/// A round is due: the loop starts no new group, and runs the round once nothing is in flight. +inline bool pipe_adapt_due(const PipeAdapt& p) { + return p.every > 0 && p.tier_on && !p.async_tier && !p.prompt_read && !p.swaps_pending && p.windows - p.last >= p.every; +} + /// What kept `auto` from pipelining. enum class Serial { None, BatchMtp, AdaptAsync, TwoCardsSerialFaster }; diff --git a/src/program/batch_groups_test.cpp b/src/program/batch_groups_test.cpp index 5debcd29..037defe6 100644 --- a/src/program/batch_groups_test.cpp +++ b/src/program/batch_groups_test.cpp @@ -4,7 +4,9 @@ // 2. a layer split with --batch >= 2 and no --batch-groups means `auto` (0.1.41); // 3. --batch-mtp (or --adapt-async 1) turns that default into one group, and says which feature did it; // 4. a number or `auto` given explicitly is honoured, with or without those features; -// 5. no layer split: the number given (1) stays. +// 5. no layer split: the number given (1) stays; +// 6. STRATA_PIPE_ADAPT_EVERY: off unless a positive number; a round is due after N group windows, never with the tier +// off, beside --adapt-async, while a prompt is read or while the last round's copies are in flight. #include "strata/program/batch_groups.hpp" #include @@ -126,6 +128,41 @@ int main() { check(bg::resolve(i).groups == 2, "an explicit number without a split is returned (the engine warns)"); } + // STRATA_PIPE_ADAPT_EVERY + check(bg::pipe_adapt_every(nullptr) == 0 && bg::pipe_adapt_every("") == 0 && bg::pipe_adapt_every("0") == 0, + "pipe adapt: unset, empty or 0 is off"); + check(bg::pipe_adapt_every("-5") == 0 && bg::pipe_adapt_every("off") == 0, "pipe adapt: negative or not a number is off"); + check(bg::pipe_adapt_every("128") == 128 && bg::pipe_adapt_every("1") == 1, "pipe adapt: a positive number is the interval"); + { + bg::PipeAdapt p; + p.every = 128; + p.tier_on = true; + p.windows = 127; + check(!bg::pipe_adapt_due(p), "pipe adapt: not before N group windows"); + p.windows = 128; + check(bg::pipe_adapt_due(p), "pipe adapt: due after N group windows"); + p.last = 128; + p.windows = 200; + check(!bg::pipe_adapt_due(p), "pipe adapt: counted again from the last round"); + p.windows = 256; + check(bg::pipe_adapt_due(p), "pipe adapt: due N windows after the last round"); + bg::PipeAdapt q = p; + q.every = 0; + check(!bg::pipe_adapt_due(q), "pipe adapt: never when off"); + q = p; + q.tier_on = false; + check(!bg::pipe_adapt_due(q), "pipe adapt: never with the adaptive tier off"); + q = p; + q.async_tier = true; + check(!bg::pipe_adapt_due(q), "pipe adapt: never beside --adapt-async 1"); + q = p; + q.prompt_read = true; + check(!bg::pipe_adapt_due(q), "pipe adapt: never while a prompt is read beside the slots"); + q = p; + q.swaps_pending = true; + check(!bg::pipe_adapt_due(q), "pipe adapt: never while the last round's copies are in flight"); + } + std::printf("%s\n", g_fail == 0 ? "batch_groups_test: all passed" : "batch_groups_test: FAILED"); return g_fail == 0 ? 0 : 1; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a57ea871..0d4f4fc2 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8223,6 +8223,15 @@ int main(int argc, char** argv) { : nullptr; if (why != nullptr) adapt_async_off(why); } + // STRATA_PIPE_ADAPT_EVERY (batch_groups.hpp; the rounds run in the pipelined loop below): said once here, with the + // other start-up lines, before READY + if (o.serve && o.batch > 0 && o.batch_groups > 1 && multi_gpu) { + const int every = strata::program::batch_groups::pipe_adapt_every(std::getenv("STRATA_PIPE_ADAPT_EVERY")); + if (every > 0) + std::fprintf(stderr, "strata batch: STRATA_PIPE_ADAPT_EVERY=%d: the pipelined groups run an adaptive-tier round " + "every %d group windows (the pipeline empties for it)%s\n", every, every, + o.adapt_every <= 0 || o.adapt_swaps <= 0 ? " - but the adaptive tier is off" : ""); + } // #340 / STRATA_SPLIT_RING: a layer split's streamed-ring override, decided from the stage caches' residency. It // has to be in place BEFORE the split's lend regions are sized (Prefill::bytes_needed counts the ring): they were // sized with the default ring and the override applied afterwards, so a ring of 384 borrowed 5396 slots and the RAM @@ -12037,6 +12046,28 @@ int main(int argc, char** argv) { std::mutex bell_mu; std::condition_variable bell_cv; std::atomic bell_waiting{false}; + // STRATA_PIPE_ADAPT_EVERY=N (opt-in; unset or 0: off, as before): the pipelined groups start no adaptive-tier round + // of their own (batch_step starts one every --adapt-every windows; pump below never does), so under steady parallel + // load the VRAM tier only moves when the slots go back to the solo path, and a fresh engine keeps its start-up + // profile for minutes. With N > 0, after N group windows the pipeline starts no new group, lets the ones in flight + // finish, and runs one round there as batch_step runs it between serial windows (nothing in flight reads a cache + // slot; the swapped-in experts land before the next launch), then goes on. Never while a prompt is read beside + // the slots (its loan of cache slots), nor with --adapt-async (its own ticks). + // (the rule: batch_groups.hpp pipe_adapt_every / pipe_adapt_due, tested in batch_groups_test) + const int pipe_adapt_every = strata::program::batch_groups::pipe_adapt_every(std::getenv("STRATA_PIPE_ADAPT_EVERY")); + int64_t pa_windows = 0, pa_last = 0, pa_rounds = 0, pa_swaps = 0; + double pa_ms = 0; + auto pa_due = [&] { + strata::program::batch_groups::PipeAdapt p; + p.every = pipe_adapt_every; + p.tier_on = !drive.d.usage.empty(); + p.async_tier = (bool) ajob; + p.prompt_read = in_prompt_read; + p.swaps_pending = !pending.empty(); + p.windows = pa_windows; + p.last = pa_last; + return strata::program::batch_groups::pipe_adapt_due(p); + }; // one turn: serve every running stage, hand finished groups on, start what can start auto pump = [&](bool may_start) -> bool { ++pipe_tick; @@ -12102,6 +12133,7 @@ int main(int argc, char** argv) { rows_wait = nullptr; } ++bt_windows; + ++pa_windows; G.inflight = false; report_batch_window(G.S, G.active, !pipe_inflight() && !batch_on(), G.started); } @@ -12116,7 +12148,7 @@ int main(int argc, char** argv) { pick = gi; if (pick < 0) continue; } else { - if (!may_start) continue; + if (!may_start || pa_due()) continue; // STRATA_PIPE_ADAPT_EVERY: a round is due, the pipeline empties first for (int j = 0; j < (int) pg.size() && pick < 0; ++j) { const int gi = (int) ((rr + j) % (int64_t) pg.size()); if (!pg[(size_t) gi].inflight && group_active(gi)) pick = gi; @@ -12165,6 +12197,18 @@ int main(int argc, char** argv) { } } if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; } + if (pa_due() && !pipe_inflight()) { // STRATA_PIPE_ADAPT_EVERY: the pipeline is empty - one round, as batch_step + const Clock::time_point ta = Clock::now(); + pa_last = pa_windows; + if (!adapt()) { + std::printf("ERR an adaptive refill failed\n"); + return false; + } + ++pa_rounds; + pa_swaps += (int64_t) pending.size(); + apply_pending(true); // the copies land and the tables follow (the next launch plans from them) + pa_ms += std::chrono::duration(Clock::now() - ta).count(); + } if (batch_telemetry_enabled) { const auto sample = stage_in_flight.sample(Clock::now(), !pipe_inflight() && !batch_on()); if (sample) { @@ -12176,9 +12220,15 @@ int main(int argc, char** argv) { } if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step const double w = (double) bt_windows, wall = std::chrono::duration(Clock::now() - bt_start).count(); + char pa_txt[160] = ""; + if (pipe_adapt_every > 0) + std::snprintf(pa_txt, sizeof pa_txt, "; adaptive tier (STRATA_PIPE_ADAPT_EVERY): %lld rounds, %lld experts " + "swapped in, %.0f ms", (long long) pa_rounds, (long long) pa_swaps, pa_ms); std::fprintf(stderr, "strata batch (pipelined, %d groups of %d): %lld group-steps, %lld rows in %.0f ms = " - "%.1f rows/s (admissions included)\n", o.batch_groups, GS, (long long) bt_windows, - (long long) bt_rows, wall, 1000.0 * bt_rows / std::max(wall, 1e-9)); + "%.1f rows/s (admissions included)%s\n", o.batch_groups, GS, (long long) bt_windows, + (long long) bt_rows, wall, 1000.0 * bt_rows / std::max(wall, 1e-9), pa_txt); + pa_rounds = pa_swaps = 0; + pa_ms = 0; for (int k = 0; k < n_pipe; ++k) { const std::string pr = stage_verifier(k).profile_report(); if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str()); From 2299c8f70a28ed0d96e2e39b5f0348bb4c72475f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:07:23 +0100 Subject: [PATCH 115/177] native_mmvq: sm_89 MMVQ-IL tables opt-in with STRATA_MMVQ_IL_89=1 (#3453) Review of the first port: it registered kIlRows_89 / kIl1Rows_89 for every compute capability 8.9 card by default. Bit-identity of an interleaved-kernel choice to native_mmvq is a property of the compiled code, and the release engine builds its own sm_89 cubin that no card of ours can run; the issue also saw no end-to-end decode change on a 4090 or a 4080, and the 4070 and 4080 runs agree in 53 of the 75 cells of the 2-4 column table (33 of them non-zero). So the default change has no measured benefit and an unproven bitwise claim on the card it changes. Change: sm_89 answers the shared table, with no one-column row, exactly as before, unless STRATA_MMVQ_IL_89=1 is set (read once, like the neighbouring switches). With it set the cells from the two community runs apply. Nothing else in the lookup changes; sm_86, sm_120 and the others are untouched. Why it is bitwise: native_mmvq_il_kernel keeps a separate accumulator set per row (acc[v][i][c]) and sums each row over the same chunk order and the same warp_sum, so the rows-a-warp count R only changes how many rows a warp walks, not the order of any row's float additions; the plain-versus-interleaved equality is what mmvq_il_parity measures (memcmp against native_mmvq for rows 1/2/4, T 1-8, odd row counts). That test passes on sm_86; it has not run on an Ada card. Tests: mmvq_il_parity now checks the unset behaviour (sm_89 equals the shared table, Q3_K and the one-column row answer 0) or, with STRATA_MMVQ_IL_89=1, the 4070/4080 agreement. A second ctest, mmvq_il_parity_89table, runs the table check with the switch set and no kernel case. On z440 (2x RTX A4000, sm_86, CUDA 13.0, gpu lock): mmvq_il_parity and mmvq_il_parity_89table both pass, and the binary prints "mmvq_il_parity: OK (every case, T 1-8, rows 1/2/4 and the table, bitwise)" with the switch unset and set. Model gate owed on an sm_89 card: phaseA-tests/gh027/gates/3453-sm89-il.sh (mmvq_il_parity on the card, then identity of the answers with the switch on, then a speed A/B that decides whether the default flips). Co-authored-by: rodi4eg <160655730+rodi4eg@users.noreply.github.com> --- CMakeLists.txt | 3 +++ docs/MMVQ_IL_TABLE.md | 2 +- src/kernels/cuda/native_mmvq.cu | 10 +++++++--- src/kernels/mmvq_il_parity.cpp | 16 +++++++++++----- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6356e27b..ed296bab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1111,6 +1111,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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) + # sm_89's opt-in tables (#3453, STRATA_MMVQ_IL_89=1): the table check only (no case matches MMVQ_IL_ONLY) + add_test(NAME mmvq_il_parity_89table COMMAND mmvq_il_parity) + set_tests_properties(mmvq_il_parity_89table PROPERTIES ENVIRONMENT "STRATA_MMVQ_IL_89=1;MMVQ_IL_ONLY=no-such-case") # 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) diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index c4929625..8974c3be 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -15,7 +15,7 @@ Which table a card gets: |---|---| | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | -| sm_89 (Ada) | `kIlRows_89`: the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card, so it is not taken until it reproduces. No end-to-end decode change was seen on a 4090 or a 4080 (issue 3453), so this is a microbenchmark gain only. | +| sm_89 (Ada) | the shared table (`kIlRowsShared`) unless `STRATA_MMVQ_IL_89=1`, which switches on `kIlRows_89`: the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. It is opt-in because no sm_89 card has run `mmvq_il_parity` on this code, and the issue saw no end-to-end decode change on a 4090 or a 4080 (issue 3453), so the gain is a microbenchmark one. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card. To flip the default, run `mmvq_il_parity` on an Ada card (it must end with `OK`) and an interleaved decode A/B with the switch on and off. | | every other sm_80+ card | `kIlRowsShared` | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index c4b11942..f0c3913e 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -3037,7 +3037,7 @@ constexpr IlRows kIlRowsShared[] = { // sm_86 + sm_120, and the fallback for e {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}}, // Q6_K }; // Per-architecture tables (P10). A card whose compute capability (major * 10 + minor) is listed here uses its own table; -// every other sm_80+ card uses kIlRowsShared. sm_89 (Ada) has its own table (kIlRows_89, below). To add one, run +// every other sm_80+ card uses kIlRowsShared. sm_89 (Ada) has an opt-in table (kIlRows_89, below; STRATA_MMVQ_IL_89=1). To add one, run // `mmvq_il_parity --bench --emit-table` on the card (docs/MMVQ_IL_TABLE.md), paste the printed block as a // `constexpr IlRows kIlRows_[]` and add {, kIlRows_, sizeof(kIlRows_) / sizeof(IlRows)} below. Each choice // is bitwise the same output, so a table is only speed. Without a rebuild: STRATA_MMVQ_IL_ROWS (see il_env_rows). @@ -3158,6 +3158,10 @@ bool il_env_on(const char* name) { } bool il_t1_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_T1"); return on; } bool il_q3k_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_Q3K"); return on; } +// #3453: sm_89's own tables (kIlRows_89 / kIl1Rows_89) are opt-in with STRATA_MMVQ_IL_89=1 until an sm_89 card has run +// mmvq_il_parity and an end-to-end A/B (docs/MMVQ_IL_TABLE.md). Unset, an Ada card answers what it answered before: the +// shared table, no one-column row. Cached once; the lookup runs on the host once a launch. +bool il_89_opt_in() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL_89"); return v != nullptr && v[0] == '1'; }(); return on; } struct IlArch { int cc; const IlRows* t; size_t n; }; constexpr IlArch kIlArch[] = { {60, kIlRows_60, sizeof(kIlRows_60) / sizeof(IlRows)}, // Pascal GP100: measured on a Tesla P100 @@ -3222,7 +3226,7 @@ int native_mmvq_il_rows_for(int cc, int type, int ncols, int n_out) { if (ncols == 1) { // 143-dense: one column (the plain q8_1 blocks, no interleaved copy); STRATA_MMVQ_IL_T1=0 turns it off if (!il_t1_on()) return 0; for (const Il1Arch& a : kIl1Arch) - if (a.cc == cc) + if (a.cc == cc && (cc != 89 || il_89_opt_in())) for (size_t i = 0; i < a.n; ++i) if (a.t[i].type == type) return a.t[i].r[cls]; return 0; @@ -3232,7 +3236,7 @@ int native_mmvq_il_rows_for(int cc, int type, int ncols, int n_out) { size_t n = sizeof(kIlRowsShared) / sizeof(IlRows); static const bool own120 = il_env_on("STRATA_MMVQ_IL_120"); // 147-verify: =0 gives a big 12.0 card the shared table again for (const IlArch& a : kIlArch) - if (a.cc == cc && a.t != nullptr && (cc != 1201 || own120)) { t = a.t; n = a.n; } + if (a.cc == cc && a.t != nullptr && (cc != 1201 || own120) && (cc != 89 || il_89_opt_in())) { t = a.t; n = a.n; } for (size_t i = 0; i < n; ++i) if (t[i].type == type) return t[i].r[ncols - 2][cls]; return 0; diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 05225d9f..9e9cd165 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -272,6 +272,8 @@ const int kAda4080[5][3][5] = { {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}; int check_tables() { int bad = 0; + const char* e89 = std::getenv("STRATA_MMVQ_IL_89"); + const bool opt89 = e89 != nullptr && e89[0] == '1'; // sm_89's own tables are opt-in (#3453) for (int type : {23, 12, 13, 14, 11}) for (int nc = 2; nc <= 4; ++nc) for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) { @@ -281,11 +283,14 @@ int check_tables() { const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; const int ti = type == 23 ? 0 : type == 12 ? 1 : type == 13 ? 2 : type == 14 ? 3 : 4; const int b = native_mmvq_il_rows_for(89, type, nc, n_out); - const int want = kAda4070[ti][nc - 2][cls] == kAda4080[ti][nc - 2][cls] ? kAda4070[ti][nc - 2][cls] : 0; + // STRATA_MMVQ_IL_89=1: the agreement; unset: what sm_89 answered before #3453 (the shared table, which is + // sm_86's except Q3_K, a type the shared table has no row for) + const int want = opt89 ? (kAda4070[ti][nc - 2][cls] == kAda4080[ti][nc - 2][cls] ? kAda4070[ti][nc - 2][cls] : 0) + : (type == 11 ? 0 : a); if (b != want) { ++bad; - std::printf("FAIL table: sm_89 is %d, the 4070/4080 agreement says %d at type %d ncols %d n_out %d\n", b, want, - type, nc, n_out); + std::printf("FAIL table: sm_89 is %d, %s says %d at type %d ncols %d n_out %d\n", b, + opt89 ? "the 4070/4080 agreement" : "the shared table", want, type, nc, n_out); } } // Volta has its own table (PR 1401): Q6_K at 2 columns, 2560 rows -> 1 row a warp; the Ampere table says 0 there @@ -298,8 +303,9 @@ int check_tables() { ++bad; std::printf("FAIL table: the sm_60 table is not the P100's\n"); } - // sm_89 one column: only Q3_K (the 4070 and the 4080 agree); wider than 4: the plain kernels - if (native_mmvq_il_rows_for(89, 11, 1, 2560) != 0 || native_mmvq_il_rows_for(89, 11, 1, 6144) != 1 || native_mmvq_il_rows_for(89, 12, 1, 6144) != 0) { + // sm_89 one column: only Q3_K with STRATA_MMVQ_IL_89=1 (the 4070 and the 4080 agree), else none; wider than 4: the plain kernels + if (native_mmvq_il_rows_for(89, 11, 1, 2560) != 0 || native_mmvq_il_rows_for(89, 11, 1, 6144) != (opt89 ? 1 : 0) || + native_mmvq_il_rows_for(89, 12, 1, 6144) != 0) { ++bad; std::printf("FAIL table: the sm_89 one-column row is not Q3_K only\n"); } From 9ea044962a8acf4cd16a66a1a9f351302e13cf24 Mon Sep 17 00:00:00 2001 From: xiezhipeng-git <12825243+xiezhipeng-git@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:08:35 +0100 Subject: [PATCH 116/177] OpenAI logprobs, top_logprobs and allowed_token_ids on /v1/chat/completions (#3200) /v1/chat/completions on the CUDA and HIP engine accepted logprobs and returned an empty choices[0].logprobs.content. Now "logprobs": true with "top_logprobs" 0 to 20 (and the legacy "logprobs": N) returns one entry per token with its alternatives, streamed or not, and "allowed_token_ids" returns a distribution renormalised over exactly the ids the caller named. Engine (src/program/generate.cpp): the GEN line takes logprobs=K and allowed=a,b,c. After each "T id" the engine writes one "LP [id:logprob ...]" line from the verify window's head logits before sampling, penalties and temperature. The SYCL engine already wrote LP lines for logprobs=K; it now reads allowed= as well, with the same line format. A request without logprobs reaches none of this: both call sites are behind "req_logprobs >= 0", a local int of the request, so the default path prints what it printed before and does no extra work per token. Changes from the PR: the call sites are guarded instead of calling the function for every token, the function is static, the token index is checked against the row, and the Chinese comment is in English. Server (serve/server.py): LP lines are read before the token is yielded and belong to the request that asked (tagged with its cancel Event), the entries spell the reply, json_schema replies return no logprobs rather than a mismatching set, an allowed id past the vocabulary is a 400, and logprobs on a --parallel server is answered for max_tokens 1 only (a slot's BT lines carry no LP line). serve/structured.py: _extract_json is now extract_json (the logprobs alignment uses it); the two uses added by the #2893 retry follow the rename. Left out: the PR's bench and result files (none in the diff). #3332 (/v1/completions) and #4056 (logprobs on it) build on this change; this one needs nothing from them. Tests: serve.test_logprobs and serve.test_logprobs_parallel (30 tests with the PR's), serve.test_structured, serve.test_responses: 94 tests OK. Not covered: no model ran here. The PR author reports 28 of 28 on an RTX 5080 with MTP and on a GTX 1080 Ti; the layer-split pipelined decode path (the first call site) was not run by anyone, and the LP values were not compared with a CPU softmax of dumped logits. Co-authored-by: Leonardo Murillo <4869242+leonardomurillo@users.noreply.github.com> --- docs/DETAILS.md | 15 + serve/server.py | 395 +++++++++++++++++++++-- serve/structured.py | 9 +- serve/test_logprobs.py | 541 ++++++++++++++++++++++++++++++++ serve/test_logprobs_parallel.py | 117 +++++++ src/program/generate.cpp | 64 ++++ sycl/src/program/generate.cpp | 23 +- 7 files changed, 1132 insertions(+), 32 deletions(-) create mode 100644 serve/test_logprobs.py create mode 100644 serve/test_logprobs_parallel.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 0f16b8be..ee84fab9 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -511,6 +511,21 @@ applies at the next start. Network, key, MCP and program keys are not editable t `STRATA_SPEC_GUMBEL=1` raise the accepted-draft rate on some machines; `STRATA_SPEC_PROB=1` is speculative rejection sampling. `STRATA_SPEC_DEPTH=1` prints acceptance by draft depth and `STRATA_SPEC_MIN_TEMP=0.9` limits sampled drafting to hotter requests. Try them on your own card before relying on them. +- **logprobs: how likely each token was (CUDA/HIP).** `"logprobs": true` with `"top_logprobs": 0..20` on + `/v1/chat/completions`, streamed or not, adds `choices[0].logprobs.content[]` to the reply (`token`, `logprob`, + `bytes`, `top_logprobs`); with thinking on, the thinking's entries come under `reasoning_content` instead. The + tokens, joined, spell the reply exactly (a character split across two tokens lands in the one that finishes it). + A reply is bounded by `max_tokens` -- or by the rest of the context when it is not sent -- and by no cap of our + own, as on OpenAI and vLLM, neither of which ties a length limit to logprobs. A reply that is not streamed, or + that answers a `json_schema` (buffered to be validated), does hold every entry until it ends, so a long one holds + a lot of them; a streamed reply hands each entry out with its chunk and keeps none. `"allowed_token_ids": [ids]` + keeps only those ids in `top_logprobs`, most likely first, renormalised to sum to 1; the chosen token is one of + them when it was named (vLLM's field, but vLLM masks generation with it, while here it filters what is reported, + so a token outside the named ids keeps its own `logprob` and an empty list). An id past the model's vocabulary is + a 400. A token whose probability could not be read gets no entry, and the reply goes on. On a server started with + `--parallel`, only a `max_tokens` 1 request gets them: it is the one a batch slot decodes through the single-token + path, which writes an LP line. A longer reply there is a 400, since the slot's `BT` lines carry none -- entries for + a prefix only, which a client cannot tell from the model's own answer. - **Non-finite logits end the request and drop the cached state (on by default).** If a verify window's logits are NaN, the window emits no tokens, the request ends, and the next request drops the live session, checkpoints and parked conversations and reads its prompt from token 0. The server retries a request that had sent nothing once, transparently. diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..7a268a46 100644 --- a/serve/server.py +++ b/serve/server.py @@ -80,7 +80,7 @@ from serve import owner_guard # noqa: E402 from serve import launch_identity # noqa: E402 from serve import logit_bias as bias_api # noqa: E402 from serve import lifeline # noqa: E402 -from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json, extract_json # noqa: E402 from serve import responses as responses_api # noqa: E402 from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 from serve import images as images_api # noqa: E402 @@ -1456,6 +1456,15 @@ class StrataEngine: pn = prefix.get("tokens") if isinstance(pn, int) and not isinstance(pn, bool) and pn > 0: keys += f" pin={pn}" + # logprobs: the engine writes an `LP` line after each `T` line (an engine without them ignores + # the key, so an older engine answers exactly as it did). Absent = no LP lines at all. + k = top_logprobs(sampling) + if k is not None: + keys += f" logprobs={k}" + ids = allowed_ids(sampling) + if ids: + # only these ids are printed; the engine's comma-separated list, renormalised below + keys += " allowed=" + ",".join(str(i) for i in ids) return keys + StrataEngine.projection_key(sampling) + bias_api.engine_key(sampling.get("logit_bias")) @staticmethod @@ -1474,35 +1483,56 @@ class StrataEngine: except (OSError, AttributeError): # the pipe is gone (or a restart's close() took the process): raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None - def _control(self, cancel, on_token, stop_when=None, on_quiet=None): + def _control(self, cancel, on_token, stop_when=None, on_quiet=None, want_lp=False): """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` true sends STOP once (the request is then read to its DONE). `on_quiet()` runs whenever the engine has been - quiet for half a second: between two PP lines of a read whose chunks take longer than that.""" + quiet for half a second: between two PP lines of a read whose chunks take longer than that. + + `want_lp`: a batch admission's token is the only one this reader ever sees with an `LP` line after it (a + slot's `BT` lines carry none), so a request asking for logprobs there is a `max_tokens` 1 one: read the + line here, for the request itself (its own lines: the engine's is shared by the slots' readers).""" stopped = False beat = time.monotonic() + held = NO_LINE # a line read while looking for a token's LP line while True: - try: - # A client can leave before the first PP/token. Poll its Event as often as _take_control does; - # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. - line = self.lines.get(timeout=0.5) - except queue.Empty: - if cancel.is_set() and not stopped: - self._send("STOP") - stopped = True - if on_quiet is not None: - on_quiet() - if time.monotonic() - beat >= 10.0: - beat = time.monotonic() - yield None - continue + if held is not NO_LINE: + line, held = held, NO_LINE + else: + try: + # A client can leave before the first PP/token. Poll its Event as often as _take_control does; + # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. + line = self.lines.get(timeout=0.5) + except queue.Empty: + if cancel.is_set() and not stopped: + self._send("STOP") + stopped = True + if on_quiet is not None: + on_quiet() + if time.monotonic() - beat >= 10.0: + beat = time.monotonic() + yield None + continue beat = time.monotonic() if line is None: raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") if not line.startswith(("PP ", "INFO")): btrace("ctl<", self._ctl_mode, line.strip()[:60]) if line.startswith("T "): - on_token(int(line[2:])) + t = int(line[2:]) + if want_lp: + # the engine writes the token and its LP line in one flush: the next line is that one, or a + # line this reader must still see (held for the next turn, as generate() does) + try: + held = self.lines.get(timeout=0.5) + except queue.Empty: + held = NO_LINE + if isinstance(held, str) and held.startswith("LP "): + own = getattr(cancel, "_strata_lp_lines", None) + if own is not None: + own.append((t, held)) + held = NO_LINE + on_token(t) if not stopped and (cancel.is_set() or (stop_when is not None and stop_when())): self._send("STOP") stopped = True @@ -1779,6 +1809,12 @@ class StrataEngine: self.progress, self.progress_ms, self.reused = None, 0, 0 born = self.gen # the engine process this request is sent to keys = self.sampling_keys(sampling or {}) + # logprobs: only an admission's token can have an LP line here (the slot's "BT" lines carry none), so the + # server refuses these requests unless max_tokens is 1. The lines go to the request itself, through its + # cancel Event: several requests read control lines at once, and the engine's lp_lines is one attribute. + want_lp = top_logprobs(sampling or {}) is not None + if want_lp: + cancel._strata_lp_lines = LPLines(cancel) out: list[int] = [] pending: list[int] = [] prompt, left = list(ids), int(max_new) @@ -1833,7 +1869,8 @@ class StrataEngine: self.slot_claims.add(reserved) if reserved is not None: self._send(f"BYIELD {reserved}") - for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way): + for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way, + want_lp=want_lp): while pending: t = pending.pop(0) out.append(t) @@ -1961,7 +1998,8 @@ class StrataEngine: if self.progress and live["state"] == "reading": live["prompt_read"] = self.progress[0] try: - for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress())): + for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress()), + want_lp=want_lp): while pending: t = pending.pop(0) out.append(t) @@ -2195,6 +2233,12 @@ class StrataEngine: return self.progress, self.progress_ms, self.reused = None, 0, 0 self.prefill_tok_s_mean = None + # logprobs: the engine writes "LP [id:logprob ...]" right after each "T " (the same + # flush), read here before the token is yielded, so whoever takes the token finds its line in + # lp_lines. Not asked for = the deque stays empty and nothing on this path changes. + want_lp = top_logprobs(sampling or {}) is not None + self.lp_lines = LPLines(cancel) + carry = NO_LINE # a line read for a token's LP line, held until it is used # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" @@ -2222,7 +2266,10 @@ class StrataEngine: raise self._silent(f"the engine said nothing for {time.monotonic() - heard:.0f} s during " "the request") try: - line = self.lines.get(timeout=min(wait, 0.5)) + if carry is not NO_LINE: # the line read after a token for its LP line + line, carry = carry, NO_LINE + else: + line = self.lines.get(timeout=min(wait, 0.5)) except queue.Empty: if cancel.is_set(): return @@ -2249,7 +2296,18 @@ class StrataEngine: allow = silence if cancel.is_set(): return - yield int(line[2:]) + t = int(line[2:]) + if want_lp: + # the engine writes the token and its `LP` line in one flush, so the line is + # here now; an engine without logprobs leaves the next line a normal one + try: + carry = self.lines.get(timeout=0.5) + except queue.Empty: + carry = NO_LINE + if isinstance(carry, str) and carry.startswith("LP "): + self.lp_lines.append((t, carry)) + carry = NO_LINE + yield t elif line.startswith("PP "): f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): @@ -2292,9 +2350,12 @@ class StrataEngine: while True: left = allow - (time.monotonic() - heard) if allow > 0 else None try: - if left is not None and left <= 0: + if carry is not NO_LINE: # read already, after the last token + line, carry = carry, NO_LINE + elif left is not None and left <= 0: raise queue.Empty - line = self.lines.get(timeout=left) + else: + line = self.lines.get(timeout=left) except queue.Empty: raise self._silent("the engine did not finish the request after it was stopped (STOP) " f"within {allow:.0f} s") from None @@ -3720,6 +3781,40 @@ class Detokenizer: OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` +def top_logprobs(req: dict): + """The K for the engine's logprobs=K, or None when the request did not ask. + + OpenAI: "logprobs": true with "top_logprobs" 0..20; the legacy completions form, + "logprobs": N, is taken as N.""" + lp = req.get("logprobs") + if lp is True: + k = req.get("top_logprobs") + return max(0, min(20, k)) if isinstance(k, int) and not isinstance(k, bool) else 0 + if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 0: + return min(20, lp) + return None + + +def allowed_ids(req: dict) -> list: + """`allowed_token_ids`: the ids a caller named, or [] (vLLM's semantics, see LogprobEntries).""" + ids = req.get("allowed_token_ids") + if not isinstance(ids, (list, tuple)): + return [] + return [x for x in ids if isinstance(x, int) and not isinstance(x, bool) and x >= 0] + + +def batch_slots_on(engine) -> bool: + """Does this engine run requests in batch slots ("parallel", whose `BT` lines carry no LP lines)? + + Asked of each engine behind a ReplicaEngine: its own `batch` is how many requests it can run at once, so it + counts a replica without slots as one (serve/replicas.py) -- a server with `--replicas 2` and no `--parallel` + has none, and reads every reply by the GEN path, which does write them.""" + return any(int(getattr(e, "batch", 0) or 0) for e in (getattr(engine, "engines", None) or [engine])) + + +NO_LINE = object() # StrataEngine.generate: no line held after a token + + def stop_strings(req: dict) -> list[str]: """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` (a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" @@ -5814,6 +5909,141 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, PP_DONE_TAIL = 64 + +class LPLines(collections.deque): + """One request's LP lines, tagged with its cancel Event (one per request, handed unchanged from the handler + through Service.run to Engine.generate). The last events of a request - the parser's and the stop strings' + tail - come after it has left the queue, when the next request may already have replaced the engine's lp_lines + with its own: LogprobEntries reads only the lines tagged with its own request's Event.""" + + def __init__(self, owner=None): + super().__init__() + self.owner = owner + + +class LogprobEntries: + """The engine's LP lines as OpenAI's logprobs.content entries. + + Each token's "token" is the text it completes (an incremental UTF-8 decode, as the reply's + text is made), so a character split across tokens lands in the token that finishes it and + the tokens, joined, spell the reply. "bytes" are the token's own bytes. The stop token + ends the reply and is not listed (OpenAI does not list it either). Tokens that make no + text of the reply are left out, because spell() gives each piece of text the tokens that + spell it. + + `allowed_token_ids`: only those ids are kept, and the logprobs are renormalised over them, + so a caller asking about specific candidates gets a distribution over exactly those instead + of a top-K list it has to hope contains them. vLLM, which named the field, masks generation + with these ids instead (every other logit -inf before sampling) and reports the unmasked + distribution; here they filter what is reported, so the chosen token can be outside them. + + On `--parallel`: only a `max_tokens` 1 request gets entries (an admission, decoded through the single-token path + that writes an LP line); the slot's `BT` lines carry none, so a longer reply is refused (400) before it starts. + """ + + def __init__(self, svc, allowed=(), owner=None): + self.tok, self.stop_ids = svc.tok, svc.stop_ids + self.allowed = [i for i in allowed] + self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") + self.pending = [] # entries read but not yet given to a piece of text + self.owner = owner # the request's cancel Event (LPLines) + self.lines = None # this request's current LPLines, kept once seen + + def spell(self, eng, text: str) -> list: + """The entries whose tokens spell `text`, the next piece of the reply.""" + self.pending += self.take(eng) + at = [0] + for e in self.pending: + at.append(at[-1] + len(e["token"])) + joined = "".join(e["token"] for e in self.pending) + i = joined.find(text) + while i >= 0 and text: + if i in at: + a = at.index(i) # the first token there + end = i + len(text) + b = next((j for j in range(a + 1, len(at)) if at[j] == end), None) + if b is not None: + out, self.pending = self.pending[a:b], self.pending[b:] + return out + i = joined.find(text, i + 1) + out, self.pending = self.pending, [] + return out + + def raw(self, t): + if hasattr(self.tok, "token_bytes"): + return self.tok.token_bytes(t) + return self.tok.decode([t]).encode("utf-8") + + def take(self, eng) -> list: + # the engine's current lines are this request's only when they carry its Event (a later generate pass + # of the same request makes new ones: the old ones are read to the end first); another request's never are. + # A batch admission keeps its own lines on the request's cancel Event: the engine's is one attribute, and + # the next request to read control lines may already have replaced it. + own = getattr(self.owner, "_strata_lp_lines", None) + cur, old = (own if own is not None else getattr(eng, "lp_lines", None)), None + if cur is not self.lines and getattr(cur, "owner", None) is self.owner: + old, self.lines = self.lines, cur + out = [] + for lines in (old, self.lines): + while lines: + t, line = lines.popleft() + if t in self.stop_ids: + continue + f = line.split() + if len(f) < 2: + continue + try: # "nan" (no head logits for that window row), "-nan(ind)" + lp = float(f[1]) # (MSVC) or a cut line: no entry for that token + alts = [(int(i), float(v)) for i, _, v in (x.partition(":") for x in f[2:])] + except ValueError: + continue + if not math.isfinite(lp) or not all(math.isfinite(v) for _, v in alts): + continue + b = self.raw(t) + e = {"token": self.inc.decode(b), "logprob": lp, "bytes": list(b), + "top_logprobs": []} + if self.allowed: + alts = [(i, v) for i, v in alts if i in self.allowed] + for i, v in alts: + alt = self.raw(i) + e["top_logprobs"].append({"token": alt.decode("utf-8", "replace"), + "logprob": v, "bytes": list(alt)}) + if self.allowed: + e = self._renormalise(e, t, lp) + out.append(e) + return out + + def _renormalise(self, e, t, lp): + """Keep only the named ids and normalise over them, so they sum to 1. + + The line carries the chosen token's own logprob on its head and the named ids after it, and never + repeats the chosen one among them. So the chosen token is put back when the caller named it: with + `allowed_token_ids` naming only the token the model chose, that token is then the whole distribution, + at 1 (logprob 0), which is what vLLM's mask gives -- here it used to leave nothing to normalise over, + which returned None, the entry was appended all the same, and the reply failed on e["token"]. A line + that carries none of the named ids has nothing to normalise over either: the entry keeps the chosen + token and its own logprob, with no alternatives. It is never None and never dropped, because the + reply's tokens have to keep spelling its text. + """ + cand = e["top_logprobs"] + own = None + if t in self.allowed: # named, and not repeated on the line: it is a candidate + b = self.raw(t) + own = {"token": b.decode("utf-8", "replace"), "logprob": lp, "bytes": list(b)} + cand = [own] + cand + if not cand: + return e # no named id observed for this token: its own logprob, no top + mx = max(x["logprob"] for x in cand) + se = sum(math.exp(x["logprob"] - mx) for x in cand) + lse = mx + math.log(se) + for x in cand: + x["logprob"] -= lse + cand.sort(key=lambda x: -x["logprob"]) # most likely first, as the unfiltered top-k already is + e["top_logprobs"] = cand + if own is not None: # the chosen token is in the distribution: report its own value + e["logprob"] = own["logprob"] # (it used to copy the first alternative's, another token's) + return e + def prompt_progress(svc: Service): """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a @@ -5847,6 +6077,13 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} yield chunk({"role": "assistant", "content": ""}) + lp = LogprobEntries(svc, allowed_ids(req), cancel) if top_logprobs(req) is not None else None + + def with_lp(c, key): + got = lp.spell(svc.engine, c["choices"][0]["delta"][key]) if lp is not None else None + if got: + c["choices"][0]["logprobs"] = {key: got} + return c calls = 0 streamed = {} # tool call id -> index, for calls sent piece by piece finished = set() # ... and the ones whose final tool_call came (#211) @@ -5863,9 +6100,9 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel elif kind == "event": ev: Event = x if ev.kind == "reasoning" and ev.text: - yield chunk({"reasoning_content": ev.text}) + yield with_lp(chunk({"reasoning_content": ev.text}), "reasoning_content") elif ev.kind == "content" and ev.text: - yield chunk({"content": ev.text}) + yield with_lp(chunk({"content": ev.text}), "content") elif ev.kind == "tool_start": streamed[ev.call.id] = calls calls += 1 @@ -5905,11 +6142,14 @@ def _is_json(text: str) -> bool: def openai_collect(chunks) -> dict: content, reasoning, by_index, last, mcp = [], [], {}, None, [] + lps = {} # "content" / "reasoning_content" -> logprob entries for c in chunks: if c is None: # a heartbeat continue if c.get("strata_mcp"): mcp.append(c["strata_mcp"]) + for k, v in (c["choices"][0].get("logprobs") or {}).items(): + lps.setdefault(k, []).extend(v) d = c["choices"][0]["delta"] content.append(d.get("content") or "") reasoning.append(d.get("reasoning_content") or "") @@ -5936,11 +6176,80 @@ def openai_collect(chunks) -> dict: out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"], "choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}], "usage": last["usage"]} + if lps: + out["choices"][0]["logprobs"] = {"content": lps.get("content", []), "refusal": None, **( + {"reasoning_content": lps["reasoning_content"]} if lps.get("reasoning_content") else {})} if last.get("timings"): out["timings"] = last["timings"] return out +def logprob_span(text: str, part: str, entries: list): + """The entries whose tokens spell `part`, a piece of `text`, or None when the tokens do not + spell `text` or no token boundary falls at both ends of `part`.""" + if "".join(e["token"] for e in entries) != text: + return None + start = text.find(part) + if start < 0: + return None + at, first = 0, None + for i, e in enumerate(entries): + if at == start and first is None: + first = i + if at == start + len(part) and first is not None: + return entries[first:i] + at += len(e["token"]) + return entries[first:] if first is not None and at == start + len(part) else None + + +def _same_json(a: str, b: str) -> bool: + """Are two strings the same JSON value (whitespace and key order aside)? No -> False.""" + try: + return json.loads(a) == json.loads(b) + except Exception: + return False + + +def _structured_logprobs(choice: dict, content: str): + """`content`'s logprobs, and the content the tokens actually spell. + + Returns `(content, logprobs)`: on failure `(the content as validated, None)`. + + `structured_chunks` returns the canonical JSON the validator produced, which the model never + generated, so its tokens do not spell it. Two honest outcomes: + + 1. a run of tokens spells what is being returned -> use it as it is; + 2. the tokens spell the model's own JSON, which is the same JSON value (the fenced-with-spaces + case, the common one) -> return the model's form, so `''.join(token) == content` again. + + Neither holds (a rearranged key order, or a reply that is not that JSON at all) and there are no + logprobs: a caller that joins the tokens must not silently get something that does not match. + """ + lps = choice.get("logprobs") + if not lps or not lps.get("content"): + return content, None + raw = choice["message"]["content"] or "" + entries = lps["content"] + if raw == content: # not rewritten: the entries are already its + return content, _with_reasoning(lps, entries) + span = logprob_span(raw, content, entries) + if span is not None: + return content, _with_reasoning(lps, span) + inner = extract_json(raw) + if inner and _same_json(inner, content): + span = logprob_span(raw, inner, entries) + if span is not None: + return inner, _with_reasoning(lps, span) # the model's own form: the tokens spell it + return content, None + + +def _with_reasoning(lps: dict, entries: list) -> dict: + out = {"content": entries} + if lps.get("reasoning_content"): + out["reasoning_content"] = lps["reasoning_content"] + return out + + def structured_chunks(chunks, validator): """Buffer structured streams so a client never receives unvalidated content.""" buffered = [] @@ -5956,12 +6265,23 @@ def structured_chunks(chunks, validator): result = openai_collect(buffered) choice = result["choices"][0] content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + # logprobs: the entries spell what the model wrote, which this function replaces with the + # canonical JSON. `_structured_logprobs` gives back the form the tokens spell, or None. + content, logprobs = _structured_logprobs(choice, content) yield buffered[0] delta = {"content": content} if choice["message"].get("reasoning_content"): delta["reasoning_content"] = choice["message"]["reasoning_content"] - yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} - yield buffered[-1] + piece = {"index": 0, "delta": delta, "finish_reason": None} + if logprobs: + piece["logprobs"] = logprobs + yield {**buffered[0], "choices": [piece]} + end = buffered[-1] + if end["choices"][0].get("logprobs"): + # those entries went out in the piece above (or were dropped with it): the closing + # chunk must not carry a second copy + end = {**end, "choices": [{k: v for k, v in end["choices"][0].items() if k != "logprobs"}]} + yield end finally: chunks.close() @@ -7146,6 +7466,25 @@ def make_handler(svc: Service): raise ValueError("structured response_format with tools/MCP is not supported") svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest + # No cap of our own on the reply's length when logprobs are asked for: the reply is already bounded by + # max_tokens (by the rest of the context when it is not sent), which is the only bound OpenAI and vLLM + # put on it either. A reply that is not streamed does hold every entry (its token, bytes and up to 20 + # alternatives) until it ends, so a long one holds a lot: streaming hands each entry out with its chunk. + if top_logprobs(req) is not None and batch_slots_on(svc.engine) and max_req != 1: + # --parallel/--batch: a slot's "BT " lines carry no LP line, and the batched loop never + # calls emit_lp_line (src/program/generate.cpp); an admission -- a max_tokens 1 request -- is read + # as GEN 1, which does write them. Past that one token a reply would hold entries for a prefix + # only, which a client cannot tell from the model's own answer, so the longer one is refused. + raise ValueError('logprobs is available with "parallel" (batch slots) only for max_tokens 1; ' + 'run the server without "--parallel" for longer replies') + n_vocab = len(getattr(svc.tok, "tokens", ())) or None + if top_logprobs(req) is not None and n_vocab: + # emit_lp_line indexes the logits row with each named id as given, so an id past the vocabulary + # would read out of bounds: refused here, before anything is sent + bad = [i for i in allowed_ids(req) if i >= n_vocab] + if bad: + raise ValueError(f"allowed_token_ids: {bad[0]} is outside the vocabulary " + f"(0..{n_vocab - 1})") bias_api.validate_request(req, svc.engine, len(getattr(svc.tok, "tokens", ())) or None) use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) own = {t.get("name") for t in tools or [] if isinstance(t, dict)} # #592: a second line of defence diff --git a/serve/structured.py b/serve/structured.py index 99ecf1c8..1809a0c3 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -194,7 +194,10 @@ def prepare_format(response_format, messages, with_tools=False): return messages, validator -def _extract_json(text: str) -> str: +def extract_json(text: str) -> str: + """The first JSON object in `text`: a ```-fenced block's inside when there is one, else the text + from its first `{`. Empty when there is nothing to take. The server's json_schema logprobs + alignment reads the model's own JSON form with it.""" s = (text or "").strip() if not s: return "" @@ -246,13 +249,13 @@ def validated_json(text, validator, finish): if finish != "stop": raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") try: - value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant) + value = json.loads(extract_json(text), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) except (ValueError, TypeError) as exc: value = None if getattr(validator, "repair_escapes", False): # opt-in (#2893); only after the strict parse failed try: - value = json.loads(repair_latex_escapes(_extract_json(text)), object_pairs_hook=pairs, + value = json.loads(repair_latex_escapes(extract_json(text)), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) print("[strata] structured output: repaired backslashes that were not valid JSON escapes", flush=True) diff --git a/serve/test_logprobs.py b/serve/test_logprobs.py new file mode 100644 index 00000000..a21237db --- /dev/null +++ b/serve/test_logprobs.py @@ -0,0 +1,541 @@ +"""OpenAI logprobs on /v1/chat/completions, from the engine's LP lines: python -m unittest serve.test_logprobs. + +The engine (src/program/generate.cpp) writes an `LP [id:logprob ...]` line right after +each `T ` when the request carries `logprobs=K`; this is the server half that turns those +lines into OpenAI's logprobs, and the parts that are easy to get wrong: + + - `allowed_token_ids`: only the named ids, renormalised over them (vLLM's semantics). + - `response_format: json_schema` rewrites the content, so the tokens no longer spell what is + returned; the entries are re-aligned or dropped, never returned wrong. +""" +from __future__ import annotations + +import json +import math +import queue +import threading +import unittest +import urllib.request +from pathlib import Path +from types import SimpleNamespace + +from serve.frontend import ChatTemplate +from serve.server import (ByteTokenizer, LogprobEntries, LPLines, MockEngine, Service, StrataEngine, batch_slots_on, + logprob_span, serve, top_logprobs, allowed_ids) + +ROOT = Path(__file__).resolve().parent.parent +TEMPLATE = ChatTemplate(ROOT / "serve" / "chat_template.jinja") + + +class Tokenizer(ByteTokenizer): + def token_bytes(self, token): + return self.SPECIALS[token - 256].encode() if token >= 256 else bytes([token]) + + +class ThinkTokenizer(Tokenizer): + # two extra special tokens that decode as the thinking marks; ALWAYS so the byte-level + # encode() maps them wherever they appear ("" would loop forever in startswith, so they + # are real strings, like the engine's own think tokens are) + SPECIALS = ByteTokenizer.SPECIALS + ["", ""] + ALWAYS = ("", "") + + +class LpEngine(MockEngine): + """MockEngine with the LP line of each token on lp_lines before the token is yielded, as the + engine leaves it; token i has the log-probability -(i + 1) / 100 and four named alternatives.""" + + def __init__(self, tok, script, lines=True): + super().__init__(tok, script, max_context=16384) + self.with_lines, self.sampling = lines, None + + def line(self, i, t): + """The LP line of token t, the i-th of the reply: the same four ids whatever was asked.""" + return (f"LP {-(i + 1) / 100:.6f} 65:-0.500000 72:-1.250000 " + f"88:-3.000000 91:-4.200000\n") + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.sampling, self.lp_lines = dict(sampling or {}), LPLines(cancel) + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if self.with_lines: + self.lp_lines.append((t, self.line(i, t))) + yield t + + +class NamedEngine(LpEngine): + """LpEngine that prints the request's own `allowed_token_ids`, as the engine's emit_lp_line does: + `LP : ...`, the chosen id left out (it is on the head).""" + + def line(self, i, t): + named = [int(x) for x in (self.sampling or {}).get("allowed_token_ids") or [] if int(x) != t] + alts = "".join(f" {x}:{-0.700000 - 0.010000 * j:.6f}" for j, x in enumerate(named)) + return f"LP {-(i + 1) / 100:.6f}{alts}\n" + + +class NextEngine(LpEngine): + """LpEngine for two requests: the second one stops after its first token (its LP line is in lp_lines) + until the first request's reply has been read.""" + + def __init__(self, tok, scripts, first_out): + super().__init__(tok, scripts) + self.first_out, self.calls = first_out, 0 + self.first_in, self.first_generated, self.second_started = (threading.Event(), threading.Event(), + threading.Event()) + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.calls += 1 + mine = self.calls + if mine == 1: + self.first_in.set() + try: + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if mine == 2 and i == 0: + self.second_started.set() + self.first_out.wait(10) + yield t + finally: + if mine == 1: + self.first_generated.set() + + +class HandOver: + """Service.fifo that, once the first request has generated, lets its turn go and then waits until the + next request is generating before the first one goes on.""" + + def __init__(self, engine): + self.lock, self.engine, self.waited = threading.Lock(), engine, False + + def acquire(self, *a, **k): + return self.lock.acquire(*a, **k) + + def release(self): + self.lock.release() + if self.engine.first_generated.is_set() and not self.waited: + self.waited = True + self.engine.second_started.wait(10) + + def locked(self): + return self.lock.locked() + + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *exc): + self.release() + + +SCHEMA = {"type": "json_schema", "json_schema": {"name": "a", "strict": True, "schema": { + "type": "object", "properties": {"rent": {"type": "string"}, "quote": {"type": "string"}}, + "required": ["rent", "quote"], "additionalProperties": False}}} + + +class Keys(unittest.TestCase): + """What the request asks for, and what reaches the engine line.""" + + def test_what_the_request_asks(self): + self.assertEqual(top_logprobs({"logprobs": True}), 0) + self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 3}), 3) + self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 50}), 20) + self.assertEqual(top_logprobs({"logprobs": 2}), 2) # the legacy completions form + for req in ({}, {"logprobs": False}, {"logprobs": None}, {"top_logprobs": 3}): + self.assertIsNone(top_logprobs(req)) + + def test_allowed_ids(self): + self.assertEqual(allowed_ids({"allowed_token_ids": [1, 2, 3]}), [1, 2, 3]) + for req in ({}, {"allowed_token_ids": "1,2"}, {"allowed_token_ids": [True]}, {"allowed_token_ids": [-1]}): + self.assertEqual(allowed_ids(req), []) + + def test_the_engine_key_only_when_asked(self): + self.assertIn(" logprobs=0", StrataEngine.sampling_keys({"logprobs": True})) + self.assertIn(" logprobs=5", StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 5})) + self.assertNotIn("logprobs", StrataEngine.sampling_keys({})) + self.assertNotIn("logprobs", StrataEngine.sampling_keys({"logprobs": False, "temperature": 0})) + + def test_allowed_reaches_the_engine_line(self): + keys = StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 2, + "allowed_token_ids": [7, 8, 9]}) + self.assertIn(" logprobs=2 ", keys) + self.assertIn(" allowed=7,8,9", keys) + + def test_unreadable_lines_give_no_entry(self): + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + for line in ("LP nan", "LP -nan(ind)", "LP inf", "LP -0.1 65:x", "LP -0.1 65:-inf", "LP -0.1 65", + "LP -0.200000 65:-1.0"): + eng.lp_lines.append((72, line)) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), owner=a).take(eng) + self.assertEqual([e["logprob"] for e in got], [-0.2]) + + def test_a_filtered_line_with_nothing_left_keeps_its_token(self): + # none of the named ids on the line: the entry keeps the chosen token and its own logprob, and no + # alternatives. It used to be None, appended all the same, and the reply failed on e["token"]. + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + eng.lp_lines.append((72, "LP -0.300000 65:-0.500000")) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [70], a).take(eng) + self.assertEqual([(e["token"], e["logprob"], e["top_logprobs"]) for e in got], [("H", -0.3, [])]) + + def test_a_named_token_the_line_does_not_repeat_is_its_own_distribution(self): + # the engine prints the chosen token's logprob on the head and the named ids after it, never repeating + # the chosen one: naming only that id leaves it alone in the distribution, at 1 (logprob 0) + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + eng.lp_lines.append((72, "LP -0.300000 65:-0.500000")) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [72], a).take(eng) + self.assertEqual(got[0]["top_logprobs"], [{"token": "H", "logprob": 0.0, "bytes": [72]}]) + self.assertEqual(got[0]["logprob"], 0.0) + + +class Generate(unittest.TestCase): + """The token's LP line is read next to it, and only when it was asked for.""" + + def engine(self, *lines): + e = StrataEngine.__new__(StrataEngine) + e.proc = __import__("types").SimpleNamespace( + stdin=__import__("io").StringIO(), poll=lambda: None) + e.lines, e.can_stop, e.max_context, e.silence_s = queue.Queue(), False, 262144, 0 + for line in lines: + e.lines.put(line) + return e + + def test_a_token_is_yielded_with_its_lp_line_read(self): + e = self.engine("PP 3 3", "T 72", "LP -0.100000 72:-0.1 65:-2.5", "T 105", + "LP -0.200000 105:-0.2 65:-3", "T 257", "LP -0.010000", + "DONE 3 3 0 3 stop 0 0 0") + seen = [] + for t in e.generate([1, 2, 3], 8, {"logprobs": True, "top_logprobs": 2}, threading.Event()): + if t is not None: + seen.append((t, [x[0] for x in e.lp_lines])) + self.assertEqual(seen, [(72, [72]), (105, [72, 105]), (257, [72, 105, 257])]) + self.assertIn(" logprobs=2 ", e.proc.stdin.getvalue()) + self.assertEqual(e.lp_lines[1][1], "LP -0.200000 105:-0.2 65:-3") + + def test_an_engine_without_lp_lines(self): + e = self.engine("T 72", "T 105", "DONE 3 3 0 2 stop 0 0 0") + toks = [t for t in e.generate([1], 8, {"logprobs": True}, threading.Event()) if t is not None] + self.assertEqual(toks, [72, 105]) + self.assertEqual(list(e.lp_lines), []) + self.assertEqual(e.last["finish"], "stop") + + def test_not_asked_reads_as_before(self): + e = self.engine("T 72", "LP -0.1", "T 105", "DONE 3 3 0 2 stop 0 0 0") + toks = [t for t in e.generate([1], 8, {}, threading.Event()) if t is not None] + self.assertEqual(toks, [72, 105]) + self.assertEqual(list(e.lp_lines), []) + + def test_a_consumer_that_stops_early_does_not_lose_the_done_read_after_the_token(self): + # the DONE line was read while looking for the token's LP line: the drain must take it, + # not wait for another + e = self.engine("T 72", "DONE 3 3 0 1 length 0 0 0", None) + gen = e.generate([1], 1, {"logprobs": True}, threading.Event()) + self.assertEqual(next(gen), 72) + gen.close() + self.assertEqual(e.last["finish"], "length") + + +class Api(unittest.TestCase): + def setUp(self): + self.tok = Tokenizer() + self.engine = LpEngine(self.tok, "Café costs €5.") + self.svc = Service(self.engine, self.tok, TEMPLATE) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, body, stream=False): + body = {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 200, + "chat_template_kwargs": {"enable_thinking": False}, **body} + if stream: + body["stream"] = True + req = urllib.request.Request(self.base + "/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + if not stream: + return json.loads(raw) + return [json.loads(x[6:]) for x in raw.splitlines() if x.startswith("data: {")] + + def test_the_tokens_spell_the_content(self): + out = self.post({"logprobs": True, "top_logprobs": 1}) + choice = out["choices"][0] + content = choice["message"]["content"] + lps = choice["logprobs"]["content"] + self.assertEqual(content, "Café costs €5.") + self.assertEqual("".join(e["token"] for e in lps), content) + self.assertEqual(len(lps), len(content.encode())) # one per byte token; no stop token + self.assertEqual(b"".join(bytes(e["bytes"]) for e in lps), content.encode()) + e_acute = [e for e in lps if len(e["bytes"]) == 1 and e["bytes"][0] >= 0x80] + self.assertEqual([e["token"] for e in e_acute[:2]], ["", "é"]) # split across two tokens + self.assertEqual(lps[0]["logprob"], -0.01) + self.assertEqual(lps[0]["top_logprobs"][0]["token"], "A") + self.assertEqual(self.engine.sampling.get("logprobs"), True) + + def test_a_request_reads_only_its_own_lines(self): + # A's last "." is held by its stop string and sent after A has left the queue, when B is + # already generating on the same engine: each reply's tokens must spell that reply + first_out = threading.Event() + engine = NextEngine(self.tok, ["Café costs €5.", "Bonjour!"], first_out) + svc = Service(engine, self.tok, TEMPLATE) + svc.fifo = HandOver(engine) + httpd = serve(svc, port=0) + got = {} + try: + self.base = f"http://127.0.0.1:{httpd.server_address[1]}" + a = threading.Thread(target=lambda: got.update(a=self.post({"logprobs": True, "stop": [".!"]}))) + b = threading.Thread(target=lambda: got.update(b=self.post({"logprobs": True}))) + a.start() + self.assertTrue(engine.first_in.wait(10)) + b.start() + a.join(30) + first_out.set() + b.join(30) + finally: + first_out.set() + httpd.shutdown() + httpd.server_close() + for key, text in (("a", "Café costs €5."), ("b", "Bonjour!")): + choice = got[key]["choices"][0] + self.assertEqual(choice["message"]["content"], text) + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), text, key) + + def test_logprobs_take_any_max_tokens(self): + # No cap of our own: the reply is already bounded by max_tokens (the rest of the context when it is not + # sent), which is the only bound OpenAI and vLLM put on it too -- openai-node's max_tokens is optional + # and vLLM's defaults to 16 or None, neither tying it to logprobs. + for max_tokens in (200, 5000, 0, -1, None): # 0 / -1: "the rest of the context"; None: not sent + choice = self.post({"logprobs": True, "top_logprobs": 1, "max_tokens": max_tokens})["choices"][0] + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), + "Café costs €5.", max_tokens) + self.assertNotIn("logprobs", self.post({"max_tokens": 0})["choices"][0]) # not asked: as before + + def test_a_streamed_reply_needs_no_bound(self): + # A streamed reply hands each entry out with its chunk and keeps none, so it is bounded by the reply's own + # length. OpenAI itself bounds a reply only by the model's context, and its SDKs send no max_tokens by + # default. 5000 and "the rest of the context" must both be answered, as they are without logprobs. + for max_tokens in (5000, 0, None): # None: the field is not sent at all + chunks = self.post({"logprobs": True, "max_tokens": max_tokens}, stream=True) + text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(text, "Café costs €5.", max_tokens) + self.assertEqual("".join(toks), text, max_tokens) # an entry for every token, streamed or not + + def test_a_json_schema_reply_takes_any_max_tokens(self): + # structured_chunks buffers the reply to validate it, logprobs included: it holds the entries until the + # end, as a reply that is not streamed does. That memory is bounded by max_tokens, not by a cap of ours. + written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' + self.engine = self.svc.engine = LpEngine(self.tok, written) + content = '{"rent": "$1,250", "quote": "x"}' + for max_tokens in (200, 0, 5000): + choice = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA})["choices"][0] + self.assertEqual(choice["message"]["content"], content, max_tokens) + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content, max_tokens) + chunks = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA}, stream=True) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), content, (max_tokens, "streamed")) + + def test_logprobs_are_refused_on_the_batch_path(self): + # --parallel/--batch: the engine's batched loop prints "BT " and never calls emit_lp_line + # (src/program/generate.cpp), so no LP line reaches the server and the field would simply be absent. + # Refused up front instead, before anything is generated; a request that does not ask is untouched. + self.engine.batch = 2 + with self.assertRaises(urllib.error.HTTPError) as cm: + self.post({"logprobs": True}) + self.assertEqual(cm.exception.code, 400) + self.assertIn("--parallel", cm.exception.read().decode()) + self.engine.batch = 0 + self.assertIn("logprobs", self.post({"logprobs": True})["choices"][0]) + + def test_allowed_token_ids_outside_the_vocabulary_is_a_400(self): + # emit_lp_line indexes its logits row with each named id, so an id past the vocabulary would read out of + # bounds; the request is refused before anything is generated + self.tok.tokens = [str(i) for i in range(300)] # a tokenizer that knows its vocabulary + with self.assertRaises(urllib.error.HTTPError) as cm: + self.post({"logprobs": True, "top_logprobs": 1, "allowed_token_ids": [300]}) + self.assertEqual(cm.exception.code, 400) + self.assertIn("allowed_token_ids", cm.exception.read().decode()) + self.assertIn("logprobs", self.post({"logprobs": True, "top_logprobs": 1, + "allowed_token_ids": [299]})["choices"][0]) + + def test_streamed(self): + chunks = self.post({"logprobs": True}, stream=True) + content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(content, "Café costs €5.") + self.assertEqual("".join(toks), content) + + def test_with_thinking_each_part_is_spelled_by_its_tokens(self): + tok = ThinkTokenizer() + svc = Service(LpEngine(tok, "Two times three.\n\nSix."), tok, + TEMPLATE) + httpd = serve(svc, port=0) + try: + self.base = f"http://127.0.0.1:{httpd.server_address[1]}" + for stream in (False, True): + out = self.post({"logprobs": True, "chat_template_kwargs": {"enable_thinking": True}}, + stream) + chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"], + "logprobs": out["choices"][0]["logprobs"]}]}] + for key in ("content", "reasoning_content"): + text = "".join(c["choices"][0]["delta"].get(key) or "" for c in chunks if c.get("choices")) + toks = "".join(e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get(key, [])) + self.assertTrue(text) + self.assertEqual(toks, text, (key, stream)) + self.assertNotIn("think>", toks) + finally: + httpd.shutdown() + httpd.server_close() + + def test_not_asked_no_logprobs(self): + out = self.post({}) + self.assertNotIn("logprobs", out["choices"][0]) + + def test_an_engine_without_lp_lines_gives_none(self): + self.engine.with_lines = False + out = self.post({"logprobs": True}) + self.assertEqual(out["choices"][0]["message"]["content"], "Café costs €5.") + self.assertNotIn("logprobs", out["choices"][0]) + + def test_allowed_token_ids_are_renormalised_over_the_named_ids(self): + out = self.post({"logprobs": True, "allowed_token_ids": [65, 72]}) + lps = out["choices"][0]["logprobs"]["content"] + self.assertTrue(lps) + for e in lps: + ids = [t["token"] for t in e["top_logprobs"]] + self.assertEqual(ids, ["A", "H"]) # only the named ones + import math + total = sum(math.exp(t["logprob"]) for t in lps[0]["top_logprobs"]) + self.assertAlmostEqual(total, 1.0, places=6) # renormalised: they sum to 1 + + def test_allowed_token_ids_with_nothing_to_renormalise(self): + # the mock's alternatives are 65/72/88/91: naming another id leaves every line with no survivor. Each + # token keeps its own logprob and an empty candidate list, and the reply still comes back whole (this + # used to be a 400 on the unstreamed path and a reply cut after the role chunk when streamed). + for body in ({"logprobs": True, "allowed_token_ids": [66]}, + {"logprobs": True, "allowed_token_ids": [66, 70, 71]}): + choice = self.post(body)["choices"][0] + lps = choice["logprobs"]["content"] + self.assertEqual(choice["message"]["content"], "Café costs €5.") + self.assertEqual("".join(e["token"] for e in lps), "Café costs €5.") + self.assertEqual([e["top_logprobs"] for e in lps], [[]] * len(lps)) + self.assertEqual(lps[0]["logprob"], -0.01) # the token's own, as the engine reported it + streamed = self.post(body, stream=True) + toks = [e["token"] for c in streamed if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), "Café costs €5.") + + def test_a_named_token_the_model_chose_is_in_its_distribution(self): + # 46 is the reply's final ".": the engine does not repeat the chosen token among the named ids, so + # naming only it used to leave nothing to normalise over. It is the whole distribution now, at 0. + lps = self.post({"logprobs": True, "allowed_token_ids": [46]})["choices"][0]["logprobs"]["content"] + dot = [e for e in lps if e["token"] == "."] + self.assertEqual(len(dot), 1) + self.assertEqual(dot[0]["top_logprobs"], [{"token": ".", "logprob": 0.0, "bytes": [46]}]) + self.assertEqual(dot[0]["logprob"], 0.0) + self.assertEqual([e["top_logprobs"] for e in lps if e["token"] != "."], [[]] * (len(lps) - 1)) + + def test_a_choice_of_ten_that_only_the_ended_reply_settles(self): + # ten named ids, and a reply that is two of them: "1" alone is already one of the choices, so which + # one was picked is only known when the reply ends. Here "11": each token's entries cover the ten + # named ids (the chosen one included, because the engine never repeats it), and they sum to 1. + self.engine = self.svc.engine = NamedEngine(self.tok, "11") + digits = [ord(c) for c in "0123456789"] + for stream in (False, True): + out = self.post({"logprobs": True, "top_logprobs": 10, "allowed_token_ids": digits}, stream) + chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"], + "logprobs": out["choices"][0]["logprobs"]}]}] + content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + lps = [e for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(content, "11") + self.assertEqual([e["token"] for e in lps], ["1", "1"]) # the first token alone is a choice too + self.assertEqual("".join(e["token"] for e in lps), content) + for e in lps: + ids = [t["token"] for t in e["top_logprobs"]] + self.assertEqual(sorted(ids), sorted("0123456789")) # the ten named ids, and only them + self.assertIn(e["token"], ids) # the chosen one is one of them + self.assertEqual(ids[0], e["token"]) # ... and the most likely, here + self.assertEqual([t["logprob"] for t in e["top_logprobs"]], + sorted((t["logprob"] for t in e["top_logprobs"]), reverse=True)) + self.assertAlmostEqual(sum(math.exp(t["logprob"]) for t in e["top_logprobs"]), 1.0, places=6) + + def test_a_held_tail_of_more_than_one_token(self): + # "5." is the start of the stop string, so the parser holds two tokens and sends them as one piece + # after the request has left the queue: both entries come from this request's own lines all the same + chunks = self.post({"logprobs": True, "stop": ["5.!"]}, stream=True) + content = [c for c in chunks if c.get("choices") and c["choices"][0]["delta"].get("content")] + self.assertEqual(content[-1]["choices"][0]["delta"]["content"], "5.") # held, then flushed whole + self.assertEqual([e["token"] for e in content[-1]["choices"][0]["logprobs"]["content"]], ["5", "."]) + text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + self.assertEqual(text, "Café costs €5.") + self.assertEqual("".join(e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])), text) + choice = self.post({"logprobs": True, "stop": ["5.!"]})["choices"][0] # and not streamed + self.assertEqual(choice["message"]["content"], "Café costs €5.") + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), "Café costs €5.") + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"][-2:]), "5.") + + def test_json_schema_answer_as_written_with_its_logprobs(self): + # MockEngine appends the stop token to the script it is built with, and reports + # finish_reason=length when it runs out -- so the engine is rebuilt with this answer + # rather than re-pointed at a raw token list (which would drop the stop token). + written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' + self.engine = self.svc.engine = LpEngine(self.tok, written) + out = self.post({"logprobs": True, "temperature": 0, "response_format": SCHEMA}) + choice = out["choices"][0] + content = choice["message"]["content"] + self.assertEqual(content, '{"rent": "$1,250", "quote": "x"}') # the JSON as written + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content) + streamed = self.post({"logprobs": True, "response_format": SCHEMA}, stream=True) + toks = [e["token"] for c in streamed if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), content) + plain = self.post({"temperature": 0, "response_format": SCHEMA}) # not asked: as before + self.assertEqual(plain["choices"][0]["message"]["content"], + '{"rent":"$1,250","quote":"x"}') + self.assertNotIn("logprobs", plain["choices"][0]) + + +class Replicas(unittest.TestCase): + """`--replicas`: a ReplicaEngine's own `batch` is how many requests its engines run at once and counts a replica + without slots as one, so asking it "does this engine use batch slots" refused logprobs on a server that has + none -- one that reads every reply by the GEN path, which does write LP lines.""" + + @staticmethod + def replica(*batches): + from serve.replicas import ReplicaEngine + return ReplicaEngine([SimpleNamespace(gen=1, batch=b) for b in batches]) + + def test_no_slots_behind_replicas(self): + self.assertFalse(batch_slots_on(self.replica(0, 0))) + self.assertFalse(batch_slots_on(SimpleNamespace(batch=0))) # no replicas: the engine's own figure + + def test_slots_behind_replicas(self): + self.assertTrue(batch_slots_on(self.replica(2, 3))) # every one of them + self.assertTrue(batch_slots_on(self.replica(0, 2))) # one is enough + self.assertTrue(batch_slots_on(SimpleNamespace(batch=4))) + + +class Span(unittest.TestCase): + def entries(self, *toks): + return [{"token": t} for t in toks] + + def test_span(self): + es = self.entries("```", "json", "\n", "{", "}", "\n", "```") + self.assertEqual([e["token"] for e in logprob_span("```json\n{}\n```", "{}", es)], ["{", "}"]) + self.assertEqual(len(logprob_span("{}", "{}", self.entries("{", "}"))), 2) + + def test_no_span(self): + self.assertIsNone(logprob_span("x{}", "{}", self.entries("x{", "}"))) # no boundary at the start + self.assertIsNone(logprob_span("{}x", "{}", self.entries("{", "}x"))) # none at the end + self.assertIsNone(logprob_span("{}", "{}", self.entries("{"))) # do not spell it + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_logprobs_parallel.py b/serve/test_logprobs_parallel.py new file mode 100644 index 00000000..cc494aa3 --- /dev/null +++ b/serve/test_logprobs_parallel.py @@ -0,0 +1,117 @@ +"""Logprobs with "parallel" (batch slots): python -m unittest serve.test_logprobs_parallel. + +The fake engine of serve/test_parallel.py behind the real StrataEngine and Service, writing an LP line after each +T line when the GEN / BGEN line asks for logprobs. A typed decision (max_tokens 1) is read on the control lines +(an admission: BGEN, one T, DONE, BADM 0) and gets its logprobs; longer replies are refused with a 400, since the +slot's BT lines carry none. +""" +import json +import threading +import unittest +import urllib.error +import urllib.request +from unittest import mock + +import serve.test_parallel as tp + +# LP after each T when asked: the token's log-probability is -(prompt length) / 1000 (so two requests can be told +# apart) and "A" (65) is its one alternative at -1.5 -- or the named ids themselves, at -1, when the line carries +# `allowed=` (the engine's own branch: it prints those and no top-K) +_T_LINE = ' print(f"T {t}", flush=True)\n' +assert tp.FAKE_BATCH.count(_T_LINE) == 1 +FAKE_LP = tp.FAKE_BATCH.replace(_T_LINE, _T_LINE + ( + ' if " logprobs=" in line:\n' + ' al = [x[8:] for x in line.split() if x.startswith("allowed=")]\n' + ' cs = (" " + " ".join(i + ":-1.000000" for i in al[0].split(","))) if al else " 65:-1.500000"\n' + ' print(f"LP {-len(ids) / 1000:.6f}" + cs, flush=True)\n')) + + +class LogprobsWithBatchSlots(unittest.TestCase): + start, tearDown, get = tp.ParallelService.start, tp.ParallelService.tearDown, tp.ParallelService.get + + def start_lp(self, fake=FAKE_LP, slots=2): + with mock.patch.object(tp, "FAKE_BATCH", fake): + self.start(slots) + + def chat(self, text, max_tokens=1, logprobs=True, allowed=None): + body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "reasoning_effort": "none"} + if logprobs: + body |= {"logprobs": True, "top_logprobs": 1} + if allowed: + body["allowed_token_ids"] = allowed + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + return json.loads(r.read().decode()) + + @staticmethod + def entries(reply): + return ((reply["choices"][0].get("logprobs") or {}).get("content")) or [] + + def test_a_decision_gets_its_logprobs(self): + self.start_lp() + r = self.chat("Is it A or B?") + self.assertEqual(r["choices"][0]["message"]["content"], "o") + e = self.entries(r) + self.assertEqual(len(e), 1) + self.assertEqual(e[0]["token"], "o") + self.assertLess(e[0]["logprob"], 0) + self.assertEqual(e[0]["top_logprobs"], [{"token": "A", "logprob": -1.5, "bytes": [65]}]) + self.assertTrue(any(x.startswith("BGEN") for x in self.log.read_text().splitlines())) # an admission + + def test_the_named_ids_reach_the_slot_and_are_what_is_reported(self): + # allowed_token_ids travels in the same BGEN keys as logprobs, so the engine's own branch answers with + # exactly those ids: the admission path carries the whole feature, not just the top-K one + self.start_lp() + e = self.entries(self.chat("Is it A or B?", allowed=[65])) + self.assertEqual(len(e), 1) + self.assertEqual([x["token"] for x in e[0]["top_logprobs"]], ["A"]) + self.assertEqual(e[0]["top_logprobs"][0]["logprob"], 0) # the whole distribution: just that id + + def test_two_at_once_each_get_their_own(self): + self.start_lp() + short, long_ = "A or B?", "A or B? " + "x" * 300 + alone = {t: self.entries(self.chat(t))[0]["logprob"] for t in (short, long_)} + self.assertNotEqual(alone[short], alone[long_]) + for _ in range(5): + got, errs = {}, [] + + def run(t): + try: + got[t] = self.entries(self.chat(t))[0]["logprob"] + except Exception as exc: # noqa: BLE001 - reported below + errs.append(repr(exc)) + th = [threading.Thread(target=run, args=(t,)) for t in (short, long_, short, long_)] + for x in th: + x.start() + for x in th: + x.join(60) + self.assertEqual(errs, []) + self.assertEqual(got, alone) + + def test_not_asked_nothing_changes(self): + self.start_lp() + r = self.chat("Is it A or B?", logprobs=False) + self.assertEqual(r["choices"][0]["message"]["content"], "o") + self.assertIsNone(r["choices"][0].get("logprobs")) + + def test_longer_replies_are_refused_with_batch_slots(self): + self.start_lp() + with self.assertRaises(urllib.error.HTTPError) as cm: + self.chat("Is it A or B?", max_tokens=8) + self.assertEqual(cm.exception.code, 400) + self.assertIn("max_tokens 1", cm.exception.read().decode()) + # the server is still serving, and a reply that does not ask is untouched + self.assertEqual(self.chat("still serving?", max_tokens=16, logprobs=False)["choices"][0]["message"]["content"], + "ok, done.") + + def test_an_engine_without_lp_lines(self): + self.start_lp(fake=tp.FAKE_BATCH) # an older engine: the key is ignored, no LP line at all + r = self.chat("Is it A or B?") + self.assertEqual(r["choices"][0]["message"]["content"], "o") + self.assertEqual(self.entries(r), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 75d404ac..2b309cd1 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -155,6 +155,51 @@ namespace strata::metal_engine { void set_model_shard(const char* shard1); } / #include #include +// logprobs=K / allowed=...: one `LP` line for the token just emitted, from `ver`'s head +// logits for the window row it came from (before sampling, penalties and temperature). +// Format matches the SYCL port's LP line so one server-side reader serves both. +// Called only when the request asked (`req_logprobs >= 0`): a request without logprobs never reaches it, so the +// default path does no work for this and prints exactly what it printed before. +static void emit_lp_line(const strata::core::Verifier& ver, int t, int32_t token, int k, + const std::vector& allowed) { + if (k < 0) return; + static std::vector row; + row.resize((size_t) ver.vocab()); + if (!ver.copy_logits(t, row.data()) || token < 0 || (size_t) token >= row.size()) { + std::printf("LP nan\n"); + return; + } + float mx = -INFINITY; + for (const float v : row) mx = std::max(mx, v); + double se = 0.0; + for (const float v : row) se += std::exp((double) v - (double) mx); + const double lse = (double) mx + std::log(se); + std::printf("LP %.6f", (double) row[(size_t) token] - lse); + if (!allowed.empty()) { + // Only the ids the caller named; the server renormalises over them, which is what allowed_token_ids means. + // The server refuses an id past the vocabulary with a 400 only when it can read the vocabulary size from the + // tokenizer. The engine's own vocab() is the authority: an id past it is left off the line, so the logits + // are never read out of bounds. + for (const int32_t id : allowed) { + if (id == token || id < 0 || (int64_t) id >= ver.vocab()) continue; + std::printf(" %d:%.6f", (int) id, (double) row[(size_t) id] - lse); + } + std::printf("\n"); + return; + } + if (k > 0) { + static std::vector ord; + ord.resize(row.size()); + for (size_t v = 0; v < row.size(); ++v) ord[v] = (int32_t) v; + const int kk = std::min(k, (int) row.size()); + std::partial_sort(ord.begin(), ord.begin() + kk, ord.end(), + [&](int32_t a, int32_t b) { return row[(size_t) a] > row[(size_t) b]; }); + for (int j = 0; j < kk; ++j) + std::printf(" %d:%.6f", ord[(size_t) j], (double) row[(size_t) ord[(size_t) j]] - lse); + } + std::printf("\n"); +} + namespace { // Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, // pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); @@ -12474,6 +12519,11 @@ int main(int argc, char** argv) { std::string req_bias_text; bool req_bias_present = false; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) + // logprobs=K (0..20): after each "T id" an "LP logprob id:logprob ..." line. + // -1 (absent) = no LP lines, so a server that never asks sees today's output. + int req_logprobs = -1; + // allowed=a,b,c: with logprobs, print only these token ids (renormalized server-side). + std::vector req_allowed; // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root @@ -12513,6 +12563,18 @@ int main(int argc, char** argv) { else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); + else if (key == "logprobs") req_logprobs = std::atoi(tok.c_str() + eq + 1); + else if (key == "allowed") { + const std::string csv = tok.substr(eq + 1); + size_t p = 0; + while (p < csv.size()) { + const size_t c = csv.find(",", p); + const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p); + if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str())); + if (c == std::string::npos) break; + p = c + 1; + } + } else if (key == "min_p") req_min_p = fv; else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1); else if (key == "penalty_repeat") req_penalty_repeat = fv; @@ -14919,6 +14981,7 @@ int main(int argc, char** argv) { bool eos = false; for (int i = 0; !nf && i <= a && produced_n < max_new && !eos; ++i) { std::printf("T %d\n", (int) outp[(size_t) i]); + if (req_logprobs >= 0) emit_lp_line(V1(A), i, outp[(size_t) i], req_logprobs, req_allowed); strata::core::progress_beat(); ++produced_n; if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]); @@ -15339,6 +15402,7 @@ int main(int argc, char** argv) { bool eos = false; for (int i = merged ? a : 0; i <= a && produced_n < max_new && !eos; ++i) { // (merged: row T-1 only) std::printf("T %d\n", (int) outv[(size_t) i]); + if (req_logprobs >= 0) emit_lp_line(ver, i, outv[(size_t) i], req_logprobs, req_allowed); strata::core::progress_beat(); ++produced_n; if (sfx_on) sfx.append(outv[(size_t) i]); diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index a3852930..a3325c6d 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -9706,6 +9706,9 @@ int main(int argc, char **argv) try { // log-probability and the K most likely tokens', from the verify window's head logits (before sampling, // penalties and temperature). -1 (absent): no LP lines; a server that does not ask never sees one. int req_logprobs = -1; + // allowed=a,b,c: with logprobs, print only these token ids (the server renormalises over them; the same key + // the CUDA engine reads). Absent: the K most likely tokens, as before. + std::vector req_allowed; // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root @@ -9741,6 +9744,17 @@ int main(int argc, char **argv) try { else if (key == "penalty_present") req_penalty_present = fv; else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); else if (key == "logprobs") req_logprobs = std::clamp(std::atoi(tok.c_str() + eq + 1), -1, 20); + else if (key == "allowed") { + const std::string csv = tok.substr(eq + 1); + size_t p = 0; + while (p < csv.size()) { + const size_t c = csv.find(",", p); + const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p); + if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str())); + if (c == std::string::npos) break; + p = c + 1; + } + } else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); else if (key == "img_keys") { @@ -11625,7 +11639,14 @@ int main(int argc, char **argv) try { for (const float v : lrow) se += std::exp((double) v - mx); const double lse = (double) mx + std::log(se); std::printf("LP %.6f", (double) lrow[(size_t) outv[(size_t) i]] - lse); - if (req_logprobs > 0) { + if (!req_allowed.empty()) { + // only the ids the caller named (never the chosen one, which the head carries, and never an id + // past the engine's own vocabulary); the server renormalises over them + for (const int32_t id : req_allowed) { + if (id == outv[(size_t) i] || id < 0 || (size_t) id >= lrow.size()) continue; + std::printf(" %d:%.6f", (int) id, (double) lrow[(size_t) id] - lse); + } + } else if (req_logprobs > 0) { lord.resize(lrow.size()); for (size_t v = 0; v < lrow.size(); ++v) lord[v] = (int32_t) v; std::partial_sort(lord.begin(), lord.begin() + req_logprobs, lord.end(), From 211fca87df43f8eac878d2a7cc8fec896b952a0e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:10:55 +0100 Subject: [PATCH 117/177] Shared speed-switch table and Terminal: DS4_DEFAULTS=026 with the DeepSeek off switch, the 12 GB NVIDIA row, and a Qwen "0.2.6 behaviour" row (Advanced only) - DeepSeek speed-ups Off now writes DS4_DEFAULTS=026 (the engine's master switch back to the 0.2.6 defaults) plus the six DS4_*=0 for older engines; On removes all seven. A file with only the six (an earlier test build) still reads as Off and On removes them (`legacy` entries). - New switch "Faster answers on 12 GB NVIDIA cards" (the residency-biased routing default): on by default, Off writes STRATA_ROUTE_PRIOR=0. Applies to Qwen Flash-Next (no arch) on a CUDA build with a discrete NVIDIA card of 13 GiB or less (not a chip that shares system memory), the engine's own rule. - New Terminal-only switch "Qwen: 0.2.6 behaviour" (STRATA_DEFAULTS=026, off by default), a row of the Advanced table for every Qwen model, for troubleshooting; the app never shows it. DeepSeek has DS4_DEFAULTS instead. tests/terminal/test_speed_switches.py covers the new defaults, applicability, the seven DeepSeek entries and the legacy six, the Advanced rows and the comparison with the app's table (the Terminal-only switch is left out of it). --- strata_control/speed_switches.py | 48 +++++++++++- tests/terminal/test_speed_switches.py | 101 ++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 17 deletions(-) diff --git a/strata_control/speed_switches.py b/strata_control/speed_switches.py index f39d314e..8f9871cd 100644 --- a/strata_control/speed_switches.py +++ b/strata_control/speed_switches.py @@ -26,14 +26,19 @@ class Switch: label: str # the words the app shows effect: str # one plain sentence: what it does and what the other choice does env: tuple[tuple[str, str], ...] # the environment entries written when the switch is NOT in its default state - only: str # "qwen-gpu" | "qwen-radeon-9000" | "deepseek": where it applies + only: str # "qwen-gpu" | "qwen-cuda-12gb" | "qwen-radeon-9000" | "deepseek" | "qwen-any": where it applies default: str = "on" # "on" | "off": what a launch without the entries does + legacy: tuple[tuple[str, str], ...] = () # entries an earlier 0.2.7 test build wrote for the same state: they read as the switch being set, and are removed with it + terminal_only: bool = False # shown in the Terminal's Advanced table only, never in the app SWITCHES: tuple[Switch, ...] = ( Switch("faster_long_prompts", "Faster long prompts", "Reads very long prompts faster by approximating part of the work. Off by default: answers about long documents can miss or mix up details.", (("STRATA_KVA", "1"),), "qwen-gpu", default="off"), + Switch("faster_12gb_nvidia", "Faster answers on 12 GB NVIDIA cards", + "Prefers the parts of the model already on the graphics card, which makes answers much faster on 12 GB cards. Turn off if answers look worse than before.", + (("STRATA_ROUTE_PRIOR", "0"),), "qwen-cuda-12gb"), Switch("faster_radeon_9000", "Faster answers on Radeon RX 9000 / AI PRO R9700", "Shares the work between the graphics card and the processor in a way that makes answers faster on these cards. " "Turn off to go back to the previous setting, which is slower.", @@ -41,8 +46,15 @@ SWITCHES: tuple[Switch, ...] = ( Switch("deepseek_speedups", "DeepSeek speed-ups", "Reads long prompts faster and loads the parts of the model it needs faster. " "Turn off if DeepSeek stops working or its answers look wrong; it then runs as in version 0.2.6.", - (("DS4_FAST_ATTN", "0"), ("DS4_ATTN_SLAB", "0"), ("DS4_COPY_PIN", "0"), ("DS4_COPY_HUGETLB", "0"), - ("DS4_STORE_SPARE", "0"), ("DS4_STORE_PUT", "0")), "deepseek"), + # DS4_DEFAULTS=026: the engine's master switch back to the 0.2.6 defaults; the six are what older engines (and the test builds) read + (("DS4_DEFAULTS", "026"), ("DS4_FAST_ATTN", "0"), ("DS4_ATTN_SLAB", "0"), ("DS4_COPY_PIN", "0"), ("DS4_COPY_HUGETLB", "0"), + ("DS4_STORE_SPARE", "0"), ("DS4_STORE_PUT", "0")), "deepseek", + legacy=(("DS4_FAST_ATTN", "0"), ("DS4_ATTN_SLAB", "0"), ("DS4_COPY_PIN", "0"), ("DS4_COPY_HUGETLB", "0"), + ("DS4_STORE_SPARE", "0"), ("DS4_STORE_PUT", "0"))), + # Troubleshooting only, in the Terminal's Advanced table and nowhere else: every Qwen 0.2.7 default back to its 0.2.6 behaviour. + Switch("qwen_defaults_026", "Qwen: 0.2.6 behaviour", + "Starts every Qwen speed setting new in 0.2.7 the way 0.2.6 did, for troubleshooting. Use it if something that worked before no longer does.", + (("STRATA_DEFAULTS", "026"),), "qwen-any", default="off", terminal_only=True), ) BY_ID = {s.id: s for s in SWITCHES} @@ -51,6 +63,20 @@ _GFX12 = re.compile(r"^gfx120[01]$", re.IGNORECASE) _RADEON_9000 = re.compile(r"\b(?:RX\s*9\d{3}|AI\s*PRO\s*R97\d{2}|R97\d{2})\b", re.IGNORECASE) +def _small_nvidia(gpus: Iterable[Mapping[str, Any]] | None) -> bool: + """A discrete NVIDIA card of 13 GiB or less (the engine's rule for residency-biased routing: not an integrated chip, not a card that shares system memory).""" + for g in gpus or []: + if g.get("usable") is False or g.get("uma") or g.get("integrated") or (g.get("unified_gb") or 0) > 0: + continue + vendor = str(g.get("vendor") or "").lower() + if vendor not in ("nvidia", "") or (vendor == "" and not re.search(r"nvidia|geforce|\brtx\b|\bgtx\b|quadro|tesla", str(g.get("name") or ""), re.IGNORECASE)): + continue + vram = float(g.get("vram_gb") or 0) + if 0 < vram <= 13.0: + return True + return False + + def is_deepseek(cfg: Mapping[str, Any] | None) -> bool: cfg = cfg or {} return cfg.get("arch") == "deepseek41" or bool(re.search(r"strata-dsv41", str(cfg.get("exe") or ""), re.IGNORECASE)) @@ -74,11 +100,16 @@ def applies(switch: Switch | str, cfg: Mapping[str, Any] | None, gpus: Iterable[ return is_deepseek(cfg) if is_deepseek(cfg): return False + if sw.only == "qwen-any": + return True backend = (cfg or {}).get("backend") or backend if sw.only == "qwen-gpu": # KVA was measured on the Qwen3.8-Flash-Next shape (48 layers, 512 experts); the engine declines any other. Setup writes "arch" only for the # families with an engine path of their own (Qwen3.6-35B-A3B: qwen35moe), so a Flash-Next config (the original, Swift, Coder, Unsloth, Gyro, NVFP4) has none. return not (cfg or {}).get("arch") and backend in ("cuda", "hip") + if sw.only == "qwen-cuda-12gb": + # the engine's residency-biased routing needs the Flash-Next shape (512 experts, top-10) and a CUDA build; a Qwen3.6 config has an "arch" + return not (cfg or {}).get("arch") and backend == "cuda" and _small_nvidia(gpus) if sw.only == "qwen-radeon-9000": return backend == "hip" and _radeon_9000(gpus) return False @@ -89,11 +120,17 @@ def applicable(cfg: Mapping[str, Any] | None, gpus: Iterable[Mapping[str, Any]] return [s for s in SWITCHES if applies(s, cfg, gpus, backend)] +def app_switches() -> list[Switch]: + """The switches the app shows (apps/host/server/native-settings.mjs SPEED_SWITCHES): all but the Terminal-only ones.""" + return [s for s in SWITCHES if not s.terminal_only] + + def is_set(env: Mapping[str, Any] | None, switch: Switch | str) -> bool: """Every entry the switch writes is there with its value (the switch is out of its default). A file with only some of them, or other values (``STRATA_KVA=0``), is in the default state and is left alone.""" sw = BY_ID[switch] if isinstance(switch, str) else switch - return all((env or {}).get(name) == value for name, value in sw.env) + have = lambda entries: bool(entries) and all((env or {}).get(name) == value for name, value in entries) # noqa: E731 + return have(sw.env) or have(sw.legacy) def is_on(env: Mapping[str, Any] | None, switch: Switch | str) -> bool: @@ -112,6 +149,9 @@ def set_switch(env: Mapping[str, Any] | None, switch: Switch | str, on: bool) -> out[name] = value else: out.pop(name, None) + if not write: + for name, _ in sw.legacy: + out.pop(name, None) return out diff --git a/tests/terminal/test_speed_switches.py b/tests/terminal/test_speed_switches.py index 8f338632..b7b596a8 100644 --- a/tests/terminal/test_speed_switches.py +++ b/tests/terminal/test_speed_switches.py @@ -21,11 +21,17 @@ ROOT = Path(__file__).resolve().parents[2] ENV = { # what each switch writes outside its default "faster_long_prompts": {"STRATA_KVA": "1"}, + "faster_12gb_nvidia": {"STRATA_ROUTE_PRIOR": "0"}, "faster_radeon_9000": {"STRATA_PCIE_FRAC_DEFAULT": "old"}, - "deepseek_speedups": {"DS4_FAST_ATTN": "0", "DS4_ATTN_SLAB": "0", "DS4_COPY_PIN": "0", "DS4_COPY_HUGETLB": "0", + "deepseek_speedups": {"DS4_DEFAULTS": "026", "DS4_FAST_ATTN": "0", "DS4_ATTN_SLAB": "0", "DS4_COPY_PIN": "0", "DS4_COPY_HUGETLB": "0", "DS4_STORE_SPARE": "0", "DS4_STORE_PUT": "0"}, + "qwen_defaults_026": {"STRATA_DEFAULTS": "026"}, # the Terminal's troubleshooting switch: not in the app } -DEFAULT = {"faster_long_prompts": "off", "faster_radeon_9000": "on", "deepseek_speedups": "on"} +DEFAULT = {"faster_long_prompts": "off", "faster_12gb_nvidia": "on", "faster_radeon_9000": "on", "deepseek_speedups": "on", "qwen_defaults_026": "off"} +SIX = ("DS4_FAST_ATTN", "DS4_ATTN_SLAB", "DS4_COPY_PIN", "DS4_COPY_HUGETLB", "DS4_STORE_SPARE", "DS4_STORE_PUT") +RTX3060 = {"name": "NVIDIA GeForce RTX 3060", "vendor": "nvidia", "arch": "86", "vram_gb": 12.0} +RTX4070S = {"name": "NVIDIA GeForce RTX 4070 SUPER", "vendor": "nvidia", "arch": "89", "vram_gb": 12.0} +RTX4060TI16 = {"name": "NVIDIA GeForce RTX 4060 Ti 16GB", "vendor": "nvidia", "arch": "89", "vram_gb": 16.0} R9700 = {"name": "AMD Radeon AI PRO R9700", "vendor": "amd", "arch": "gfx1201"} RX7900 = {"name": "AMD Radeon RX 7900 XTX", "vendor": "amd", "arch": "gfx1100"} STRIX = {"name": "AMD Radeon 8060S", "vendor": "amd", "arch": "gfx1151", "uma": True} @@ -37,11 +43,12 @@ DEEPSEEK = {"arch": "deepseek41", "exe": "C:/s/engine-dsv41/0.1.52-win/strata-ds def ids(cfg, gpus, backend=None): - return [s.id for s in W.applicable(cfg, gpus, backend)] + """The switches the app would show (the Terminal-only one is tested apart).""" + return [s.id for s in W.applicable(cfg, gpus, backend) if not s.terminal_only] class Contract(unittest.TestCase): - def test_three_switches_with_the_contract_names_and_their_defaults(self): + def test_five_switches_with_the_contract_names_and_their_defaults(self): self.assertEqual([s.id for s in W.SWITCHES], list(ENV)) for s in W.SWITCHES: self.assertEqual(dict(s.env), ENV[s.id], s.id) @@ -49,7 +56,8 @@ class Contract(unittest.TestCase): def test_an_effect_text_says_what_the_feature_does_in_plain_words(self): for s in W.SWITCHES: - self.assertRegex(s.effect, r"Off by default" if s.default == "off" else r"[Tt]urn off", s.id) + if not s.terminal_only: + self.assertRegex(s.effect, r"Off by default" if s.default == "off" else r"[Tt]urn off", s.id) self.assertNotRegex(s.effect, r"STRATA_|DS4_|--|env", s.id) self.assertEqual(W.SWITCHES[0].effect, "Reads very long prompts faster by approximating part of the work. Off by default: answers about long documents can miss or mix up details.") @@ -67,6 +75,59 @@ class Contract(unittest.TestCase): self.assertEqual(ids({**DEEPSEEK, "backend": "cuda"}, [RTX]), ["deepseek_speedups"]) self.assertEqual(ids({"exe": "C:/x/strata-dsv41.exe"}, [RTX]), ["deepseek_speedups"], "found by the engine's name too") + def test_faster_answers_on_12gb_nvidia_cards_only_where_the_engine_routing_default_applies(self): + """The engine turns residency-biased routing on by default on a DISCRETE NVIDIA card of 13 GiB or less in a CUDA build (the Flash-Next shape).""" + self.assertEqual(ids(QWEN, [RTX3060]), ["faster_long_prompts", "faster_12gb_nvidia"]) + self.assertEqual(ids(QWEN, [RTX4070S]), ["faster_long_prompts", "faster_12gb_nvidia"]) + self.assertEqual(ids(QWEN, [{**RTX3060, "vram_gb": 13.0}]), ["faster_long_prompts", "faster_12gb_nvidia"], "13 GiB counts") + self.assertEqual(ids(QWEN, [{**RTX3060, "vram_gb": 13.5}]), ["faster_long_prompts"]) + self.assertEqual(ids(QWEN, [RTX4060TI16]), ["faster_long_prompts"], "16 GB is not a 12 GB card") + self.assertEqual(ids(QWEN, [RTX]), ["faster_long_prompts"]) + self.assertEqual(ids(QWEN, [RTX3060, RTX]), ["faster_long_prompts", "faster_12gb_nvidia"], "one small card among others") + self.assertEqual(ids(QWEN, [{**RTX3060, "uma": True}]), ["faster_long_prompts"], "not a chip that shares system memory") + self.assertEqual(ids(QWEN, [{**RTX3060, "integrated": True}]), ["faster_long_prompts"]) + self.assertEqual(ids(QWEN, [{**RTX3060, "usable": False}]), ["faster_long_prompts"]) + self.assertEqual(ids({**QWEN, "backend": "hip"}, [{"name": "AMD Radeon RX 7700 XT", "vendor": "amd", "arch": "gfx1101", "vram_gb": 12.0}]), ["faster_long_prompts"], "not a Radeon") + self.assertEqual(ids({**QWEN, "backend": "sycl"}, [RTX3060]), [], "not a CUDA build") + self.assertEqual(ids(QWEN36, [RTX3060]), [], "Qwen3.6-35B-A3B: the routing needs 512 experts") + self.assertEqual(ids(DEEPSEEK, [RTX3060]), ["deepseek_speedups"]) + self.assertEqual(ids(QWEN, [{"name": "GeForce RTX 3060", "vram_gb": 12.0}]), ["faster_long_prompts", "faster_12gb_nvidia"], "no vendor reported: the name decides") + self.assertEqual(ids(QWEN, [{"name": "Mystery card", "vram_gb": 12.0}]), ["faster_long_prompts"]) + + def test_the_12gb_switch_off_writes_route_prior_zero_and_on_removes_it(self): + env = {"PATH": "/bin"} + off = W.set_switch(env, "faster_12gb_nvidia", False) + self.assertEqual(off, {"PATH": "/bin", "STRATA_ROUTE_PRIOR": "0"}) + self.assertFalse(W.is_on(off, "faster_12gb_nvidia")) + self.assertTrue(W.is_on({}, "faster_12gb_nvidia")) + self.assertEqual(W.set_switch(off, "faster_12gb_nvidia", True), env) + self.assertTrue(W.is_on({"STRATA_ROUTE_PRIOR": "2.0"}, "faster_12gb_nvidia"), "any other value is the user's own and reads as the default") + + def test_deepseek_off_writes_the_master_switch_and_the_six_and_on_removes_all_seven(self): + env = {"DS4_ASYNC_T": "4"} + off = W.set_switch(env, "deepseek_speedups", False) + self.assertEqual(list(off)[:2], ["DS4_ASYNC_T", "DS4_DEFAULTS"], "the master switch first") + self.assertEqual(off, {"DS4_ASYNC_T": "4", "DS4_DEFAULTS": "026", **{k: "0" for k in SIX}}) + self.assertFalse(W.is_on(off, "deepseek_speedups")) + self.assertEqual(W.set_switch(off, "deepseek_speedups", True), env) + # an earlier test build wrote only the six: it still reads as off, and turning it on removes them + six = {"DS4_ASYNC_T": "4", **{k: "0" for k in SIX}} + self.assertFalse(W.is_on(six, "deepseek_speedups")) + self.assertEqual(W.set_switch(six, "deepseek_speedups", True), env) + self.assertTrue(W.is_on({"DS4_DEFAULTS": "026"}, "deepseek_speedups"), "the master switch alone is not the whole switch: a hand-edited file is left alone") + + def test_the_terminal_only_switch_is_for_qwen_and_never_in_the_app(self): + sw = W.BY_ID["qwen_defaults_026"] + self.assertTrue(sw.terminal_only) + self.assertEqual(dict(sw.env), {"STRATA_DEFAULTS": "026"}) + self.assertNotIn("qwen_defaults_026", [s.id for s in W.app_switches()]) + for cfg, gpus in ((QWEN, [RTX]), (QWEN36, [RTX]), ({**QWEN, "backend": "sycl"}, []), ({**QWEN, "backend": "cpu"}, [])): + self.assertIn("qwen_defaults_026", [s.id for s in W.applicable(cfg, gpus)]) + self.assertNotIn("qwen_defaults_026", [s.id for s in W.applicable(DEEPSEEK, [RTX])], "DeepSeek has its own master switch (DS4_DEFAULTS)") + self.assertEqual(W.set_switch({"PATH": "/bin"}, sw, True), {"PATH": "/bin", "STRATA_DEFAULTS": "026"}) + self.assertFalse(W.is_on({}, sw)) + self.assertEqual(W.set_switch({"STRATA_DEFAULTS": "026"}, sw, False), {}) + def test_faster_long_prompts_is_for_qwen38_flash_next_only(self): """KVA was measured on the 48-layer / 512-expert Flash-Next shape and the engine declines other shapes: no row for Qwen3.6-35B-A3B (arch qwen35moe) or DeepSeek.""" self.assertEqual(ids(QWEN36, [RTX]), [], "Qwen3.6-35B-A3B on CUDA: no KVA row") @@ -130,10 +191,23 @@ class Terminal(unittest.TestCase): def names(cfg, gpus, extra=None): rows = P.build_rows(None, cfg["args"], None, cfg["env"], None, extra or {}, P.switch_params(W.applicable(cfg, gpus))) return [r.name for r in rows if r.name in W.env_names()] - self.assertEqual(names(QWEN, [RTX]), ["STRATA_KVA"]) - self.assertEqual(names({**QWEN, "backend": "hip"}, [R9700]), ["STRATA_KVA", "STRATA_PCIE_FRAC_DEFAULT"]) - self.assertEqual(names(DEEPSEEK, [R9700]), list(ENV["deepseek_speedups"]), "the six, in the contract order") - self.assertEqual(names({**QWEN, "backend": "sycl"}, [R9700]), []) + # (STRATA_DEFAULTS, the Qwen "0.2.6 behaviour" row, closes every Qwen table; the DeepSeek table has DS4_DEFAULTS instead) + self.assertEqual(names(QWEN, [RTX]), ["STRATA_KVA", "STRATA_DEFAULTS"]) + self.assertEqual(names(QWEN, [RTX3060]), ["STRATA_KVA", "STRATA_ROUTE_PRIOR", "STRATA_DEFAULTS"]) + self.assertEqual(names({**QWEN, "backend": "hip"}, [R9700]), ["STRATA_KVA", "STRATA_PCIE_FRAC_DEFAULT", "STRATA_DEFAULTS"]) + self.assertEqual(names(DEEPSEEK, [R9700]), list(ENV["deepseek_speedups"]), "the master switch and the six, in the contract order") + self.assertEqual(names({**QWEN, "backend": "sycl"}, [R9700]), ["STRATA_DEFAULTS"]) + self.assertEqual(names(QWEN36, [RTX]), ["STRATA_DEFAULTS"]) + + def test_the_qwen_0_2_6_row_in_the_advanced_table(self): + rows = P.build_rows(None, QWEN["args"], None, QWEN["env"], None, {}, P.switch_params(W.applicable(QWEN, [RTX]))) + row = next(r for r in rows if r.name == "STRATA_DEFAULTS") + self.assertEqual((row.default, row.yours, row.known), ("off", "", True)) + self.assertIn("Qwen: 0.2.6 behaviour", row.description) + self.assertIn("off by default; set 026 to turn on", row.description) + cfg = derive_config(QWEN, S.LaunchSettings(extra=S.settings_from_pairs(["STRATA_DEFAULTS=026"])), bool_flags=frozenset()) + self.assertEqual(cfg["env"], {**QWEN["env"], "STRATA_DEFAULTS": "026"}) + self.assertEqual(derive_config(QWEN, S.LaunchSettings(), bool_flags=frozenset())["env"], QWEN["env"], "a default launch carries nothing") def test_a_row_shows_its_default_until_it_is_changed_and_explains_itself(self): rows = P.build_rows(None, QWEN["args"], None, QWEN["env"], None, {}, P.switch_params(W.applicable(QWEN, [RTX]))) @@ -151,7 +225,7 @@ class Terminal(unittest.TestCase): def test_the_six_deepseek_rows_say_they_go_together(self): text = W.env_words("DS4_COPY_PIN") - self.assertIn("all 6 speed-up rows go together", text) + self.assertIn("all 7 speed-up rows go together", text) self.assertEqual({W.env_names()[n].id for n in ENV["deepseek_speedups"]}, {"deepseek_speedups"}) @@ -159,15 +233,16 @@ class SameAsTheApp(unittest.TestCase): @unittest.skipUnless(shutil.which("node"), "node is not installed") def test_the_apps_table_has_the_same_names_and_words(self): script = ("import {SPEED_SWITCHES} from './apps/host/server/native-settings.mjs';" - "console.log(JSON.stringify(SPEED_SWITCHES.map(s=>({id:s.id,label:s.label,hint:s.hint,default:s.default,env:s.env}))))") + "console.log(JSON.stringify(SPEED_SWITCHES.map(s=>({id:s.id,label:s.label,hint:s.hint,default:s.default,env:s.env,legacy:s.legacy??{}}))))") out = subprocess.run(["node", "--input-type=module", "-e", script], cwd=ROOT, capture_output=True, text=True, timeout=60, check=True).stdout app = json.loads(out) - self.assertEqual([a["id"] for a in app], [s.id for s in W.SWITCHES]) - for a, s in zip(app, W.SWITCHES): + self.assertEqual([a["id"] for a in app], [s.id for s in W.app_switches()], "the Terminal-only switch is not in the app's table") + for a, s in zip(app, W.app_switches()): self.assertEqual(a["label"], s.label) self.assertEqual(a["hint"], s.effect, s.id) self.assertEqual(a["env"], dict(s.env), s.id) self.assertEqual(a["default"], s.default, s.id) + self.assertEqual(a["legacy"], dict(s.legacy), s.id) if __name__ == "__main__": From 6f1bd21e59a480313c0695f0b02b7e8e71dee107 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:10:55 +0100 Subject: [PATCH 118/177] App: "Faster answers on 12 GB NVIDIA cards" row; DeepSeek speed-ups Off also writes DS4_DEFAULTS=026 The Speed group gets a row for Qwen on a discrete CUDA card of 13 GiB or less: "Prefers the parts of the model already on the graphics card, which makes answers much faster on 12 GB cards. Turn off if answers look worse than before." On (recommended) by default; Off writes STRATA_ROUTE_PRIOR=0, On removes it. The DeepSeek speed-ups row, when Off, writes DS4_DEFAULTS=026 and the six DS4_*=0; On removes all of them, and a file that holds only the six (an earlier test build) shows as Off. The Qwen "0.2.6 behaviour" switch is Terminal-only and is not in the app. New strings fx82 and fx83 in the eight fix catalogs. --- apps/host/server/native-settings.mjs | 19 ++++++-- apps/host/src/components/NativeSettings.tsx | 7 ++- apps/host/src/locales/fix-de.json | 4 +- apps/host/src/locales/fix-en.json | 4 +- apps/host/src/locales/fix-es.json | 4 +- apps/host/src/locales/fix-ja.json | 4 +- apps/host/src/locales/fix-ko.json | 4 +- apps/host/src/locales/fix-pt.json | 4 +- apps/host/src/locales/fix-ru.json | 4 +- apps/host/src/locales/fix-zh.json | 4 +- apps/host/tests/speed-switches.test.mjs | 53 +++++++++++++++++++-- 11 files changed, 95 insertions(+), 16 deletions(-) diff --git a/apps/host/server/native-settings.mjs b/apps/host/server/native-settings.mjs index 82f93ed8..e1ebc954 100644 --- a/apps/host/server/native-settings.mjs +++ b/apps/host/server/native-settings.mjs @@ -39,12 +39,17 @@ export const SPEED_SWITCHES=[ {id:'faster_long_prompts',label:'Faster long prompts',group:'Speed', hint:'Reads very long prompts faster by approximating part of the work. Off by default: answers about long documents can miss or mix up details.', default:'off',env:{STRATA_KVA:'1'}}, + {id:'faster_12gb_nvidia',label:'Faster answers on 12 GB NVIDIA cards',group:'Speed', + hint:'Prefers the parts of the model already on the graphics card, which makes answers much faster on 12 GB cards. Turn off if answers look worse than before.', + default:'on',env:{STRATA_ROUTE_PRIOR:'0'}}, {id:'faster_radeon_9000',label:'Faster answers on Radeon RX 9000 / AI PRO R9700',group:'Speed', hint:'Shares the work between the graphics card and the processor in a way that makes answers faster on these cards. Turn off to go back to the previous setting, which is slower.', default:'on',env:{STRATA_PCIE_FRAC_DEFAULT:'old'}}, {id:'deepseek_speedups',label:'DeepSeek speed-ups',group:'Speed', hint:'Reads long prompts faster and loads the parts of the model it needs faster. Turn off if DeepSeek stops working or its answers look wrong; it then runs as in version 0.2.6.', - default:'on',env:{DS4_FAST_ATTN:'0',DS4_ATTN_SLAB:'0',DS4_COPY_PIN:'0',DS4_COPY_HUGETLB:'0',DS4_STORE_SPARE:'0',DS4_STORE_PUT:'0'}}, + default:'on',env:{DS4_DEFAULTS:'026',DS4_FAST_ATTN:'0',DS4_ATTN_SLAB:'0',DS4_COPY_PIN:'0',DS4_COPY_HUGETLB:'0',DS4_STORE_SPARE:'0',DS4_STORE_PUT:'0'}, + /* an earlier test build wrote only these six for the same state: they read as the switch being set, and go with it */ + legacy:{DS4_FAST_ATTN:'0',DS4_ATTN_SLAB:'0',DS4_COPY_PIN:'0',DS4_COPY_HUGETLB:'0',DS4_STORE_SPARE:'0',DS4_STORE_PUT:'0'}}, ]; const GFX12=/^gfx120[01]$/i, RADEON_9000=/\b(?:RX\s*9\d{3}|AI\s*PRO\s*R97\d{2}|R97\d{2})\b/i; /** @@ -53,21 +58,29 @@ const GFX12=/^gfx120[01]$/i, RADEON_9000=/\b(?:RX\s*9\d{3}|AI\s*PRO\s*R97\d{2}|R * the Qwen3.8-Flash-Next files (the original, Swift, Coder, Unsloth, Gyro, NVFP4) have none. KVA was measured on the Flash-Next shape (48 layers, 512 * experts) and the engine declines it on any other, so "Faster long prompts" is shown for a model without an "arch" only. */ +/** A discrete NVIDIA card of 13 GiB or less: the engine's rule for residency-biased routing (not an integrated chip, not a card that shares system memory). */ +const smallNvidia=gpus=>(gpus??[]).some(g=>{ + if(g.usable===false||g.uma||g.integrated||(g.unified_gb??0)>0)return false; + const vendor=String(g.vendor??'').toLowerCase(); + if(vendor!=='nvidia'&&!(vendor===''&&/nvidia|geforce|\brtx\b|\bgtx\b|quadro|tesla/i.test(String(g.name??''))))return false; + return g.vram_gb>0&&g.vram_gb<=13; +}); export function speedSwitchApplies(id,{deepseek=false,backend=null,gpus=[],arch=null}={}){ if(id==='deepseek_speedups')return !!deepseek; if(deepseek)return false; // the Qwen engine's switches if(id==='faster_long_prompts')return !arch&&(backend==='cuda'||backend==='hip'); + if(id==='faster_12gb_nvidia')return !arch&&backend==='cuda'&&smallNvidia(gpus); // the engine's routing needs the Flash-Next shape (512 experts, top-10) and a CUDA build if(id==='faster_radeon_9000')return backend==='hip'&&(gpus??[]).some(g=>(!g.vendor||g.vendor==='amd')&&(GFX12.test(String(g.arch??''))||(!g.arch&&RADEON_9000.test(String(g.name??''))))); return false; } /** The switch is outside its default when every entry it writes is in the environment with its value; anything less or other (a hand-edited file, STRATA_KVA=0) is the default state and is left alone. */ -export function speedSwitchIsSet(env,id){const sw=SPEED_SWITCHES.find(s=>s.id===id);return !!sw&&Object.entries(sw.env).every(([name,value])=>env?.[name]===value);} +export function speedSwitchIsSet(env,id){const sw=SPEED_SWITCHES.find(s=>s.id===id),has=entries=>!!entries&&Object.keys(entries).length>0&&Object.entries(entries).every(([name,value])=>env?.[name]===value);return !!sw&&(has(sw.env)||has(sw.legacy));} /** Is the feature on for a launch with this environment? */ export function speedSwitchIsOn(env,id){const sw=SPEED_SWITCHES.find(s=>s.id===id);return !!sw&&speedSwitchIsSet(env,id)!==(sw.default==='on');} /** The environment with the feature on or off: its default removes the switch's entries, the other state writes them. Nothing else in it changes. */ export function setSpeedSwitch(env,id,on){ const sw=SPEED_SWITCHES.find(s=>s.id===id);if(!sw)throw new Error(`Unknown speed switch: ${id}`); - const write=on!==(sw.default==='on'),next={...(env??{})};for(const [name,value] of Object.entries(sw.env)){if(write)next[name]=value;else delete next[name];}return next; + const write=on!==(sw.default==='on'),next={...(env??{})};for(const [name,value] of Object.entries(sw.env)){if(write)next[name]=value;else delete next[name];}if(!write)for(const name of Object.keys(sw.legacy??{}))delete next[name];return next; } /** What the settings answer carries: each switch that applies, with its words, its default, the entries it writes outside the default, and whether the feature is on. */ export function speedSwitchRows(env,context){return SPEED_SWITCHES.filter(s=>speedSwitchApplies(s.id,context)).map(s=>({...s,on:speedSwitchIsOn(env,s.id)}));} diff --git a/apps/host/src/components/NativeSettings.tsx b/apps/host/src/components/NativeSettings.tsx index 062874f1..356652fa 100644 --- a/apps/host/src/components/NativeSettings.tsx +++ b/apps/host/src/components/NativeSettings.tsx @@ -16,8 +16,11 @@ interface SpeedSwitch { hint: string; default: 'on' | 'off'; env: Record; + /** What an earlier test build wrote for the same state: it reads as set, and goes with it. */ + legacy?: Record; } -const switchIsSet = (sw: SpeedSwitch, env: Record | undefined) => Object.entries(sw.env).every(([name, value]) => env?.[name] === value); +const switchHas = (entries: Record | undefined, env: Record | undefined) => !!entries && Object.keys(entries).length > 0 && Object.entries(entries).every(([name, value]) => env?.[name] === value); +const switchIsSet = (sw: SpeedSwitch, env: Record | undefined) => switchHas(sw.env, env) || switchHas(sw.legacy, env); const switchIsOn = (sw: SpeedSwitch, env: Record | undefined) => switchIsSet(sw, env) !== (sw.default === 'on'); export function NativeSettings({ model }: { model: string; @@ -61,7 +64,7 @@ export function NativeSettings({ model }: { }, [model,revision]); const change = (id: string, value: any) => { const next = { ...values, [id]: value }; setValues(next); setText(JSON.stringify(next, null, 2)); setNotice(''); }; /** The default removes the switch's environment entries, the other state writes them: the model's file then carries nothing for a default launch. */ - const changeSwitch = (sw: SpeedSwitch, on: boolean) => { const env = { ...(values.env ?? {}) }; const write = on !== (sw.default === 'on'); for (const [name, value] of Object.entries(sw.env)) { if (write) env[name] = value; else delete env[name]; } change('env', env); }; + const changeSwitch = (sw: SpeedSwitch, on: boolean) => { const env = { ...(values.env ?? {}) }; const write = on !== (sw.default === 'on'); for (const [name, value] of Object.entries(sw.env)) { if (write) env[name] = value; else delete env[name]; } if (!write) for (const name of Object.keys(sw.legacy ?? {})) delete env[name]; change('env', env); }; async function save() { setPending(true); setError(''); diff --git a/apps/host/src/locales/fix-de.json b/apps/host/src/locales/fix-de.json index f378e020..20e77cad 100644 --- a/apps/host/src/locales/fix-de.json +++ b/apps/host/src/locales/fix-de.json @@ -77,5 +77,7 @@ "fx76": "Ein (empfohlen)", "fx77": "Das ist ein sehr großes Modell. Der Download umfasst {0} GB und braucht etwa so viel freien Speicherplatz. Es läuft auf NVIDIA-RTX-Karten der Serien 30, 40 und 50, auf einer Radeon AI PRO R9700 (Linux) oder auf einem Ryzen-AI-Max-/Strix-Halo-PC (Windows); wie schnell es ist, hängt von Speicher und Grafikkarte ab (die Zeile darunter sagt, was auf diesem Computer zu erwarten ist). Was nicht in den Speicher passt, wird von deiner SSD gelesen, deshalb zählt eine NVMe-SSD.", "fx78": "Noch nicht getestet. Ein so langer Kontext nimmt dem Modell Grafikspeicher weg, und lange Prompts werden langsam gelesen.", - "fx79": "Aus (empfohlen)" + "fx79": "Aus (empfohlen)", + "fx82": "Schnellere Antworten auf NVIDIA-Karten mit 12 GB", + "fx83": "Bevorzugt die Teile des Modells, die schon auf der Grafikkarte liegen. Das macht Antworten auf Karten mit 12 GB deutlich schneller. Schalten Sie die Option aus, wenn die Antworten schlechter aussehen als vorher." } diff --git a/apps/host/src/locales/fix-en.json b/apps/host/src/locales/fix-en.json index efe52962..c64be1ee 100644 --- a/apps/host/src/locales/fix-en.json +++ b/apps/host/src/locales/fix-en.json @@ -77,5 +77,7 @@ "fx76": "On (recommended)", "fx77": "This is a very large model. The download is {0} GB and it needs about as much free disk space. It runs on NVIDIA RTX 30, 40 and 50 cards, on a Radeon AI PRO R9700 (Linux) or on a Ryzen AI Max / Strix Halo PC (Windows); how fast it is depends on the memory and card (the line below says what to expect on this computer). What does not fit in memory is read from your SSD, so an NVMe drive matters.", "fx78": "Not tested yet. A context this long takes graphics memory from the model and reads long prompts slowly.", - "fx79": "Off (recommended)" + "fx79": "Off (recommended)", + "fx82": "Faster answers on 12 GB NVIDIA cards", + "fx83": "Prefers the parts of the model already on the graphics card, which makes answers much faster on 12 GB cards. Turn off if answers look worse than before." } diff --git a/apps/host/src/locales/fix-es.json b/apps/host/src/locales/fix-es.json index 211c1988..e05f3251 100644 --- a/apps/host/src/locales/fix-es.json +++ b/apps/host/src/locales/fix-es.json @@ -77,5 +77,7 @@ "fx76": "Activado (recomendado)", "fx77": "Es un modelo muy grande. La descarga es de {0} GB y necesita casi el mismo espacio libre en disco. Funciona con tarjetas NVIDIA RTX de las series 30, 40 y 50, con una Radeon AI PRO R9700 (Linux) o en un PC con Ryzen AI Max / Strix Halo (Windows); su velocidad depende de la memoria y de la tarjeta (la línea de abajo indica qué esperar en este equipo). Lo que no cabe en memoria se lee de tu SSD, así que importa que sea NVMe.", "fx78": "Aún sin probar. Un contexto tan largo le quita memoria gráfica al modelo y lee los prompts largos con lentitud.", - "fx79": "Desactivado (recomendado)" + "fx79": "Desactivado (recomendado)", + "fx82": "Respuestas más rápidas en tarjetas NVIDIA de 12 GB", + "fx83": "Prefiere las partes del modelo que ya están en la tarjeta gráfica, lo que hace las respuestas mucho más rápidas en tarjetas de 12 GB. Desactívalo si las respuestas parecen peores que antes." } diff --git a/apps/host/src/locales/fix-ja.json b/apps/host/src/locales/fix-ja.json index 2b888a77..10003fac 100644 --- a/apps/host/src/locales/fix-ja.json +++ b/apps/host/src/locales/fix-ja.json @@ -77,5 +77,7 @@ "fx76": "オン(推奨)", "fx77": "とても大きなモデルです。ダウンロードは {0} GB で、ほぼ同じ大きさの空き容量が必要です。NVIDIA RTX 30・40・50 シリーズ、Radeon AI PRO R9700(Linux)、または Ryzen AI Max / Strix Halo の PC(Windows)で動きます。速さはメモリとカードによって変わります(この PC での目安は下の行に表示されます)。メモリに入らない分は SSD から読むため、NVMe ドライブが重要です。", "fx78": "まだテストされていません。これほど長いコンテキストは、モデルが使うグラフィックスメモリを消費し、長いプロンプトの読み込みも遅くなります。", - "fx79": "オフ(推奨)" + "fx79": "オフ(推奨)", + "fx82": "12 GB の NVIDIA カードでの高速な応答", + "fx83": "グラフィックスカード上にすでにあるモデルの部分を優先して使うため、12 GB のカードで応答がとても速くなります。以前より回答が悪くなったと感じたらオフにしてください。" } diff --git a/apps/host/src/locales/fix-ko.json b/apps/host/src/locales/fix-ko.json index befec99d..85c435fc 100644 --- a/apps/host/src/locales/fix-ko.json +++ b/apps/host/src/locales/fix-ko.json @@ -77,5 +77,7 @@ "fx76": "켬(권장)", "fx77": "매우 큰 모델입니다. 다운로드는 {0}GB이고, 거의 같은 크기의 여유 디스크 공간이 필요합니다. NVIDIA RTX 30·40·50 시리즈 카드, Radeon AI PRO R9700(Linux), 또는 Ryzen AI Max / Strix Halo PC(Windows)에서 실행됩니다. 속도는 메모리와 카드에 따라 달라집니다(아래 줄에 이 컴퓨터에서 기대할 수 있는 속도가 표시됩니다). 메모리에 들어가지 않는 부분은 SSD에서 읽으므로 NVMe 드라이브가 중요합니다.", "fx78": "아직 테스트하지 않았습니다. 이렇게 긴 컨텍스트는 모델이 쓸 그래픽 메모리를 차지하고, 긴 프롬프트를 느리게 읽습니다.", - "fx79": "끔(권장)" + "fx79": "끔(권장)", + "fx82": "12GB NVIDIA 카드에서 더 빠른 응답", + "fx83": "이미 그래픽 카드에 올라와 있는 모델 부분을 우선 사용해 12GB 카드에서 응답이 훨씬 빨라집니다. 답변이 이전보다 나빠 보이면 끄세요." } diff --git a/apps/host/src/locales/fix-pt.json b/apps/host/src/locales/fix-pt.json index 3accb7ef..35c4d471 100644 --- a/apps/host/src/locales/fix-pt.json +++ b/apps/host/src/locales/fix-pt.json @@ -77,5 +77,7 @@ "fx76": "Ativado (recomendado)", "fx77": "Este é um modelo muito grande. O download tem {0} GB e precisa de quase o mesmo espaço livre em disco. Ele roda em placas NVIDIA RTX das séries 30, 40 e 50, em uma Radeon AI PRO R9700 (Linux) ou em um PC com Ryzen AI Max / Strix Halo (Windows); a velocidade depende da memória e da placa (a linha abaixo diz o que esperar neste computador). O que não cabe na memória é lido do seu SSD, então um NVMe faz diferença.", "fx78": "Ainda não testado. Um contexto tão longo tira memória gráfica do modelo e lê prompts longos devagar.", - "fx79": "Desativado (recomendado)" + "fx79": "Desativado (recomendado)", + "fx82": "Respostas mais rápidas em placas NVIDIA de 12 GB", + "fx83": "Prefere as partes do modelo que já estão na placa de vídeo, o que deixa as respostas bem mais rápidas em placas de 12 GB. Desative se as respostas parecerem piores do que antes." } diff --git a/apps/host/src/locales/fix-ru.json b/apps/host/src/locales/fix-ru.json index d2147327..f9cc74ff 100644 --- a/apps/host/src/locales/fix-ru.json +++ b/apps/host/src/locales/fix-ru.json @@ -77,5 +77,7 @@ "fx76": "Вкл. (рекомендуется)", "fx77": "Это очень большая модель. Загрузка — {0} ГБ, и нужно почти столько же свободного места на диске. Она работает на видеокартах NVIDIA RTX серий 30, 40 и 50, на Radeon AI PRO R9700 (Linux) или на ПК с Ryzen AI Max / Strix Halo (Windows); скорость зависит от памяти и видеокарты (строка ниже подскажет, чего ждать на этом компьютере). То, что не помещается в память, читается с вашего SSD, поэтому важен накопитель NVMe.", "fx78": "Ещё не проверено. Такой длинный контекст отнимает у модели видеопамять, а длинные запросы читаются медленно.", - "fx79": "Выкл. (рекомендуется)" + "fx79": "Выкл. (рекомендуется)", + "fx82": "Более быстрые ответы на видеокартах NVIDIA с 12 ГБ", + "fx83": "Отдаёт предпочтение частям модели, которые уже находятся на видеокарте, поэтому ответы на картах с 12 ГБ становятся намного быстрее. Отключите, если ответы стали выглядеть хуже, чем раньше." } diff --git a/apps/host/src/locales/fix-zh.json b/apps/host/src/locales/fix-zh.json index 48b64cd1..9d66e038 100644 --- a/apps/host/src/locales/fix-zh.json +++ b/apps/host/src/locales/fix-zh.json @@ -77,5 +77,7 @@ "fx76": "开启(推荐)", "fx77": "这是一个非常大的模型。下载大小为 {0} GB,需要差不多同样大小的可用磁盘空间。它可在 NVIDIA RTX 30、40 和 50 系列显卡、Radeon AI PRO R9700(Linux)或 Ryzen AI Max / Strix Halo 电脑(Windows)上运行;速度取决于内存和显卡(下面一行会说明在这台电脑上的预期)。内存放不下的部分会从你的 SSD 读取,所以 NVMe 硬盘很重要。", "fx78": "尚未测试。这么长的上下文会占用本该给模型使用的显存,读取长提示词也会很慢。", - "fx79": "关闭(推荐)" + "fx79": "关闭(推荐)", + "fx82": "12 GB NVIDIA 显卡上更快的回答", + "fx83": "优先使用已经在显卡上的模型部分,使 12 GB 显卡上的回答快很多。如果回答看起来比以前差,请关闭。" } diff --git a/apps/host/tests/speed-switches.test.mjs b/apps/host/tests/speed-switches.test.mjs index 58b8c638..7bef737f 100644 --- a/apps/host/tests/speed-switches.test.mjs +++ b/apps/host/tests/speed-switches.test.mjs @@ -13,16 +13,19 @@ import { nativeFixture } from './helpers/native-fixture.mjs'; const read = rel => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8').replace(/\r\n/g, '\n'); const ENV = { // what each switch writes outside its default faster_long_prompts: { STRATA_KVA: '1' }, + faster_12gb_nvidia: { STRATA_ROUTE_PRIOR: '0' }, faster_radeon_9000: { STRATA_PCIE_FRAC_DEFAULT: 'old' }, - deepseek_speedups: { DS4_FAST_ATTN: '0', DS4_ATTN_SLAB: '0', DS4_COPY_PIN: '0', DS4_COPY_HUGETLB: '0', DS4_STORE_SPARE: '0', DS4_STORE_PUT: '0' }, + deepseek_speedups: { DS4_DEFAULTS: '026', DS4_FAST_ATTN: '0', DS4_ATTN_SLAB: '0', DS4_COPY_PIN: '0', DS4_COPY_HUGETLB: '0', DS4_STORE_SPARE: '0', DS4_STORE_PUT: '0' }, }; -const DEFAULT = { faster_long_prompts: 'off', faster_radeon_9000: 'on', deepseek_speedups: 'on' }; +const SIX = ['DS4_FAST_ATTN', 'DS4_ATTN_SLAB', 'DS4_COPY_PIN', 'DS4_COPY_HUGETLB', 'DS4_STORE_SPARE', 'DS4_STORE_PUT']; +const DEFAULT = { faster_long_prompts: 'off', faster_12gb_nvidia: 'on', faster_radeon_9000: 'on', deepseek_speedups: 'on' }; +const RTX3060 = { index: 0, name: 'NVIDIA GeForce RTX 3060', vendor: 'nvidia', arch: '86', vram_gb: 12 }; const R9700 = { index: 0, name: 'AMD Radeon AI PRO R9700', vendor: 'amd', arch: 'gfx1201', vram_gb: 32 }; const RX7900 = { index: 0, name: 'AMD Radeon RX 7900 XTX', vendor: 'amd', arch: 'gfx1100', vram_gb: 24 }; const RTX = { index: 0, name: 'NVIDIA GeForce RTX 4090', vendor: 'nvidia', arch: '89', vram_gb: 24 }; const STRIX = { index: 0, name: 'AMD Radeon 8060S', vendor: 'amd', arch: 'gfx1151', vram_gb: 96, uma: true }; -test('there are exactly three switches; each writes the engine names of the contract and has its default (KVA off, the others on)', () => { +test('there are exactly four switches in the app (the Terminal has one more); each writes the engine names of the contract and has its default (KVA off, the others on)', () => { assert.deepEqual(SPEED_SWITCHES.map(s => s.id), Object.keys(ENV)); for (const sw of SPEED_SWITCHES) { assert.deepEqual(sw.env, ENV[sw.id], sw.id); @@ -30,6 +33,50 @@ test('there are exactly three switches; each writes the engine names of the cont } }); +test('the Terminal\'s Qwen "0.2.6 behaviour" switch is not in the app', () => { + assert.ok(!SPEED_SWITCHES.some(s => s.env.STRATA_DEFAULTS || /0\.2\.6 behaviour/.test(s.label))); + assert.ok(!Object.values(SPEED_SWITCHES.flatMap(s => Object.keys(s.env))).includes('STRATA_DEFAULTS')); +}); + +test('Faster answers on 12 GB NVIDIA cards: only for Qwen on a discrete CUDA card of 13 GiB or less; Off writes STRATA_ROUTE_PRIOR=0', () => { + const ids = context => speedSwitchRows({}, context).map(r => r.id); + assert.deepEqual(ids({ backend: 'cuda', gpus: [RTX3060] }), ['faster_long_prompts', 'faster_12gb_nvidia']); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ ...RTX3060, vram_gb: 13 }] }), ['faster_long_prompts', 'faster_12gb_nvidia'], '13 GiB counts'); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ ...RTX3060, vram_gb: 13.5 }] }), ['faster_long_prompts']); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ ...RTX3060, vram_gb: 16 }] }), ['faster_long_prompts'], 'a 16 GB card is not a 12 GB card'); + assert.deepEqual(ids({ backend: 'cuda', gpus: [RTX] }), ['faster_long_prompts']); + assert.deepEqual(ids({ backend: 'cuda', gpus: [RTX, RTX3060] }), ['faster_long_prompts', 'faster_12gb_nvidia'], 'one small card among others'); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ ...RTX3060, uma: true }] }), ['faster_long_prompts'], 'not a chip that shares system memory'); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ ...RTX3060, integrated: true }] }), ['faster_long_prompts']); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ ...RTX3060, usable: false }] }), ['faster_long_prompts']); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ name: 'GeForce RTX 3060', vram_gb: 12 }] }), ['faster_long_prompts', 'faster_12gb_nvidia'], 'no vendor reported: the name decides'); + assert.deepEqual(ids({ backend: 'cuda', gpus: [{ name: 'Mystery card', vram_gb: 12 }] }), ['faster_long_prompts']); + assert.deepEqual(ids({ backend: 'hip', gpus: [{ name: 'AMD Radeon RX 7700 XT', vendor: 'amd', arch: 'gfx1101', vram_gb: 12 }] }), ['faster_long_prompts'], 'not a Radeon'); + assert.deepEqual(ids({ backend: 'sycl', gpus: [RTX3060] }), [], 'not a CUDA build'); + assert.deepEqual(ids({ backend: 'cuda', gpus: [RTX3060], arch: 'qwen35moe' }), [], 'Qwen3.6-35B-A3B: the routing needs 512 experts'); + assert.deepEqual(ids({ deepseek: true, backend: 'cuda', gpus: [RTX3060] }), ['deepseek_speedups']); + const off = setSpeedSwitch({ PATH: '/bin' }, 'faster_12gb_nvidia', false); + assert.deepEqual(off, { PATH: '/bin', STRATA_ROUTE_PRIOR: '0' }); + assert.equal(speedSwitchIsOn(off, 'faster_12gb_nvidia'), false); + assert.equal(speedSwitchIsOn({}, 'faster_12gb_nvidia'), true); + assert.deepEqual(setSpeedSwitch(off, 'faster_12gb_nvidia', true), { PATH: '/bin' }); + assert.equal(speedSwitchIsOn({ STRATA_ROUTE_PRIOR: '2.0' }, 'faster_12gb_nvidia'), true, 'any other value is the user\'s own and reads as the default'); +}); + +test('DeepSeek speed-ups Off writes DS4_DEFAULTS=026 and the six; On removes all seven; the six alone (an earlier test build) still read as Off', () => { + const env = { DS4_ASYNC_T: '4' }; + const off = setSpeedSwitch(env, 'deepseek_speedups', false); + assert.deepEqual(Object.keys(off).slice(0, 2), ['DS4_ASYNC_T', 'DS4_DEFAULTS'], 'the master switch first'); + assert.deepEqual(off, { DS4_ASYNC_T: '4', DS4_DEFAULTS: '026', ...Object.fromEntries(SIX.map(k => [k, '0'])) }); + assert.equal(speedSwitchIsOn(off, 'deepseek_speedups'), false); + assert.deepEqual(setSpeedSwitch(off, 'deepseek_speedups', true), env); + const six = { DS4_ASYNC_T: '4', ...Object.fromEntries(SIX.map(k => [k, '0'])) }; + assert.equal(speedSwitchIsOn(six, 'deepseek_speedups'), false); + assert.deepEqual(setSpeedSwitch(six, 'deepseek_speedups', true), env, 'turning it on removes the six too'); + assert.equal(speedSwitchIsOn({ DS4_DEFAULTS: '026' }, 'deepseek_speedups'), true, 'the master switch alone is a hand-edited file: left alone'); + assert.deepEqual(speedSwitchRows(six, { deepseek: true }).map(r => [r.id, r.on, Object.keys(r.legacy).length]), [['deepseek_speedups', false, 6]], 'the client gets the six to recognise and remove'); +}); + test('a default launch has none of the new environment entries: KVA reads as off, the others as on, and an environment in its default stays as it is', () => { for (const sw of SPEED_SWITCHES) assert.equal(speedSwitchIsSet({}, sw.id), false); const env = { PATH: '/native/bin', STRATA_PREFILL: '2' }; From a3ab37fc039ca7487913c3d8551aebb01070eb45 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:13:25 +0100 Subject: [PATCH 119/177] Master switches DS4_DEFAULTS=026 (DeepSeek) and STRATA_DEFAULTS=026 (Qwen): every default changed since v0.2.6 gives v0.2.6's behaviour; explicit per-feature variables and flags still win; every rule is a pure function with a v026 argument and a test --- include/strata/core/arch_defaults.hpp | 4 +- include/strata/core/defaults_026.hpp | 39 +++++++++++ include/strata/core/ple_residency.hpp | 8 +++ include/strata/core/sm120_series.hpp | 16 +++-- src/core/arch_defaults.cpp | 16 +++-- src/core/arch_defaults_test.cpp | 49 ++++++++++++++ src/core/ple_residency_test.cpp | 6 ++ src/core/verify.cpp | 3 +- src/dsv41/ds4_experts_rule.hpp | 95 +++++++++++++++++++++++++-- src/dsv41/ds4_iq.cu | 6 +- src/dsv41/ds4_kernels.cu | 6 +- src/dsv41/ds4_main.cpp | 5 +- src/dsv41/ds4_model.cu | 52 ++++++++------- src/kernels/cuda/fused_gr.cu | 5 +- src/kernels/cuda/qsa_prompt_attn.cu | 3 +- src/program/generate.cpp | 6 +- tests/dsv41/experts_rule_test.cpp | 92 ++++++++++++++++++++++++++ 17 files changed, 358 insertions(+), 53 deletions(-) create mode 100644 include/strata/core/defaults_026.hpp diff --git a/include/strata/core/arch_defaults.hpp b/include/strata/core/arch_defaults.hpp index 969e4cee..7062f4b2 100644 --- a/include/strata/core/arch_defaults.hpp +++ b/include/strata/core/arch_defaults.hpp @@ -18,7 +18,9 @@ namespace strata::core { /// The environment settings that are the defaults of `gcn_arch` (hipDeviceProp_t::gcnArchName; "gfx1151" or -/// "gfx1151:sramecc-:xnack-"): empty for every other architecture. +/// "gfx1151:sramecc-:xnack-"): empty for every other architecture. `defaults026` (STRATA_DEFAULTS=026, defaults_026.hpp): the gfx12 table of +/// v0.2.6 (the five prompt switches only, without the four 0.2.7 decode switches); the one-argument form asks the environment. +std::vector> arch_default_env(const char* gcn_arch, bool defaults026); std::vector> arch_default_env(const char* gcn_arch); /// The integrated Radeons (Phoenix / Hawk Point 780M gfx1103, Strix Point 890M / 880M gfx1150, Strix Halo gfx1151) whose diff --git a/include/strata/core/defaults_026.hpp b/include/strata/core/defaults_026.hpp new file mode 100644 index 00000000..84221a54 --- /dev/null +++ b/include/strata/core/defaults_026.hpp @@ -0,0 +1,39 @@ +// include/strata/core/defaults_026.hpp - STRATA_DEFAULTS=026: the master switch of the Qwen engine's 0.2.7 defaults. +// +// Every default the Qwen engine (`strata`) changed since v0.2.6 goes back to what v0.2.6 did when STRATA_DEFAULTS=026 is in the +// environment (the app's "off" for its speed switches sends it): the residency-biased routing (STRATA_ROUTE_PRIOR), the wide +// hyper-connection up read (STRATA_GR_UP_WIDE), the stream-split hyper-connection read (STRATA_GR_V3), the int8 prompt attention +// (STRATA_PROMPT_ATTN_IMMA), the four gfx12 decode switches of the arch table, the PLE residency policy (STRATA_PLE_AUTO_RAM), and the +// gfx12 decode miss split of 0.15 (back to 0.55). KVA is off by default in 0.2.7 and stays whatever STRATA_KVA says. +// An explicit per-feature variable (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, STRATA_PLE_AUTO_RAM=1, ...) or flag (--pcie-frac, --ple-io) +// still wins over the master switch. Each rule is a pure function that takes the answer of qwen_defaults_026() as its `v026` +// argument, so a test can check both settings without touching the environment (src/core/arch_defaults_test.cpp, +// src/core/ple_residency_test.cpp). +#pragma once + +#include +#include + +namespace strata { + +/// "026", "0.2.6" and "v0.2.6" name version 0.2.6; anything else (unset, "", "0", "027") does not. +inline bool is_026_token(const char* v) { + return v != nullptr && (std::strcmp(v, "026") == 0 || std::strcmp(v, "0.2.6") == 0 || std::strcmp(v, "v0.2.6") == 0); +} + +/// STRATA_DEFAULTS=026 (read once). +inline bool qwen_defaults_026() { + static const bool on = is_026_token(std::getenv("STRATA_DEFAULTS")); + return on; +} + +/// The decode miss split's start value (the share of a native pack's missing experts the CPU pool takes) when --pcie-frac is not given: +/// NVFP4 packs 0.25, other native packs 0.55 (the x16 share), and 0.15 on gfx12 (0.2.7) unless STRATA_PCIE_FRAC_DEFAULT=old or the master +/// switch is 026; a canonical pack 0.2. +inline double pcie_start_frac(bool nvfp4_pack, bool native_pack, bool gfx12_default, bool pf_old, bool v026 = false) { + if (nvfp4_pack) return 0.25; + if (!native_pack) return 0.2; + return gfx12_default && !pf_old && !v026 ? 0.15 : 0.55; +} + +} // namespace strata diff --git a/include/strata/core/ple_residency.hpp b/include/strata/core/ple_residency.hpp index 1135b89e..b9e3829e 100644 --- a/include/strata/core/ple_residency.hpp +++ b/include/strata/core/ple_residency.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include "strata/core/conversation_memory.hpp" @@ -26,4 +27,11 @@ inline bool ple_resident_admit(std::optional available, uint64_t table return conversation_memory_admit(available, table_bytes + experts_ram_bytes, headroom_bytes); } +/// May the residency policy run at all? STRATA_PLE_AUTO_RAM when it is set (0 off, anything else on: an explicit value wins), otherwise on +/// except under STRATA_DEFAULTS=026 (`v026`: v0.2.6 had no such policy, the direct reads stayed). +inline bool ple_auto_ram_allowed(const char* env_value, bool v026) { + if (env_value != nullptr) return std::atoi(env_value) != 0; + return !v026; +} + } // namespace strata::core diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index b1cc1192..8a6932a6 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -44,25 +44,31 @@ inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) // ---- 0.2.7 defaults of the CUDA speed work (pure rules; the engine reads the device and calls these; tests in arch_defaults_test) // `hip`: a HIP build, where a gfx1200 / gfx1201 reports compute capability 12.0 as well and none of these is measured or wanted. +// `v026`: STRATA_DEFAULTS=026 (defaults_026.hpp qwen_defaults_026()): every one of these is then off, as in v0.2.6. An explicit variable +// (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, ...) is decided by the caller before it asks the rule, so it still wins. // `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory. constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0 /// STRATA_ROUTE_PRIOR when the user set nothing: 2.0 (residency-biased routing, changes which experts run; owner-approved for 12 GB cards) on a /// discrete CUDA card of 13 GiB or less, 0 everywhere else. Measured on an RTX 3060 12 GB only. -inline float route_prior_default(bool hip, bool integrated, double total_bytes) { - return !hip && !integrated && total_bytes > 0.0 && total_bytes / 1073741824.0 <= kSmallCardGiB ? 2.0f : 0.0f; +inline float route_prior_default(bool hip, bool integrated, double total_bytes, bool v026 = false) { + return !v026 && !hip && !integrated && total_bytes > 0.0 && total_bytes / 1073741824.0 <= kSmallCardGiB ? 2.0f : 0.0f; } /// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability /// 12.0 card (STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB, CUDA builds only. Measured: RTX PRO 5000 72 GB +1.2% decode clean, /// -3.0% / -5.9% on 2x RTX A4000 (sm_86), +1.0% / -3.4% on an RTX 3060 (sm_86): so not those; a 12 GB sm_120 card is unmeasured. -inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes) { - return !hip && !integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB; +inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes, bool v026 = false) { + return !v026 && !hip && !integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB; } /// STRATA_PROMPT_ATTN_IMMA (the prompt attention on int8 tensor cores, another summation order) when the user set nothing: ON for every CUDA card of /// compute capability 8.0 or newer (the int8 m16n8k32 MMA), not Turing / Volta / Pascal, not HIP. `cc` = 10 * major + minor as the engine /// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt. -inline bool prompt_attn_imma_default(bool hip, int cc) { return !hip && cc >= 80; } +inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc >= 80; } + +/// STRATA_GR_UP_WIDE (the hyper-connection up projection, one warp a row; bitwise the old kernel) when the user set nothing: ON for a compute +/// capability 12.0 card (STRATA_SM120_PERF=0 turns the set off), CUDA builds only. +inline bool gr_up_wide_default(bool hip, int major, int minor, bool v026 = false) { return !v026 && !hip && sm120_default(major, minor); } } // namespace strata diff --git a/src/core/arch_defaults.cpp b/src/core/arch_defaults.cpp index efacbdad..47b9ba7a 100644 --- a/src/core/arch_defaults.cpp +++ b/src/core/arch_defaults.cpp @@ -1,5 +1,6 @@ // src/core/arch_defaults.cpp - see include/strata/core/arch_defaults.hpp. #include "strata/core/arch_defaults.hpp" +#include "strata/core/defaults_026.hpp" #include "strata/kernels/gfx_arch.hpp" @@ -10,6 +11,10 @@ namespace strata::core { std::vector> arch_default_env(const char* gcn_arch) { + return arch_default_env(gcn_arch, strata::qwen_defaults_026()); +} + +std::vector> arch_default_env(const char* gcn_arch, bool defaults026) { std::vector> t; if (strata::kernels::gfx_arch_is_gfx12(gcn_arch)) { // gfx1200 / gfx1201 (RDNA4): the PROMPT half of the gfx1151 table (reported exact on an R9700 in #1478, re-checked @@ -30,12 +35,13 @@ std::vector> arch_default_env(const char* gc {"STRATA_GDN_CONVL2", "1"}, {"STRATA_GDN_NOY", "1"}, {"STRATA_CVEC_FUSE", "1"}, - // decode (bit-identical on the R9700 measurement above) - {"STRATA_ATTN_LANECELL", "1"}, - {"STRATA_ATTN_MERGE_V2", "1"}, - {"STRATA_TSUM", "1"}, - {"STRATA_EXPDEC", "1"}, }; + if (defaults026) return t; // STRATA_DEFAULTS=026: v0.2.6's table, the prompt half only + // decode (bit-identical on the R9700 measurement above) + t.push_back({"STRATA_ATTN_LANECELL", "1"}); + t.push_back({"STRATA_ATTN_MERGE_V2", "1"}); + t.push_back({"STRATA_TSUM", "1"}); + t.push_back({"STRATA_EXPDEC", "1"}); return t; } if (!strata::kernels::gfx_arch_is_gfx1151(gcn_arch)) return t; diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index 9723b2b7..db193a7f 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -2,6 +2,7 @@ #include "strata/core/arch_defaults.hpp" #include "strata/core/gfx12_platform_defaults.hpp" #include "strata/core/sm120_series.hpp" +#include "strata/core/defaults_026.hpp" #include #include @@ -226,6 +227,54 @@ int main() { CHECK(!igpu_uma_arena_default("gfx1103", true, false, true)); // the user registers the arena as before unset("STRATA_UMA_REGISTER"); // both platforms: no Windows guard on the iGPU set (the owner wants it there too; untested on Windows is only said in the log) + // ---- STRATA_DEFAULTS=026 (defaults_026.hpp): every 0.2.7 Qwen default gives v0.2.6's answer; an explicit variable is decided by the caller first + { + const double GiB = 1073741824.0; + using namespace strata; + CHECK(is_026_token("026") && is_026_token("0.2.6") && is_026_token("v0.2.6")); + CHECK(!is_026_token(nullptr) && !is_026_token("") && !is_026_token("0") && !is_026_token("027")); + // residency-biased routing: 0 under 026 on the card that gets 2.0 otherwise + CHECK(route_prior_default(false, false, 12.0 * GiB, false) == 2.0f); + CHECK(route_prior_default(false, false, 12.0 * GiB, true) == 0.0f); + CHECK(route_prior_default(false, false, 8.0 * GiB, true) == 0.0f); + // the wide HC up read: on for a 12.0 card on CUDA, off under 026, off in HIP, off on sm_86 / sm_121 + CHECK(gr_up_wide_default(false, 12, 0)); + CHECK(!gr_up_wide_default(false, 12, 0, true)); + CHECK(!gr_up_wide_default(true, 12, 0)); + CHECK(!gr_up_wide_default(false, 8, 6)); + CHECK(!gr_up_wide_default(false, 12, 1)); + // GR_V3 and IMMA + CHECK(gr_v3_default(false, 12, 0, false, 72.0 * GiB, false)); + CHECK(!gr_v3_default(false, 12, 0, false, 72.0 * GiB, true)); + CHECK(prompt_attn_imma_default(false, 86, false)); + CHECK(!prompt_attn_imma_default(false, 86, true)); + CHECK(!prompt_attn_imma_default(false, 120, true)); + // the gfx12 decode switches: the arch table is v0.2.6's five prompt switches under 026, nine otherwise; gfx1151 and the others do not move + { + const auto t26 = strata::core::arch_default_env("gfx1201", true); + const auto t27 = strata::core::arch_default_env("gfx1201", false); + auto has = [](const std::vector>& t, const char* k) { + for (const auto& kv : t) if (kv.first == k) return true; + return false; + }; + CHECK(t26.size() == 5 && t27.size() == 9); + CHECK(has(t26, "STRATA_GDN_HEAD") && has(t26, "STRATA_CVEC_FUSE")); + CHECK(!has(t26, "STRATA_ATTN_LANECELL") && !has(t26, "STRATA_ATTN_MERGE_V2") && !has(t26, "STRATA_TSUM") && !has(t26, "STRATA_EXPDEC")); + CHECK(has(t27, "STRATA_ATTN_LANECELL") && has(t27, "STRATA_ATTN_MERGE_V2") && has(t27, "STRATA_TSUM") && has(t27, "STRATA_EXPDEC")); + CHECK(strata::core::arch_default_env("gfx1200", true).size() == 5); + CHECK(strata::core::arch_default_env("gfx1151", true) == strata::core::arch_default_env("gfx1151", false)); + CHECK(strata::core::arch_default_env("gfx1100", true).empty() && strata::core::arch_default_env("gfx1100", false).empty()); + } + // the decode miss split start value: 0.15 on gfx12 native packs, 0.55 under 026 or STRATA_PCIE_FRAC_DEFAULT=old; the others do not move + CHECK(pcie_start_frac(false, true, true, false, false) == 0.15); + CHECK(pcie_start_frac(false, true, true, false, true) == 0.55); + CHECK(pcie_start_frac(false, true, true, true, false) == 0.55); + CHECK(pcie_start_frac(false, true, false, false, false) == 0.55); + CHECK(pcie_start_frac(true, true, true, false, true) == 0.25); + CHECK(pcie_start_frac(true, true, true, false, false) == 0.25); + CHECK(pcie_start_frac(false, false, true, false, true) == 0.2); + CHECK(pcie_start_frac(false, false, true, false, false) == 0.2); + } std::printf(fails ? "arch_defaults_test: %d FAILED\n" : "arch_defaults_test: OK\n", fails); // ---- 0.2.7 CUDA defaults (sm120_series.hpp): which cards get which, and which never do { diff --git a/src/core/ple_residency_test.cpp b/src/core/ple_residency_test.cpp index 4673b7ad..fedfb9f2 100644 --- a/src/core/ple_residency_test.cpp +++ b/src/core/ple_residency_test.cpp @@ -21,6 +21,12 @@ int main() { // (table + 8 GiB) admitted it and the expert load then failed with error 1453. Not admitted now. check(!ple_resident_admit(45ull * GiB + (1ull << 28), table, arena, 8 * GiB), "64 GB PC with the IQ3_S arena: not admitted"); check(!ple_resident_admit(40ull * GiB, table, arena, 8 * GiB), "40 GiB: not admitted"); + // STRATA_DEFAULTS=026: the policy does not run (v0.2.6 had none); an explicit STRATA_PLE_AUTO_RAM wins either way + check(ple_auto_ram_allowed(nullptr, false), "policy on by default"); + check(!ple_auto_ram_allowed(nullptr, true), "policy off under STRATA_DEFAULTS=026"); + check(ple_auto_ram_allowed("1", true), "STRATA_PLE_AUTO_RAM=1 wins over 026"); + check(!ple_auto_ram_allowed("0", false), "STRATA_PLE_AUTO_RAM=0 is the old off switch"); + check(!ple_auto_ram_allowed("0", true), "STRATA_PLE_AUTO_RAM=0 under 026"); // a PC that holds the table, the arena and 8 GiB check(ple_resident_admit(table + arena + 8 * GiB, table, arena, 8 * GiB), "exactly table + arena + headroom is admitted"); check(!ple_resident_admit(table + arena + 8 * GiB - 1, table, arena, 8 * GiB), "one byte below is not"); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index f99dc9e8..ac3f874a 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -2,6 +2,7 @@ #include "strata/core/batch_rows.hpp" #include "strata/core/sm75_series.hpp" #include "strata/core/sm120_series.hpp" +#include "strata/core/defaults_026.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/core/verify.hpp" #include "strata/core/pin_budget.hpp" @@ -225,7 +226,7 @@ inline float g_route_prior() { cudaDeviceProp p; const bool ok = cudaGetDeviceProperties(&p, dev) == cudaSuccess; if (!ok) cudaGetLastError(); - per_dev[dev] = 1.0f + (ok ? strata::route_prior_default(false, p.integrated != 0, (double) p.totalGlobalMem) : 0.0f); + per_dev[dev] = 1.0f + (ok ? strata::route_prior_default(false, p.integrated != 0, (double) p.totalGlobalMem, strata::qwen_defaults_026()) : 0.0f); } return per_dev[dev] - 1.0f; #endif diff --git a/src/dsv41/ds4_experts_rule.hpp b/src/dsv41/ds4_experts_rule.hpp index ae872def..79e9c4b9 100644 --- a/src/dsv41/ds4_experts_rule.hpp +++ b/src/dsv41/ds4_experts_rule.hpp @@ -9,9 +9,24 @@ #include #include #include +#include namespace strata::ds4 { +// DS4_DEFAULTS=026: the master switch. Every default the DeepSeek engine changed since v0.2.6 goes back to what v0.2.6 did, so "off" in the app's +// "DeepSeek speed-ups" really is version 0.2.6. Each rule below takes `v026` (the engine passes defaults_026()); an explicit per-feature variable or +// flag (DS4_ATTN_SLAB=N, DS4_COPY_PIN=1, DS4_FAST_ATTN=1, --experts N, --prefill-chunk N, ...) still wins over it. The list, from +// `git diff v0.2.6..f-027-int2 -- src/dsv41`: the staging ring, the prompt chunk rule, the attention slab (base and growth), the pinned copy, +// the huge-page arena, the matrix-core attention, the drafter's cumulative cut, the 5-experts default, the store's spare slots and put, the +// store settle after a prompt, the dense dequantizer, the F16 gate/up operand, the markov head in Q8, the head's column count, the RDNA3 WMMA GEMM. +inline bool is_026_token(const char* v) { + return v != nullptr && (std::strcmp(v, "026") == 0 || std::strcmp(v, "0.2.6") == 0 || std::strcmp(v, "v0.2.6") == 0); +} +inline bool defaults_026() { + static const bool on = is_026_token(std::getenv("DS4_DEFAULTS")); + return on; +} + constexpr uint64_t kFasterModeVramMax = 16ull << 30; // GiB of graphics memory in all, at most constexpr int kFasterModeExperts = 5; @@ -21,8 +36,10 @@ constexpr int kFasterModeExperts = 5; // multi_rdna4: two or more RDNA4 cards (gfx1200 / gfx1201: R9700, RX 9000) that together hold at least half of the routed experts - the 4 x R9700 box // the Marlin stream measured: 5 against 6 experts, 2.25 bpw, 8K prompt 1339 -> 1419 ppts (+6%) and decode 78.1 -> 81.2 tok/s (+4%), reference KL // 0.10987 against 0.10833 and top-1 87.59% against 87.53% (the gate is 0.006). Faster mode there too, by default. -inline int experts_per_word(int requested, uint64_t vram_bytes, int model_k, bool integrated = false, bool multi_rdna4 = false) { +inline int experts_per_word(int requested, uint64_t vram_bytes, int model_k, bool integrated = false, bool multi_rdna4 = false, + bool v026 = false) { if (model_k <= 1) return model_k; + if (v026) multi_rdna4 = false; // 0.2.6: Faster by default on a small card or an integrated GPU only int n = requested; if (n < 1) n = integrated || multi_rdna4 || (vram_bytes != 0 && vram_bytes <= kFasterModeVramMax) ? kFasterModeExperts : model_k; if (n > model_k) n = model_k; @@ -45,7 +62,8 @@ constexpr uint64_t kChunkInPlace4096Below = 16ull << 30; // gguf_copy: a GGUF pack with --mmap-experts off; file_experts: the experts stay in the files; hip: a HIP build; min_vram_bytes: the // smallest card; big: the chunk of the streamed case (the engine's kVlRows, 8192) inline int prefill_chunk_default(bool own_default, double gpu_share, bool gguf_copy, bool file_experts, bool hip, uint64_t min_vram_bytes, - int big = 8192, bool multi_tp = false) { + int big = 8192, bool multi_tp = false, bool v026 = false) { + if (v026) multi_tp = false; // 0.2.6: the 1024 chunk for a --tp 1 run only // The cards hold most of the experts: the small chunk is the measured one. Two datapoints, both on 4 x R9700: with `--tp 1` (what // `strata launch` writes for 4 or more AMD cards), share 0.86: 1024 370 against 214 tok/s at 8192; and with the engine's own default tp // (2, pairs of cards, nothing written), where the rule used to fall through to 2048/8192: 2.25 bpw, --dspark auto, ids 5705e1164a, 8K @@ -86,8 +104,10 @@ inline bool copy_all_fits(double lane_bytes, uint64_t ram_avail, double ram_marg // experts), and never less than the base; the automatic growth on top of it still applies where the room is there. A unified-memory GPU // (the caller passes env 0 there) and DS4_ATTN_SLAB=0 never take either branch. The caller passes 0 for `expert_share` in a build that is not // HIP: that branch is the 4 x R9700 measurement. -inline int attn_slab_rows(int env, int chunk, int base, double spare_bytes, double bytes_per_row, double expert_share = 0.0) { +inline int attn_slab_rows(int env, int chunk, int base, double spare_bytes, double bytes_per_row, double expert_share = 0.0, + bool v026 = false) { auto clampn = [&](int a) { return std::max(64, std::min(chunk, a) / 64 * 64); }; + if (v026 && env < 0) env = 0; // 0.2.6: DS4_ATTN_SLAB unset gave the base; DS4_ATTN_SLAB=N still asks for N rows if (env == 0) return base; if (env > 0) return clampn(env); int rows = base; @@ -113,7 +133,8 @@ inline int attn_slab_rows(int env, int chunk, int base, double spare_bytes, doub // A unified-memory GPU never takes the small ring (its datapoint is the 1200 MB one): it keeps the 16 MB "fit" rule at 1/1.3. // `hip`: the 0.5..0.82 band and the 0.82 threshold are the 4 x R9700 measurements, so only an RDNA4 system (every device a gfx1200 or gfx1201; the parameter is named hip) takes them; any other build keeps main's // rule there (16 MB from 1/1.3, the streamed ring below it) until a CUDA multi-card rig is measured. -inline int staging_ring_mb(double share, double room_bytes, int n_dev, bool integrated, bool hip) { +inline int staging_ring_mb(double share, double room_bytes, int n_dev, bool integrated, bool hip, bool v026 = false) { + if (v026) return share >= 1.0 / 1.3 ? 16 : 400; // 0.2.6: 16 MB where the cards hold the experts, a fixed 400 MB otherwise const double GB = 1e9; const double per_dev = n_dev > 0 ? room_bytes / (double) n_dev : 0.0; const double streamed = std::min(1200.0, std::max(400.0, room_bytes / GB * 64.0)); @@ -132,4 +153,70 @@ inline int experts_test_override(int chosen, int model_k) { return chosen; } + +// The base of the attention slab, MB of q (rows = MB / the heads' width, rounded to 64): STRATA_DS4_A_MB when given; 0.2.6 and a discrete card 8 MB; +// a unified-memory GPU 32 MB (main's 3133160ed, Strix Halo). +inline size_t attn_slab_base_mb(bool unified, size_t env_mb, bool v026 = false) { + if (env_mb != 0) return env_mb; + return !v026 && unified ? 32 : 8; +} + +// DS4_COPY_PIN (pin the CPU lane's RAM copy so the prompt DMAs it in place): env -1 unset, else 0 / 1. Explicit wins; 0.2.6: opt-in, so unset = off; +// 0.2.7: on when the whole arena is on explicit huge pages OR (RDNA4 and the cards hold at least half the experts). +inline bool copy_pin_default(int env, bool arena_all_huge, bool rdna4, double share, bool have_chunks, bool v026 = false) { + if (env >= 0) return env != 0; + if (v026) return false; + return (arena_all_huge || (rdna4 && share >= 0.5)) && have_chunks; +} + +// DS4_COPY_HUGETLB (the copy arena on explicit 2 MB pages): env -1 unset, else 0 / 1; 0.2.6: opt-in; 0.2.7: on when the reserved pool already holds the whole copy. +inline bool copy_hugetlb_default(int env, double pool_free_bytes, double copy_bytes, bool v026 = false) { + if (env >= 0) return env != 0; + if (v026) return false; + return pool_free_bytes > 0.0 && pool_free_bytes >= copy_bytes; +} + +// DS4_FAST_ATTN (the chunked prompt's attention on the matrix cores): env -1 unset, else 0 / 1; 0.2.6: opt-in; 0.2.7: on for gfx1200 / gfx1201. +inline bool fast_attn_default(int env, bool gfx12, bool v026 = false) { + if (env >= 0) return env != 0; + return !v026 && gfx12; +} + +// The drafter's cumulative confidence cut (STRATA_DS4_DSPARK_CUM, a request's dspark_cum): the variable when set; 0.2.6: 0; 0.2.7: 0.5 on gfx1200 / gfx1201. +inline float dspark_cum_value(bool has_env, float env_value, bool gfx12, bool v026 = false) { + if (has_env) return env_value; + return !v026 && gfx12 ? 0.5f : 0.0f; +} + +// DS4_STORE_SPARE (the RAM store takes the spare slots) and DS4_STORE_PUT (an expert the VRAM cache gives back is put into the store from memory): +// env -1 unset, else 0 / 1; 0.2.6: neither existed (off); 0.2.7: on. +inline bool store_feature_default(int env, bool v026 = false) { + if (env >= 0) return env != 0; + return !v026; +} + +// DS4_SETTLE_STORE (the RAM store's post-prompt preload) when the variable is unset: 0.2.6 ran it (1), 0.2.7 does not (0: it cost a 4K prompt 4.7 s). +inline float settle_store_default(bool v026 = false) { return v026 ? 1.0f : 0.0f; } +// The preload skips the experts the CPU lane already holds as a RAM copy (0.2.7); 0.2.6 did not. +inline bool settle_skips_copy_experts(bool v026 = false) { return !v026; } + +// The chunked prompt's dense dequantizer: the row-per-lane dq_rows_kernel (0.2.6's values, bit for bit) or dq_rows_kernel2 (the coalesced transpose). +// DS4_DQ_OLD (-1 unset, else 0 / 1) wins; 0.2.6: the old one; 0.2.7: the old one on gfx11 only. +inline bool dq_old_default(int env, bool gfx11, bool v026 = false) { + if (env >= 0) return env != 0; + return v026 || gfx11; +} + +// The head's columns a pass for a GGUF head (DS4_HEAD_PER overrides): 0.2.6 4, 0.2.7 8 (the same logits per column). +inline int head_per_default(bool v026 = false) { return v026 ? 4 : 8; } +// The drafter's markov head quantised to Q8_0 as it loads (0.2.7) or read as F16 (0.2.6). +inline bool markov_head_q8_default(bool v026 = false) { return !v026; } +// The gate/up tiles read the layer's F16 copy of the activations (0.2.7, bit-identical) or the F32 rows (0.2.6). +inline bool gate_up_x16_default(bool v026 = false) { return !v026; } +// STRATA_DENSE_PFGEMM (the RDNA3 WMMA dense GEMM before hipBLAS; -1 unset, else 0 / 1): 0.2.6 did not have it. +inline bool dense_pfgemm_default(int env, bool v026 = false) { + if (env >= 0) return env != 0; + return !v026; +} + } // namespace strata::ds4 diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index 931e3d33..da5e8e5d 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -4,6 +4,7 @@ // ggml's (ggml-common.h, MIT, third_party/ggml/LICENSE); the sign and grid tricks are llama.cpp's vecdotq.cuh. #include "ds4_iq.cuh" #include "ds4_numerics.cuh" +#include "ds4_experts_rule.hpp" #include #if !defined(STRATA_USE_HIP) @@ -1393,7 +1394,10 @@ __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __rest // prompt 79.5 -> 88.5 tok/s with it, so a gfx11 device defaults to it. DS4_DQ_OLD=1 forces it anywhere, DS4_DQ_OLD=0 forces kernel2 // anywhere. The detection is the device's gcnArchName (HIP only; a CUDA build has no gfx11). Decided once per device. static bool dq_use_old_kernel() { - if (const char* e = std::getenv("DS4_DQ_OLD"); e != nullptr && *e != '\0') return std::atoi(e) != 0; + const char* dq_env = std::getenv("DS4_DQ_OLD"); + const int env = dq_env != nullptr && *dq_env != '\0' ? (std::atoi(dq_env) != 0 ? 1 : 0) : -1; + const bool v026 = strata::ds4::defaults_026(); // DS4_DEFAULTS=026: 0.2.6's row-per-lane dequantizer (the same values, bit for bit) + if (env >= 0 || v026) return strata::ds4::dq_old_default(env, false, v026); #if defined(STRATA_USE_HIP) static std::atomic cache[64]; // 0 unknown, 1 no, 2 yes int dev = 0; diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index a05091f0..baf63dcc 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -7,6 +7,7 @@ #include "ds4_q6k.cuh" #include "ds4_attn_split.cuh" #include "ds4_wmma.cuh" +#include "ds4_experts_rule.hpp" #include @@ -2056,11 +2057,10 @@ bool fast_attn_enabled() { const char* e = std::getenv("DS4_FAST_ATTN"); return e == nullptr ? -1 : (std::atoi(e) != 0 ? 1 : 0); }(); - if (env >= 0) return env == 1; #if defined(STRATA_USE_HIP) - return device_is_gfx12(); + return strata::ds4::fast_attn_default(env, device_is_gfx12(), strata::ds4::defaults_026()); #else - return false; + return strata::ds4::fast_attn_default(env, false, strata::ds4::defaults_026()); #endif } attnsplit::AttnSplitScratch split_scratch(cudaStream_t s, int heads) { diff --git a/src/dsv41/ds4_main.cpp b/src/dsv41/ds4_main.cpp index 2c11b876..3b259b2a 100644 --- a/src/dsv41/ds4_main.cpp +++ b/src/dsv41/ds4_main.cpp @@ -19,6 +19,7 @@ // read stops there for a checkpoint, so a request behind the same start - another agent - goes back to it instead of // reading it again (also without slots). STRATA_DS4_REUSE=0 turns every reuse off (each request reads its whole prompt). #include "ds4_model.hpp" +#include "ds4_experts_rule.hpp" #include "ds4_os.hpp" #include "ds4_packinfo.hpp" #include "ds4_slotmeta.hpp" @@ -158,8 +159,8 @@ static int g_round_nd = 0; // Strix keeps 0 until it is; the CUDA measurements in 0.2.7 had it flat, so CUDA keeps 0. STRATA_DS4_DSPARK_CUM overrides everywhere. float dspark_cum_default(const strata::ds4::Model& m) { static const char* const e = std::getenv("STRATA_DS4_DSPARK_CUM"); - if (e != nullptr) return (float) std::atof(e); - return m.gpus_are_gfx12() ? 0.5f : 0.0f; + return strata::ds4::dspark_cum_value(e != nullptr, e != nullptr ? (float) std::atof(e) : 0.0f, m.gpus_are_gfx12(), + strata::ds4::defaults_026()); } // One round of decoding after `tok` (the token at pos(), not fed yet): with the drafter, its drafts while their diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 9c359644..91d29a26 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -85,6 +85,12 @@ constexpr bool kHipBuild = true; constexpr bool kHipBuild = false; #endif +// an environment variable as 0 / 1, or -1 when it is not set (the rules in ds4_experts_rule.hpp take this form) +int env_tri(const char* name) { + const char* v = std::getenv(name); + return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; +} + double now_ms() { return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); } @@ -2067,7 +2073,7 @@ struct Model::Impl { #else const bool hip_build = false; #endif - const int rule_chunk = prefill_chunk_default(own_default, gpu_expert_share(), gguf_copy, file_experts, hip_build, vmin_bytes, kVlRows, multi_tp); + const int rule_chunk = prefill_chunk_default(own_default, gpu_expert_share(), gguf_copy, file_experts, hip_build, vmin_bytes, kVlRows, multi_tp, defaults_026()); chunk = prompt_par ? (o.prefill_chunk >= 0 ? o.prefill_chunk : rule_chunk) : 0; if (prompt_par && o.prefill_chunk < 0 && rule_chunk == 4096 && gguf_copy) std::fprintf(stderr, "ds4: prompts in chunks of 4096 tokens (the experts are copied into RAM, %.0f GiB of graphics memory; --prefill-chunk N changes it)\n", @@ -2134,7 +2140,7 @@ struct Model::Impl { } // two or more RDNA4 cards holding at least half of the experts (the 4 x R9700 class): Faster by default too const bool multi_rdna4 = rdna4() && devs.size() >= 2 && gpu_expert_share() >= 0.5; - const int n = experts_test_override(experts_per_word(o.experts, vram_all, l.k_exp, integrated, multi_rdna4), l.k_exp); + const int n = experts_test_override(experts_per_word(o.experts, vram_all, l.k_exp, integrated, multi_rdna4, defaults_026()), l.k_exp); experts_used = n; if (n < l.k_exp) std::fprintf(stderr, "ds4: experts per word: %d (%s; full quality: --experts %d)\n", n, @@ -3002,7 +3008,7 @@ struct Model::Impl { cudaDeviceProp ip{}; if (cudaGetDeviceProperties(&ip, d.id) == cudaSuccess && ip.integrated != 0) unified = true; } - const size_t mb = (size_t) strata::ds4::staging_ring_mb(exp_b > 0 ? share : 0.0, room, (int) devs.size(), unified, rdna4()); + const size_t mb = (size_t) strata::ds4::staging_ring_mb(exp_b > 0 ? share : 0.0, room, (int) devs.size(), unified, rdna4(), defaults_026()); if (o.verbose) std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9, room / 1e9, other_b / 1e9, (int) mb); @@ -3039,7 +3045,7 @@ struct Model::Impl { const char* v = std::getenv("STRATA_DS4_A_MB"); return (size_t) (v != nullptr ? std::max(1, std::atoi(v)) : 0); }(); - const size_t a_mb = a_mb_env != 0 ? a_mb_env : (unified ? 32 : 8); + const size_t a_mb = strata::ds4::attn_slab_base_mb(unified, a_mb_env, defaults_026()); c.A = std::max(64, (int) ((a_mb << 20) / (size_t) HQ) / 64 * 64); // DS4_ATTN_SLAB=N: the attention slab's rows. The dense projections (q_b, wo_a/b) are dequantized and GEMM'd // once a slab, so a slab of 256 rows dequantizes the same weights 32 times for an 8K prompt (measured: the @@ -3062,7 +3068,7 @@ struct Model::Impl { const int base = c.A; // one rule (ds4_experts_rule.hpp: attn_slab_rows): the chunk's whole slab (<= 1024 rows) where the cards hold half the // experts or more (4 x R9700, +9% prompt), up to 2048 rows where the VRAM is spare, the base otherwise - c.A = strata::ds4::attn_slab_rows(env, chunk, base, spare, bpr, rdna4() ? share : 0.0); + c.A = strata::ds4::attn_slab_rows(env, chunk, base, spare, bpr, rdna4() ? share : 0.0, defaults_026()); if (env < 0 && c.A > base) { slab_auto_grew_ = true; if (di == 0 && o.verbose) { @@ -3153,10 +3159,7 @@ struct Model::Impl { std::string& err) { if (rows <= 0) return true; #if defined(STRATA_USE_HIP) // (wmma_gemm.cu is part of the AMD builds only: a CUDA build has no such kernel and keeps cuBLAS) - static const bool pf = [] { - const char* v = std::getenv("STRATA_DENSE_PFGEMM"); - return v == nullptr || v[0] != '0'; - }(); + static const bool pf = strata::ds4::dense_pfgemm_default(env_tri("STRATA_DENSE_PFGEMM"), defaults_026()); #endif const int cols = std::max(128, (int) std::min((size_t) m.n, c.w16_elems / (size_t) m.k) / 128 * 128); for (int c0 = 0; c0 < m.n; c0 += cols) { @@ -3790,7 +3793,7 @@ struct Model::Impl { sa.limit = g.lim; // gate / up read the layer's F16 copy of the activations (the same rounding the tiles make for their // shared tile): with 18-36 column blocks an expert the F32 rows were read that many times - sa.x16 = c.x16; + sa.x16 = strata::ds4::gate_up_x16_default(defaults_026()) ? c.x16 : nullptr; EkMark ek{}; const bool ekp = prof_chunk; if (ekp) { @@ -3965,7 +3968,9 @@ struct Model::Impl { return false; } if (!dalloc(d, d_mk_embed, te->bytes / 2, err, acct) || !upload(d, *te, d_mk_embed, err) || - !mk_head_q8(d, Z + "markov_head.head.weight", d_mk_head_q8, err, acct)) + (strata::ds4::markov_head_q8_default(defaults_026()) + ? !mk_head_q8(d, Z + "markov_head.head.weight", d_mk_head_q8, err, acct) + : !f16raw(d, Z + "markov_head.head.weight", d_mk_head, err, acct))) // (0.2.6: the head as F16) return false; } } @@ -4450,11 +4455,7 @@ struct Model::Impl { // 0.2.7: DS4_COPY_HUGETLB unset = ON when the reserved pool already holds the whole copy (HugePages_Free), else the // ordinary arena exactly as before; =0 is the off switch, =1 asks for it anyway (a smaller pool is used, the rest warns). const uint64_t pool_free = os::huge_free_bytes(); - const bool huge_arena = [&] { - const char* e = std::getenv("DS4_COPY_HUGETLB"); - if (e != nullptr) return std::atoi(e) != 0; - return pool_free > 0 && (double) pool_free >= all; - }(); + const bool huge_arena = strata::ds4::copy_hugetlb_default(env_tri("DS4_COPY_HUGETLB"), (double) pool_free, all, defaults_026()); if (huge_arena && std::getenv("DS4_COPY_HUGETLB") == nullptr) std::fprintf(stderr, "ds4: the reserved huge-page pool (%.1f GB free) holds the whole copy (%.1f GB): the arena on 2 MB pages " "(DS4_COPY_HUGETLB=0 keeps the ordinary arena)\n", (double) pool_free / 1e9, all / 1e9); @@ -4620,8 +4621,8 @@ struct Model::Impl { // THP arena registers 4 KB pages and the DMA rate was erratic on the 12 GB cell: 11.9 s one prompt, 30.4 s the next), or (b) the // cards hold at least half the routed experts on RDNA4 (4 x R9700: the pin was reliable in 4/4 runs there, see above). =0 is the off // switch, =1 pins any arena. - const char* cp = std::getenv("DS4_COPY_PIN"); - const bool pin_copies = cp != nullptr ? std::atoi(cp) != 0 : ((arena_all_huge || (rdna4() && gpu_expert_share() >= 0.5)) && !ram_chunks.empty()); + const bool pin_copies = strata::ds4::copy_pin_default(env_tri("DS4_COPY_PIN"), arena_all_huge, rdna4(), gpu_expert_share(), + !ram_chunks.empty(), defaults_026()); if (pin_copies) { const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; const double tr = now_ms(); @@ -5013,7 +5014,7 @@ struct Model::Impl { // up its coldest to the CPU lane, and a store without them reads each from the SSD while the CPU lane waits - 1.8 misses a // token on the 251 GB R9700 box, 2.9 ms of a 49 ms token), then the lane's experts the profile never saw. Last in the list: they // take only the slots the likely ones left. DS4_STORE_SPARE=0: off. - if (!(std::getenv("DS4_STORE_SPARE") && std::atoi(std::getenv("DS4_STORE_SPARE")) == 0)) { + if (strata::ds4::store_feature_default(env_tri("DS4_STORE_SPARE"), defaults_026())) { std::vector>> vr, zero; for (const Layer& l : L) { if (l.il >= g.nl) continue; @@ -5029,7 +5030,7 @@ struct Model::Impl { } const double t0 = now_ms(); // (with the spare experts in the list the reserve is theirs: last in the list, so the oldest ticks, so the first a demand read replaces) - const bool spare_on = !(std::getenv("DS4_STORE_SPARE") && std::atoi(std::getenv("DS4_STORE_SPARE")) == 0); + const bool spare_on = strata::ds4::store_feature_default(env_tri("DS4_STORE_SPARE"), defaults_026()); const size_t leave = spare_on ? 0 : (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192) + 64; // The first 48 GB (what a store held before it could take every expert) are read before the first token; the rest of the // hottest-first list is read after it, in pieces of 128 experts on a thread of its own, behind the model's own reads (a @@ -6417,7 +6418,7 @@ struct Model::Impl { } if (got) blob_to_ram(l, sw_b, sw.ram); else sw.ram = -1; // (back to the file's pages then) - } else if (ok && store && l.nm == 1 && l.lay.fmt == gg::kFmtMXFP4 && !(std::getenv("DS4_STORE_PUT") && std::atoi(std::getenv("DS4_STORE_PUT")) == 0)) { + } else if (ok && store && l.nm == 1 && l.lay.fmt == gg::kFmtMXFP4 && strata::ds4::store_feature_default(env_tri("DS4_STORE_PUT"), defaults_026())) { // `out` goes back to the CPU lane: its blob is in VRAM, so it is copied into a store slot now - the lane would otherwise read it from // the SSD and wait for it (1-2 misses a token on the 251 GB R9700 box). DS4_STORE_PUT=0: off. uint8_t* dst = store->put_begin(l.il, sw.out); @@ -6481,7 +6482,7 @@ struct Model::Impl { // The RAM store's preload after a chunked prompt is off by default: measured on Strix Halo (code fixture, prompt + // 256 tokens, 3 runs a side) it costs the prompt 4.7 s and the decode that follows gains nothing (13.9/14.4 s with it // against 14.2 s without). The swaps above are what the decode actually uses; DS4_SETTLE_STORE=1 restores it. - if (store && env_f("DS4_SETTLE_STORE", 0.0f) != 0.0f) { // the RAM store too: a window prompt fills it through the CPU + if (store && env_f("DS4_SETTLE_STORE", strata::ds4::settle_store_default(defaults_026())) != 0.0f) { // the RAM store too: a window prompt fills it through the CPU // lane's picks, a chunked one streams past it - the hottest CPU-lane experts of the prompt into its free slots // (copy_mode: an expert already in the CPU lane's RAM copy gains nothing from a second copy of the same bytes - // measured on the R9700 12 GB cell: 4152 such experts, 40 GB read at 6.4 GB/s, 6.2 s of an 8K prompt, 0.0 store @@ -6490,7 +6491,7 @@ struct Model::Impl { for (const Layer& l : L) { if (l.mtp) continue; for (int e = 0; e < l.n_exp; ++e) - if (l.slot[(size_t) e] < 0 && !(copy_mode && !l.ram.empty() && l.ram[(size_t) e] >= 0) && + if (l.slot[(size_t) e] < 0 && !(strata::ds4::settle_skips_copy_experts(defaults_026()) && copy_mode && !l.ram.empty() && l.ram[(size_t) e] >= 0) && l.heat[(size_t) e] >= 4.0f) hot.push_back({l.heat[(size_t) e], {l.il, e}}); } std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); @@ -7121,7 +7122,8 @@ struct Model::Impl { sp.seed = dq_seed; } for (int i = 0; i < T; ++i) { // the markov bias of the token before, then that position's draft - markov_add_q8(hd.logits + (size_t) i * V, d_mk_embed, d_mk_head_q8, d_ints + i, V, R, hd.st); + if (d_mk_head_q8 != nullptr) markov_add_q8(hd.logits + (size_t) i * V, d_mk_embed, d_mk_head_q8, d_ints + i, V, R, hd.st); + else markov_add(hd.logits + (size_t) i * V, d_mk_embed, d_mk_head, d_ints + i, V, R, hd.st); if (drafts_q) { sp.counter = dq_counter + (uint64_t) i; strata::dsv41k::sample_draft(hd.logits + (size_t) i * V, 1, V, sp, d_specq + i, d_ints + i + 1, hd.st); @@ -8803,7 +8805,7 @@ struct Model::Impl { // for a whole one, each pass reading the whole share; a GGUF's: 8, so that every window the engine can build (rows // <= kWin = 8) walks the head once instead of twice - measured on the drafter's fixed T=5: 4.55 -> 2.83 ms, its // round 14.49 -> 13.46; the verify window's head 3.48 -> 2.68 ms, the same logits. DS4_HEAD_PER overrides.) - const int per = d.head.fmt != 0 ? (std::getenv("DS4_HEAD_PER") ? std::atoi(std::getenv("DS4_HEAD_PER")) : 8) + const int per = d.head.fmt != 0 ? (std::getenv("DS4_HEAD_PER") ? std::atoi(std::getenv("DS4_HEAD_PER")) : strata::ds4::head_per_default(defaults_026())) : std::max(1, x3::mv_cols(d.head)); for (int c = 0; c < rows; c += per) if (!mv(d, {job(d.head, xn + (size_t) c * D, out + (size_t) c * ld, std::min(per, rows - c), D, ld)}, err)) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index ad1fcbd3..6f6f3232 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -2,6 +2,7 @@ #include "strata/core/emulate.hpp" #include "strata/core/sm75_series.hpp" #include "strata/core/sm120_series.hpp" +#include "strata/core/defaults_026.hpp" #include "strata/kernels/q8_1_finite.hpp" // #606: q8_1_ds #include "strata/core/geometry.hpp" #include "strata/kernels/fused_gr.hpp" @@ -461,7 +462,7 @@ bool gr_up_wide_on() { int major = 0, minor = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); - per_dev[dev] = strata::sm120_default(major, minor) ? 2 : 1; + per_dev[dev] = strata::gr_up_wide_default(false, major, minor, strata::qwen_defaults_026()) ? 2 : 1; cudaGetLastError(); // drop what an attribute query on a CPU-only box leaves behind } return per_dev[dev] == 2; @@ -2322,7 +2323,7 @@ static bool gr_v3_default_on(int dev) { cudaDeviceProp p; const bool ok = cudaGetDeviceProperties(&p, dev) == cudaSuccess; if (!ok) cudaGetLastError(); - per_dev[dev] = ok && strata::gr_v3_default(false, p.major, p.minor, p.integrated != 0, (double) p.totalGlobalMem) ? 2 : 1; + per_dev[dev] = ok && strata::gr_v3_default(false, p.major, p.minor, p.integrated != 0, (double) p.totalGlobalMem, strata::qwen_defaults_026()) ? 2 : 1; } return per_dev[dev] == 2; #endif diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index f2b2d0a0..82b199b1 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1,6 +1,7 @@ // src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. #include "strata/core/emulate.hpp" #include "strata/core/sm120_series.hpp" +#include "strata/core/defaults_026.hpp" #include "strata/core/sm75_series.hpp" #include "strata/core/geometry.hpp" #include "strata/core/gfx12_platform_defaults.hpp" @@ -2428,7 +2429,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 const char* v = std::getenv("STRATA_PROMPT_ATTN_IMMA"); g_pa_imma = v == nullptr ? 2 : (v[0] == '1' ? 1 : 0); // 2: the default (on where the kernel can run) } - if (!turing && (g_pa_imma == 1 || (g_pa_imma == 2 && strata::prompt_attn_imma_default(false, 80)))) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st); + if (!turing && (g_pa_imma == 1 || (g_pa_imma == 2 && strata::prompt_attn_imma_default(false, 80, strata::qwen_defaults_026())))) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st); return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st); } if (!pools.k_pool || !pools.v_pool) return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 43b9bcb5..4e871b0d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -30,6 +30,7 @@ #include "strata/core/session_save_reclaim.hpp" #include "strata/core/conversation_memory.hpp" #include "strata/core/ple_residency.hpp" +#include "strata/core/defaults_026.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/foresight_swap.hpp" @@ -3585,8 +3586,7 @@ int main(int argc, char** argv) { const bool pf_old = pfd != nullptr && std::strcmp(pfd, "old") == 0; // 0.2.7: gfx12 native packs start at 0.15 (see pcie_share_gfx12_default above); other cards and // STRATA_PCIE_FRAC_DEFAULT=old keep the x16 share measured for them. - const double base = nvfp4_pack ? 0.25 - : native_pack ? (pcie_share_gfx12_default() && !pf_old ? 0.15 : 0.55) : 0.2; + const double base = strata::pcie_start_frac(nvfp4_pack, native_pack, pcie_share_gfx12_default(), pf_old, strata::qwen_defaults_026()); std::string bursts; #if !defined(STRATA_USE_HIP) && defined(_WIN32) // Windows: opt-in (STRATA_PCIE_AUTO_CANON=1); an RTX 5070 decoded a short Q2_0 answer 3% slower with it, code 2.5% faster @@ -4095,7 +4095,7 @@ int main(int argc, char** argv) { if (pio.mode == strata::kernels::PleIo::Direct && !o.ple_io_explicit) { const strata::kernels::PleIoOptions direct_pio = pio; const char* auto_ram = std::getenv("STRATA_PLE_AUTO_RAM"); - const bool allowed = auto_ram == nullptr || std::atoi(auto_ram) != 0; + const bool allowed = strata::core::ple_auto_ram_allowed(auto_ram, strata::qwen_defaults_026()); const uint64_t need = ple_table.table_bytes(); const auto available = strata::core::available_host_bytes(); uint64_t experts_ram = 0; // every routed expert's blob, the arena the engine copies into RAM at start diff --git a/tests/dsv41/experts_rule_test.cpp b/tests/dsv41/experts_rule_test.cpp index 6fb5a1d8..895df7f0 100644 --- a/tests/dsv41/experts_rule_test.cpp +++ b/tests/dsv41/experts_rule_test.cpp @@ -215,6 +215,98 @@ int main() { // a 192 GB Windows PC with a 4 GB page file: 150 GB free RAM but only 100 GB of commit room: no CHECK_EQ(copy_all_fits(108 * GB, (uint64_t) (150 * GB), margin, 100 * GB), 0); } + // ---- DS4_DEFAULTS=026: every rule gives v0.2.6's answer (the last argument v026 = true); an explicit variable / flag still wins; the six old + // DS4_*=0 switches keep working with v026 = false + { + using namespace strata::ds4; + const double GB = 1e9; + CHECK_EQ(is_026_token("026"), 1); + CHECK_EQ(is_026_token("0.2.6"), 1); + CHECK_EQ(is_026_token("v0.2.6"), 1); + CHECK_EQ(is_026_token("0"), 0); + CHECK_EQ(is_026_token(""), 0); + CHECK_EQ(is_026_token("027"), 0); + CHECK_EQ(is_026_token(nullptr), 0); + // the 5-experts default: 4 x R9700 goes back to 6; a small card and an integrated GPU were Faster in 0.2.6 already; --experts wins + CHECK_EQ(experts_per_word(-1, 4 * 32 * GiB, 6, false, true, true), 6); + CHECK_EQ(experts_per_word(-1, 4 * 32 * GiB, 6, false, true, false), 5); + CHECK_EQ(experts_per_word(-1, 12 * GiB, 6, false, false, true), 5); + CHECK_EQ(experts_per_word(-1, 91 * GiB, 6, true, false, true), 5); + CHECK_EQ(experts_per_word(5, 4 * 32 * GiB, 6, false, true, true), 5); + // the chunk rule: the multi-card tp run loses the 1024; a --tp 1 run keeps it (0.2.6 had it); an explicit --prefill-chunk is not this rule + CHECK_EQ(prefill_chunk_default(false, 0.86, false, true, true, 32 * GiB, 8192, true, true), 8192); + CHECK_EQ(prefill_chunk_default(false, 0.86, false, true, true, 32 * GiB, 8192, true, false), 1024); + CHECK_EQ(prefill_chunk_default(true, 0.86, false, true, true, 32 * GiB, 8192, true, true), 1024); + CHECK_EQ(prefill_chunk_default(false, 0.30, false, false, false, 24 * GiB, 8192, true, true), 2048); + // the slab: the base 8 MB everywhere, no growth, no whole-chunk slab; DS4_ATTN_SLAB=N (env N) and =0 still do what they say + CHECK_EQ(attn_slab_base_mb(true, 0, true), 8); + CHECK_EQ(attn_slab_base_mb(true, 0, false), 32); + CHECK_EQ(attn_slab_base_mb(false, 0, false), 8); + CHECK_EQ(attn_slab_base_mb(false, 0, true), 8); + CHECK_EQ(attn_slab_base_mb(true, 16, true), 16); // STRATA_DS4_A_MB wins + CHECK_EQ(attn_slab_rows(-1, 8192, 256, 1e18, 377000.0, 1.0, true), 256); // spare room: the 0.2.6 slab + CHECK_EQ(attn_slab_rows(-1, 1024, 256, -5.0e9, 377000.0, 0.77, true), 256); // the 4 x R9700 whole-chunk slab: off + CHECK_EQ(attn_slab_rows(1024, 1024, 256, -5.0e9, 377000.0, 0.77, true), 1024); // DS4_ATTN_SLAB=1024 wins + CHECK_EQ(attn_slab_rows(0, 8192, 256, 1e18, 377000.0, 1.0, true), 256); + CHECK_EQ(attn_slab_rows(0, 8192, 256, 1e18, 377000.0, 1.0, false), 256); // the old DS4_ATTN_SLAB=0 switch + // the staging ring: 16 MB where the cards hold the experts (>= 1/1.3), a fixed 400 MB below, whatever the platform + CHECK_EQ(staging_ring_mb(0.86, 4 * 30 * GB, 4, false, true, true), 16); + CHECK_EQ(staging_ring_mb(0.77, 4 * 31 * GB, 4, false, true, true), 16); + CHECK_EQ(staging_ring_mb(0.72, 4 * 31 * GB, 4, false, true, true), 400); + CHECK_EQ(staging_ring_mb(0.06, 10 * GB, 1, false, false, true), 400); + CHECK_EQ(staging_ring_mb(0.30, 18.75 * GB, 1, true, false, true), 400); // Strix Halo: not 1200 + CHECK_EQ(staging_ring_mb(0.0, 0.0, 0, false, false, true), 400); + // the pinned copy and the huge-page arena: opt-in again; =1 / =0 win + CHECK_EQ(copy_pin_default(-1, true, true, 0.8, true, true), 0); + CHECK_EQ(copy_pin_default(-1, true, true, 0.8, true, false), 1); + CHECK_EQ(copy_pin_default(1, false, false, 0.0, false, true), 1); + CHECK_EQ(copy_pin_default(0, true, true, 0.8, true, false), 0); // the old DS4_COPY_PIN=0 + CHECK_EQ(copy_pin_default(-1, false, true, 0.5, true, false), 1); + CHECK_EQ(copy_pin_default(-1, false, true, 0.49, true, false), 0); + CHECK_EQ(copy_pin_default(-1, false, false, 0.9, true, false), 0); + CHECK_EQ(copy_pin_default(-1, true, false, 0.0, false, false), 0); // nothing to pin + CHECK_EQ(copy_hugetlb_default(-1, 120 * GB, 100 * GB, true), 0); + CHECK_EQ(copy_hugetlb_default(-1, 120 * GB, 100 * GB, false), 1); + CHECK_EQ(copy_hugetlb_default(-1, 90 * GB, 100 * GB, false), 0); + CHECK_EQ(copy_hugetlb_default(1, 0.0, 100 * GB, true), 1); + CHECK_EQ(copy_hugetlb_default(0, 120 * GB, 100 * GB, false), 0); // the old DS4_COPY_HUGETLB=0 + // the matrix-core attention: opt-in again + CHECK_EQ(fast_attn_default(-1, true, true), 0); + CHECK_EQ(fast_attn_default(-1, true, false), 1); + CHECK_EQ(fast_attn_default(-1, false, false), 0); + CHECK_EQ(fast_attn_default(1, false, true), 1); + CHECK_EQ(fast_attn_default(0, true, false), 0); // the old DS4_FAST_ATTN=0 + // the drafter's cumulative cut: 0 again; STRATA_DS4_DSPARK_CUM wins + CHECK_EQ((int) (dspark_cum_value(false, 0.0f, true, true) * 100), 0); + CHECK_EQ((int) (dspark_cum_value(false, 0.0f, true, false) * 100), 50); + CHECK_EQ((int) (dspark_cum_value(false, 0.0f, false, false) * 100), 0); + CHECK_EQ((int) (dspark_cum_value(true, 0.7f, true, true) * 100), 70); + CHECK_EQ((int) (dspark_cum_value(true, 0.0f, true, false) * 100), 0); + // the store: spare slots and put off, the post-prompt settle back on (and without the copy-mode skip); the old =0 switches keep working + CHECK_EQ(store_feature_default(-1, true), 0); + CHECK_EQ(store_feature_default(-1, false), 1); + CHECK_EQ(store_feature_default(1, true), 1); + CHECK_EQ(store_feature_default(0, false), 0); // the old DS4_STORE_SPARE=0 / DS4_STORE_PUT=0 + CHECK_EQ((int) settle_store_default(true), 1); + CHECK_EQ((int) settle_store_default(false), 0); + CHECK_EQ(settle_skips_copy_experts(true), 0); + CHECK_EQ(settle_skips_copy_experts(false), 1); + // the dense dequantizer, the head, the drafter's markov head, the F16 operand, the RDNA3 GEMM + CHECK_EQ(dq_old_default(-1, false, true), 1); + CHECK_EQ(dq_old_default(-1, false, false), 0); + CHECK_EQ(dq_old_default(-1, true, false), 1); + CHECK_EQ(dq_old_default(0, true, true), 0); // DS4_DQ_OLD=0 wins + CHECK_EQ(head_per_default(true), 4); + CHECK_EQ(head_per_default(false), 8); + CHECK_EQ(markov_head_q8_default(true), 0); + CHECK_EQ(markov_head_q8_default(false), 1); + CHECK_EQ(gate_up_x16_default(true), 0); + CHECK_EQ(gate_up_x16_default(false), 1); + CHECK_EQ(dense_pfgemm_default(-1, true), 0); + CHECK_EQ(dense_pfgemm_default(-1, false), 1); + CHECK_EQ(dense_pfgemm_default(1, true), 1); + CHECK_EQ(dense_pfgemm_default(0, false), 0); + } if (fails == 0) std::printf("experts rule: all checks passed\n"); return fails == 0 ? 0 : 1; } From 9db497056b0c1857f6ece0e1c5b0284d5444cf16 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:14:00 +0100 Subject: [PATCH 120/177] docs: the two master switches in the 0.2.7 release-notes draft --- docs/release-notes-0.2.7.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index de029522..6e806ade 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -24,6 +24,23 @@ decode on the RTX PRO 5000 with identical tokens**, about +1.5% together with the switch above. On 2x RTX A4000 and the RTX 3060 it was slower, so those cards keep the old read. Off switch: `STRATA_GR_V3=0`. +## Going back to 0.2.6 + +Two switches bring back every default that 0.2.7 changed, in one step, for a test or for a PC where something looks wrong. The app's +"off" for its speed switches sends them. + +- **`DS4_DEFAULTS=026`** (DeepSeek): the staging ring, the prompt chunk rule, the attention slab (its base and its growth), the pinned + copy and the huge-page arena, the matrix-core attention, the drafter's cumulative cut, the 5-experts default on several Radeon cards, + the RAM store's spare slots and put and its settle after a prompt, the dense dequantizer, the F16 gate/up operand, the drafter's + markov head and the head's column count, and the RDNA3 dense GEMM all go back to what 0.2.6 did. +- **`STRATA_DEFAULTS=026`** (Qwen): the residency-biased routing, the wide and the stream-split hyper-connection reads, the int8 + prompt attention, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). + Long prompts on the approximate read (`STRATA_KVA`) are off by default and stay as `STRATA_KVA` says. + +A variable or flag you set yourself (`DS4_ATTN_SLAB=N`, `STRATA_ROUTE_PRIOR=2`, `--experts 5`, `--prefill-chunk N`, `--pcie-frac`, +`--ple-io`) still wins over the switch. The older single switches (`DS4_FAST_ATTN=0`, `DS4_ATTN_SLAB=0`, `DS4_COPY_PIN=0`, +`DS4_COPY_HUGETLB=0`, `DS4_STORE_SPARE=0`, `DS4_STORE_PUT=0`, `STRATA_ROUTE_PRIOR=0`, ...) work as before. + ## What is faster if your PC is set up for it These need no engine change; they are settings. Each was measured on the same boxes. From a33899018638e697bdf21052ab1cc928ee3df7ff Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:24:50 +0100 Subject: [PATCH 121/177] qsa_pattn: sm_6x prompt attention without partials, opt-in STRATA_PATTN_SM60=1 (#3943) Problem: below sm_70 the prompt reads each QSA layer's attention through the decode kernels (qsa_prompt_attn_batch returns false without tensor cores): 32 queries a call, every chunk's partial results (817 KB a query) written to scratch and merged by a second kernel. Change: src/kernels/cuda/qsa_pattn.cu keeps the contributor's default variant only, ps_score_x_kernel (q in registers, the chunk's K staged with 16-byte loads, two cells at a time through a select-free reduce-scatter) and ps_value_d4_kernel (four dims per thread, merged into the output as the merge kernel does). Every float operation of attn_chunk_kernel_pre75 and attn_merge_kernel is kept in its order, so the output is the decode kernels' bit for bit. The PR's other variants (per-chunk, fused persistent, bench split codes), pattn_bench and the variant argument are not ported; pattn_bench needs a STRATA_QSA_DUMP file from a model run. Gating: compiled only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (HIP and Metal link a stub that answers false; prefill.cpp keeps the call out of the Metal build). At run time only with STRATA_PATTN_SM60=1, on compute capability 6.x, int8 K/V, head_dim 256, 12 query heads per KV head, at most 33 chunks. Unset, the only cost on the default path is one cached int test per QSA layer, and only when qsa_prompt_attn_batch has already declined. Any refusal or a failed launch returns false and the usual 32-query loop runs (one warning, no exit; the PR called exit(1) on a launch failure). Tests: src/kernels/qsa_pattn_parity.cpp (new, registered in CMakeLists.txt in the experimental sm_60 test block, skips with 77 when the kernels are absent) compares the kernels with the Daily's chunk kernel plus attn_merge_kernel on random int8 K/V: a shuffled page table with ~3% unresident pages and a run of 64 unresident pages (whole chunks masked, some queries empty), three selection shapes, caps 64 / 130 / 2051 / 2112, widths 0..cap, n_q up to 40 with a scratch that holds only 2 decode-layout queries (several batches), junk in the scratch and output. On a Pascal card it also requires the checked entry to take the shapes and qsa_decode_attn_batch to match. The kernel entry that skips the compute-capability test (qsa_pattn_batch_any_arch) exists for this test only. Results: z440 (RTX A4000, sm_86, CUDA 13.0, build with -DSTRATA_EXPERIMENTAL_SM60=ON, gpu lock): "qsa_pattn_parity: 468 cases, 0 differ, 29724792 nonzero output values in all -> PASS". sm_60 compile of the whole tree (CUDA 12.9, P1004): exit 0. Not covered: no P100 run here (the Pascal-only checks of the test and the speed claims wait for the gate, phaseA-tests/gh027/gates/3943-pattn.sh). The contributor's numbers (43.3 -> 30.8 ms a 1,536-query chunk per QSA layer at 26K context, 2-3% less time on 8K-150K token prompts on four dies) were not re-measured; compute capability 6.1 is covered by the same switch and was not measured by anyone. --- CMakeLists.txt | 11 + docs/OLDER_GPUS.md | 10 +- include/strata/kernels/qsa_pattn.hpp | 46 +++ src/kernels/cuda/qsa_pattn.cu | 458 +++++++++++++++++++++++++++ src/kernels/qsa_pattn_parity.cpp | 260 +++++++++++++++ src/prefill/prefill.cpp | 11 + 6 files changed, 795 insertions(+), 1 deletion(-) create mode 100644 include/strata/kernels/qsa_pattn.hpp create mode 100644 src/kernels/cuda/qsa_pattn.cu create mode 100644 src/kernels/qsa_pattn_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ed296bab..ff5494d2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -430,6 +430,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/fused_gdn.cu src/kernels/cuda/dequant_bf16.cu src/kernels/cuda/qsa_select.cu + src/kernels/cuda/qsa_pattn.cu src/kernels/cuda/verify_kernels.cu src/kernels/cuda/dflash2.cu src/kernels/cuda/iq_kernels.cu @@ -459,6 +460,16 @@ 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 CUDA::cudart) endif() + # PR #3943: STRATA_PATTN_SM60's score and value kernels against the decode kernels' output (the Daily's chunk kernel and + # the merge), bitwise, on random int8 K/V (GPU, synthetic, no model). Only in the experimental sm_60 build; it skips + # (77) on a build without the kernels. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_pattn_parity src/kernels/qsa_pattn_parity.cpp) + target_include_directories(qsa_pattn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_pattn_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_pattn_parity COMMAND qsa_pattn_parity) + set_tests_properties(qsa_pattn_parity PROPERTIES SKIP_RETURN_CODE 77) + 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) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 1ddd99a6..93a0aa7c 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -129,7 +129,7 @@ in [DETAILS.md](DETAILS.md#rtx-30-series-sm_86-and-tesla-p100-sm_60-bitwise-deco ## Pascal GP100: a Q8_0 decode kernel (opt-in) GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projections read their weights at 40-80 GB/s of about -730, decoding K- and i-quant blocks one int at a time. Three opt-in changes, all measured on a PH402 only: +730, decoding K- and i-quant blocks one int at a time. Four opt-in changes, all measured on a PH402 only: - **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp per row, 16-byte weight loads, activations copied once per workgroup into shared memory, @@ -147,6 +147,14 @@ GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projectio on one PH402 die, Swift 1.5 IQ3_S, one-token window: IQ4_NL 72.6 us (mode 8, the cc 6.0 default) and 54.5 us (mode 0) become 42.3 us; Q2_0 53.5 / 65.4 us become 38.6 us. It replaces the down step in either expert mode. Not measured end to end on a single card here. +- **`STRATA_PATTN_SM60=1`** (prompt reading with int8 K/V, CUDA build with `STRATA_EXPERIMENTAL_SM60`, compute capability 6.x): below + sm_70 the prompt reads each QSA layer's attention through the decode kernels, 32 queries a call, with 817 KB of partial results a + query and a merge kernel. The switch runs a score kernel and a value kernel that merges as it folds + (`src/kernels/cuda/qsa_pattn.cu`), in the same scratch and with the same arithmetic in the same order, so the output matches the + decode kernels bit for bit. If a launch fails or the shape does not fit, the usual loop runs. The author measured a 1,536-query + chunk's attention at 43.3 -> 30.8 ms per QSA layer at 26K context on one GP100 die, and 2-3% less time on 8K-150K token prompts + on four dies; we have not measured it here, and nobody has measured compute capability 6.1. `qsa_pattn_parity` (built with the + tests in this build) checks the bytes on random data. None of these changes is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default application clock is 759 MHz and a layer split leaves each die idle most of a window, so lock the clocks diff --git a/include/strata/kernels/qsa_pattn.hpp b/include/strata/kernels/qsa_pattn.hpp new file mode 100644 index 00000000..3fd8de0b --- /dev/null +++ b/include/strata/kernels/qsa_pattn.hpp @@ -0,0 +1,46 @@ +// include/strata/kernels/qsa_pattn.hpp - STRATA_PATTN_SM60: the prompt path's QSA attention on sm_6x, bit for bit +// what prefill.cpp gets today from qsa_decode_attn_batch (attn_chunk_kernel_pre75<1, 2> + attn_merge_kernel or +// attn_merge_v2_kernel, 32 queries a call) with int8 K/V. +// +// On sm_6x qsa_prompt_attn_batch returns false (no tensor cores) and the prompt reads every QSA layer's attention +// through the decode kernels: one CTA per (64-cell chunk, KV head, query), the partials of all 33 chunks written to +// scratch (817 KB a query) and merged by a second kernel. The kernels here keep every operation of that path in its +// order - each lane's 8-dimension products, warp_sum's tree over the 32 lanes, the chunk softmax (warp_max / __expf / +// warp_sum pairs), the ascending fmaf value fold, the merge's chunk order (fmaxf, __expf(m - M), fmaf(l, w, L), +// fmaf(acc, w, acc), acc / L) - and change only where operands live and which thread does what: +// - ps_score_x_kernel, one CTA per (chunk, KV head, query): q in registers (loaded once in a per-lane slot order), +// the chunk's K staged with 16-byte loads, two cells at a time through one reduce-scatter whose 24 sums are +// warp_sum's tree without reduce12's selects; writes the chunk's probabilities, rows, m and l to the scratch; +// - ps_value_d4_kernel, one CTA per (KV head, query): four dims x 12 heads a thread, V four bytes a load, the chunks +// in ascending order, each merged into the output as the merge kernel does (no partial accumulators, no merge +// kernel). +// The caller's attention scratch holds the blocks of ~100 queries; a prompt chunk runs in batches of that size. +// +// Off unless STRATA_PATTN_SM60=1, and compiled only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (every other build +// links stubs that answer false, so the usual attention runs). +#pragma once + +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +namespace strata::kernels { + +/// STRATA_PATTN_SM60: 0 off (default, and in a build without the sm_6x kernels); 1 on. +int pattn_mode(); + +/// qsa_decode_attn_batch for all `n_q` queries of a prompt chunk in one call (int8 K/V, sm_6x, experimental build). +/// `scratch` / `scratch_floats`: the caller's attention scratch (prefill.cpp: attn_batch x qsa_decode_attn_scratch_floats). +/// False: not applicable or a launch failed (nothing the caller can rely on was written; it runs the usual loop). +bool qsa_pattn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, + void* stream); + +/// The same without the compute-capability test, for src/kernels/qsa_pattn_parity.cpp (it runs the kernels on any card +/// to compare them with the decode kernels' output). False in a build without the sm_6x kernels. +bool qsa_pattn_batch_any_arch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, + int64_t n_q, void* stream); + +} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_pattn.cu b/src/kernels/cuda/qsa_pattn.cu new file mode 100644 index 00000000..0b1174a7 --- /dev/null +++ b/src/kernels/cuda/qsa_pattn.cu @@ -0,0 +1,458 @@ +// src/kernels/cuda/qsa_pattn.cu - see include/strata/kernels/qsa_pattn.hpp. +// +// Every value below is computed by the operation the production path uses, on the same operands, in the same order: +// - score of (cell, head): each lane l's partial k8[0] * q[8l] + ... + k8[7] * q[8l + 7] with k8[e] = (float) code * sc, +// the 32 partials summed in warp_sum's pairs (reduce12's tree), times `scale`; +// - chunk softmax: m = warp_max over fmaxf(s[lane], s[lane + 32]); e = __expf(s - m) (0 for a masked or absent cell); +// l = warp_sum(e[lane] + e[lane + 32]); +// - chunk value: acc[h] = fmaf(e[c][h], v, acc[h]) over the chunk's cells in ascending order, masked cells skipped, +// v = (float) code * sc; +// - merge (attn_merge_kernel): M = fmaxf over the chunks' m; for each chunk in order with m != -FLT_MAX: +// w = __expf(m - M), L = fmaf(l, w, L), acc = fmaf(acc_c, w, acc); out = L > 0 ? acc / L : 0. +// qsa_pattn_parity compares the outputs with qsa_decode_attn_batch's byte for byte on synthetic selections. +// Only the default variant of the contributor's PR (#3943) is kept: ps_score_x_kernel + ps_value_d4_kernel. +#include "strata/kernels/qsa_pattn.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/core/geometry.hpp" + +#include + +#include +#include +#include +#include + +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +#define STRATA_PATTN_BUILT 1 // the CUDA build with STRATA_EXPERIMENTAL_SM60 only (not HIP, not Metal) +#include +#else +#define STRATA_PATTN_BUILT 0 +#endif + +namespace strata::kernels { + +// STRATA_PATTN_SM60=1 turns it on (a tester switch, read once). In a build without the sm_6x kernels it says so and stays off. +int pattn_mode() { + static const int m = [] { + const char* v = std::getenv("STRATA_PATTN_SM60"); + const int x = v != nullptr && *v != '\0' ? std::atoi(v) : 0; + if (x == 0) return 0; +#if STRATA_PATTN_BUILT + std::fprintf(stderr, "strata pattn: STRATA_PATTN_SM60=%d: the prompt path's QSA attention on the sm_6x score / " + "value kernels (bit for bit qsa_decode_attn_batch; int8 K/V)\n", x); + return 1; +#else + std::fprintf(stderr, "strata pattn: STRATA_PATTN_SM60 is set, but this build has no sm_6x kernels " + "(CUDA with STRATA_EXPERIMENTAL_SM60 only); the usual attention runs\n"); + return 0; +#endif + }(); + return m; +} + +#if STRATA_PATTN_BUILT +namespace { + +constexpr int HD = 256; +constexpr int G = 12; +static_assert(HD == strata::core::kCompiledGeometry.head_dim && + G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, + "qsa_pattn is compiled for core/geometry.hpp"); +constexpr int CHUNK = 64; +constexpr int THREADS = 256; +constexpr int WARPS = THREADS / 32; +constexpr int NSC = HD / KV_Q8_GROUP; // scales per row (4) + +__device__ __forceinline__ float warp_sum_x(float v) { + v += __shfl_xor_sync(0xffffffffu, v, 16); v += __shfl_xor_sync(0xffffffffu, v, 8); + v += __shfl_xor_sync(0xffffffffu, v, 4); v += __shfl_xor_sync(0xffffffffu, v, 2); + v += __shfl_xor_sync(0xffffffffu, v, 1); + return v; +} +__device__ __forceinline__ float warp_max_x(float v) { + v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 16)); v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 8)); + v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 4)); v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 2)); + v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 1)); + return v; +} + +// pool row of cell `c0 + t` of query selection `ids` (attn_chunk_kernel_pre75's srow), -1 masked / absent +__device__ __forceinline__ long long cell_row(const QsaAttnPools& p, const int32_t* __restrict__ ids, int c0, int t, + int n_here, int n_kv_heads, int kvh, int page_size) { + long long r = -1; + if (t < n_here) { + const int cell = __ldg(ids + c0 + t); + const long long page = (long long) __ldg(p.page_table + cell / page_size); + if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + return r; +} + +// the chunk's K codes (16-byte loads) and scales (as float) into shared memory; masked / absent cells read row 0 +__device__ __forceinline__ void stage_rows(const int8_t* __restrict__ codes, const uint16_t* __restrict__ scales, + const long long* srow, int n_here, int t, int8_t (*sk)[HD], + float (*sks)[NSC]) { + uint4 kv[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = t + THREADS * j, c = idx >> 4, part = idx & 15; + const long long row = srow[c]; + const long long rr = (c < n_here && row >= 0) ? row : 0; + kv[j] = __ldg(reinterpret_cast(codes + rr * HD) + part); + } + float sc; + { + const int c = t >> 2, g = t & 3; + const long long row = srow[c]; + const long long rr = (c < n_here && row >= 0) ? row : 0; + sc = __half2float(__ushort_as_half(__ldg(scales + rr * NSC + g))); + } +#pragma unroll + for (int j = 0; j < 4; ++j) reinterpret_cast(&sk[0][0])[t + THREADS * j] = kv[j]; + sks[t >> 2][t & 3] = sc; +} + +constexpr int PS_BLK = G * CHUNK + 2 * CHUNK + 2 * G; // floats per (query, KV head, chunk): e, rows (int64), m, l +constexpr int NCM = 33; // chunks the value kernel keeps (cap <= 2112) + +// --------------------------------------------------------------------------------------------------------------------- +// ps_score_x_kernel: the score phase two cells at a time with a select-free reduce-scatter. reduce12's selects exist +// because the two lanes of an exchange send different slots; here every lane keeps the same slots and sends the same +// slots, and the lane-dependent part is moved into which query head each register slot holds (q is loaded once, so the +// permutation costs nothing per cell) and which of the two cells is "first": +// slot i (0..11) of lane L holds head P_L(i) = 6 ((i / 6) ^ b3) + ((i % 6 + 3 b2) % 6) (b_k: bit k of L) +// first = cell B if b4 else cell A, second = the other one; part1[i] / part2[i] = lane partials of (first / second, +// head P_L(i)) - the same expression as attn_chunk_kernel_pre75. +// level 16: r[i] = part1[i] + shfl(part2[i], 16) (partner: b4 flipped, so its second is my first, same P) +// level 8 : r6[i] = r[i] + shfl(r[i + 6], 8) (P_{L^8}(i) = P_L(i + 6)) +// level 4 : r3[i] = r6[i] + shfl(r6[i + 3], 4) (P_{L^4}(i) = P_L(i + 3), i < 3) +// level 2 / 1: reduce24's (heads 6 b3 + 3 b2 + {0, 1, 2}; o0 head +2 b1, o1 head +1 where b1 = 0) +// At every level the value at lane L is its partial at L plus its partial at L ^ o, the same operands warp_sum adds, +// so every score is reduce12's bit for bit. A pair with an absent / masked cell runs the same code on row 0's staged +// codes and that cell's outputs are not stored (it gets -FLT_MAX). 25 shuffles, 25 adds and 4 selects per pair +// instead of 2 x (15 + 15 + ~30). +__device__ __forceinline__ int px_head(int i, int lane) { + const int b3 = (lane >> 3) & 1, b2 = (lane >> 2) & 1; + return 6 * ((i / 6) ^ b3) + ((i % 6 + 3 * b2) % 6); +} +__device__ __forceinline__ void load_q_perm(const float* __restrict__ qh, int lane, float4 (&qa)[G], float4 (&qb)[G]) { +#pragma unroll + for (int i = 0; i < G; ++i) { + const float4* p4 = reinterpret_cast(qh + (size_t) px_head(i, lane) * HD + lane * 8); + qa[i] = __ldg(p4); + qb[i] = __ldg(p4 + 1); + } +} +__device__ __forceinline__ void dequant8(const int8_t* krow, float sc, int lane, float (&k8)[8]) { + const uint2 raw = *reinterpret_cast(krow + lane * 8); + const int8_t* cb = reinterpret_cast(&raw); +#pragma unroll + for (int e = 0; e < 8; ++e) k8[e] = (float) cb[e] * sc; +} +__device__ __forceinline__ float dot8(const float (&k8)[8], const float4& qa, const float4& qb) { + return k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + + k8[7] * qb.w; +} +template +__device__ __forceinline__ void score_chunk_x(const float4 (&qa)[G], const float4 (&qb)[G], const int8_t (*sk)[HD], + const float (*sks)[NSC], const long long* srow, float (*sp)[CHUNK], + int n_here, float scale, int warp, int lane) { + const bool h16 = (lane & 16) != 0, h2 = (lane & 2) != 0, even = (lane & 1) == 0; + const int hb = 6 * ((lane >> 3) & 1) + 3 * ((lane >> 2) & 1); + const int h0 = hb + (h2 ? 2 : 0), h1 = hb + 1; +#pragma unroll UNR + for (int i = 0; i < CHUNK / WARPS; i += 2) { + const int ca = warp + WARPS * i, cb = warp + WARPS * (i + 1); + const bool va = ca < n_here && srow[ca] >= 0, vb = cb < n_here && srow[cb] >= 0; + if (!va && !vb) { + if (lane < G) { sp[lane][ca] = -FLT_MAX; sp[lane][cb] = -FLT_MAX; } + continue; + } + const int c1 = h16 ? cb : ca, c2 = h16 ? ca : cb; // first / second (the staged rows of absent cells are row 0's) + float r[G]; + { + float k8[8]; + dequant8(sk[c2], sks[c2][lane >> 3], lane, k8); + float p2[G]; +#pragma unroll + for (int s = 0; s < G; ++s) p2[s] = dot8(k8, qa[s], qb[s]); + dequant8(sk[c1], sks[c1][lane >> 3], lane, k8); +#pragma unroll + for (int s = 0; s < G; ++s) r[s] = dot8(k8, qa[s], qb[s]) + __shfl_xor_sync(0xffffffffu, p2[s], 16); + } + float r6[6]; +#pragma unroll + for (int s = 0; s < 6; ++s) r6[s] = r[s] + __shfl_xor_sync(0xffffffffu, r[s + 6], 8); + float r3[3]; +#pragma unroll + for (int s = 0; s < 3; ++s) r3[s] = r6[s] + __shfl_xor_sync(0xffffffffu, r6[s + 3], 4); + const float x0 = (h2 ? r3[2] : r3[0]) + __shfl_xor_sync(0xffffffffu, h2 ? r3[0] : r3[2], 2); + const float x1 = r3[1] + __shfl_xor_sync(0xffffffffu, r3[1], 2); + const float o0 = x0 + __shfl_xor_sync(0xffffffffu, x0, 1); + const float o1 = x1 + __shfl_xor_sync(0xffffffffu, x1, 1); + const bool vmine = h16 ? vb : va; + if (even && vmine) { + sp[h0][c1] = o0 * scale; + if (!h2) sp[h1][c1] = o1 * scale; + } + if (lane < G) { + if (!va) sp[lane][ca] = -FLT_MAX; + if (!vb) sp[lane][cb] = -FLT_MAX; + } + } +} + +// ps_score_kernel with score_chunk_x (q loaded in the permuted slot order) +template +__global__ void __launch_bounds__(THREADS, 2) ps_score_x_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, float* __restrict__ blocks, + int n_chunks, int cap) { + q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; + ids += (size_t) blockIdx.z * (size_t) cap; + step += (size_t) blockIdx.z * kStepCount; + const int chunk = blockIdx.x, kvh = blockIdx.y; + float* const blk = blocks + (((size_t) blockIdx.z * n_kv_heads + kvh) * n_chunks + chunk) * PS_BLK; + __shared__ __align__(16) int8_t sk[CHUNK][HD]; + __shared__ __align__(16) float sks[CHUNK][NSC]; + __shared__ float sp[G][CHUNK]; + __shared__ long long srow[CHUNK]; + const int n_ids = __ldg(step + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int c0 = chunk * CHUNK; + const int n_here = min(CHUNK, n_ids - c0); + if (n_here <= 0) { + if (t < G) { blk[G * CHUNK + 2 * CHUNK + t] = -FLT_MAX; blk[G * CHUNK + 2 * CHUNK + G + t] = 0.0f; } + return; + } + if (t < CHUNK) { + const long long r = cell_row(p, ids, c0, t, n_here, n_kv_heads, kvh, page_size); + srow[t] = r; + reinterpret_cast(blk + G * CHUNK)[t] = r; + } + float4 qa[G], qb[G]; + load_q_perm(q + (size_t) (kvh * G) * HD, lane, qa, qb); + __syncthreads(); + stage_rows(p.k_q, p.k_scale, srow, n_here, t, sk, sks); + __syncthreads(); + score_chunk_x(qa, qb, sk, sks, srow, sp, n_here, scale, warp, lane); + __syncthreads(); + for (int h = warp; h < G; h += WARPS) { + const float a = sp[h][lane], b = sp[h][lane + 32]; + const float m = warp_max_x(fmaxf(a, b)); + const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f; + const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f; + blk[h * CHUNK + lane] = ea; + blk[h * CHUNK + lane + 32] = eb; + const float l = warp_sum_x(ea + eb); + if (lane == 0) { blk[G * CHUNK + 2 * CHUNK + h] = m; blk[G * CHUNK + 2 * CHUNK + G + h] = l; } + } +} + +// ps_value_d4_kernel: the value kernel with four dims a thread (64 threads, one CTA per (KV head, query)): a cell's four +// codes are one 32-bit load (a warp reads 128 contiguous bytes), its 12 weights three broadcast float4 reads for 48 +// fmaf. V loads run four cells ahead. Per (dim, head) the fold and the merge are ps_value_kernel's. +__global__ void __launch_bounds__(64) ps_value_d4_kernel(QsaAttnPools p, const int32_t* __restrict__ steps, + const float* __restrict__ blocks, int n_kv_heads, int n_chunks, + float* __restrict__ attn) { + constexpr int NT = 64; + const int kvh = blockIdx.x, z = blockIdx.y; + const int t = threadIdx.x; + const float* const blk0 = blocks + ((size_t) z * n_kv_heads + kvh) * n_chunks * PS_BLK; + __shared__ float sm_m[NCM][G], sm_w[NCM][G], sm_l[NCM][G]; + __shared__ float sL[G]; + __shared__ __align__(16) float spt[CHUNK][G]; + __shared__ long long srow[CHUNK]; + __shared__ int s_masked; + const int width = __ldg(steps + (size_t) z * kStepCount + kStepWidth); + const int n_act = width > 0 ? min(n_chunks, (width - 1) / CHUNK + 1) : 0; + for (int i = t; i < n_act * G; i += NT) { + const int c = i / G, h = i % G; + sm_m[c][h] = __ldg(blk0 + (size_t) c * PS_BLK + G * CHUNK + 2 * CHUNK + h); + sm_l[c][h] = __ldg(blk0 + (size_t) c * PS_BLK + G * CHUNK + 2 * CHUNK + G + h); + } + __syncthreads(); + if (t < G) { + float M = -FLT_MAX; + for (int c = 0; c < n_act; ++c) M = fmaxf(M, sm_m[c][t]); + float L = 0.0f; + for (int c = 0; c < n_act; ++c) { + const float m = sm_m[c][t]; + const float w = __expf(m - M); + sm_w[c][t] = w; + const float L_next = fmaf(sm_l[c][t], w, L); + L = (m == -FLT_MAX) ? L : L_next; + } + sL[t] = L; + } + const int d0 = 4 * t, g = d0 / KV_Q8_GROUP; + float acc[4][G]; +#pragma unroll + for (int h = 0; h < G; ++h) +#pragma unroll + for (int d = 0; d < 4; ++d) acc[d][h] = 0.0f; + for (int c = 0; c < n_act; ++c) { + const float* blk = blk0 + (size_t) c * PS_BLK; + const int n_here = min(CHUNK, width - c * CHUNK); + __syncthreads(); + if (t == 0) s_masked = 0; + __syncthreads(); + { + const long long r = __ldg(reinterpret_cast(blk + G * CHUNK) + t); + srow[t] = r; + if (t < n_here && r < 0) s_masked = 1; + } +#pragma unroll + for (int j = 0; j < G * CHUNK / NT; ++j) { + const int idx = t + NT * j, h = idx / CHUNK, cell = idx % CHUNK; + spt[cell][h] = __ldg(blk + idx); + } + __syncthreads(); + float a[4][G]; +#pragma unroll + for (int h = 0; h < G; ++h) +#pragma unroll + for (int d = 0; d < 4; ++d) a[d][h] = 0.0f; + const auto fold4 = [&](int cl, uint32_t codes, float sc) { + const float v0 = (float) (int8_t) (codes & 0xFF) * sc, v1 = (float) (int8_t) ((codes >> 8) & 0xFF) * sc; + const float v2 = (float) (int8_t) ((codes >> 16) & 0xFF) * sc, v3 = (float) (int8_t) (codes >> 24) * sc; + const float4* w4 = reinterpret_cast(spt[cl]); + const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2]; + const float ww[G] = {w0.x, w0.y, w0.z, w0.w, w1.x, w1.y, w1.z, w1.w, w2.x, w2.y, w2.z, w2.w}; +#pragma unroll + for (int h = 0; h < G; ++h) { + a[0][h] = fmaf(ww[h], v0, a[0][h]); + a[1][h] = fmaf(ww[h], v1, a[1][h]); + a[2][h] = fmaf(ww[h], v2, a[2][h]); + a[3][h] = fmaf(ww[h], v3, a[3][h]); + } + }; + const auto vld = [&](int cl, uint32_t& codes, float& sc) { + const long long r = srow[cl]; + const long long rr = r >= 0 ? r : 0; + codes = __ldg(reinterpret_cast(p.v_q + rr * HD + d0)); + sc = __half2float(__ushort_as_half(__ldg(p.v_scale + rr * NSC + g))); + }; + if (!s_masked) { + int cl = 0; + for (; cl + 4 <= n_here; cl += 4) { + uint32_t k0, k1, k2, k3; + float s0, s1, s2, s3; + vld(cl, k0, s0); vld(cl + 1, k1, s1); vld(cl + 2, k2, s2); vld(cl + 3, k3, s3); + fold4(cl, k0, s0); + fold4(cl + 1, k1, s1); + fold4(cl + 2, k2, s2); + fold4(cl + 3, k3, s3); + } + for (; cl < n_here; ++cl) { + uint32_t k0; + float s0; + vld(cl, k0, s0); + fold4(cl, k0, s0); + } + } else { + for (int cl = 0; cl < n_here; ++cl) { + if (srow[cl] < 0) continue; + uint32_t k0; + float s0; + vld(cl, k0, s0); + fold4(cl, k0, s0); + } + } +#pragma unroll + for (int h = 0; h < G; ++h) { + const bool live = !(sm_m[c][h] == -FLT_MAX); + const float w = sm_w[c][h]; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const float acc_next = fmaf(a[d][h], w, acc[d][h]); + acc[d][h] = live ? acc_next : acc[d][h]; + } + } + } + __syncthreads(); + float* out = attn + ((size_t) z * n_kv_heads + kvh) * G * HD; +#pragma unroll + for (int h = 0; h < G; ++h) { + const float L = sL[h]; + *reinterpret_cast(out + (size_t) h * HD + d0) = + make_float4(L > 0.0f ? acc[0][h] / L : 0.0f, L > 0.0f ? acc[1][h] / L : 0.0f, + L > 0.0f ? acc[2][h] / L : 0.0f, L > 0.0f ? acc[3][h] / L : 0.0f); + } +} + +bool sm6x_device() { + static int cc[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cc[dev] == 0) { + int major = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) { + cudaGetLastError(); + return false; + } + cc[dev] = major; + } + return cc[dev] == 6; +} + +} // namespace + +bool qsa_pattn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, + void* stream) { + return sm6x_device() && qsa_pattn_batch_any_arch(q, pools, ids, steps, cap, s, scratch, scratch_floats, attn, n_q, stream); +} + +bool qsa_pattn_batch_any_arch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, + int64_t n_q, void* stream) { + if (n_q <= 0) return true; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || + !pools.page_table || pools.k_q == nullptr || pools.v_q == nullptr || pools.k_q4 != nullptr || + pools.v_q4 != nullptr || !pools.k_scale || !pools.v_scale) + return false; + const cudaStream_t st = (cudaStream_t) stream; + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const float scale = 1.0f / sqrtf((float) HD); + if (n_chunks > NCM) return false; // a longer selection keeps the usual path + // the scratch holds the blocks of one batch of queries (probabilities, rows, m and l of every chunk), evenly split + const uint64_t per_q = (uint64_t) s.n_head_kv * (uint64_t) n_chunks * PS_BLK; + const int64_t max_batch = (int64_t) (scratch_floats / per_q); + if (max_batch < 1) return false; + const int64_t n_batches = (n_q + max_batch - 1) / max_batch; + const int64_t batch = (n_q + n_batches - 1) / n_batches; + for (int64_t t0 = 0; t0 < n_q; t0 += batch) { + const int64_t nb = n_q - t0 < batch ? n_q - t0 : batch; + const dim3 g1((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) nb); + const dim3 g2((unsigned) s.n_head_kv, (unsigned) nb); + const float* qb = q + (size_t) t0 * s.n_head * HD; + const int32_t* ib = ids + (size_t) t0 * cap; + const int32_t* sb = steps + (size_t) t0 * kStepCount; + ps_score_x_kernel<1><<>>(qb, pools, ib, sb, (int) s.n_head_kv, (int) s.page_size, scale, + scratch, n_chunks, (int) cap); + ps_value_d4_kernel<<>>(pools, sb, scratch, (int) s.n_head_kv, n_chunks, + attn + (size_t) t0 * s.n_head * HD); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + // a launch that did not start: say so once, and let the caller run the usual attention over the whole chunk + static bool warned = false; + if (!warned) { + warned = true; + std::fprintf(stderr, "strata pattn: launch failed (%s); the usual attention runs instead\n", cudaGetErrorString(e)); + } + return false; + } + return true; +} + +#else // not the experimental sm_60 CUDA build +bool qsa_pattn_batch(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, + float*, uint64_t, float*, int64_t, void*) { return false; } +bool qsa_pattn_batch_any_arch(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, + float*, uint64_t, float*, int64_t, void*) { return false; } +#endif + +} // namespace strata::kernels diff --git a/src/kernels/qsa_pattn_parity.cpp b/src/kernels/qsa_pattn_parity.cpp new file mode 100644 index 00000000..ab67038d --- /dev/null +++ b/src/kernels/qsa_pattn_parity.cpp @@ -0,0 +1,260 @@ +// src/kernels/qsa_pattn_parity.cpp - STRATA_PATTN_SM60's score and value kernels (qsa_pattn.cu, PR #3943) against the +// decode kernels' output, bitwise (GPU, synthetic data, no model). +// +// The reference is what the prompt path reads on sm_6x today: the chunk pass of attn_chunk_kernel_pre75 (the Daily's +// chunk kernel, qsa_decode_attn_chunks_only with daily_chunk 1, which runs on any card) and attn_merge_kernel +// (qsa_decode_attn_merge_only, v2 0). The candidate is qsa_pattn_batch_any_arch (no compute-capability test), so the +// same bytes can be checked on an Ampere card too: the two paths do the same operations in the same order, and a +// pass there shows the indexing, masking and merge are right. The last word is a run on a Pascal card (P100): there +// the checked entry qsa_pattn_batch must take the shapes and the production qsa_decode_attn_batch must give the same +// bytes as the reference. +// +// Data: random int8 K/V codes, fp16 scales in a safe range, normal queries, a shuffled page table with ~3% unresident +// (-1) pages and one run of 64 unresident pages (so whole chunks are masked and some queries read nothing), selections +// shaped like the drafter's window, the indexer's (ascending with gaps) and unordered with repeats, caps 64 / 130 / +// 2051 / 2112 (1, 3 and 33 chunks), widths 0 .. cap, n_q up to 40 with a scratch that holds only 2 queries of the +// decode layout (so qsa_pattn_batch runs several batches). The pattn scratch and the output are filled with +// junk before each call, so a read of a block that was not written shows up as a difference. +// +// qsa_pattn_parity [--device N] exit 0: every case is bit-identical; 77: no GPU or a build without the kernels +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_pattn.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_pattn_parity: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(2); + } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc((void**) &p, n * sizeof(T) + 256), "cudaMalloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 256), "cudaMemset"); + return p; +} +template T* upload(const std::vector& h) { + T* d = dalloc(h.size()); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +// positive fp16 scale in [1/64, 1/32): codes up to 127 give |x| < 4 +uint16_t f16_scale_q8(uint32_t r) { return (uint16_t) ((9u << 10) | (r & 0x3FFu)); } + +constexpr int64_t kCells = 40960; // the cells this harness can address +constexpr int64_t kHole = 8192; // 64 unresident pages in a row: cells [kHole, kHole + 256) + +void selection(int32_t* ids, int64_t cap, int width, int shape, std::mt19937& rng) { + const int64_t w = std::max(0, std::min(width, cap)); + if (shape == 0) { // the drafter's window: consecutive cells, often across the unresident run + int64_t start; + if (rng() % 2 == 0) start = std::max(0, kHole - 64 * (int64_t) (rng() % 8)); + else start = (int64_t) (rng() % (uint32_t) (kCells - std::max(w, 1))); + if (start + w > kCells) start = kCells - w; + for (int64_t j = 0; j < cap; ++j) ids[j] = (int32_t) ((start + j) % kCells); + } else if (shape == 1) { // the indexer's: ascending with gaps + std::vector v((size_t) cap); + for (auto& x : v) x = (int32_t) (rng() % (uint32_t) kCells); + std::sort(v.begin(), v.begin() + w); + std::copy(v.begin(), v.end(), ids); + } else { // unordered, with repeats + for (int64_t j = 0; j < cap; ++j) ids[j] = (int32_t) (rng() % (uint32_t) kCells); + } +} + +struct Harness { + k::QsaShapes s = k::qsa_real_shapes(); + k::QsaAttnPools pools; + int32_t* table = nullptr; + float *q = nullptr, *scratch_ref = nullptr, *scratch_new = nullptr, *attn_ref = nullptr, *attn_new = nullptr; + int32_t *ids = nullptr, *steps = nullptr; + int64_t max_q = 0, max_cap = 0; + std::vector to_free; + + template T* keep(T* p) { to_free.push_back(p); return p; } + + void init(std::mt19937& rng, int64_t max_q_, int64_t max_cap_) { + max_q = max_q_; + max_cap = max_cap_; + const int64_t PS = s.page_size, pages = kCells / PS, H = s.n_head_kv, D = s.head_dim; + std::vector tab((size_t) pages); // logical page -> physical page: a permutation, with holes + for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i; + std::shuffle(tab.begin(), tab.end(), rng); + for (int64_t i = 0; i < pages; ++i) + if (rng() % 32u == 0) tab[(size_t) i] = -1; + for (int64_t i = kHole / PS; i < (kHole + 256) / PS; ++i) tab[(size_t) i] = -1; + table = keep(upload(tab)); + const int64_t rows = pages * H * PS; + pools.page_table = table; + std::vector c((size_t) (rows * D)); + for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127); + pools.k_q = keep(upload(c)); + for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127); + pools.v_q = keep(upload(c)); + std::vector sc((size_t) (rows * (D / 64))); + for (auto& x : sc) x = f16_scale_q8(rng()); + pools.k_scale = keep(upload(sc)); + for (auto& x : sc) x = f16_scale_q8(rng()); + pools.v_scale = keep(upload(sc)); + q = keep(dalloc((size_t) (max_q * s.n_head * D))); + ids = keep(dalloc((size_t) (max_q * max_cap))); + steps = keep(dalloc((size_t) (max_q * k::kStepCount))); + const size_t sf = (size_t) (k::qsa_decode_attn_scratch_floats(max_cap, s) * (uint64_t) max_q); + scratch_ref = keep(dalloc(sf)); + scratch_new = keep(dalloc(sf)); + attn_ref = keep(dalloc((size_t) (max_q * s.n_head * D))); + attn_new = keep(dalloc((size_t) (max_q * s.n_head * D))); + } + ~Harness() { + for (void* p : to_free) cudaFree(p); + } + + // returns 0 identical, 1 differs, -1 the candidate declined (build without the kernels) + int run(int64_t cap, int n_q, int scr_q, const std::vector& widths, std::mt19937& rng, bool on_pascal, + long long& nonzero) { + const int64_t D = s.head_dim, NH = s.n_head; + std::normal_distribution nd(0.0f, 1.0f); + std::vector hq((size_t) (n_q * NH * D)); + for (auto& x : hq) x = nd(rng); + ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q"); + std::vector hid((size_t) (n_q * cap)); + std::vector hst((size_t) (n_q * k::kStepCount), 0); + for (int i = 0; i < n_q; ++i) { + selection(hid.data() + (size_t) i * cap, cap, widths[(size_t) i], (int) (rng() % 3u), rng); + hst[(size_t) i * k::kStepCount + k::kStepWidth] = widths[(size_t) i]; + } + ck(cudaMemcpy(ids, hid.data(), hid.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps"); + const size_t n = (size_t) (n_q * NH * D); + const size_t sbytes = (size_t) k::qsa_decode_attn_scratch_floats(cap, s) * (size_t) n_q * 4; + + // the reference: the pre-sm_75 chunk kernel and attn_merge_kernel + ck(cudaMemset(scratch_ref, 0xFF, sbytes), "scratch_ref fill"); + ck(cudaMemset(attn_ref, 0xFF, n * 4), "attn_ref fill"); + k::qsa_decode_attn_chunks_only(q, pools, ids, steps, cap, s, scratch_ref, n_q, 1, nullptr); + k::qsa_decode_attn_merge_only(steps, cap, s, scratch_ref, attn_ref, n_q, 0, nullptr); + ck(cudaDeviceSynchronize(), "reference"); + std::vector a(n), b(n); + ck(cudaMemcpy(a.data(), attn_ref, n * 4, cudaMemcpyDeviceToHost), "read reference"); + nonzero = 0; + for (size_t i = 0; i < n; ++i) { + if (!std::isfinite(a[i])) { std::printf("FAIL: the reference has a non-finite value\n"); return 1; } + if (a[i] != 0.0f) ++nonzero; + } + + // the candidate: the scratch holds scr_q queries of the decode layout (the caller's attn_batch), junk in it + ck(cudaMemset(scratch_new, 0xFF, sbytes), "scratch_new fill"); + ck(cudaMemset(attn_new, 0x7F, n * 4), "attn_new fill"); + const uint64_t scratch_floats = (uint64_t) scr_q * k::qsa_decode_attn_scratch_floats(cap, s); + const bool took = k::qsa_pattn_batch_any_arch(q, pools, ids, steps, cap, s, scratch_new, scratch_floats, attn_new, + n_q, nullptr); + if (!took) return -1; + ck(cudaDeviceSynchronize(), "candidate"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read candidate"); + bool same = std::memcmp(a.data(), b.data(), n * 4) == 0; + if (!same) { + size_t first = 0; + while (first < n && std::memcmp(&a[first], &b[first], 4) == 0) ++first; + std::printf("FAIL cap %lld n_q %d scratch %d queries, widths", (long long) cap, n_q, scr_q); + for (int32_t w : widths) std::printf(" %d", w); + std::printf(": first difference at query %lld head %lld dim %lld: %.9g vs %.9g\n", + (long long) (first / (NH * D)), (long long) (first / D % NH), (long long) (first % D), a[first], + b[first]); + } + if (on_pascal) { // the checked entry takes the shapes, and the production path is the reference + ck(cudaMemset(scratch_new, 0xFF, sbytes), "scratch_new refill"); + ck(cudaMemset(attn_new, 0x7F, n * 4), "attn_new refill"); + if (!k::qsa_pattn_batch(q, pools, ids, steps, cap, s, scratch_new, scratch_floats, attn_new, n_q, nullptr)) { + std::printf("FAIL: qsa_pattn_batch declined on a compute capability 6 card (cap %lld n_q %d)\n", + (long long) cap, n_q); + same = false; + } else { + ck(cudaDeviceSynchronize(), "checked entry"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read checked entry"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::printf("FAIL: qsa_pattn_batch differs from the reference (cap %lld n_q %d)\n", (long long) cap, n_q); + same = false; + } + } + ck(cudaMemset(scratch_new, 0xFF, sbytes), "scratch_new refill"); + k::qsa_decode_attn_batch(q, pools, ids, steps, cap, s, scratch_new, attn_new, n_q, nullptr); + ck(cudaDeviceSynchronize(), "production"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read production"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::printf("FAIL: qsa_decode_attn_batch differs from the reference (cap %lld n_q %d)\n", (long long) cap, + n_q); + same = false; + } + } + return same ? 0 : 1; + } +}; +} // namespace + +int main(int argc, char** argv) { + int device = 0; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else { + std::fprintf(stderr, "usage: qsa_pattn_parity [--device N]\n"); + return 2; + } + } + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::puts("SKIP: no GPU"); + return 77; + } + ck(cudaSetDevice(device), "cudaSetDevice"); + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + const bool on_pascal = prop.major == 6; + std::printf("qsa_pattn_parity on device %d (%s, %d.%d)%s\n", device, prop.name, prop.major, prop.minor, + on_pascal ? ": the checked entry and the production path are compared too" : ""); + + std::mt19937 rng(20261026u); + Harness hx; + hx.init(rng, 40, 2112); + + const int32_t base_widths[] = {0, 1, 63, 64, 65, 1023, 1024, 1025, 2051, 2112}; + const int n_base = (int) (sizeof(base_widths) / sizeof(base_widths[0])); + long long cases = 0, failed = 0, nonzero_total = 0; + for (int64_t cap : {(int64_t) 64, (int64_t) 130, (int64_t) 2051, (int64_t) 2112}) { + for (int n_q : {1, 2, 3, 7, 40}) { + for (int scr_q : {n_q, 2}) { + if (scr_q > n_q) continue; + for (int wc = 0; wc < n_base + 3; ++wc) { + std::vector widths; + for (int i = 0; i < n_q; ++i) + widths.push_back(std::min((int32_t) cap, wc < n_base ? base_widths[wc] : base_widths[rng() % (uint32_t) n_base])); + long long nz = 0; + const int r = hx.run(cap, n_q, scr_q, widths, rng, on_pascal, nz); + if (r < 0) { + std::puts("SKIP: this build has no sm_6x kernels (CUDA with STRATA_EXPERIMENTAL_SM60)"); + return 77; + } + nonzero_total += nz; + ++cases; + if (r != 0) ++failed; + } + } + } + } + std::printf("qsa_pattn_parity: %lld cases, %lld differ, %lld nonzero output values in all -> %s\n", cases, failed, + nonzero_total, failed == 0 && nonzero_total > 0 ? "PASS" : "FAIL"); + return failed == 0 && nonzero_total > 0 ? 0 : 1; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 08b529e6..a9d121f9 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -38,6 +38,7 @@ #include "strata/core/native_head.hpp" #include "strata/kernels/verify_kernels.hpp" #include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_pattn.hpp" #include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/kernels/qsa_select.hpp" #include "strata/prefill/gemm.hpp" @@ -3723,8 +3724,18 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // 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; + // STRATA_PATTN_SM60=1 (qsa_pattn.hpp, sm_6x, int8 K/V): the decode kernels' output bit for bit from a + // score kernel and a value kernel that merges as it folds (no partials, no merge kernel), ~100 + // queries a batch in the same scratch; any refusal or launch failure runs the loop below if (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)) +#if !defined(STRATA_GPU_METAL) // qsa_pattn.cu is in the CUDA / HIP kernel library only + if (!(strata::kernels::pattn_mode() != 0 && + strata::kernels::qsa_pattn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, m.attn_scratch, + (uint64_t) m.attn_batch * + strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), + m.attn, T, m.cs))) +#endif for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { const int64_t nb = std::min(m.attn_batch, T - t0); strata::kernels::qsa_decode_attn_batch(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap, From d98d8f977f9cd00224d6eb8ec1cb1319d032740c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:36:15 +0100 Subject: [PATCH 122/177] docs/TROUBLESHOOTING.md: every entry of v0.2.4.2 is back, updated for 0.2.7 The 0.2.5 rewrite dropped about 25 entries: the Mac quarantine steps, strata doctor, sending logs, the first-start freeze, the graphics memory the app keeps free, Smart App Control, UPDATE.bat and git pull (#1276), the build tools and the gcc/glibc compile problems, the engine checksum, the engine stopped unexpectedly, slower than the tables, the empty-reply and Turing switches, --expert-cache and --resident-budget-gib, the page-locked OOM, the NVIDIA 0x141 reset, CUDA 13.2 on RTX 50, the AMD section (KFD, the build list, 0xC0000005, the driver reset, pinned allocations, verify timeouts) and the body of the verify-timeout entry, which the rewrite had left empty. Each is back with the 0.2.7 facts: the app's reserve defaults (native-resources.mjs), the Drafting setting, --vision on|off|gpu|cpu in the Terminal and --vision no in a source checkout, Intel Arc's CPU reader, and the Terminal route next to the source-checkout one. Every pointer resolves: setup.py's driver-reset pointer, the server's Smart App Control message, DETAILS.md's STRATA_KEEP_EMPTY_TURNS / STRATA_TOPK_STREAM line, OLDER_GPUS.md and MAC.md. tests/terminal/test_troubleshooting_page.py checks the entries, those pointers and the page's own links and anchors. --- docs/TROUBLESHOOTING.md | 319 ++++++++++++++++---- tests/terminal/test_troubleshooting_page.py | 77 +++++ 2 files changed, 332 insertions(+), 64 deletions(-) create mode 100644 tests/terminal/test_troubleshooting_page.py diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 37c97734..23ca9934 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -1,6 +1,6 @@ # Troubleshooting -This page is for anyone whose install or startup fails. Find your symptom below. Each entry gives one fix. +This page is for anyone whose install or startup fails, or whose answers go wrong. Find your symptom below. Each entry gives one fix. Start from the route you installed: [desktop app or Terminal](INSTALL.md), or [source checkout](SOURCE_INSTALL.md). The normal release uses the app or `strata launch` and needs no `.bat` file. Detailed engine errors are in the [engine reference](DETAILS.md#troubleshooting). @@ -25,16 +25,25 @@ startup path for the app. For a fresh desktop install, download the one installe On Windows, open a new PowerShell window after installing. On Linux or Mac, use the full path the installer printed, normally `~/.local/bin/strata`, and add `~/.local/bin` to PATH if needed. Check `strata --version`. -**Strata could not find an engine for this computer.** -Run `strata doctor --live` and `strata update --check`. Check the selected GPU, driver and -[backend guide](INSTALL.md#what-you-need). Supported paths include Apple Silicon and Intel Arc on Linux; do not -assume every machine without an NVIDIA/AMD discrete card is unsupported. A model download can finish even when -no engine starts. Verify `strata launch --status` and `/health` before calling the installation successful. +**A warning says Strata "couldn't find an engine for this computer".** +The engine is the part that talks to your graphics card. Strata only warns and still downloads the model, and the model +files stay on your computer, but the model may not run until the right engine is installed. The usual reasons are that +no engine is installed yet and the update source has none for your card, that the engine found is for another make of +card, or that the graphics driver is too old. In the app, open Settings, then Engine. In the Terminal, the message names +the next step: run `strata update` and start again. Run `strata doctor --live` and `strata update --check` to see the +selected GPU and driver, and check the [backend guide](INSTALL.md#what-you-need). Supported paths include Apple Silicon and +Intel Arc on Linux, so do not assume every machine without an NVIDIA or AMD discrete card is unsupported. If the computer +has no graphics card Strata can use (only an Intel UHD or Iris chip, a virtual machine, or Windows on ARM), Strata says so +and there is nothing to install. Verify `strata launch --status` and `/health` before calling the installation successful. -**This model needs a newer engine.** -Unload running models, then use the app's engine update or `strata update`. Minimum engine versions vary by model and -backend. Check the model guide and the installed engine, not only the app version. If the feed has no compatible engine, -report the missing combination. +**"This model needs a newer engine." (the app), or a button called Update engine.** +Some models need an engine newer than the one installed: Gyro needs 0.1.45.1 or newer, NVFP4 needs 0.1.44, and NVFP4 +(NVIDIA, trained for FP4) needs 0.1.45. Minimum versions vary by model and backend, so check the model guide and the +installed engine, not only the app version. In the app, open Settings, then Engine, and press Update engine. It asks +first, keeps your model files and settings, and wants running models unloaded. In the Terminal: `strata update --check` +says what would change, `strata update` installs it (it switches to the new engine only after a test start). If the engine +you installed is the newest and the message stays, the update source has no newer engine for your card yet; report the +missing combination. **An update says it succeeded but `strata --version` is still old.** The Terminal switches to the updated Control on the next command, so run `strata --version` again. If it is still old, @@ -42,26 +51,58 @@ run the one-line installer once more; it keeps models and settings. The app, Con numbers; see [updating](INSTALL.md#updating) and the [release notes](https://github.com/Niko1221/Strata/releases). **A new engine misbehaves after an update.** -Stop the model, then use the app's rollback control or `strata components rollback`. Source-checkout engines use a -separate rollback workflow, `python setup.py --rollback-engine`, described in [source setup](SOURCE_INSTALL.md). +Stop the model, then use the app's rollback control or `strata components rollback`. An update keeps the engine it +replaced (one generation, about 210 MiB). Source-checkout engines use a separate rollback workflow, in `engine\.previous`: +`python setup.py --rollback-engine` puts the old one back and keeps the newer one there, so run it again to go forward +(#670). It is described in [source setup](SOURCE_INSTALL.md). -**The Mac app cannot be opened.** -Check that the download is for Apple Silicon and that macOS is 15 or newer. Follow -[Mac installation](MAC.md#the-desktop-app-and-strata-launch-on-a-mac). A warning alone does not establish that a file -is safe or intact: verify the download source and release before changing quarantine settings. Release signing and -test-build handling are described in [Mac packaging](../packaging/mac/README.md). +**On a Mac: "Strata is damaged and can't be opened", "cannot be opened", or "unidentified developer".** +Check first that the download is for Apple Silicon and that macOS is 15 or newer ([Mac installation](MAC.md#the-desktop-app-and-strata-launch-on-a-mac)). +Nothing is wrong with the file if the message is only about the developer: macOS marks everything a browser downloads, and +only lets a marked program run if Apple has checked it. Strata's release builds are checked by Apple ("notarised"): drag +Strata onto Applications and open it; the first time, macOS asks "Are you sure you want to open it?" and you press Open. A +test build that is not notarised says "damaged". Do not move it to the Trash. Open the Terminal app and remove the mark, +with the line that matches what you have (drag the file from Finder into the Terminal window to type its path): + + xattr -dr com.apple.quarantine ~/Downloads/ # the .dmg, before opening it + xattr -dr com.apple.quarantine /Applications/Strata.app # the app, after dragging it over + xattr -dr com.apple.quarantine # an unzipped Terminal folder + +Then open it again. If macOS says only "the developer cannot be verified", you can instead try to open it once, then open +System Settings > Privacy & Security and press "Open Anyway" next to the message about Strata. Only remove the mark from a +file you downloaded from the official release; a warning alone does not show that a file is safe or intact. Installs made +with `curl ... | sh` carry no mark and need none of this. To see which kind you have: `spctl -a -vv /Applications/Strata.app` +answers "accepted" and "Notarized Developer ID" for a notarised build. How the builds are signed is in +[Mac packaging](../packaging/mac/README.md). **The Linux AppImage does not open.** Make the downloaded file executable. It may need FUSE 2 (`libfuse2` on Ubuntu 22.04, `libfuse2t64` on newer Ubuntu; package names vary by distribution). Without FUSE, run the file with `--appimage-extract-and-run`. For a crash log, -run it with `--save-logs`; see the logs section below. +run it with `--save-logs`; see [Logs and bug reports](#logs-and-bug-reports). + +**Checking what is installed: `strata doctor`.** +It is a read-only check of the installed engine parts (it changes nothing): which engine and helper files a saved model +needs, and whether they are there. `strata doctor --live` also asks the computer which graphics cards it sees and compares +them with the cards the model is set to use; `--output json` prints the same as data. Put its output into a bug report. ## While installing or starting +**My PC froze, or got very slow, the first time Strata started.** +That is normal while it starts, most of all the first time. Strata loads 35-55 GB into your RAM, locks part of it for the +graphics card, and works out how much of the model fits on your GPU. The mouse can freeze for a few minutes. **Wait, and +don't close the window.** The next starts are much faster. Still frozen after 10 minutes? Restart the PC, close other +programs (browsers use a lot of RAM) and try again. If it keeps happening, pick a smaller size (Q2_0 or IQ2_XS). + **A download stopped.** Retry it in the app, or rerun the same `strata launch` command. Completed model-download steps are reused. Check free space and the error message. For an interrupted Terminal installer, rerun the install command. Only a source -checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup. +checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup; it continues where it stopped. + +**Setup says the engine does not match GitHub's checksum.** +Setup checks the downloaded ready-made engine against the SHA-256 GitHub publishes. On a mismatch the file is corrupt or +was changed on the way, so setup deletes it and stops; run setup again to download it afresh. If GitHub gives no checksum +(offline, rate limited, your own mirror), setup warns and installs anyway. `STRATA_SKIP_SHA256=1` skips the check, only if +you insist. **The engine stops at the start with no line in its log, and the error says `the engine process ended: ...`.** The error names how the system ended the engine process, because the engine log is silent then: for example `killed by signal 4 (SIGILL, Illegal @@ -71,56 +112,202 @@ Report it with the CPU model. **Startup takes a long time or the computer becomes slow.** Large models need time to check files, prepare packs and fill memory. A first launch can take many minutes; there is -no fixed startup time. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a +no fixed startup time. The engine reads 34-55 GB into RAM, and the second start is faster while the files are in the OS +cache. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a smaller model or context. DeepSeek V4.1-Flash needs 46 GB of RAM at least ([model page](MODELS.md#deepseek-v41-flash)); `strata launch --plan --family deepseek41 --model ist-das-2.00bpw` shows what your computer is missing. +Started from Task Scheduler, a start can be 24x slower: see [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). +On Linux the engine asks the kernel to read the model files ahead (a cold start went from ~920 s to 70 s on one PC); +`STRATA_READ_AHEAD=0` turns that off. With transparent huge pages on `always`, the arena does not ask for `MADV_HUGEPAGE` +on top (a fragmented machine spent minutes compacting memory, #771); `STRATA_NO_ARENA_THP=1` skips that request on any setting. **The NVIDIA driver is too old.** Use the driver required by the engine package. CUDA 13 needs driver 580 or newer; older cards use the -[CUDA 12 route](OLDER_GPUS.md). After updating the driver and restarting if needed, open the app or rerun -`strata launch`. +[CUDA 12 route](OLDER_GPUS.md). Update it (NVIDIA App or [nvidia.com/drivers](https://www.nvidia.com/drivers)), restart the +PC if needed, then open the app or rerun `strata launch`. **Port 8080 is already in use, or I changed a running model's settings.** -Check `strata launch --status`. To replace your existing launch, rerun the intended command with `--restart`; -it stops current answers. To run beside it, choose another port, for example `--port 8081`, if memory permits. -Do not stop an unrelated program just because it holds the port. `--yes` alone does not restart a running model. +Strata may already be running: check `strata launch --status`. To replace your existing launch, rerun the intended command +with `--restart`; it stops current answers. To run beside it, choose another port, for example `--port 8081`, if memory +permits (source checkout: `START-HERE.bat --port 8081`). Only an address that is really taken says "already in use". Any +other reason (Windows keeps the port reserved, or the config's `"host"` is not an address of this PC) is printed as what +the OS said, with what to change (#769). Do not stop an unrelated program just because it holds the port. `--yes` alone +does not restart a running model. -**The engine stops on a small GPU or low-memory computer.** -Try a smaller pack or context. The draft layer also uses memory. In the app, set the model's Draft layer to Off; -in the Terminal, an explicit example is: +**The engine stops on a small GPU or low-memory computer. Can I turn the draft layer off?** +Yes. The draft layer (MTP) is what makes answers faster, and it takes about 1 GB of graphics memory (plus some RAM and a +memory copy that grows with the context). Without it the expert cache gets that memory back and answers are slower. Turn +it off for one model: in the app, the model's Drafting setting in Expert settings; in the Terminal: ```sh strata launch --family qwen --model q2_0 --context 32k --mtp off ``` -Use `--restart` if replacing an active run. Turning MTP off can slow decoding. Keep some VRAM free for the display; -setting the reserve to zero is not a general speed fix. +(older Terminals: `--set mtp=off --set spec-min-p=off`); by hand, add `"mtp": false` to the model's `strata-.json`. +The choice is kept per model and applied on every start. Use `--restart` if replacing an active run. Also try a smaller +pack or context. Keep some VRAM free for the display; setting the reserve to zero is not a general speed fix. -**Pictures do not work.** -The model, backend and installed engine package must include a compatible picture reader. Inspect the startup -error and the model guide. `--vision off` disables reading pictures; it is different from optional -[image generation](IMAGES.md). In the Terminal, use `on|off|gpu|cpu`, not source setup's `yes|no` spelling. +**I changed `strata-.json` by hand and the change came back.** +Engine options you add to `args` by hand (control vectors, `--spec`, `--vram-reserve-mib 0`, anything the app does not offer) +are kept. The file has two helper keys for this. `user_args` lists your options; every start and every setup run puts them +over the ones the app generates, and for the same option your value wins. `args_written` is a copy of `args` as the app last +wrote it, so an option you added or changed in `args` is noticed and moved into `user_args` the next time the app or setup +touches the file. To undo one, delete it from both `args` and `user_args`. A value you save in the app's Expert settings +("GPU memory for other apps") is put in `user_args` for you. Prefer the app's Expert settings or the Terminal `--set` for +supported overrides. -**Windows blocks an executable.** -Verify the official release and the component named in the message. Feed signatures and Windows code-signing are -different checks. If only the picture reader is blocked, `--vision off` may let text requests run. Do not disable -system-wide protection as the routine installation fix; include the blocked file and exact message in a bug report. +Two things the app still chooses itself: the context size, KV type, picture reading and draft layer. Set them in the Models +screen or with the matching `strata launch` flags, or `"mtp": false` (draft layer). The app keeps the earlier file as +`strata-.json.bak`. Inspect the effective config rather than assuming a saved preference was applied. + +**The app keeps more graphics memory free than I want (decode is slower than in 0.1.45).** +Without a value of yours the app keeps graphics memory free for the desktop: 1536 MiB on a card of 16 GB or less that drives +a display (1024 MiB on a larger card), more with a picture reader on the GPU (2048 MiB), and with the "Leave 20% for my work" +profile a fifth of the card (at most 1536 MiB on a card of 16 GB or less). A card that has no display attached, such as a +second GPU with the screen on the integrated one, keeps 512 MiB (700 MiB with pictures on the GPU). It reads that from the +driver (nvidia-smi `display_active`, or the Windows adapter that has the desktop); when it cannot tell, it assumes a display. +A card that shares the PC's memory (Strix Halo) does not keep a fifth. Your own value is never raised or lowered: set "GPU +memory for other apps" in Expert settings, or `--vram-reserve-mib 0` in `args`. The engine's own warning about low free +memory stays; a card that also draws the desktop can freeze or slow to a few tokens a second with a very small reserve. + +**Pictures are refused, or slow.** +"this server was started without the vision encoder": the model was set up for text only (someone chose "No", or the engine +has no picture reader). Switch pictures on in the app or on the Pictures step of `strata launch` (`--vision on|gpu|cpu`); +in a source checkout run setup again with `--vision yes` (or `--vision gpu` / `--vision cpu`). Pictures are on by default +wherever a model can read them, and `--vision off` (source setup: `--vision no`) turns them off; that is different from +optional [image generation](IMAGES.md). The reader runs on the CPU under 24 GB of graphics memory and on the card from +24 GB, on NVIDIA and AMD cards. Pictures that take several seconds (about 3 s at 300 image tokens on 8 cores, more with more +tokens) are read by the encoder on the CPU; `--vision gpu` (NVIDIA and AMD, ~1.4 GB of VRAM) makes it 0.1-0.5 s. On AMD the +card's reader is `strata-vision-hip`; if it cannot start, the server prints "the GPU picture reader did not start (...); +pictures are read on the CPU" and goes on with the CPU reader. On a Mac the reader runs on the GPU; `--vision cpu` takes +about 50 s per picture there. On Intel Arc the CPU reader is the default. The model, backend and installed engine package +must include a compatible picture reader; inspect the startup error and the model guide. + +**"Windows blocked the Strata engine (or the image encoder) ... Smart App Control".** +On a clean Windows 11, Smart App Control refuses programs that are not signed, and Strata's `strata.exe` and +`strata-vision.exe` are not signed yet (#735). Verify that the file is from the official release and that the message names +a Strata component. The choices are to turn Smart App Control off (Windows Security > App & browser control > Smart App +Control settings; it cannot be turned back on without a reset of Windows) or, if only the image encoder is blocked, to run +without pictures: `strata launch --vision off` (source checkout: `START-HERE.bat --setup --vision no`), which lets text +requests run. Do not disable system-wide protection as a routine fix, and include the blocked file and the exact message in +a bug report. Feed signatures and Windows code signing are different checks. + +**UPDATE.bat / update.sh say "git pull did not succeed", or "has no commit in common" (#1276).** +This is for a source checkout. The repository's history was cleaned up on 2026-10-06, so a clone made before that cannot +be updated with `git pull`. The scripts from 0.1.40.2 handle it: when no tracked file is edited they keep your old commits +in the branch `pre-cleanup-backup` and move the clone to the new history; otherwise they print the two commands for you. +Your models, settings and engine are untracked files and are never touched. An older UPDATE.bat / update.sh (before +0.1.40.2) cannot do this itself: back up local work, run these once in the Strata folder, then use UPDATE.bat as usual +(add `git stash` first if `git status` lists edited files): + + git fetch origin + git branch pre-cleanup-backup + git checkout -B main origin/main + +**Python or the build tools could not be installed.** +Install what it names (links are printed), then run it again. Everything already done is kept. The packaged Terminal +carries Python; a missing system Python is not a reason to install a compiler for the normal release. + +**Linux: the engine does not compile (`unsupported GNU version`, or `exception specification is incompatible` for +`cospi`/`sinpi`/`rsqrt`).** This is for a source build. Two known mismatches between the CUDA toolkit and a new Linux (#601): +- gcc newer than 14 (Ubuntu 26.04's default 15): CUDA 12.x and 13.0 refuse it. Install g++-14 and run + `CXX=g++-14 ./setup.sh` (CC, CXX and CUDAHOSTCXX name the build's compilers; setup passes them to CMake itself, + so an already-configured build folder picks them up too, #1645). +- glibc 2.43 with CUDA 12.9: the toolkit's math headers clash with glibc's, already in CMake's first test compile. + Use CUDA 12.8 or 13.x instead. Setup takes the newest toolkit it finds; `STRATA_NVCC=/usr/local/cuda-12.8/bin/nvcc + ./setup.sh` makes it use that one (only that one). ## While it answers -**It is slow and the disk stays busy.** -The chosen model may exceed available RAM/VRAM and be using the file tier. Close other programs, check memory in -the monitor, and choose a smaller model or context. Compare performance only with the same hardware and workload. +**It is slow and the disk light keeps blinking.** +Your PC is out of free RAM, or the chosen model exceeds the available RAM/VRAM and is using the file tier. Close other +programs, check memory in the monitor, and pick a smaller model or size (Q2_0 or IQ2_XS) or context. Compare performance +only with the same hardware and workload. + +**An answer stopped with "the engine stopped unexpectedly".** +Usually not enough RAM (on Linux the system then stops the engine). Just send your message again: Strata starts the +engine by itself. If it keeps happening, close other programs or pick a smaller size. + +**On Linux the engine stops with "exit code -9", but nothing ran out of RAM.** +Check system logs for an out-of-memory kill first. Then check `ulimit -R`. If it prints 0 (or any number), the desktop +session sets a real-time CPU limit: the audio system (PipeWire) does that when rtkit is not installed, and every program +started from the desktop inherits it. The kernel can then end a program with signal 9 and no message. Install `rtkit`, or +start Strata outside the session's limits, for example `systemd-run --user --collect -p LimitRTTIME=infinity -- strata serve ...`. +Strata prints a warning at start when it sees this limit. **The prompt exceeds the context.** -Start a new chat, shorten the input, or use the app's Summarize and continue action. A larger context needs more -memory. In the Terminal, restart your chosen model with an explicit `--context`, such as `64k`; preserve its family, -model and other choices. Do not look for `SETUP.bat` in an app install. +The conversation is longer than the context you chose. Start a new chat, shorten the input, or use the app's Summarize and +continue action. A larger context needs more memory. In the Terminal, restart your chosen model with an explicit +`--context`, such as `64k`; keep its family, model and other choices. In a source checkout, run `SETUP.bat` and pick more +context. Do not look for `SETUP.bat` in an app install. -**On Linux the engine exits with code -9.** -Check system logs for an out-of-memory kill. Also check `ulimit -R`: a desktop-session real-time limit can cause a -kill even when memory is available. The engine prints a warning for that condition; see the -[detailed troubleshooting table](DETAILS.md#troubleshooting) before changing system limits. +**It is slower than the tables.** +The monitor plugged into the graphics card and other GPU programs take VRAM from the expert cache; RAM running below its +rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. + +**An earlier reply that came back empty is gone from the chat history (0.1.40, #843).** +The server leaves out finished assistant turns that have no text, so the next reply does not copy the empty ones. +`STRATA_KEEP_EMPTY_TURNS=1` in the server's environment renders them as before. + +**A Turing card (RTX 20) reads prompts above ~90K tokens differently (0.1.40, #743).** +The prompt's top-k selection takes a wider kernel there, with the same ids. `STRATA_TOPK_STREAM=0` restores the old one. + +**Decode is several times slower with `--expert-cache N` than with `auto` (#781, #831).** +An explicit N is a byte budget that is not checked against the free VRAM once the slots are written. On a card it +fills (the log says `0 MiB of VRAM free with everything loaded - LOW`), Windows pages the GPU's memory and decode drops +from 100 to 14 tok/s with only a few hundred slots too many. Use `--expert-cache auto`, or a smaller N. + +**A low-RAM PC (about 32 GB) stalls with `--resident-budget-gib N` (#649).** +The budget is pinned (locked) in RAM, which leaves the OS and the CPU workers little room. `STRATA_RESIDENT_PIN=0` keeps +it pageable; a smaller budget works too. + +**Decode got slower in 0.1.40 on a 32 GB PC with `--resident-budget-gib N`, and the drive is read hard (#1194, #1116, #1085).** +The start line "the file tier reads unbuffered" means the experts outside the RAM copy are read straight from the drive. +0.1.40 chose that whenever the free RAM could not hold all of them; but the same few come back token after token, and +a cache a twentieth of their size serves most of the repeats. 0.1.40.2 asks for that much (at least 1.5 GiB beside the +4 GiB headroom) and reads through the cache otherwise, which measured 7% to 118% faster decode with a third to a sixth of +the drive traffic on a 20 to 32 GB box. On 0.1.40 / 0.1.40.1: `STRATA_UNBUFFERED_LOAD=0` does the same, `=1` forces the +unbuffered reads. + +**Linux: the start is OOM-killed while the engine allocates the page-locked expert copy (#1250).** +Page-locked pages come from the driver in one go and cannot wait for the kernel to give back file cache, so with the +model files' cache in the way (little really free RAM, much "available") the host could run out. Since 0.1.40.2 the engine +gives back the cached pages of the model files it mapped before it page-locks the copy; when the really free RAM still +does not cover it, it takes the pages in 1 GiB steps while the RAM available (cgroup limits included) stays above the +headroom, page-locks what it has, and keeps the rest resident but pageable with a warning ("only N of M GiB could be +page-locked"): the answers are the same, only the copies of the pageable part to the GPU go through the CPU. +`STRATA_PIN_GUARD=0` turns this off, `STRATA_PIN_RESERVE_GIB=N` sets the RAM that must stay free (default: +`STRATA_RESIDENT_HEADROOM_GIB`, 4 GiB). + +**The Windows display driver resets, then the PC blue-screens (0x141, then 0x116 in `nvlddmkm`) during an answer (#961).** +This is the NVIDIA driver, not Strata: the report shows the same wedge with other CUDA programs on that driver (610.88, +RTX 4080 SUPER). Try another driver (a Studio one, or an older one) and a lower power limit; if it only happens with +`--spec 4`, `--spec 0` avoids the verify window while you wait for a driver fix (a native (IQ) pack needs `--spec` 2 or +more and cannot turn speculation off). + +**An RTX 50 card (a source build with CUDA 13.2) answers with nonsense, or reads prompts wrongly (#892, #968).** +CUDA 13.2.0 and 13.2.1's compiler (nvcc 13.2.51) miscompile some of the engine's kernels for sm_120: on our RTX 5070 the IQ2_S and IQ3_S +products are wrong (relative error 0.5 to 1.0 in the tests) with 13.2 and right with 13.0. The ready-made engine is built +with 13.0. If you compile it yourself, use CUDA 13.0, 13.1 or 13.2.2 (13.2.2, nvcc build 13.2.86, fixes it; an older one can sit next to a newer: `STRATA_NVCC=`); +setup warns when it finds 13.2.0 or 13.2.1 for such a card, and takes an older 13.x when one is installed. + +## AMD cards + +**"No AMD GPU found (the amdgpu driver's KFD topology is empty)" on Linux.** +The kernel's amdgpu driver is not loaded for the card. Integrated Radeon GPUs are listed as not supported; setup +lists every card it found and whether Strata can use it. + +**The engine stops at start with the card's name, its architecture and the build's list.** +The engine was compiled for another card (for example after moving the Strata folder to another PC). Update the engine +(`strata update`), or in a source checkout run `./setup.sh --setup --backend hip`: it compiles the engine for this card's +architecture. + +**On Windows the engine exits with `0xC0000005` in `amdhip64_7.dll` before it prints anything (#654).** +Two things in your environment can cause it, and the server repairs both before it starts the engine (it says so in +the log): `HIP_PATH`, `HIP_DEVICE_LIB_PATH` or `LLVM_PATH` naming a ROCm folder that no longer exists (a deleted build), +and a `TEMP`/`TMP` folder the engine cannot create files in (AMD's runtime compiles its first kernels through temporary +files). If you start `strata.exe` by hand, fix them yourself: `set HIP_PATH=`, and point `TEMP` and `TMP` at a normal +folder such as `C:\Temp`. **Windows AMD: the driver resets (VIDEO_ENGINE_TIMEOUT_DETECTED / screen flicker / the engine dies mid-answer).** Windows gives a GPU about 2 seconds to answer; when a graphics card does not, it resets the driver (a TDR): the screen @@ -155,28 +342,32 @@ in order, one at a time, and tell us what changed: See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. **"verify: timed out at layer N" or "no progress for 60 s" on AMD (Linux), mostly with `--mmap-experts`.** - -**A hand-edited engine option disappears.** -The run config tracks explicit options in `user_args` and the generated baseline in `args_written`. Prefer the -app's Expert settings or Terminal `--set` for supported overrides. Context, KV, picture reading and drafting are -launch choices; set them through the app or the corresponding `strata launch` flags. Inspect the effective config -rather than assuming a saved preference was applied. +Two reports fixed it with `"GPU_PINNED_MIN_XFER_SIZE": "1048576"` (RX 6800) or `"HSA_USERPTR_FOR_PAGED_MEM": "0"` (two +R9700) in the `env` block of the server JSON, then a restart. Experimental, one machine each; on a systemd unit use +`MemoryMax`, not `MemoryHigh`. Details: [AMD_HIP.md](AMD_HIP.md#linux-verify-timeouts-while-the-kernel-reclaims-host-memory). ## Source-checkout problems Python/venv, CUDA compiler versions, ROCm builds, `UPDATE.bat`, `update.sh` and generated `run-` scripts -belong to [SOURCE_INSTALL.md](SOURCE_INSTALL.md). Use the backend guide for build prerequisites. The packaged -Terminal carries Python; a missing system Python is not a reason to install a compiler for the normal release. - -If `git pull` fails in an old clone, back up your local work and follow the recovery steps the source update script prints. -Do not overwrite local branches or edits just to make `git pull` succeed. +belong to [SOURCE_INSTALL.md](SOURCE_INSTALL.md); the entries above marked "source checkout" are the common ones. Use the +backend guide for build prerequisites. If `git pull` fails in an old clone, see the `UPDATE.bat` entry above and do not +overwrite local branches or edits just to make `git pull` succeed. ## Logs and bug reports -- **App:** Settings → Engine → Diagnostics → View logs → Save logs. The diagnostic file goes to Downloads. +**Sending logs for a bug report.** +- **App:** Settings → Engine → Diagnostics → View logs → Save logs. It writes one text file, + `strata-diagnostics-.txt`, into your Downloads folder and shows where. It holds the engine's messages, the failed + steps and the end of each model's server log. - **Terminal:** include `strata --version`, `strata doctor --live`, `strata launch --status`, and the relevant log excerpt. -- **Windows app crash:** inspect `%LOCALAPPDATA%\Strata\logs` for `desktop-crash-.log`. -- **Linux app crash:** start the AppImage with `--save-logs` to collect diagnostics. +- **Windows app crash:** if the app closes right after you start it, it shows a message with the reason and writes + `desktop-crash-.log` in `%LOCALAPPDATA%\Strata\logs`; Save logs includes it, and so can you, by hand. +- **Linux app crash:** if the window crashes or will not open, run the AppImage with `--save-logs` in a terminal; it writes + the crash log and the other logs to one file in Downloads. +- **Installer or source checkout:** `strata-.log` from the Strata folder. -Include model and quantization, OS, GPU/VRAM, RAM, driver, install route, exact command, expected result and actual -error. Remove API keys and private data before sharing. Follow [CONTRIBUTING.md](../CONTRIBUTING.md). +Look through a log before you send it, and never send an API key. Include model and quantization, OS, GPU/VRAM, RAM, +driver, install route (app, Terminal or the installer), Strata and engine versions, exact command, expected result and +actual error. Open an [issue](https://github.com/Niko1221/Strata/issues) and attach the log. Follow +[CONTRIBUTING.md](../CONTRIBUTING.md). The full table of error messages, with the older engine fixes, is in the +[details](DETAILS.md#troubleshooting). diff --git a/tests/terminal/test_troubleshooting_page.py b/tests/terminal/test_troubleshooting_page.py new file mode 100644 index 00000000..f6ef6506 --- /dev/null +++ b/tests/terminal/test_troubleshooting_page.py @@ -0,0 +1,77 @@ +"""docs/TROUBLESHOOTING.md keeps every entry the 0.2.5 rewrite lost (restored for 0.2.7), and every pointer to it resolves. + +setup.py and the server print "see docs/TROUBLESHOOTING.md" with an entry's name, DETAILS.md sends readers there for environment variables, and other +pages link to its headings. An entry that disappears turns those pointers into dead ends (the "Windows AMD: the driver resets" entry did, and setup's own +test failed on it). +""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +PAGE = ROOT / "docs" / "TROUBLESHOOTING.md" + +# One distinctive phrase from the title of each entry the v0.2.4.2 page had (the page may reword the rest). +ENTRIES = [ + "couldn't find an engine for this computer", "needs a newer engine", "damaged and can't be opened", "strata doctor", "Sending logs for a bug report", + "froze, or got very slow", "app keeps more graphics memory free", "A download stopped", "driver is too old", "Port 8080 is already in use", + "Smart App Control", "new engine misbehaves", "git pull did not succeed", "build tools could not be installed", "does not compile", + "Startup takes a long time", "does not match GitHub's checksum", "It is slow and the disk light", "engine stopped unexpectedly", "exit code -9", + "exceeds the context", "slower than the tables", "came back empty", "Turing card", "--expert-cache N", "--resident-budget-gib N", + "page-locked expert copy", "0x141", "RTX 50 card", "Pictures are refused", "KFD topology is empty", "build's list", "0xC0000005", + "the driver resets", "Large pinned host allocations", "verify: timed out at layer N", +] + + +def slug(heading: str) -> str: + return re.sub(r"[^\w\- ]", "", heading.strip().lower()).replace(" ", "-") + + +def anchors(path: Path) -> set[str]: + return {slug(h) for h in re.findall(r"^#+\s+(.*)$", path.read_text(encoding="utf-8"), re.M)} + + +class TroubleshootingPage(unittest.TestCase): + def setUp(self): + self.text = PAGE.read_text(encoding="utf-8") + self.flat = re.sub(r"\s+", " ", self.text.replace("*", "")) + + def test_every_entry_of_v0_2_4_2_is_on_the_page(self): + for phrase in ENTRIES: + self.assertIn(re.sub(r"\s+", " ", phrase), self.flat, f"the entry about {phrase!r} is missing") + + def test_what_setup_and_the_server_point_to_is_there(self): + setup = (ROOT / "setup.py").read_text(encoding="utf-8") + for name in re.findall(r'docs/TROUBLESHOOTING\.md, \\"([^"\\]+)\\"', setup): + self.assertIn(name, self.text, f"setup.py points to the entry {name!r}") + server = (ROOT / "serve" / "server.py").read_text(encoding="utf-8") + self.assertIn("docs/TROUBLESHOOTING.md", server) + self.assertIn("Smart App Control", self.text) # that pointer is the blocked-executable message + self.assertIn("--vision no", self.text) # which names the way out for a source checkout + + def test_the_variables_that_other_pages_send_here_are_explained(self): + details = (ROOT / "docs" / "DETAILS.md").read_text(encoding="utf-8") + for line in details.splitlines(): + if "TROUBLESHOOTING.md" in line: + for name in re.findall(r"STRATA_[A-Z0-9_]+", line): + self.assertIn(name, self.text, f"DETAILS.md sends readers here for {name}") + + def test_links_into_the_page_and_out_of_it_resolve(self): + own = anchors(PAGE) + for md in sorted((ROOT / "docs").glob("*.md")) + [ROOT / "README.md", ROOT / "SECURITY.md"]: + for target in re.findall(r"\(((?:\.\./)?(?:docs/)?TROUBLESHOOTING\.md#[^)\s]+)\)", md.read_text(encoding="utf-8")): + self.assertIn(target.split("#", 1)[1], own, f"{md.name} links to {target}") + for match in re.finditer(r"\]\(([^)#\s]+)?(#[^)\s]*)?\)", self.text): + name, anchor = match.group(1), match.group(2) + if name and name.startswith("http"): + continue + target = (PAGE.parent / name).resolve() if name else PAGE + self.assertTrue(target.exists(), f"the page links to {name}, which is not there") + if anchor and target.suffix == ".md": + self.assertIn(anchor[1:], anchors(target), f"the page links to {name or ''}{anchor}") + + +if __name__ == "__main__": + unittest.main() From 5f81454038542c8baf4cb3ada2f91a3d25ab1d83 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:39:42 +0100 Subject: [PATCH 123/177] AMD on Windows: the shared-expert fork with KV streaming is not measured, never picked, and warned about when set by hand (#3895) On one Windows RX 6900 XT STRATA_SH_STREAM=1 together with --kv-resident failed the engine on its first request (verify: unspecified launch failure). setup --calibrate (tools/calibrate.py) no longer measures the fork on Windows when KV streaming is on (the fork is off by default on AMD, so nothing changes unless the person sets it), strata tune's never-pick list holds the combination (strata_control/tune_knobs.py), and a config that sets STRATA_SH_STREAM=1 with --kv-resident on Windows HIP gets one warning line when the engine starts (serve/server.py sh_stream_warning). Nothing is refused or removed: the variable still reaches the engine. Shipped without a hardware run, from one report; the reply to #3895 asks RX 6000 owners on Windows to test and report. Tests: tests/terminal/test_sh_stream_windows.py. --- serve/server.py | 17 +++++ strata_control/tune_knobs.py | 3 + tests/terminal/test_sh_stream_windows.py | 97 ++++++++++++++++++++++++ tools/calibrate.py | 16 +++- 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 tests/terminal/test_sh_stream_windows.py diff --git a/serve/server.py b/serve/server.py index adf9f552..25202d32 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3531,6 +3531,9 @@ def child_env(cfg: dict, *, offline: bool = False) -> dict: env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) if cfg.get("backend") == "hip": hip_env_guard(env, cfg) + note = sh_stream_warning(env, cfg) + if note: + print(note, flush=True) auto = hip_auto_devices(cfg, env) if auto: env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in auto) @@ -3545,6 +3548,20 @@ def _dir_writable(p: str) -> bool: return False +def sh_stream_warning(env: dict, cfg: dict) -> str | None: + """#3895: the shared-expert fork (STRATA_SH_STREAM=1) together with KV streaming (--kv-resident) made one Windows RX 6900 XT fail on the first + request ("verify: unspecified launch failure"); each alone, or Linux, did not. A warning, not a refusal: the person set the variable, the + engine runs as asked, and the line says what to take out.""" + if os.name != "nt" or str(env.get("STRATA_SH_STREAM", "")).strip() in ("", "0"): + return None + args = [str(a) for a in cfg.get("args") or []] + if "--kv-resident" not in args: + return None + return ("[strata] WARNING: STRATA_SH_STREAM=1 with --kv-resident (KV streaming) failed on the first request on one Windows RX 6000 PC " + "(\"verify: unspecified launch failure\", #3895). If the engine stops that way, take STRATA_SH_STREAM out of the config's env " + "(AMD runs without it by default) or run without --kv-resident, and tell us the card and the driver.") + + def hip_env_guard(env: dict, cfg: dict) -> list[str]: """#654: two things in an AMD user's environment that crash the HIP runtime before it prints a line. (1) HIP_PATH, HIP_DEVICE_LIB_PATH or LLVM_PATH naming a folder that is gone (a ROCm build that was deleted): the bundled runtime diff --git a/strata_control/tune_knobs.py b/strata_control/tune_knobs.py index 54f27f72..0ee3842a 100644 --- a/strata_control/tune_knobs.py +++ b/strata_control/tune_knobs.py @@ -16,6 +16,7 @@ bit-exact run to run). Only ``exact`` is picked on its own; the others need the from __future__ import annotations +import sys from dataclasses import dataclass, field from typing import Any, Callable, Sequence @@ -152,6 +153,7 @@ BOUNDS: dict[str, dict[str, Any]] = { #: in plain words. ``when`` names facts from `condition_holds`; empty = always. NEVER: tuple[dict[str, Any], ...] = ( {"env": "STRATA_SH_STREAM", "when": ("gfx12",), "reason": "it halves decode speed on this graphics card"}, + {"env": "STRATA_SH_STREAM", "when": ("windows_amd_kv_stream",), "reason": "with KV streaming on Windows it made the engine fail on the first request on one RX 6000 PC (#3895)"}, {"env": "STRATA_RDNA2_SGEMM", "value": "all", "when": ("gfx12",), "reason": "it makes long prompts five times slower"}, {"env": "STRATA_SELECT_SIMT", "reason": "its gain is below the 3% margin"}, {"env": "STRATA_HIP_WMMA", "reason": "it changes the numbers (a quality setting)"}, @@ -220,6 +222,7 @@ def condition_holds(name: str, ctx: Context) -> bool: "vram_ge_24g": ctx.vram_mib >= 24000, "vram_le_8g": 0 < ctx.vram_mib <= 8400, "gfx12": bool(ctx.arch and ctx.arch.startswith("gfx12")), + "windows_amd_kv_stream": ctx.backend == "hip" and sys.platform == "win32" and "--kv-resident" in ctx.base_args, "pcie_bound": 0 < ctx.vram_mib < 24000, "ram_bound": bool(ctx.ram_gib and ctx.model_gib and ctx.ram_gib - ctx.model_gib < 30), "ctx_ge_128k": ctx.context_tokens >= 98304, diff --git a/tests/terminal/test_sh_stream_windows.py b/tests/terminal/test_sh_stream_windows.py new file mode 100644 index 00000000..5921710b --- /dev/null +++ b/tests/terminal/test_sh_stream_windows.py @@ -0,0 +1,97 @@ +"""#3895: STRATA_SH_STREAM=1 (the shared expert on its own stream) together with --kv-resident failed the engine on its first request on one +Windows RX 6900 XT ("verify: unspecified launch failure"). AMD runs without the fork by default. Calibrate does not measure the combination, the +tuner never picks it, and a person who set it by hand gets one warning line at the start. Nothing is refused. +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) +import calibrate as CAL # noqa: E402 +from serve import server # noqa: E402 +from strata_control import tune_knobs # noqa: E402 +from tools.test_calibrate import BASE, FakeEngine # noqa: E402 + + +class CalibrateSkipsTheCombination(unittest.TestCase): + def measure(self, platform, args): + starts, envs, said = [], [], [] + + def start(a, env=None): + envs.append(dict(env or {})) + return FakeEngine(a, lambda f, p, w: 50.0, 6, starts) + + with mock.patch.object(CAL.sys, "platform", platform): + res = CAL.measure(args, [[1, 2, 3]] * 3, start, say=said.append, hip=True) + return res, envs, said + + def test_windows_with_kv_streaming_does_not_measure_the_fork(self): + args = CAL.with_arg(BASE, "--kv-resident", "32768") + res, envs, said = self.measure("win32", args) + self.assertEqual(res["env"], {}) + self.assertNotIn("sh_stream", res["report"]) + self.assertEqual(res["report"]["sh_stream_skipped"], "windows with --kv-resident") + self.assertTrue(all(CAL.SH_STREAM not in e for e in envs)) + self.assertTrue(any("#3895" in line and "STRATA_SH_STREAM=1" in line for line in said)) + + def test_linux_with_kv_streaming_and_windows_without_it_still_measure_it(self): + for platform, args in (("linux", CAL.with_arg(BASE, "--kv-resident", "32768")), ("win32", BASE)): + with self.subTest(platform=platform): + res, envs, _ = self.measure(platform, args) + self.assertEqual(set(res["report"]["sh_stream"]), {"0", "1"}) + self.assertNotIn("sh_stream_skipped", res["report"]) + + +class TunerNeverPicksIt(unittest.TestCase): + def ctx(self, platform, backend="hip", args=("--kv-resident", "32768")): + context = tune_knobs.Context(backend=backend, arch="gfx1030", gpu_count=1, vram_mib=16384, ram_gib=64, model_gib=40.0, base_args=list(args)) + return context, mock.patch.object(tune_knobs.sys, "platform", platform) + + def test_windows_amd_with_kv_streaming(self): + ctx, patch = self.ctx("win32") + with patch: + problems = tune_knobs.check_setting({}, {"STRATA_SH_STREAM": "1"}, ctx) + self.assertEqual(len(problems), 1) + self.assertIn("#3895", problems[0]) + + def test_other_cases_stay_allowed(self): + for platform, backend, args in (("linux", "hip", ("--kv-resident", "32768")), ("win32", "hip", ()), ("win32", "cuda", ("--kv-resident", "32768"))): + ctx, patch = self.ctx(platform, backend, args) + with patch, self.subTest(platform=platform, backend=backend, args=args): + self.assertEqual(tune_knobs.check_setting({}, {"STRATA_SH_STREAM": "1"}, ctx), []) + + +class StartWarning(unittest.TestCase): + CFG = {"backend": "hip", "args": ["--kv", "int8", "--kv-resident", "32768"]} + + def test_a_hand_set_fork_with_kv_streaming_on_windows_warns_once_per_start(self): + with mock.patch.object(server.os, "name", "nt"): + note = server.sh_stream_warning({"STRATA_SH_STREAM": "1"}, self.CFG) + self.assertIn("#3895", note) + self.assertIn("WARNING", note) + self.assertIn("take STRATA_SH_STREAM out", note) + + def test_no_warning_without_the_combination(self): + with mock.patch.object(server.os, "name", "nt"): + self.assertIsNone(server.sh_stream_warning({}, self.CFG)) + self.assertIsNone(server.sh_stream_warning({"STRATA_SH_STREAM": "0"}, self.CFG)) + self.assertIsNone(server.sh_stream_warning({"STRATA_SH_STREAM": "1"}, {"backend": "hip", "args": ["--kv", "int8"]})) + with mock.patch.object(server.os, "name", "posix"): + self.assertIsNone(server.sh_stream_warning({"STRATA_SH_STREAM": "1"}, self.CFG)) + + def test_child_env_prints_it_and_still_passes_the_variable(self): + cfg = {**self.CFG, "env": {"STRATA_SH_STREAM": "1"}} + with mock.patch.object(server.os, "name", "nt"), mock.patch("builtins.print") as shown, \ + mock.patch.object(server, "hip_env_guard", return_value=[]), mock.patch.object(server, "hip_auto_devices", return_value=None): + env = server.child_env(cfg) + self.assertEqual(env["STRATA_SH_STREAM"], "1") # nothing is taken away + self.assertTrue(any("#3895" in str(call.args[0]) for call in shown.call_args_list if call.args)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/calibrate.py b/tools/calibrate.py index 182c5a4d..56819e30 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -426,8 +426,14 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke # 6. HIP: the shared-expert stream fork (a restart each), with everything chosen so far. Both values are set # explicitly, so a value the config carried before does not decide the baseline. env = {} - if hip: - tuned = apply(base_args, settings) + tuned = apply(base_args, settings) + if hip and fork_is_unsafe(tuned): + # #3895: one Windows RX 6000 PC faulted the engine on the first request with the fork and KV streaming together. The fork is off by + # default on AMD, so skipping the measurement changes nothing; whoever wants it sets the variable by hand. + say(" Not measuring the shared expert on its own stream: on Windows with KV streaming (--kv-resident) it made the engine fail on the first " + f"request on one PC (#3895). To try it anyway, put {SH_STREAM}=1 in the config's env.") + report["sh_stream_skipped"] = "windows with --kv-resident" + elif hip: by_fork = {} for v in ("0", "1"): _check_cancel(cancel_event) @@ -455,6 +461,12 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke return {"settings": settings, "env": env, "report": report} +def fork_is_unsafe(args) -> bool: + """The shared-expert fork (STRATA_SH_STREAM) with KV streaming on Windows: the one combination that has made an engine fail on its first + request (#3895, an RX 6900 XT). Not measured there; a person can still set the variable.""" + return sys.platform == "win32" and arg_value(args, "--kv-resident") is not None + + def restart(start_engine, args, what, say, report): """#1337: a later step's engine start that fails is a candidate that loses, not a failed run: what the earlier steps measured (and the settings they chose) must survive it. Returns the engine, or None after saying why and From c2490b49f504b9ffdba38916211ff0f6e86d1943 Mon Sep 17 00:00:00 2001 From: Vop3p <69450118+Vop3p@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:39:43 +0100 Subject: [PATCH 124/177] docs/AMD_HIP.md: why STRATA_SH_STREAM goes both ways, and leave it off on Windows with KV streaming (#3895) Two paragraphs from PR #3895 by Vop3p, put under the table row they explain: the fork pays only when it has a CPU-pool wait to hide (4,859 slots on one RX 6900 XT, GPU-reach wait 20.7 of 39.1 ms; with every expert resident it is 43.4 against 62.9 tok/s on an R9700), and the Windows RX 6900 XT fault with the fork plus --kv-resident, its bisection and its limits (one PC, kernel not isolated). The text now says what the code does about it and asks RX 6000 owners on Windows to test. --- docs/AMD_HIP.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index d858002f..612d9c80 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -264,6 +264,26 @@ machine then swaps or stalls, raise it. Re-check after a ROCm update. | `STRATA_DENSE_MMQ=1` | Off | Dense GGUF prompt projections through int8 MMQ kernels instead of dequantize + hipBLAS. Greedy text can diverge after a few dozen tokens (q8_1 rounding). | | `STRATA_HIP_ADAPT_KERNEL_COPY=1` | Off | Adaptive-tier swaps copied by a kernel instead of the SDMA engine; a workaround for a gfx1030 hang with MMQ prompts and adaptive swaps (untested by the reporter) | +**Why `STRATA_SH_STREAM` goes both ways.** The fork has to hide something. With experts on the CPU in the window, the shared expert forks +off only after the doorbell is published (`STRATA_SH_FORK_LATE`, `src/core/verify.cpp`), so it runs while the GPU would otherwise wait for the +CPU pool. On a 16 GB card whose cache holds only part of the experts that wait is about half of a verify window (one RX 6900 XT under Linux, +4,859 slots, `STRATA_DECODE_TIMING=1`: GPU-reach wait 20.7 of 39.1 ms per window), which is where #1272's gain comes from. When every routed +expert is on the GPU there is no wait to fill, and the fork is two cross-stream event dependencies per layer and nothing else: 7fd67dd measured +it on an R9700 with `--resident-experts` and the KV stream path running (48,067-token prompt), 43.4 tok/s with the fork against 62.9 without; +a 256-token prompt barely moved (65.4 and 62.7). Windows adds its own cost to every cross-stream dependency (#816). + +**Windows with KV streaming: leave it off.** On one RX 6900 XT under Windows 11 (the 0.2.3 `rdna2` package, engine 0.1.48, Qwen3.8-Flash-Next +IQ3_S, 64K context, `--kv int8 --kv-resident 32768 --vram-reserve-mib 1536`) the fork together with KV streaming stopped the engine on its first +request ("verify: unspecified launch failure", in other starts first reported by the MTP draft step; exit code 0xC0000409). With the fork off, or +without `--kv-resident`, the same setup answered normally. Removing the other switches one at a time (`STRATA_HIP_PROMPT_F16`, `STRATA_HC_PERSIST`, +`STRATA_HIP_ADAPT_KERNEL_COPY`, `STRATA_PREFILL_CPU_SHARE`, `STRATA_PIPED_CONCURRENT`, `STRATA_PREFILL_STREAM_MIN`, `STRATA_IO_THREADS`, a rocBLAS +table) did not clear it; removing `STRATA_SH_STREAM` did. Two RX 6900 XT under Linux (layer split, the same model, the fork and `--kv-resident +32768`) have served without the fault since 0.1.40. It is one PC and one card, and the faulting kernel was not isolated. So `--calibrate` does +not measure the fork on Windows when KV streaming is on, `strata tune` never picks it there, and a config that sets it by hand gets a warning +line at the start; nothing is refused. If you have an RX 6000 card on Windows and want to help, run it once with `STRATA_SH_STREAM=1` and +`--kv-resident` and tell us in [#3895](https://github.com/Niko1221/Strata/pull/3895) whether the first request answered, with the card and the driver. + + ## Speed switches Switches for the prompt path. A switch you set yourself, to anything, is never overridden by an architecture default. Put From ad1a310f55778eb816c4866c3c3fdee6a55c18be Mon Sep 17 00:00:00 2001 From: Matthias Nott <2168313+mnott@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:40:00 +0100 Subject: [PATCH 125/177] Web page: use wide windows and fit narrow screens (#3176) The chat, About and Monitor columns grow with the window (the chat and the composer to 1100 px, About to 1100 px, Monitor to 1920 px), the metric cards wrap with auto-fit, and under 640 / 560 / 480 px the controls get bigger touch targets, the composer bar wraps, and long words, code and tables stay inside the viewport. Ported by hand from PR #3176 by Matthias Nott (mnott); the CSS is his. --- serve/web/app.css | 48 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/serve/web/app.css b/serve/web/app.css index f9bad8cc..1191b041 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -15,12 +15,12 @@ main { flex: 1; min-height: 0; display: flex; } /* ---------------------------------------------------------------- chat */ .chat-scroll { flex: 1; min-height: 0; overflow-y: auto; } -.chat { max-width: 860px; margin: 0 auto; padding: var(--st-s-8) var(--st-s-6) var(--st-s-6); display: flex; +.chat { max-width: min(100%, 1100px); margin: 0 auto; padding: var(--st-s-8) var(--st-s-6) var(--st-s-6); display: flex; flex-direction: column; gap: var(--st-s-6); } .chat-empty { margin: 12vh auto 0; text-align: center; } .chat-empty__title { font-weight: var(--st-fw-black); font-size: var(--st-fs-display); line-height: var(--st-lh-tight); letter-spacing: -.02em; } -.chat-empty__sub { margin-top: var(--st-s-3); color: var(--st-ink-muted); } +.chat-empty__sub { overflow-wrap: anywhere; margin-top: var(--st-s-3); color: var(--st-ink-muted); } .st-msg { width: 100%; } .st-msg--assistant { align-self: flex-start; } .st-msg--assistant .st-bubble { width: 100%; overflow-wrap: anywhere; } @@ -44,6 +44,7 @@ main { flex: 1; min-height: 0; display: flex; } .msg-images img { max-width: 220px; max-height: 180px; border-radius: var(--st-r-md); border: 1px solid var(--st-line); } .st-msg .st-collapse { width: 100%; } .st-collapse__body.thinking { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 420px; overflow-y: auto; } +.st-msg { min-width: 0; } .st-msg__meta .st-btn--icon { width: 28px; height: 28px; } .st-msg__meta .st-btn--icon .st-icon { width: 16px; height: 16px; } .cursor::after { content: ""; display: inline-block; width: 8px; height: 1.1em; margin-left: 2px; vertical-align: -3px; @@ -66,7 +67,7 @@ main { flex: 1; min-height: 0; display: flex; } border: 1px solid var(--st-line-soft); border-radius: var(--st-r-sm); } .composer-wrap { flex: none; padding: 0 var(--st-s-6) var(--st-s-6); } -.st-composer { max-width: 860px; margin: 0 auto; } +.st-composer { max-width: min(100%, 1100px); margin: 0 auto; } .st-composer textarea { max-height: 40vh; } .st-btn--send { width: 42px; padding: 0; } .composer-hint { font-size: var(--st-fs-xs); color: var(--st-ink-muted); margin-right: var(--st-s-2); font-variant-numeric: tabular-nums; } @@ -79,16 +80,17 @@ main { flex: 1; min-height: 0; display: flex; } /* ---------------------------------------------------------------- monitor */ .view--monitor, .view--about { overflow-y: auto; } -.monitor, .about { max-width: 1240px; width: 100%; margin: 0 auto; padding: var(--st-s-6); display: flex; flex-direction: column; +.monitor, .about { max-width: min(100%, 1920px); width: 100%; margin: 0 auto; padding: var(--st-s-6); display: flex; flex-direction: column; gap: var(--st-s-5); } .state-card { display: flex; flex-direction: column; gap: var(--st-s-3); } .state-card__head { display: flex; align-items: center; gap: var(--st-s-4); flex-wrap: wrap; } +.state-card, .metric-card, .req-card, .ctx-card, .cc-card, .mcp-card { min-width: 0; } .badges { display: flex; gap: var(--st-s-2); flex-wrap: wrap; } .badges .st-badge { opacity: .38; transition: opacity var(--st-dur); } .badges .st-badge.on { opacity: 1; } .state-card__row { display: flex; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); font-variant-numeric: tabular-nums; } -.metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--st-s-4); } +.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: var(--st-s-4); } .metric-card { padding: var(--st-s-4) var(--st-s-5); } .st-metric__value small { font-size: var(--st-fs-md); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin-left: 4px; } .st-metric__sub { font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; min-height: 1em; } @@ -100,10 +102,10 @@ main { flex: 1; min-height: 0; display: flex; } .st-metric__spark .speed-prefill { color: color-mix(in srgb, var(--st-accent) 65%, black); } .st-metric__spark[data-tone="warn"] { color: var(--st-warn); } .st-metric__spark[data-tone="info"] { color: var(--st-info); } -.monitor-row { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); } +.monitor-row { display: grid; grid-template-columns: minmax(min(260px, 100%), 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); } .ctx-card { display: flex; flex-direction: column; gap: var(--st-s-2); } -.ctx-gauge { position: relative; width: 150px; height: 150px; margin: var(--st-s-2) auto var(--st-s-3); } -.ctx-gauge .st-gauge { width: 150px; height: 150px; } +.ctx-gauge { position: relative; width: 150px; max-width: 100%; aspect-ratio: 1; height: auto; margin: var(--st-s-2) auto var(--st-s-3); } +.ctx-gauge .st-gauge { width: 100%; height: 100%; } .ctx-gauge .st-gauge__fill { transition: stroke-dasharray 400ms var(--st-ease); } .ctx-gauge__label { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: var(--st-fs-xs); } @@ -128,9 +130,9 @@ main { flex: 1; min-height: 0; display: flex; } .cc-note { margin: 0; } .cc-note:empty { display: none; } .mcp-card { display: flex; flex-direction: column; gap: var(--st-s-3); } -.cfg-form { display: grid; grid-template-columns: minmax(0, max-content) minmax(180px, 1fr); gap: var(--st-s-3) var(--st-s-4); +.cfg-form { display: grid; grid-template-columns: minmax(min(180px, 100%), max-content) minmax(0, 1fr); gap: var(--st-s-3) var(--st-s-4); align-items: center; } -.cfg-form label { font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); overflow-wrap: anywhere; } +.cfg-form label { overflow-wrap: anywhere; font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); } .cfg-form label code { font: 400 12px var(--st-font-mono); color: var(--st-ink-muted); display: block; } .cfg-form .st-input { height: 38px; width: 100%; max-width: 360px; min-width: 0; } .cfg-actions { display: flex; align-items: center; gap: var(--st-s-3); } @@ -142,7 +144,7 @@ main { flex: 1; min-height: 0; display: flex; } .mcp-note { margin: 0; } /* ---------------------------------------------------------------- about */ -.about { max-width: 860px; } +.about { max-width: min(100%, 1100px); } .about .st-card { display: flex; flex-direction: column; gap: var(--st-s-3); } .about p { margin: 0; } .facts { display: grid; grid-template-columns: minmax(140px, max-content) 1fr; gap: 10px var(--st-s-6); margin: 0; font-size: var(--st-fs-md); } @@ -172,11 +174,13 @@ main { flex: 1; min-height: 0; display: flex; } /* ---------------------------------------------------------------- narrow screens */ @media (max-width: 1000px) { .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .monitor-row { grid-template-columns: 1fr; } .cc-bars { grid-template-columns: 1fr; } .cfg-form { grid-template-columns: 1fr; gap: 4px; } .cfg-form .st-input { margin-bottom: var(--st-s-2); } } +@media (max-width: 900px) { + .monitor-row { grid-template-columns: minmax(0, 1fr); } +} @media (max-width: 640px) { .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } .st-header .st-tabs { margin-left: 0; } @@ -188,6 +192,26 @@ main { flex: 1; min-height: 0; display: flex; } .monitor, .about { padding: var(--st-s-4); } .facts { grid-template-columns: 1fr; gap: 2px; } .facts dd { margin-bottom: var(--st-s-2); } + .cfg-form .st-input { max-width: none; } + .st-btn, .st-input, .seg button, .st-tab { min-height: 40px; } + .st-btn--icon, .st-composer__bar .st-btn--icon { width: 40px; height: 40px; } + .st-btn--send { width: 44px; } + .st-msg__meta .st-btn--icon, .facts .st-btn--icon { width: 40px; height: 40px; } + .st-composer__bar { flex-wrap: wrap; } + .tool-call__pre, .st-code pre, .table-wrap { max-width: 100%; } +} +@media (max-width: 560px) { + .metrics { grid-template-columns: minmax(0, 1fr); } +} +@media (max-width: 480px) { + .st-header { padding: 0 var(--st-s-2); gap: 6px; } + .st-header__brand { font-size: var(--st-fs-md); } + .st-tabs { gap: 2px; padding: 3px; } + .st-tab { padding: 0 8px; } + .composer-hint { display: none; } + .chat { padding: var(--st-s-4) var(--st-s-3); } + .monitor, .about { padding: var(--st-s-3); } + .st-bubble { padding: 10px 12px; } } /* Images tab (POST /v1/images/generations) */ .img-form{display:flex;flex-direction:column;gap:12px} From ab48216a7b276645c5fb37821cde2b349039f10b Mon Sep 17 00:00:00 2001 From: Norwin <17587814+NorwinYu@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:40:24 +0100 Subject: [PATCH 126/177] docs/MULTI_GPU.md: say when a layer split pays on a slow CPU (#3930) One bullet from PR #3930 by NorwinYu: on two identical RTX 2080 Ti over a dual-socket Xeon E5-2696 v4 a plain split moved decode from 35.2 to 51.0 tok/s and an 11.6K prompt from 672 to 908 tok/s, because the CPU pool per window fell from 9.52 to 0.79 ms (STRATA_DECODE_TIMING=1). The page's own 5080 + 3090 figures, where the second card is on par, came from a fast CPU; the bullet says so and that it is one measurement. No code changes: setup already splits across two cards. Shipped without a hardware run of ours; the reply asks owners of two older cards on slow CPUs to compare and report. --- docs/MULTI_GPU.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 36b35a81..37bd82aa 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -220,6 +220,14 @@ the Qwen layer split described above. On four Radeon AI PRO R9700 cards it reach An explicit `--expert-cache` on the first card is capped to leave room for them. - More cards pay off when the model's routed experts do not fit the faster ones. An extra slow card costs its own round per window and can make a good pair slower. +- **The split pays most when the CPU pool is the bottleneck.** On two identical RTX 2080 Ti 22 GB over a dual-socket Xeon E5-2696 v4 (AVX2 only, + 88 logical CPUs), a plain split moved decode from 35.2 to 51.0 tok/s (+45%) and an 11.6K-token prompt from 672 to 908 tok/s (+35%) at 180 W, + engine 0.1.49, six 300-token coding prompts. `STRATA_DECODE_TIMING=1` shows why: the window fell from 70.06 to 37.96 ms, almost entirely + because the CPU pool fell from 9.52 to 0.79 ms per window. The 5080 + 3090 measurement below, where decode with the second card is on par + with the 5080 alone, was taken over a fast CPU (Ryzen 9 9950X3D). When the CPU pool is what the window waits on, moving half the layers to a + second identical card removes that work. This is one pair of cards and one CPU, so there is no threshold, and the window breakdown from the + engine log is not the same statistic as the decode numbers beside it. Setup splits across two cards by itself; with two identical older cards + on a slow workstation CPU, compare one card against the split and tell us in [#3930](https://github.com/Niko1221/Strata/pull/3930). - For several conversations at once, `--batch N --batch-groups G --trim-stage-weights` pipelines them through the cards ([BATCHING.md](BATCHING.md)). From 4a759f82d4851107b5299b99e0d99f728a66b554 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:42:11 +0100 Subject: [PATCH 127/177] DeepSeek engine packages: add sm_89 (RTX 40) to the CUDA builds (#3935) Problem: the strata-dsv41 packages were built for sm_86 and sm_120 (+ PTX 120). An RTX 4090 user was stopped at setup on 0.2.4.1; since b750d757f an sm_86 package is accepted on an sm_89 card (cubin same-major rule), but the engine had no sm_89 image of its own, and the docs said nothing about RTX 40 or about building the engine for a card the packages do not cover. The reporter built strata-dsv41 for 86-real;89-real themselves and ran the 2.00 set at 40.2 tok/s on an RTX 4090 48 GB (theirs, --dspark on). What changed: - packaging/build_dsv41_cuda.sh and build_dsv41_windows.bat: the default architectures are now 86-real;89-real;120, so the DeepSeek CUDA 13 packages list sm_86, sm_89, sm_120, compute_120 (Windows and Linux alike). The CUDA 12.9 line in the script header says ARCH="86-real;89". - CMakeLists.txt: a build of strata-dsv41 with no -DCMAKE_CUDA_ARCHITECTURES defaults to 86-real;89-real;120 (the Qwen engine's default stays 120, and the warning now names the architectures it picked). - strata_control/engine_component.py arch_native(): true when a package holds machine code for the card itself. resolve() and feed.select_engine() use it as the last tie-breaker, so with otherwise equal packages the one with the sm_89 image is taken on an RTX 40; an sm_86-only package still fits (no refusal). - setup.py: the "engine not available" stop now points at the build recipe (docs/DEEPSEEK41.md); the developer line names the architecture to pass. The card list already said RTX 30, 40 and 50. - docs/DEEPSEEK41.md, docs/MODELS.md: RTX 40 coverage, the reporter's measurement quoted as theirs, no claim of our own (we have no Ada card), and a section "Building the engine for your card". Tests: tests/terminal/test_engine_manifest.py (arch_native; the build scripts and the CMake default name sm_89 and both OSes agree; the package list they give is sm_86 sm_89 sm_120 compute_120; an sm_89 card is accepted and prefers the package with sm_89). tools/test_setup_dsv41.py unchanged and passing. Not covered: no run on an Ada card (gate script in phaseA-tests/gh027/gates/3935-ada-dsv41.sh). --- CMakeLists.txt | 10 ++++-- docs/DEEPSEEK41.md | 28 +++++++++++++++ docs/MODELS.md | 2 ++ packaging/build_dsv41_cuda.sh | 11 +++--- packaging/build_dsv41_windows.bat | 4 +-- setup.py | 6 ++-- strata_control/engine_component.py | 10 +++++- strata_control/feed.py | 3 +- tests/terminal/test_engine_manifest.py | 48 ++++++++++++++++++++++++++ 9 files changed, 109 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c6f2879..1ff02992 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -179,7 +179,13 @@ elseif(STRATA_ENABLE_CUDA) # a build with no option was an sm_75 build. -DCMAKE_CUDA_ARCHITECTURES and the CUDAARCHS environment variable win. set(_strata_cuda_arch_defaulted OFF) if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES AND NOT DEFINED ENV{CUDAARCHS}) - set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures") + if(STRATA_BUILD_DSV41) + # #3935: the DeepSeek engine's own release shape (sm_86, sm_89, sm_120 + PTX 120, as packaging/build_dsv41_cuda.sh), so a hand + # build of strata-dsv41 with no architecture runs on an RTX 30, 40 or 50 card; the Qwen engine's default below is unchanged + set(CMAKE_CUDA_ARCHITECTURES "86-real;89-real;120" CACHE STRING "CUDA architectures") + else() + set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures") + endif() set(_strata_cuda_arch_defaulted ON) endif() enable_language(CUDA) @@ -189,7 +195,7 @@ elseif(STRATA_ENABLE_CUDA) option(STRATA_EXPERIMENTAL_SM60 "community build for GPUs below compute capability 7.5: Pascal sm_60, Volta sm_70 (#236)" OFF) if(_strata_cuda_arch_defaulted) # a recommendation, not a refusal: the release engine is built for 75;86;89;120, a hand build names its card - message(WARNING "Strata: CMAKE_CUDA_ARCHITECTURES was not set, so this build is for sm_120 (RTX 50) only. For another " + message(WARNING "Strata: CMAKE_CUDA_ARCHITECTURES was not set, so this build is for ${CMAKE_CUDA_ARCHITECTURES} only (sm_120 = RTX 50). For another " "card pass it: -DCMAKE_CUDA_ARCHITECTURES=native (the GPUs in this PC), 75 (RTX 20), 86 (RTX 30), " "89 (RTX 40), or a list like \"86;120\".") endif() diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 86a98e63..418a57e4 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -55,6 +55,12 @@ Measured: an RTX 5070 (12 GB) with 64 GB of RAM and a 3.6 GB/s NVMe drive answer tokens/s (4K) to 231 tokens/s (8K, layer-major path); an RTX 3060 (12 GB) with 46 GB of RAM about 8 to 10 tokens/s (code 9.9, agent work 7.8; 149 tokens/s at 8K; DSpark stays off there, `--dspark on` adds 2-13%); four R9700 about 48 tokens/s on 2.00 and 80 on 2.25 (code, with the shipped hot-expert profile). Under about 40 GB of RAM it is untested and slow; setup says so and still installs. +**RTX 40 series (sm_89).** The engine packages carry machine code for sm_86, sm_89 and sm_120 since 0.2.7 (before, an RTX 40 card ran the sm_86 code through +CUDA's same-generation rule). We have no RTX 40 card: the sm_89 build was compiled here but not run. A user's own build for sm_89 ran the 2.00 set on an +RTX 4090 48 GB with 128 GB of RAM (#3935, their numbers): decode 40.2 tokens/s (median of 5 answers of 64 tokens, `--ssd-cache 108 --dspark on --dspark-conf 0.65`), +prompts 141 tokens/s at 1.2K and 615 at 4.6K. They saw 16 to 22 tokens/s with `--dspark auto`, which decided "off" on their computer. This is one report on one +computer; other cards and RAM sizes can differ, and `--dspark auto` stays the default. + Setup downloads with resume and SHA-256, packs the model with the plain recipe (`pack_gguf.py --model SET --shards ... --engram engram-IQ4_NL.gguf --engram-meta --dspark-gguf dspark-...-Q8_0.gguf`; do not add `--skip-tensors` or `--dense-override`: that packs without an error and gives garbage text), copies the shipped hot-expert profile (`data/dsv41/profile-2.00.bin` or `-2.25.bin`) @@ -144,6 +150,28 @@ Strata checks the package before it uses it: it must be the DeepSeek engine (not Strata trusts, and every file must match the hash in the manifest. A damaged or foreign file is refused with a plain line and nothing is installed. The unpacked folder works as well as the archive. The Strata (Qwen) engine is not touched either way. +### Building the engine for your card + +The packages hold machine code for these NVIDIA cards (CUDA 13, Windows and Linux): sm_86 (RTX 30), sm_89 (RTX 40) and sm_120 (RTX 50), plus PTX for +sm_120. If your card is none of these, or you want your own build, compile `strata-dsv41` and put it where Strata looks for it. You need the CUDA toolkit +(the packages are built with 13.0), a C++ compiler, CMake, Ninja and the llama.cpp checkout Strata pins (`third_party/llama.cpp`). + +``` +cmake -S . -B build-dsv41 -G Ninja -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_DSV41=ON -DSTRATA_NATIVE_EXPERTS=ON "-DCMAKE_CUDA_ARCHITECTURES=89-real" -DSTRATA_GGML_DIR=third_party/llama.cpp +cmake --build build-dsv41 --target strata-dsv41 -j 8 +``` + +Use your card's number in `CMAKE_CUDA_ARCHITECTURES`: 86 for RTX 30, 89 for RTX 40, 120 for RTX 50, or `native` for the cards in this computer. Without the +option a DeepSeek build is made for 86, 89 and 120. On Windows, `packaginguild_dsv41_windows.bat BUILD_DIR` does the same (`DSV41_ARCH` names the cards); +on Linux, `packaging/build_dsv41_cuda.sh` (`ARCH=...`). Then copy the file into the `engine` folder of your Strata install (next to `strata`); setup finds it there and does not download an engine: + +``` +python setup.py --family deepseek41 --model IST-DAS-2.00bpw +``` + +`strata-dsv41 --version` prints the commit it was built from. A build you made yourself is not signed by Strata, which is fine for your own computer. +Please tell us how it runs on your card (the speed, and the card and RAM): we only list a card as tested after someone has run it. + ## Compressed experts (trellis), for testing `strata-dsv41` reads the routed experts in the trellis types as well as the source MXFP4: TQK6 and TQK7 (agentionai's files), and the diff --git a/docs/MODELS.md b/docs/MODELS.md index 4eba8f4c..8f3fbedf 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -78,6 +78,8 @@ Tested on an RTX 3060 (Linux), an RTX 5070 (Windows), four R9700 cards (Linux) a and Strix Halo on Linux do not run it yet; on Strix Halo Windows the graphics memory is the RAM, so most of the experts are read from the SSD and an NVMe drive matters. +RTX 40 cards are covered by the engine packages since 0.2.7 (sm_89 code); we have not run one ourselves, see [DEEPSEEK41.md](DEEPSEEK41.md#the-engine-package) for a user's measurement. + **What you need:** a graphics card with 12 GB or more, 46 GB of RAM at least (64 GB is the tested comfortable size), an NVMe SSD, and the disk space above. Setup warns when disk or RAM is short and does not stop you. diff --git a/packaging/build_dsv41_cuda.sh b/packaging/build_dsv41_cuda.sh index 4ebfd558..9a82b28d 100644 --- a/packaging/build_dsv41_cuda.sh +++ b/packaging/build_dsv41_cuda.sh @@ -3,18 +3,19 @@ # beside `strata` (setup.py dsv41_exe() looks for strata-dsv41 in the engine folder). Same toolchain and RUNPATH rule as the # engine build: the result finds cudart/cublas beside itself ($ORIGIN), never the toolkit it was built with. # -# SRC= B= CUDA=/usr/local/cuda-13.0 GG= [ARCH="86-real;120"] [JOBS=6] packaging/build_dsv41_cuda.sh +# SRC= B= CUDA=/usr/local/cuda-13.0 GG= [ARCH="86-real;89-real;120"] [JOBS=6] packaging/build_dsv41_cuda.sh # -# ARCH defaults to the 0.2.4 release shape: SASS for sm_86 (RTX 3090 / 3060) and sm_120 (RTX Blackwell) + PTX sm_120 (the Windows twin -# built and ran on an RTX 5070; the Linux sm_86 build is the one tested on the RTX 3060 box). Needs CUDA 13 (the sm_120 code); for a -# CUDA 12.9 package pass ARCH="86-real;89-real;89-virtual" or leave strata-dsv41 out (the Pascal cuda12 variant has no DeepSeek path). +# ARCH defaults to the 0.2.7 release shape: SASS for sm_86 (RTX 3090 / 3060), sm_89 (RTX 40, #3935) and sm_120 (RTX Blackwell) + PTX sm_120, i.e. +# the package lists sm_86, sm_89, sm_120, compute_120 (the Windows twin built and ran on an RTX 5070; the Linux sm_86 build is the one tested on the +# RTX 3060 box; sm_89 is built here, not run: the one reporter's own build ran at 40.2 tok/s on an RTX 4090). Needs CUDA 13 (the sm_120 code); +# for a CUDA 12.9 package pass ARCH="86-real;89" (sm_86, sm_89, compute_89) or leave strata-dsv41 out (the Pascal cuda12 variant has no DeepSeek path). # Prints the binary path on the last line; collect its libraries with packaging/collect_libs.py --binary --search $CUDA/lib64. set -eu SRC=${SRC:-$(cd "$(dirname "$0")/.." && pwd)} B=${B:?B=} CUDA=${CUDA:?CUDA=} GG=${GG:?GG=} -ARCH=${ARCH:-86-real;120} +ARCH=${ARCH:-86-real;89-real;120} JOBS=${JOBS:-6} export PATH=$CUDA/bin:$PATH # the build id: the commit, 9 characters. A git checkout gives it to CMake itself; a tarball has no .git, so COMMIT= is required there and goes to BUILD_ID. diff --git a/packaging/build_dsv41_windows.bat b/packaging/build_dsv41_windows.bat index 8fe958e4..8faea651 100644 --- a/packaging/build_dsv41_windows.bat +++ b/packaging/build_dsv41_windows.bat @@ -3,7 +3,7 @@ rem strata-dsv41.exe (the DeepSeek-V4.1 engine) for NVIDIA on Windows, built nex rem beside strata.exe (setup.py dsv41_exe() looks for it in the engine folder). cudart is static; the only extra DLL is cublas64_13.dll, rem which package_engine.py copies from CUDA_PATH like it does for strata.exe. rem build_dsv41_windows.bat [source dir] env: STRATA_GGML_DIR (llama.cpp), CUDA_ROOT (default CUDA 13.0), BUILD_JOBS (default 4), -rem DSV41_ARCH (default "86-real;120" = sm_86 + sm_120 SASS, PTX sm_120) +rem DSV41_ARCH (default "86-real;89-real;120" = sm_86 + sm_89 + sm_120 SASS, PTX sm_120) rem Result: \strata-dsv41.exe (about 66 MB). Windows: only the cuda13 variant gets it (sm_120 needs CUDA 13). setlocal set "BD=%~1" @@ -11,7 +11,7 @@ set "SRCD=%~2" if "%BD%"=="" ( echo usage: build_dsv41_windows.bat ^ [source dir] & exit /b 2 ) if "%SRCD%"=="" set "SRCD=%~dp0.." if "%CUDA_ROOT%"=="" set "CUDA_ROOT=C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v13.0" -if "%DSV41_ARCH%"=="" set "DSV41_ARCH=86-real;120" +if "%DSV41_ARCH%"=="" set "DSV41_ARCH=86-real;89-real;120" if "%BUILD_JOBS%"=="" set "BUILD_JOBS=4" if "%STRATA_GGML_DIR%"=="" ( echo set STRATA_GGML_DIR to the llama.cpp checkout & exit /b 2 ) call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1 diff --git a/setup.py b/setup.py index 55f8941f..7081a73c 100644 --- a/setup.py +++ b/setup.py @@ -8214,11 +8214,13 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, lib_dirs = [*lib_dirs, *dsv41_engine.lib_dirs(exe)] # its own package, and the rocm/bin an AMD package keeps the ROCm DLLs in if exe is None: if os.environ.get("STRATA_VERBOSE") == "1" or "--verbose" in sys.argv: - say(" Details for developers: build it with cmake -DSTRATA_BUILD_DSV41=ON and point STRATA_DSV41_EXE at it.") + say(" Details for developers: build it with cmake -DSTRATA_BUILD_DSV41=ON -DCMAKE_CUDA_ARCHITECTURES= " + "and point STRATA_DSV41_EXE at it (docs/DEEPSEEK41.md, \"Building the engine for your card\").") fail("DeepSeek's engine is not available for this computer yet", "Supported graphics cards: NVIDIA RTX 30, 40 and 50 series, the Radeon AI PRO R9700, and a Ryzen AI Max (Strix Halo) on " "Windows with the AMD DeepSeek engine package. " + dsv41_manual_steps(eng) - + " Or update Strata later (a newer version may add your card), or pick another model. Nothing has been downloaded.") + + " Or update Strata later (a newer version may add your card), pick another model, or build the engine for your card yourself " + "(docs/DEEPSEEK41.md, \"Building the engine for your card\"). Nothing has been downloaded.") ok(f"engine: {exe}") step(5, f"downloading {fam['title']} {model}") diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py index c7f60e0b..4fbb7e97 100644 --- a/strata_control/engine_component.py +++ b/strata_control/engine_component.py @@ -808,6 +808,14 @@ def arch_covers(archs, present: list[str]) -> bool: return False +def arch_native(archs, present: list[str]) -> bool: + """Whether a build with `archs` holds machine code made for one of the `present` cards itself (``sm_89`` on an ``sm_89`` card), + not only code that runs there through the same-major rule of `arch_covers` (``sm_86`` on an RTX 40) or as PTX. Only a tie-breaker + between packages that fit equally: a package with the card's own image is taken first (#3935).""" + cards = {item[3:] for item in present if item.startswith("sm_") and item[3:].isdigit()} + return any(arch.startswith("sm_") and arch[3:] in cards for arch in archs) + + # ----------------------------------------------------------------------------------------------- resolve def scan(root: Path | None = None) -> tuple[list[EngineComponent], list[dict]]: @@ -974,7 +982,7 @@ def resolve(root: Path | None = None, *, backend: str | None = None, target: str return item # newest version first; with equal versions the build for the newer driver (the CUDA 13 build beside the CUDA 12 one) return max(usable, key=lambda item: (_version_key(item.version), _version_key(item.min_driver.get("nvidia", "0")), - hip_preference(item.hip_archs))) + hip_preference(item.hip_archs), arch_native(item.cuda_archs, archs_here))) #: A run config can name its engine as "component:strata-engine" instead of a path: the server then asks the diff --git a/strata_control/feed.py b/strata_control/feed.py index ddbdaafe..eb0e7835 100644 --- a/strata_control/feed.py +++ b/strata_control/feed.py @@ -412,7 +412,8 @@ def select_engine(packages, hardware: dict) -> tuple[EnginePackage | None, list[ if not fitting: return None, reasons best = max(fitting, key=lambda p: (version_key(p.version), ec._version_key(p.min_driver.get("nvidia", "0")), - ec.hip_preference(p.archs) if p.backend == "hip" else 1)) + ec.hip_preference(p.archs) if p.backend == "hip" else 1, + ec.arch_native(p.archs, hardware.get("cuda_archs") or []) if p.backend == "cuda" else False)) kept = str(hardware.get("installed_variant") or "") if best.backend == "cuda" and kept and best.variant != kept: # An update never switches the CUDA build (#3835): a model on the CUDA 12 engine (its card is one CUDA 13 has no code for) must not diff --git a/tests/terminal/test_engine_manifest.py b/tests/terminal/test_engine_manifest.py index 3cb5b00d..46375ffd 100644 --- a/tests/terminal/test_engine_manifest.py +++ b/tests/terminal/test_engine_manifest.py @@ -218,6 +218,54 @@ class Arch(unittest.TestCase): self.assertFalse(ec.arch_covers(["sm_89"], ["sm_100"]), "sm_100 is major 10, not major 1 + minor 00") self.assertTrue(ec.arch_covers(["sm_86", "sm_120"], ["sm_75", "sm_89"]), "one covered card is enough") + def test_a_native_image_is_the_card_itself_only(self): + """#3935: arch_native tells a package with the card's own machine code from one that only runs there.""" + self.assertTrue(ec.arch_native(["sm_86", "sm_89", "sm_120", "compute_120"], ["sm_89"])) + self.assertFalse(ec.arch_native(["sm_86", "sm_120", "compute_120"], ["sm_89"]), "sm_86 code runs on an RTX 40 but is not its image") + self.assertFalse(ec.arch_native(["sm_86", "compute_89"], ["sm_89"]), "PTX is not machine code") + self.assertFalse(ec.arch_native(["sm_89"], [])) + self.assertTrue(ec.arch_native(["sm_75", "sm_89"], ["sm_75", "sm_120"])) + + def test_the_deepseek_package_lists_89_and_an_rtx_40_card_is_accepted(self): + """#3935: the build scripts and the CMake default name sm_89, the manifest list a build of them gets covers an sm_89 card + with its own image, and the engine picker takes it for an RTX 4090 with no refusal and prefers it to a package without it.""" + import re + from strata_control import feed + + def package_archs(spec): + """CMAKE_CUDA_ARCHITECTURES to the package's archs list: N-real = sm_N, N = sm_N + compute_N.""" + out = [] + for item in spec.split(";"): + number, _, kind = item.partition("-") + out.append(f"sm_{number}") + if not kind: + out.append(f"compute_{number}") + return out + + sh = (ROOT / "packaging" / "build_dsv41_cuda.sh").read_text(encoding="utf-8") + bat = (ROOT / "packaging" / "build_dsv41_windows.bat").read_text(encoding="utf-8") + cmake = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + linux = re.search(r"^ARCH=\$\{ARCH:-([^}]+)\}", sh, re.M).group(1) + windows = re.search(r'set "DSV41_ARCH=([^"]+)"', bat).group(1) + self.assertEqual(linux, windows, "Windows and Linux ship the same DeepSeek architectures") + self.assertEqual(package_archs(linux), ["sm_86", "sm_89", "sm_120", "compute_120"]) + self.assertIn('set(CMAKE_CUDA_ARCHITECTURES "86-real;89-real;120" CACHE', cmake) + + def package(archs): + return feed.EnginePackage(version="0.1.50", platform="linux-x86_64", backend="cuda", variant="cuda13", archs=tuple(archs), + min_driver={}, min_runtime=None, build_id="b", url="u", format="tar.gz", size=1, sha256="a" * 64, + manifest_sha256="b" * 64, installed_bytes=1) + + hw = {"platform": "linux-x86_64", "backend": "cuda", "cuda_archs": ["sm_89"], "nvidia_driver": None} + old, new = package(["sm_86", "sm_120", "compute_120"]), package(package_archs(linux)) + self.assertFalse(feed.engine_fit_reasons(new, hw), "an RTX 4090 is accepted") + self.assertFalse(feed.engine_fit_reasons(old, hw), "the old package still fits through sm_86 (no refusal)") + for order in ((old, new), (new, old)): + best, _ = feed.select_engine(list(order), hw) + self.assertIs(best, new, "the package with sm_89 machine code wins an otherwise equal choice") + best, _ = feed.select_engine([old, new], {**hw, "cuda_archs": ["sm_86"]}) + self.assertIsNotNone(best) + def test_the_packages_of_each_engine(self): """The Qwen engine (sm_86 + PTX 89) and the DeepSeek engine (sm_86 + sm_120 + PTX 120) on the RTX 20 to 50 families.""" from strata_control import feed From 10a62b8d2f500fca3bf8feecf9cf2ff8bb896d9f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:42:58 +0100 Subject: [PATCH 128/177] docker: model files left in the older /data/models stop the start instead of being downloaded again (#3421) A volume or bind mount from the 0.1.x image keeps its models in /data/models. The entry point moves a folder that is part of the volume, but a folder the person mounted there is left alone, and a failed move leaves the files too; with no MODEL_PATH the start then did not see them and downloaded the model again (tens of GB) without a word. Now, when .gguf files are still in /data/models and MODEL_PATH is not set, the container stops with code 2 and names the folder, says what to do (MODEL_PATH to the folder with the shards, or the files into /data/Strata-data/models) and that nothing was downloaded. ALLOW_DOWNLOAD=1 goes on anyway with the same text as a warning. docs/DOCKER.md lists the setting. The other points of the issue (the key, the removed variables, the status loop) are the owner's design questions and are not changed here. Tested by running the guard function with sh (tests/terminal/test_docker_files.py); the whole container was not run (no docker on this PC). --- docker/entrypoint.sh | 13 +++++++ docs/DOCKER.md | 6 ++- tests/terminal/test_docker_files.py | 57 +++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 6b6f87cf..f5476e3a 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -10,6 +10,7 @@ # MODEL model size, e.g. IQ3_XXS, Q2_0 (empty: Strata picks one for this card and says so) # FAMILY model family when a size is offered by several (qwen, swift, coder, ...) # MODEL_PATH GGUF files you already have, a folder or one .gguf, inside the container (mount it read-only) +# ALLOW_DOWNLOAD 1: go on and download the model although model files of the older layout (/data/models) were left unread (default: stop) # CONTEXT 32k, 64k, 128k, 256k or a number of tokens # PARALLEL requests answered at the same time, 1 to 8 (empty: fit to the card) # VISION off | on | gpu | cpu (pictures; the picture reader file is downloaded with the model) @@ -38,6 +39,17 @@ warn() { printf '[!] %s\n' "$*" >&2; } die() { printf '[X] %s\n' "$*" >&2; exit "${2:-1}"; } phase() { printf '%s\n' "$1" > "$PHASE_FILE" 2>/dev/null || true; } +# Model files of the older layout that this image did not move (a folder you mounted at /data/models, or a move that failed) are not read here, and +# the start would download the model again. Say so and stop instead (#3421); ALLOW_DOWNLOAD=1 goes on, with the same text as a warning. +# $1: MODEL_PATH (when it is set the files are named and nothing is lost), $2: the older models folder. +legacy_models_guard() { + [ -n "$1" ] && return 0 + stuck=$(find "$2" -maxdepth 3 -name '*.gguf' 2>/dev/null | head -1) + [ -n "$stuck" ] || return 0 + msg="There are model files in ${stuck%/*} (the older image's place). This image keeps its models in /data/Strata-data/models and does not read them there, so it would download the model again (tens of GB). To use them: mount that folder read-only and set MODEL_PATH to the folder that holds the shards (docs/DOCKER.md, \"Files you already have\"), or put them in /data/Strata-data/models//. To download anyway: set ALLOW_DOWNLOAD=1. Nothing was downloaded." + if [ "${ALLOW_DOWNLOAD:-0}" = "1" ]; then warn "$msg Going on, because ALLOW_DOWNLOAD=1."; else die "$msg" 2; fi +} + # ---- other commands: `docker run image strata ...`, `docker run image sh` if [ "$#" -gt 0 ] && [ "$1" != "run" ] && [ "$1" != "serve" ]; then case "$1" in strata) shift; exec "$STRATA" "$@" ;; *) exec "$@" ;; esac @@ -174,6 +186,7 @@ if [ -n "$model_path" ]; then die "MODEL_PATH=$model_path holds no .gguf files. Mount the folder with the model's shards (the -0000N-of-0000M.gguf files). Nothing was downloaded." 2 fi fi +legacy_models_guard "$model_path" "${STRATA_LEGACY_MODELS:-/data/models}" [ -n "${MODEL:-}" ] && { set -- "$@" --model "$MODEL"; have=1; } [ -n "${FAMILY:-}" ] && { set -- "$@" --family "$FAMILY"; have=1; } [ -n "$model_path" ] && { set -- "$@" --model-path "$model_path"; have=1; } diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 3ea6f661..d0825fd6 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -115,6 +115,7 @@ screens; leave out what you do not care about. | `MODEL` | model size: `IQ2_XS`, `IQ3_XXS`, `IQ3_S`, `Q2_0`, `UD-Q4_K_XL`, ... ([MODELS.md](MODELS.md)) | Strata picks what suits the card, and says so in the log | | `FAMILY` | `qwen`, `unsloth`, `gyro`, `coder`, `swift`, ...; use `qwen` for the original ISTA-DASLab packs | installer recommendation; may differ by hardware | | `MODEL_PATH` | GGUF files you already have: a folder or one `.gguf`, **inside the container** (mount it with `-v`, `:ro` is fine) | download | +| `ALLOW_DOWNLOAD` | `1`: go on and download the model although model files of the older layout were left unread in `/data/models` (see [From the older image](#from-the-older-image)) | stop | | `CONTEXT` | how much text it remembers at once: `32k`, `64k`, `128k`, `256k` or a number | the largest that fits | | `PARALLEL` | requests answered at the same time, 1 to 8 | fitted to the card | | `VISION` | `off`, `on` (the model reads pictures), `gpu`, `cpu`; the picture-reader file (about 0.9 GB) is downloaded with the model | `off` | @@ -276,7 +277,10 @@ package and start through `strata launch`. Mapping: A volume from the older image is picked up: the first start moves `/data/models`, `/data/packs` and `/data/mtp` into `/data/Strata-data` (a rename inside the volume: nothing is copied or downloaded again, and the prepared pack is kept). The old `/data/config` is not read; the run settings are made again from the files. A folder you mounted yourself at one of those places -is left alone: point `MODEL_PATH` at it. The container name, the volume and the port can stay as they were. +is left alone: point `MODEL_PATH` at it. If model files are still in `/data/models` when the container starts (a folder you mounted there, or +a move that failed) and `MODEL_PATH` is not set, the start **stops at once and says where the files are**: it would otherwise download the model +again, tens of GB, because this image does not read that place. Name the folder in `MODEL_PATH`, or set `ALLOW_DOWNLOAD=1` to download anyway. +The container name, the volume and the port can stay as they were. ## Build it yourself diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index 3f2a5520..d146282a 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -133,6 +133,63 @@ class Compose(unittest.TestCase): self.assertNotIn("/dev/kfd:/dev/kfd", intel["devices"]) +@unittest.skipIf(SH is None, "needs sh") +class LegacyModelsGuard(unittest.TestCase): + """#3421: model files left in the older image's /data/models (a folder the person mounted there, or a failed move) are not read by this image, + so the start would download the model again. It stops and says where the files are; MODEL_PATH names them, ALLOW_DOWNLOAD=1 goes on.""" + + def run_guard(self, folder, model_path="", allow=None): + import os + import tempfile + entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8") + body = entry[entry.index("legacy_models_guard() {"):] + body = body[:body.index("\n}\n") + 3] + with tempfile.TemporaryDirectory() as tmp: + script = Path(tmp) / "guard.sh" + script.write_text("warn() { printf '[!] %s\\n' \"$*\" >&2; }\ndie() { printf '[X] %s\\n' \"$*\" >&2; exit \"${2:-1}\"; }\n" + body + + f"\nlegacy_models_guard '{model_path}' '{sh_path(folder)}'\necho CONTINUED\n", encoding="utf-8", newline="\n") + env = dict(os.environ) + env.pop("ALLOW_DOWNLOAD", None) + if allow is not None: + env["ALLOW_DOWNLOAD"] = allow + return subprocess.run([SH, sh_path(script)], capture_output=True, text=True, env=env) + + def test_files_in_the_older_place_stop_the_start_with_the_folder_named(self): + import tempfile + with tempfile.TemporaryDirectory() as tmp: + shards = Path(tmp) / "IQ3_XXS" + shards.mkdir() + (shards / "model-00001-of-00002.gguf").write_bytes(b"GGUF") + done = self.run_guard(Path(tmp)) + self.assertEqual(done.returncode, 2, done.stdout + done.stderr) + self.assertNotIn("CONTINUED", done.stdout) + self.assertIn(shards.name, done.stderr) + self.assertIn("MODEL_PATH", done.stderr) + self.assertIn("ALLOW_DOWNLOAD=1", done.stderr) + self.assertIn("Nothing was downloaded", done.stderr) + + def test_model_path_allow_download_an_empty_folder_and_a_missing_one_go_on(self): + import tempfile + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "IQ3_XXS").mkdir() + (Path(tmp) / "IQ3_XXS" / "model-00001-of-00002.gguf").write_bytes(b"GGUF") + named = self.run_guard(Path(tmp), model_path="/models") + self.assertEqual((named.returncode, "CONTINUED" in named.stdout), (0, True), named.stderr) + allowed = self.run_guard(Path(tmp), allow="1") + self.assertEqual((allowed.returncode, "CONTINUED" in allowed.stdout), (0, True), allowed.stderr) + self.assertIn("[!]", allowed.stderr) + self.assertIn("ALLOW_DOWNLOAD=1", allowed.stderr) + with tempfile.TemporaryDirectory() as empty: + nothing = self.run_guard(Path(empty)) + self.assertEqual((nothing.returncode, "CONTINUED" in nothing.stdout), (0, True), nothing.stderr) + missing = self.run_guard(Path("/no/such/folder")) + self.assertEqual((missing.returncode, "CONTINUED" in missing.stdout), (0, True), missing.stderr) + + def test_the_entry_point_runs_the_guard_before_any_flag_is_built(self): + entry = (DOCKER / "entrypoint.sh").read_text(encoding="utf-8") + self.assertLess(entry.index('legacy_models_guard "$model_path"'), entry.index('--model "$MODEL"')) + + class Document(unittest.TestCase): def test_every_documented_setting_is_read_by_the_entry_point(self): doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8") From 47c98bb23ad8740cd693d56e20be0f92c940fadb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:45:45 +0100 Subject: [PATCH 129/177] strata launch --show-key shows the key of a model setup.py set up (#3570) --show-key only knew a running launch or a preset. A model set up by setup.py (START-HERE.bat, ./setup.sh) keeps its generated key in strata-.json, so the command said there was no key and people read the JSON by hand. With no launch and no --preset, it now looks at the run configs of the installed models: one model with a key prints that key (stdout is the key alone; a hint line with the model and the file goes to stderr), several models ask for --model NAME (any case, the size or the full id), a name that matches nothing says so. --preset never falls back to a setup config, and no key is printed while the choice is open. Tests: tests/terminal/test_launch_show_key_setup.py. --- strata_cli/launch/cmd.py | 48 +++++++++++-- tests/terminal/test_launch_show_key_setup.py | 74 ++++++++++++++++++++ 2 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_launch_show_key_setup.py diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 48cd78ed..ca248829 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -147,7 +147,8 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] m.add_argument("--delete-preset", metavar="NAME", help="delete a saved preset") m.add_argument("--status", action="store_true", help="show what this command is serving now") m.add_argument("--stop", action="store_true", help="stop what this command started (with --preset NAME: that one)") - m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch)") + m.add_argument("--show-key", action="store_true", help="print the API key of --preset NAME (or of the running launch); with none of those, the key of a model setup.py set up " + "(--model NAME picks one when several have a key)") c = sp.add_parser( "connect", help="print (or write) the setup for an app that uses the running server", epilog=EXAMPLES, @@ -650,6 +651,31 @@ def launch_info(name: str | None = None) -> dict | None: "port": port, "access": preset.access if preset else None} +def setup_config_keys(wanted: str | None = None) -> list[tuple[str, Path, str]]: + """(model id, config file, API key) for the models setup.py set up (strata-.json in the install folders) that carry a key, #3570. + `wanted` keeps the model whose id is that name or ends with it (coder-iq1_m for IQ1_M); case does not matter.""" + from strata_control import models + try: + listed = models.list_installed().get("models", []) + except Exception: # noqa: BLE001 - a folder that cannot be read has no key to show + return [] + found = [] + for entry in listed: + source = entry.get("source_config") + if not source: + continue + model_id = str(entry.get("id") or Path(source).stem) + if wanted and not (model_id.lower() == wanted.lower() or model_id.lower().endswith(wanted.lower())): + continue + try: + key = str(json.loads(Path(source).read_text(encoding="utf-8-sig")).get("api_key") or "").strip() + except (OSError, ValueError, AttributeError): + continue + if key and key.lower() != "none": + found.append((model_id, Path(source), key)) + return found + + def run_launch(a: argparse.Namespace) -> int: from strata_cli.launch import store from strata_cli.launch.catalog import Catalog, CatalogUnavailable @@ -694,10 +720,22 @@ def run_launch(a: argparse.Namespace) -> int: return 0 if a.show_key: info = launch_info(a.preset) - if not info or not info.get("key"): - return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME."), 5) - _say(info["key"]) - return 0 + if info and info.get("key"): + _say(info["key"]) + return 0 + if not a.preset: + # not a launch: a model set up by setup.py keeps its key in its own strata-.json (#3570) + found = setup_config_keys(getattr(a, "model", None)) + if len(found) == 1: + _say(found[0][2]) + if not machine: + print(f"(the key of {found[0][0]}, from {found[0][1]})", file=sys.stderr) + return 0 + if len(found) > 1: + return fail("Several models set up by setup.py have an API key: " + ", ".join(f[0] for f in found) + ". Name one with --model NAME.", 5) + if getattr(a, "model", None): + return fail(f"No model set up by setup.py matches '{a.model}' and has an API key, and no launch is running.", 5) + return fail("There is no API key for that launch." + ("" if a.preset else " Name a preset with --preset NAME, or a model set up by setup.py with --model NAME."), 5) try: catalog = Catalog() diff --git a/tests/terminal/test_launch_show_key_setup.py b/tests/terminal/test_launch_show_key_setup.py new file mode 100644 index 00000000..b9efe00a --- /dev/null +++ b/tests/terminal/test_launch_show_key_setup.py @@ -0,0 +1,74 @@ +"""#3570: `strata launch --show-key` printed a key only for a launch (a running one or a preset). A model set up by setup.py keeps its key in +strata-.json, so there the command said "no key" and people read the JSON by hand. It now reads that file when no launch has one.""" +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli import cli +from strata_cli.launch import cmd as launch_cmd + + +class ShowKeyOfSetupConfigs(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def config(self, model_id, key="__none__", **extra): + path = self.root / f"strata-{model_id}.json" + body = {"exe": "x", "args": [], **extra} + if key != "__none__": + body["api_key"] = key + path.write_text(json.dumps(body), encoding="utf-8") + return {"id": model_id, "source_config": str(path)} + + def run_cli(self, entries, *argv, launch=None): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ + mock.patch.object(launch_cmd, "launch_info", return_value=launch), \ + mock.patch("strata_control.models.list_installed", return_value={"models": entries}): + code = cli.main(["launch", "--show-key", *argv]) + return code, out.getvalue().strip(), err.getvalue() + + def test_the_only_model_with_a_key_is_shown(self): + code, out, err = self.run_cli([self.config("coder-iq1_m", "abc123-secret"), self.config("qwen-q2_0")]) + self.assertEqual((code, out), (0, "abc123-secret")) + self.assertIn("coder-iq1_m", err) # the hint is on stderr: stdout stays the key alone, for scripts + + def test_a_launch_that_has_a_key_comes_first(self): + code, out, _ = self.run_cli([self.config("coder-iq1_m", "from-the-file")], launch={"key": "from-the-launch"}) + self.assertEqual((code, out), (0, "from-the-launch")) + + def test_several_models_need_a_name_and_the_name_picks_one_in_any_case(self): + entries = [self.config("coder-iq1_m", "key-one"), self.config("qwen-iq3_xxs", "key-two")] + code, out, err = self.run_cli(entries) + self.assertEqual(code, 5) + self.assertEqual(out, "") + self.assertIn("coder-iq1_m", err) + self.assertIn("--model NAME", err) + self.assertNotIn("key-one", err + out) # no key is printed while the choice is open + code, out, _ = self.run_cli(entries, "--model", "IQ3_XXS") + self.assertEqual((code, out), (0, "key-two")) + + def test_no_key_anywhere_and_a_name_that_matches_nothing_are_told_plainly(self): + code, out, err = self.run_cli([self.config("qwen-q2_0")]) + self.assertEqual((code, out), (5, "")) + self.assertIn("There is no API key", err) + code, out, err = self.run_cli([self.config("qwen-q2_0", "none")], "--model", "iq1_m") + self.assertEqual(code, 5) + self.assertIn("iq1_m", err) + + def test_a_preset_name_never_falls_back_to_a_setup_config(self): + code, out, err = self.run_cli([self.config("coder-iq1_m", "abc123-secret")], "--preset", "mine") + self.assertEqual((code, out), (5, "")) + self.assertNotIn("abc123", err) + + +if __name__ == "__main__": + unittest.main() From fa128f91e8adf25f225eb3261b194bd1d032fcb6 Mon Sep 17 00:00:00 2001 From: gopinath87607 <85057872+gopinath87607@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:47:22 +0100 Subject: [PATCH 130/177] docs: --prompt-cache-every does not set the size of the pieces a prompt is read in (#3311, #2834) Only the part of PR #3311 by gopinath87607 that is about this engine: a periodic mark is saved at a chunk boundary of the batched prefill and the read carries on (src/program/generate.cpp, periodic_checkpoint), so the interval is not a piece-size dial; what cuts a read into runs is the re-read, the root, a message boundary and the start of the last turn; --prompt-cache-every 0 skips the periodic and the near-tail marks. The wall-time numbers and the comparison with the Maya checkout belong to another engine and are left out. New section in docs/PROMPT_CACHE_TAIL.md, linked from the option's row in docs/DETAILS.md. --- docs/DETAILS.md | 2 +- docs/PROMPT_CACHE_TAIL.md | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 27d0fdf3..0e765106 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -621,7 +621,7 @@ system prompt with a billing header that changes on every request; the server pi | Option | Effect | | --- | --- | | `--prompt-cache N` | Number of checkpoints (`0` = off, which also disables parking). | -| `--prompt-cache-every N`, `--prompt-cache-root N`, `--turn-token ID` | Checkpoint interval, the system-prompt checkpoint (`0` = none) and the turn token. | +| `--prompt-cache-every N`, `--prompt-cache-root N`, `--turn-token ID` | Checkpoint interval, the system-prompt checkpoint (`0` = none) and the turn token. The interval is not a piece-size setting: [what it does](PROMPT_CACHE_TAIL.md#prompt-cache-every-does-not-set-the-size-of-the-pieces-a-prompt-is-read-in). | | `--prompt-cache-spread` (opt-in) | The checkpoint that leaves is the one whose removal leaves the smallest gap, so the kept points thin out geometrically back from the end. An agent that rewrites its history a few thousand tokens back then resumes near the edit instead of at the system prompt. Same RAM. | | `"strata_checkpoint": false` (per request) | A one-shot request that no later request continues saves no checkpoints and keeps no session. | | `"strata_prefix": {"messages": 1}` (per request, opt-in) | One long document, many questions. Marks where the document ends: `{"messages": 1}`, `{"message": 0, "chars": 210000}` or `{"tokens": 12345}`. The checkpoint at the boundary is pinned, so 20 questions cost one read of the document. One pinned prefix at a time per engine; needs `--prompt-cache 3` or more; a malformed field is a 400. See [RESEARCH_RUNS.md](RESEARCH_RUNS.md). | diff --git a/docs/PROMPT_CACHE_TAIL.md b/docs/PROMPT_CACHE_TAIL.md index 836e3b9e..8e1d3cf0 100644 --- a/docs/PROMPT_CACHE_TAIL.md +++ b/docs/PROMPT_CACHE_TAIL.md @@ -31,3 +31,14 @@ This is a separate conservative alternative to the Strata-2080Ti Daily's checkpoint-grid patch. The grid changes chunk boundaries to reach exact checkpoint intervals and failed its local paired numerical gate. This option does not claim that the original grid patch has been fixed or validated. + +## `--prompt-cache-every` does not set the size of the pieces a prompt is read in + +The option can look like a piece-size dial, because a mark every N tokens sounds like a cut every N tokens. In this engine it is not one: a periodic +mark is saved at a chunk boundary of the batched prefill and the read carries on, so no piece ends at it, and changing N does not change how the prompt +is split into runs. What cuts a read into runs is the list of places where a read has to stop and start again: a re-read (`STRATA_CKPT_REREAD`), +the system-prompt root (`--prompt-cache-root`), a message boundary (`STRATA_CACHE_MESSAGE_BOUNDARY`, see +[MESSAGE_BOUNDARY_CACHE.md](MESSAGE_BOUNDARY_CACHE.md)) and the start of the last turn. So the lever for a fresh long read is those cuts, not this cadence. + +What `--prompt-cache-every 0` does: it skips the periodic marks and the near-tail one (`--prompt-cache-tail` needs `--prompt-cache-every` above 0), so a client +that rewrote a turn before the last one mounts a farther mark and reads more of it again. The root mark is controlled by `--prompt-cache-root`. From d5cca319c96287b4aaa5b2fb4e197f87f2b9790a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:52:26 +0100 Subject: [PATCH 131/177] Web page: a translation mechanism, and a language choice in About > Settings The served page had no way to translate its text: every string was English in the HTML and the script. Now the English text stays in the code next to a key (tr("key", "text", vars), data-i18n="key" in the HTML), a language is a catalog serve/web/locales/.json, and a catalog that is missing or has no entry for a key leaves the English text. The language is the user's choice (About > Settings), kept in this browser; nothing is chosen from the browser's language, because a page translated in part would mix two languages. /?lang=de shows one for a visit. The server hands out /web/locales/.json and /web/vendor/katex/** from serve/webfiles.py: whitelisted names and types, no backslash, colon, percent or dot-dot, and the resolved path must stay inside the folder (also against a link out of it). tools/web_i18n.py reads the English text out of the code, writes en.json and checks every catalog for the same keys and {placeholders}; the check runs once the catalogs exist. --- serve/server.py | 16 ++++ serve/test_web_i18n.js | 92 +++++++++++++++++++ serve/test_web_i18n.py | 108 ++++++++++++++++++++++ serve/web/app.js | 35 +++++-- serve/web/i18n.js | 77 ++++++++++++++++ serve/web/index.html | 6 ++ serve/webfiles.py | 35 +++++++ tools/web_i18n.py | 203 +++++++++++++++++++++++++++++++++++++++++ 8 files changed, 565 insertions(+), 7 deletions(-) create mode 100644 serve/test_web_i18n.js create mode 100644 serve/test_web_i18n.py create mode 100644 serve/web/i18n.js create mode 100644 serve/webfiles.py create mode 100644 tools/web_i18n.py diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..ad0e10a9 100644 --- a/serve/server.py +++ b/serve/server.py @@ -65,6 +65,7 @@ from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthro tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 +from serve.webfiles import subtree_file as web_subtree_file # noqa: E402 from strata_control import engine_component # noqa: E402 from strata_control import tls # noqa: E402 @@ -6387,6 +6388,21 @@ def make_handler(svc: Service): self.end_headers() self.wfile.write(body) return + sub = web_subtree_file(path) + if path.startswith(("/web/locales/", "/web/vendor/")): + # the page's translations (serve/web/locales/.json) and the vendored KaTeX (serve/web/vendor): + # only whitelisted names and types, never a path out of those folders + if sub is None: + self._json(404, {"error": {"message": "not found"}}) + return + body = sub[0].read_bytes() + self.send_response(200) + self.send_header("Content-Type", sub[1]) + self.send_header("Cache-Control", "no-cache") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return if path.startswith("/web/"): # the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN name = path[len("/web/"):] diff --git a/serve/test_web_i18n.js b/serve/test_web_i18n.js new file mode 100644 index 00000000..a712f6e7 --- /dev/null +++ b/serve/test_web_i18n.js @@ -0,0 +1,92 @@ +// The web page's translation mechanism (serve/web/i18n.js), run in Node with a small stub of the DOM and fetch. +// node serve/test_web_i18n.js (serve/test_web_i18n.py runs it too and skips when node is missing) +"use strict"; +const assert = require("node:assert/strict"); +const path = require("node:path"); + +// a page element that holds data-i18n marks and keeps its attributes +class El { + constructor(attrs, text = "") { this.attrs = {...attrs}; this.textContent = text; this.dataset = {}; } + getAttribute(k) { return k in this.attrs ? this.attrs[k] : null; } + setAttribute(k, v) { this.attrs[k] = String(v); } +} +const marks = [ + new El({"data-i18n": "a.text"}, "Rewind to here"), + new El({"data-i18n-title": "a.title", title: "Light / dark"}), + new El({"data-i18n-label": "a.label", "aria-label": "Send"}), + new El({"data-i18n-placeholder": "a.hint", placeholder: "Ask anything…"}), +]; +globalThis.document = { + documentElement: {lang: "en"}, + querySelectorAll: (sel) => marks.filter((e) => sel.slice(1, -1) in e.attrs), +}; +const catalogs = { + de: {"a.text": "Hierher zurückspulen", "a.title": "Hell / Dunkel", "chat.hidden": {one: "{n} Nachricht ausgeblendet", other: "{n} Nachrichten ausgeblendet"}}, + ru: {"chat.hidden": {one: "{n} сообщение скрыто", few: "{n} сообщения скрыто", many: "{n} сообщений скрыто", other: "{n} сообщения скрыто"}}, + ja: {"chat.hidden": {other: "{n} 件のメッセージを非表示"}}, +}; +let fetched = []; +globalThis.fetch = async (url) => { + fetched.push(url); + const m = /web\/locales\/([\w-]+)\.json$/.exec(url); + if (m && catalogs[m[1]]) return {ok: true, json: async () => catalogs[m[1]]}; + if (m && m[1] === "zh") return {ok: true, json: async () => ["not", "an", "object"]}; + if (m && m[1] === "es") throw new Error("offline"); + return {ok: false, json: async () => { throw new Error("404"); }}; +}; +const i18n = require(path.join(__dirname, "web", "i18n.js")); +const {tr} = i18n; +const plural = {one: "{n} message hidden", other: "{n} messages hidden"}; + +(async () => { + // English: the text in the code, with its {placeholders}; a key with no text shows the key rather than nothing + assert.equal(tr("x.y", "Hello {name}", {name: "Ada"}), "Hello Ada"); + assert.equal(tr("x.y", "Hello {name}"), "Hello {name}", "an unknown placeholder stays visible"); + assert.equal(tr("chat.hidden", plural, {n: 1}), "1 message hidden"); + assert.equal(tr("chat.hidden", plural, {n: 3}), "3 messages hidden"); + assert.equal(tr("x.y", undefined), "x.y"); + assert.equal(globalThis.tr, tr, "tr is global for app.js"); + i18n.apply(); + assert.equal(marks[0].textContent, "Rewind to here", "English leaves the marked text alone"); + + // a catalog replaces the text; a key it does not have falls back to the English text in the code + assert.equal(await i18n.setLanguage("de"), "de"); + assert.equal(document.documentElement.lang, "de"); + assert.equal(marks[0].textContent, "Hierher zurückspulen"); + assert.equal(marks[1].attrs.title, "Hell / Dunkel"); + assert.equal(marks[2].attrs["aria-label"], "Send", "no German text for this key: English stays"); + assert.equal(tr("chat.hidden", plural, {n: 1}), "1 Nachricht ausgeblendet"); + assert.equal(tr("chat.hidden", plural, {n: 2}), "2 Nachrichten ausgeblendet"); + assert.equal(tr("only.english", "Only English"), "Only English"); + + // plural forms of the language: Russian has few and many, Japanese only other + await i18n.setLanguage("ru"); + assert.deepEqual([1, 2, 5, 21, 22].map((n) => tr("chat.hidden", plural, {n})), + ["1 сообщение скрыто", "2 сообщения скрыто", "5 сообщений скрыто", "21 сообщение скрыто", "22 сообщения скрыто"]); + await i18n.setLanguage("ja"); + assert.equal(tr("chat.hidden", plural, {n: 1}), "1 件のメッセージを非表示"); + + // switching back restores the English text that was in the page + await i18n.setLanguage("de"); + await i18n.setLanguage("en"); + assert.equal(marks[0].textContent, "Rewind to here"); + assert.equal(marks[1].attrs.title, "Light / dark"); + assert.equal(marks[3].attrs.placeholder, "Ask anything…"); + assert.equal(document.documentElement.lang, "en"); + + // a language that is not offered, a catalog that is not an object, one that cannot be fetched, a missing file: + // all stay English, and never throw + fetched = []; + assert.equal(await i18n.setLanguage("xx"), "en"); + assert.deepEqual(fetched, [], "an unknown code is not even requested"); + assert.equal(await i18n.setLanguage("zh"), "en"); + assert.equal(await i18n.setLanguage("es"), "en"); + assert.equal(await i18n.setLanguage("fr"), "en", "French is not in LANGUAGES yet"); + assert.equal(await i18n.setLanguage("ko"), "en", "the file does not exist in this test"); + assert.equal(tr("chat.hidden", plural, {n: 3}), "3 messages hidden"); + + // the list: English first, every entry [code, own name] + assert.equal(i18n.LANGUAGES[0][0], "en"); + for (const [code, name] of i18n.LANGUAGES) assert.ok(/^[a-z]{2,3}(-[A-Z]{2})?$/.test(code) && name, code); + console.log("ok web i18n"); +})().catch((e) => { console.error(e); process.exitCode = 1; }); diff --git a/serve/test_web_i18n.py b/serve/test_web_i18n.py new file mode 100644 index 00000000..52853373 --- /dev/null +++ b/serve/test_web_i18n.py @@ -0,0 +1,108 @@ +"""The web page's translations: the mechanism (node, serve/test_web_i18n.js), the files the server hands out for it +(serve/web/locales, serve/web/vendor), and the catalogs against the text in the code (tools/web_i18n.py).""" +from __future__ import annotations + +import shutil +import subprocess +import sys +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) + +import web_i18n # noqa: E402 +from serve.frontend import ChatTemplate # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 +from serve.webfiles import subtree_file # noqa: E402 + + +def run_node(script: str, *args: str) -> None: + result = subprocess.run([shutil.which("node"), str(Path(__file__).with_name(script)), *args], + capture_output=True, text=True, timeout=60) + if result.returncode: + raise AssertionError((result.stdout + result.stderr).strip()) + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class Mechanism(unittest.TestCase): + def test_tr_apply_and_set_language(self): + run_node("test_web_i18n.js") + + +class WhatTheServerHandsOut(unittest.TestCase): + """/web/locales and /web/vendor: whitelisted names and types, nothing outside those folders.""" + + def test_names_and_types(self): + web = Path(__file__).parent / "web" + locales = web / "locales" + if (locales / "de.json").is_file(): + self.assertEqual(subtree_file("/web/locales/de.json")[1], "application/json; charset=utf-8") + for bad in ("/web/locales/de.js", "/web/locales/DE.json", "/web/locales/../app.js", "/web/locales/x/y.json", + "/web/locales/%2e%2e%2fapp.json", "/web/locales/de.json%00.js", "/web/locales/missing.json", + "/web/locales/C:\\x.json", "/web/vendor/katex/../../app.js", "/web/vendor/katex/dist/katex.min.js.map", + "/web/vendor/other/dist/katex.min.js", "/web/vendor/katex/dist/fonts/x.ttf", "/web/vendor/katex/dist/"): + with self.subTest(bad=bad): + self.assertIsNone(subtree_file(bad)) + + def test_a_link_out_of_the_folder_is_refused(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + web = Path(d) / "web" + (web / "vendor" / "katex").mkdir(parents=True) + (web / "locales").mkdir() + (web / "secret.js").write_text("secret") + (web / "vendor" / "katex" / "ok.js").write_text("ok") + self.assertEqual(subtree_file("/web/vendor/katex/ok.js", web)[1], "text/javascript; charset=utf-8") + try: + (web / "vendor" / "katex" / "link.js").symlink_to(web / "secret.js") + except (OSError, NotImplementedError): + self.skipTest("symlinks need a privilege here") + self.assertIsNone(subtree_file("/web/vendor/katex/link.js", web)) + + +class Served(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def get(self, path): + try: + with urllib.request.urlopen(self.base + path, timeout=10) as r: + return r.status, r.headers.get("Content-Type", ""), r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers.get("Content-Type", ""), e.read() + + def test_i18n_script_and_refusals(self): + code, ctype, body = self.get("/web/i18n.js") + self.assertEqual(code, 200) + self.assertIn(b"StrataI18n", body) + for path in ("/web/locales/../server.py", "/web/locales/nope.json", "/web/vendor/katex/../../app.js", + "/web/vendor/katex/dist/missing.js", "/web/locales/de.json%00"): + with self.subTest(path=path): + self.assertEqual(self.get(path)[0], 404) + + +@unittest.skipUnless((Path(__file__).parent / "web" / "locales" / "en.json").is_file(), "no catalogs yet") +class Catalogs(unittest.TestCase): + """Every language in serve/web/i18n.js has a catalog with exactly the keys and {placeholders} of the code.""" + + def test_the_text_in_the_code_is_plain_literals(self): + self.assertTrue(web_i18n.english()) + + def test_catalogs_are_complete(self): + self.assertEqual(web_i18n.check(), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.js b/serve/web/app.js index ac84f85d..b3448d92 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -1096,14 +1096,35 @@ $("drawer-close").onclick = () => openDrawer(false); $("scrim").onclick = () => openDrawer(false); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("drawer").dataset.open === "true") openDrawer(false); }); +// ------------------------------------------------------------------ language (serve/web/i18n.js) +// The user's own choice, kept in this browser: English until they pick another. /?lang=de shows one for this visit only. +const urlLang = new URLSearchParams(location.search).get("lang"); +$("lang").innerHTML = StrataI18n.LANGUAGES.map(([code, name]) => ``).join(""); +function showLanguage() { + $("lang").value = StrataI18n.lang; + renderChat(); + setBusy(!!busy); + if (lastMetrics) render(lastMetrics); +} +$("lang").onchange = async () => { + store.set("lang", $("lang").value); + await StrataI18n.setLanguage($("lang").value); + showLanguage(); +}; + // ------------------------------------------------------------------ start -setBusy(false); -renderChat(); -const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut) -if (startQuestion) history.replaceState(null, "", location.pathname + location.hash); -loadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } }); -showTab(location.hash.slice(1) || "chat"); -poll(); +async function start() { + await StrataI18n.setLanguage(urlLang || store.get("lang", "en")); + $("lang").value = StrataI18n.lang; + setBusy(false); + renderChat(); + const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut) + if (startQuestion) history.replaceState(null, "", location.pathname + location.hash); + loadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } }); + showTab(location.hash.slice(1) || "chat"); + poll(); +} +start(); // ------------------------------------------------------------------ images (POST /v1/images/generations) $("img-form").onsubmit = async (ev) => { diff --git a/serve/web/i18n.js b/serve/web/i18n.js new file mode 100644 index 00000000..81defdbb --- /dev/null +++ b/serve/web/i18n.js @@ -0,0 +1,77 @@ +// serve/web/i18n.js - the web page's translations. +// +// The English text sits in the code, next to the key: tr("chat.rewind", "Rewind to here") and +// tr("chat.hidden", {one: "{n} message hidden", other: "{n} messages hidden"}, {n: 3}). Static page text is marked +// data-i18n="key" (also data-i18n-title, data-i18n-label, data-i18n-placeholder) and holds its English text in the HTML. +// So the page reads fine with no catalog at all. Every other language is a catalog, serve/web/locales/.json +// (a flat {"key": "text"} object; a plural is {"one": "...", "other": "..."}, the CLDR names of the language). +// serve/test_web_i18n.py keeps the catalogs complete: same keys as the English text in the code, same {placeholders}. +// +// The language is the user's choice (About > Settings), kept in this browser. Nothing is chosen for them from the +// browser's language: a page that is translated in part would mix two languages. +"use strict"; +(function (root) { + // [code, the language's own name]. A new language is a locales/.json file plus one line here. + const LANGUAGES = [["en", "English"], ["de", "Deutsch"], ["es", "Español"], ["ja", "日本語"], ["ko", "한국어"], + ["pt", "Português"], ["ru", "Русский"], ["zh", "中文"]]; + let lang = "en", catalog = null, rules = null; + + const fill = (s, vars) => String(s).replace(/\{(\w+)\}/g, (m, k) => (vars && k in vars ? String(vars[k]) : m)); + function pick(entry, vars) { + if (entry && typeof entry === "object") { + const n = vars && vars.n != null ? Number(vars.n) : 1; + let cat = "other"; + try { cat = (rules || new Intl.PluralRules(lang === "en" ? "en" : lang)).select(n); } catch (e) { /* other */ } + return entry[cat] != null ? entry[cat] : entry.other != null ? entry.other : entry.one; + } + return entry; + } + // tr(key, english, vars): the catalog's text for the chosen language, else the English text in the code + function tr(key, english, vars) { + const own = catalog && Object.prototype.hasOwnProperty.call(catalog, key) ? catalog[key] : undefined; + const text = pick(own != null ? own : english, vars); + return fill(text == null ? key : text, vars); + } + + // marked page text: the English text is read once from the HTML and kept, so switching back restores it + const ATTRS = [["data-i18n", null], ["data-i18n-title", "title"], ["data-i18n-label", "aria-label"], + ["data-i18n-placeholder", "placeholder"]]; + function apply(scope) { + const doc = scope || root.document; + if (!doc || !doc.querySelectorAll) return; + for (const [mark, attr] of ATTRS) { + for (const el of doc.querySelectorAll(`[${mark}]`)) { + const key = el.getAttribute(mark); + const slot = "en_" + mark.replace(/[^a-z]/g, ""); + if (el.dataset[slot] === undefined) el.dataset[slot] = attr ? (el.getAttribute(attr) || "") : el.textContent; + const text = tr(key, el.dataset[slot]); + if (attr) el.setAttribute(attr, text); else el.textContent = text; + } + } + if (root.document && root.document.documentElement) root.document.documentElement.lang = lang; + } + + const known = (code) => LANGUAGES.some((l) => l[0] === code); + // load a catalog; English, or a catalog that cannot be read, leaves the English text in the code + async function setLanguage(code) { + code = known(code) ? code : "en"; + let next = null; + if (code !== "en") { + try { + const r = await root.fetch(`web/locales/${code}.json`); + const j = r.ok ? await r.json() : null; + if (j && typeof j === "object" && !Array.isArray(j)) next = j; + } catch (e) { /* the English text stays */ } + if (!next) code = "en"; + } + lang = code; catalog = next; rules = null; + try { rules = new Intl.PluralRules(lang); } catch (e) { /* other */ } + apply(); + return lang; + } + + const api = {LANGUAGES, tr, apply, setLanguage, get lang() { return lang; }, fill, pick}; + root.StrataI18n = api; + root.tr = tr; + if (typeof module !== "undefined" && module.exports) module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/serve/web/index.html b/serve/web/index.html index 0c7847f2..0fdb4e6e 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -192,6 +192,11 @@ +
+ + + Chat, its settings and the buttons above are translated. The Monitor, Images and About views are still in English. +
Dark theme

Chats, settings and the key are kept in this browser only. @@ -262,6 +267,7 @@

+ diff --git a/serve/webfiles.py b/serve/webfiles.py new file mode 100644 index 00000000..d79b107d --- /dev/null +++ b/serve/webfiles.py @@ -0,0 +1,35 @@ +"""Which files of serve/web the server hands out below /web/: the page's translations and the vendored KaTeX. + +The flat files (app.js, app.css, ...) are served by serve/server.py itself. The two folders here hold more than one +level, so each has its own whitelist: a name pattern and the types it may have. Nothing outside these folders is ever +read, a name with a backslash, a colon or a percent sign is refused, and the resolved path must stay inside the folder. +""" +from __future__ import annotations + +import re +from pathlib import Path + +WEB = Path(__file__).resolve().parent / "web" + +# /web/locales/.json e.g. de.json, pt-BR.json +LOCALE = re.compile(r"^/web/locales/(?P[a-z]{2,3}(?:-[A-Z]{2})?\.json)$") +# /web/vendor/katex/dist/... : the script, the style sheet and the fonts only +VENDOR_TYPES = {".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".woff2": "font/woff2"} +VENDOR_PREFIX = "/web/vendor/katex/" + + +def subtree_file(path: str, web: Path = WEB): + """(file, content type) for a /web/locales or /web/vendor path, or None when it is not served.""" + if any(c in path for c in ("\\", ":", "%", "\0")) or ".." in path: + return None + m = LOCALE.match(path) + if m: + f = web / "locales" / m.group("name") + return (f, "application/json; charset=utf-8") if f.is_file() else None + if path.startswith(VENDOR_PREFIX): + vendor = (web / "vendor" / "katex").resolve() + f = (vendor / path[len(VENDOR_PREFIX):]).resolve() + ctype = VENDOR_TYPES.get(f.suffix) + if ctype and f.is_relative_to(vendor) and f.is_file(): + return f, ctype + return None diff --git a/tools/web_i18n.py b/tools/web_i18n.py new file mode 100644 index 00000000..747f1101 --- /dev/null +++ b/tools/web_i18n.py @@ -0,0 +1,203 @@ +"""The web page's translations: read the English text out of serve/web, write locales/en.json, check the catalogs. + + python tools/web_i18n.py # check every catalog against the text in the code (exit 1 on a problem) + python tools/web_i18n.py --write # also rewrite serve/web/locales/en.json from the code + +The English text lives in the code (see serve/web/i18n.js): + tr("key", "English text", vars) in serve/web/*.js + tr("key", {one: "{n} chat", other: "{n} chats"}, vars) a plural + English text in serve/web/index.html (also data-i18n-title, -label, -placeholder) +Both must be plain string literals (no template strings, no joined strings), so that this reader and a translator see +the same text. serve/test_web_i18n.py runs the check. +""" +from __future__ import annotations + +import html.parser +import json +import re +import sys +from pathlib import Path + +WEB = Path(__file__).resolve().parents[1] / "serve" / "web" +LOCALES = WEB / "locales" +PLACEHOLDER = re.compile(r"\{(\w+)\}") +CALL = re.compile(r"(? dict: + found = {} + for m in CALL.finditer(src): + key = m.group(1) + i = m.end() + try: + value, _ = _plural(src, i) if src[i] == "{" else _string(src, i) + except Problem as e: + line = src.count("\n", 0, m.start()) + 1 + raise Problem(f"{name}:{line}: tr({key!r}): {e}") + found[key] = value + return found + + +class _Html(html.parser.HTMLParser): + ATTRS = {"data-i18n-title": "title", "data-i18n-label": "aria-label", "data-i18n-placeholder": "placeholder"} + + def __init__(self): + super().__init__(convert_charrefs=True) + self.found: dict = {} + self.open = [] # [(tag, key, [text])] + + def handle_starttag(self, tag, attrs): + a = dict(attrs) + for mark, attr in self.ATTRS.items(): + if mark in a: + self.found[a[mark]] = a.get(attr) or "" + if "data-i18n" in a: + self.open.append((tag, a["data-i18n"], [])) + elif self.open: + self.open.append((tag, None, self.open[-1][2])) + + def handle_data(self, data): + if self.open: + self.open[-1][2].append(data) + + def handle_endtag(self, tag): + if self.open and self.open[-1][0] == tag: + _, key, text = self.open.pop() + if key: + self.found[key] = " ".join("".join(text).split()) + + +def html_strings(src: str) -> dict: + p = _Html() + p.feed(src) + return p.found + + +def english() -> dict: + """Every key in serve/web with its English text; the same key twice must have the same text.""" + out: dict = {} + sources = {p.name: js_strings(p.read_text(encoding="utf-8"), p.name) for p in sorted(WEB.glob("*.js"))} + sources["index.html"] = html_strings((WEB / "index.html").read_text(encoding="utf-8")) + for name, found in sources.items(): + for key, value in found.items(): + if key in out and out[key] != value: + raise Problem(f"{key!r} has two different English texts (one is in {name})") + out[key] = value + return dict(sorted(out.items())) + + +def languages() -> list: + src = (WEB / "i18n.js").read_text(encoding="utf-8") + block = re.search(r"const LANGUAGES = (\[.*?\]);", src, re.S).group(1) + return [m for m in re.findall(r'\["([\w-]+)",', block)] + + +def placeholders(value) -> set: + forms = value.values() if isinstance(value, dict) else [value] + return {name for form in forms for name in PLACEHOLDER.findall(form)} + + +def check_catalog(code: str, catalog: dict, en: dict) -> list: + problems = [] + for key in sorted(set(en) - set(catalog)): + problems.append(f"{code}: missing {key!r}") + for key in sorted(set(catalog) - set(en)): + problems.append(f"{code}: {key!r} is not in the page (renamed or removed?)") + for key, value in catalog.items(): + if key not in en: + continue + forms = value if isinstance(value, dict) else {"": value} + if isinstance(value, dict): + bad = [c for c in value if c not in PLURAL_CATEGORIES] + if bad or "other" not in value: + problems.append(f"{code}: {key!r}: plural forms must be CLDR names with an 'other' form, got {sorted(value)}") + if not isinstance(en[key], dict): + problems.append(f"{code}: {key!r} is a plural here but not in the code") + elif isinstance(en[key], dict): + problems.append(f"{code}: {key!r} is a plain text here but a plural in the code") + for form, text in forms.items(): + if not isinstance(text, str) or not text.strip(): + problems.append(f"{code}: {key!r} {form} is empty or not a string") + if placeholders(value) != placeholders(en[key]) and not ( + isinstance(value, dict) and isinstance(en[key], dict) + and all(placeholders(f) <= placeholders(en[key]) for f in value.values())): + problems.append(f"{code}: {key!r} uses {sorted(placeholders(value))}, the code uses {sorted(placeholders(en[key]))}") + return problems + + +def check(write: bool = False) -> list: + en = english() + if write: + LOCALES.mkdir(exist_ok=True) + (LOCALES / "en.json").write_text(json.dumps(en, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + problems = [] + on_disk = LOCALES / "en.json" + if not on_disk.is_file() or json.loads(on_disk.read_text(encoding="utf-8")) != en: + problems.append("en.json is not the text in the code (python tools/web_i18n.py --write)") + for code in languages(): + if code == "en": + continue + f = LOCALES / f"{code}.json" + if not f.is_file(): + problems.append(f"{code}: serve/web/locales/{code}.json is missing") + continue + problems += check_catalog(code, json.loads(f.read_text(encoding="utf-8")), en) + for f in sorted(LOCALES.glob("*.json")): + if f.stem not in languages(): + problems.append(f"{f.name}: not in LANGUAGES of serve/web/i18n.js") + return problems + + +if __name__ == "__main__": + try: + problems = check(write="--write" in sys.argv) + except Problem as e: + print(f"web_i18n: {e}") + sys.exit(1) + for p in problems: + print("web_i18n:", p) + sys.exit(1 if problems else 0) From a965c962cfea5c225ae40bd02a143d63b203b58d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:52:56 +0100 Subject: [PATCH 132/177] Web chat: draw math with the bundled KaTeX, opt-in and offline (#2972, #2974) Chat settings > Render math (off by default). When it is on, \( \), \[ \], $x$ and $$ $$ in an answer are drawn as formulas by KaTeX 0.19.0, which is vendored in serve/web/vendor/katex (script, style, 20 woff2 fonts, MIT licence and a PROVENANCE.json with the npm integrity and the sha256 of every file, so the page needs no network). Nothing of KaTeX loads until an answer holds a formula. The shared core (math.js, from #2972) keeps the text of every message exactly as the model wrote it: formulas are swapped for placeholders before the Markdown runs and drawn over them afterwards, so history, copying, the Markdown export and the requests never see the drawing. Code, link targets, prices ($5 and $10) and a formula still being streamed stay text. A formula that fails, is over 16 KiB or times out stays as its source text. Safety: KaTeX runs with trust off (no \href, \url, \includegraphics, \htmlClass: they are drawn as their own name), maxExpand 1000, maxSize 20 and a fresh macro table per formula; it builds DOM nodes itself, so no HTML string from a model reaches the page. A formula already drawn is placed again at once while an answer streams, so it does not flicker back to source. serve/test_web_math.js runs the real vendored KaTeX against hostile formulas; serve/test_web_math.py checks the vendored files against PROVENANCE.json and that nothing outside this server is addressed. serve/web/vendor is -text in .gitattributes so the hashes hold on a Windows checkout. Ported by hand from PRs #2972 (core) and #2974 (KaTeX) by CC-David-CC. Co-authored-by: David <336302908+CC-David-CC@users.noreply.github.com> --- .gitattributes | 3 + serve/test_web_math.js | 170 ++++++++++++++++++ serve/test_web_math.py | 107 +++++++++++ serve/web/app.css | 7 + serve/web/app.js | 21 ++- serve/web/index.html | 5 + serve/web/math-adapter.js | 34 ++++ serve/web/math.js | 142 +++++++++++++++ serve/web/vendor/katex/LICENSE | 21 +++ serve/web/vendor/katex/PROVENANCE.json | 34 ++++ .../katex/dist/fonts/KaTeX_AMS-Regular.woff2 | Bin 0 -> 28076 bytes .../dist/fonts/KaTeX_Caligraphic-Bold.woff2 | Bin 0 -> 6912 bytes .../fonts/KaTeX_Caligraphic-Regular.woff2 | Bin 0 -> 6908 bytes .../katex/dist/fonts/KaTeX_Fraktur-Bold.woff2 | Bin 0 -> 11348 bytes .../dist/fonts/KaTeX_Fraktur-Regular.woff2 | Bin 0 -> 11316 bytes .../katex/dist/fonts/KaTeX_Main-Bold.woff2 | Bin 0 -> 25324 bytes .../dist/fonts/KaTeX_Main-BoldItalic.woff2 | Bin 0 -> 16780 bytes .../katex/dist/fonts/KaTeX_Main-Italic.woff2 | Bin 0 -> 16988 bytes .../katex/dist/fonts/KaTeX_Main-Regular.woff2 | Bin 0 -> 26272 bytes .../dist/fonts/KaTeX_Math-BoldItalic.woff2 | Bin 0 -> 16400 bytes .../katex/dist/fonts/KaTeX_Math-Italic.woff2 | Bin 0 -> 16440 bytes .../dist/fonts/KaTeX_SansSerif-Bold.woff2 | Bin 0 -> 12216 bytes .../dist/fonts/KaTeX_SansSerif-Italic.woff2 | Bin 0 -> 12028 bytes .../dist/fonts/KaTeX_SansSerif-Regular.woff2 | Bin 0 -> 10344 bytes .../dist/fonts/KaTeX_Script-Regular.woff2 | Bin 0 -> 9644 bytes .../dist/fonts/KaTeX_Size1-Regular.woff2 | Bin 0 -> 5468 bytes .../dist/fonts/KaTeX_Size2-Regular.woff2 | Bin 0 -> 5208 bytes .../dist/fonts/KaTeX_Size3-Regular.woff2 | Bin 0 -> 3624 bytes .../dist/fonts/KaTeX_Size4-Regular.woff2 | Bin 0 -> 4928 bytes .../dist/fonts/KaTeX_Typewriter-Regular.woff2 | Bin 0 -> 13568 bytes serve/web/vendor/katex/dist/katex.min.css | 1 + serve/web/vendor/katex/dist/katex.min.js | 1 + 32 files changed, 542 insertions(+), 4 deletions(-) create mode 100644 serve/test_web_math.js create mode 100644 serve/test_web_math.py create mode 100644 serve/web/math-adapter.js create mode 100644 serve/web/math.js create mode 100644 serve/web/vendor/katex/LICENSE create mode 100644 serve/web/vendor/katex/PROVENANCE.json create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_AMS-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Caligraphic-Bold.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Caligraphic-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Fraktur-Bold.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Fraktur-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Main-Bold.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Main-BoldItalic.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Main-Italic.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Main-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Math-BoldItalic.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Math-Italic.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_SansSerif-Bold.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_SansSerif-Italic.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_SansSerif-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Script-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Size1-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Size2-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Size3-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Size4-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/fonts/KaTeX_Typewriter-Regular.woff2 create mode 100644 serve/web/vendor/katex/dist/katex.min.css create mode 100644 serve/web/vendor/katex/dist/katex.min.js diff --git a/.gitattributes b/.gitattributes index e9e15ba7..8a835e52 100644 --- a/.gitattributes +++ b/.gitattributes @@ -25,3 +25,6 @@ docker/compose/* text eol=lf # Apple tools (codesign, plutil) read these: LF only, wherever the repository is cloned *.plist text eol=lf + +# vendored KaTeX (serve/web/vendor): the files are hashed byte for byte (PROVENANCE.json), never convert their line endings. +serve/web/vendor/** -text diff --git a/serve/test_web_math.js b/serve/test_web_math.js new file mode 100644 index 00000000..76ad9e39 --- /dev/null +++ b/serve/test_web_math.js @@ -0,0 +1,170 @@ +// Chat math (serve/web/math.js + math-adapter.js + the vendored KaTeX), run in Node. +// node serve/test_web_math.js (serve/test_web_math.py runs it too and skips when node is missing) +// +// 1. where a formula starts and ends (prices, code, links, half-written formulas); +// 2. the Markdown step: the model's text is escaped, a formula's source only ever reaches the page escaped; +// 3. drawing: a stub adapter and a stub DOM (order, cache, stale answers, errors, size limit); +// 4. safety: the REAL vendored KaTeX with the adapter's options, fed hostile formulas. +"use strict"; +const assert = require("node:assert/strict"); +const path = require("node:path"); + +const web = path.join(__dirname, "web"); +const math = require(path.join(web, "math.js")); +const {split} = math; +const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); +const unesc = (s) => s.replace(/&(amp|lt|gt|quot|#39);/g, (m, k) => ({amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'"}[k])); +const sources = (text) => split(text).filter((p) => p.source !== undefined).map((p) => [p.source, p.display]); + +const cases = { + split_delimiters() { + assert.deepEqual(sources("a $x^2$ b"), [["x^2", false]]); + assert.deepEqual(sources("a \\(x+1\\) b"), [["x+1", false]]); + assert.deepEqual(sources("a $$\\int_0^1 f$$ b"), [["\\int_0^1 f", true]]); + assert.deepEqual(sources("a \\[\\sum_i i\\] b"), [["\\sum_i i", true]]); + assert.deepEqual(sources("$$\nx = 1\n$$"), [["\nx = 1\n", true]], "display math may span lines"); + assert.deepEqual(sources("$a$ and $b$"), [["a", false], ["b", false]]); + // the text around a formula is kept whole + assert.equal(split("a $x$ b").map((p) => p.raw).join(""), "a $x$ b"); + }, + split_not_math() { + for (const text of ["It costs $5.", "$5 and $10", "from $5 to $10 each", "$ 5 $", "a $ b", "price: $1,000", "cost $5 USD, $6 EUR", + "no formula here", "\\$x\\$", "a \\( unfinished", "100$"]) { + assert.deepEqual(sources(text), [], text); + } + assert.deepEqual(sources("`$x$` and ```\n$$y$$\n```"), [], "code is code"); + assert.deepEqual(sources("```js\nlet a = '$x$'\n```\n$z$"), [["z", false]], "a closed fence ends"); + assert.deepEqual(sources("~~~\n\\(a\\)\n~~~"), [], "tilde fences too"); + assert.deepEqual(sources("[x](https://example.com/$a$/b) $c$"), [["c", false]], "a link target is not math"); + }, + split_streaming() { + const parts = split("see $$x^2 + "); + assert.equal(parts.length, 2); + assert.equal(parts[1].incomplete, true, "a formula still being written is plain text"); + assert.equal(parts[1].source, undefined); + assert.equal(split("```\n$$never closed").filter((p) => p.source !== undefined).length, 0, "an open fence swallows the rest"); + }, + markdown_escapes_everything() { + const fmt = (t) => `

${esc(t)}

`; + const html = math.markdown("hi there $x\"'$ and ", fmt); + assert.ok(html.includes("<b>there</b>") && html.includes("<script>"), "the model's own tags are escaped"); + assert.ok(!//.test(html), html); + // the source sits in one attribute, URL-encoded, and as escaped text + const m = /data-math="([^"]*)"/.exec(html); + assert.ok(m, html); + assert.equal(decodeURIComponent(unesc(m[1])), "x\"'", "the attribute (as the browser reads it) holds the source"); + assert.ok(!m[1].includes("<") && !m[1].includes('"')); + assert.ok(html.includes("$x<y>"'$"), "the visible fallback is the escaped source"); + // an attribute break-out in the source stays in the attribute + const evil = math.markdown('$x" onmouseover="alert(1)$', fmt); + assert.equal((evil.match(/]*)>/.exec(evil)[1]; + assert.deepEqual([...tag.matchAll(/(?:^|\s)([\w-]+)="/g)].map((x) => x[1]), ["class", "data-math", "data-display"], "no attribute of the model's"); + }, + markdown_keeps_source_text() { + const text = "a $x$ and \\(y\\)"; + const seen = []; + math.markdown(text, (t) => { seen.push(t); return t; }); + assert.equal(text, "a $x$ and \\(y\\)", "strings are values, but the function must also not need a copy"); + assert.ok(!/\$x\$|\\\(y\\\)/.test(seen[0]), "the Markdown step sees placeholders, not formulas"); + // a message that contains the placeholder word itself is not confused + const html = math.markdown("STRATAMATHPLACEHOLDER0END and $x$", (t) => t); + assert.ok(html.startsWith("STRATAMATHPLACEHOLDER0END and ({querySelectorAll: () => slots, contains: (s) => slots.includes(s)}); + const mk = (tag) => ({tag, cloneNode() { return {tag, cloned: true}; }}); + globalThis.StrataMathAdapter = { + async initialize() { calls.push("init"); }, + async render(source, {display}) { + calls.push("render " + source); + if (source === "bad") return {ok: false, reason: "invalid"}; + return {ok: true, element: mk(source)}; + }, + }; + math.reset(); + const a = new Slot("x", false), b = new Slot("bad", false), c = new Slot("x", true); + const container = box([a, b, c]); + math.hydrate(container); + await new Promise((r) => setTimeout(r, 20)); + assert.deepEqual(calls, ["init", "render x", "render bad", "render x"], "one at a time, started once"); + assert.equal(a.children[0].tag, "x"); assert.equal(c.children[0].tag, "x"); + assert.equal(b.dataset.mathError, "invalid"); assert.ok(b.children.length === 0, "a bad formula stays source text"); + assert.match(b.title, /invalid/); + // drawn before: placed at once (no flicker while an answer streams), without another render + const again = new Slot("x", false); + math.hydrate(box([again])); + assert.equal(again.children[0].tag, "x", "placed synchronously from the cache"); + assert.equal(calls.length, 4); + // an answer that was replaced while a formula was drawn does not get the old drawing + const old = new Slot("slow", false); + const stale = box([old]); + globalThis.StrataMathAdapter.render = async (s) => { await new Promise((r) => setTimeout(r, 15)); return {ok: true, element: mk(s)}; }; + math.hydrate(stale); + math.hydrate(box([])); // a different container is a different generation; the same container is bumped below + stale._mathGeneration++; + await new Promise((r) => setTimeout(r, 40)); + assert.equal(old.children.length, 0, "stale generation ignored"); + // a formula over 16 KiB is not drawn, and no adapter means source text + assert.deepEqual(await math.result("x".repeat(20000), false), {ok: false, reason: "limit"}); + math.reset(); delete globalThis.StrataMathAdapter; + assert.deepEqual(await math.result("y", false), {ok: false, reason: "unavailable"}); + math.reset(); globalThis.StrataMathAdapter = {initialize: async () => { throw new Error("no engine"); }, render: async () => ({ok: true})}; + assert.deepEqual(await math.result("z", false), {ok: false, reason: "unavailable"}, "an engine that cannot start leaves the source"); + delete globalThis.StrataMathAdapter; + }, + katex_options_are_the_safe_ones() { + const {OPTIONS} = require(path.join(web, "math-adapter.js")); + assert.equal(OPTIONS.trust, false, "no \\href, \\url, \\includegraphics, \\htmlClass ..."); + assert.equal(OPTIONS.throwOnError, true, "an error returns the source, not a red error box"); + assert.ok(OPTIONS.maxExpand <= 1000 && OPTIONS.maxSize <= 20, "macro loops and huge sizes are cut"); + }, + katex_hostile_input() { + const katex = require(path.join(web, "vendor", "katex", "dist", "katex.min.js")); + const {OPTIONS} = require(path.join(web, "math-adapter.js")); + const draw = (src, display = false) => katex.renderToString(src, {...OPTIONS, displayMode: display, macros: {}}); + // with trust off these commands are not run: KaTeX draws the command's name in red, as text. There is no link, picture, + // style, id, class or data attribute of the model's making in the result. + const mathml = (h) => h.replace(/]*>[\s\S]*?<\/annotation>/g, ""); + for (const [src, name] of [["\\href{javascript:alert(1)}{click}", "\\href"], ["\\url{javascript:alert(1)}", "\\url"], + ["\\href{https://example.com}{x}", "\\href"], ["\\includegraphics{https://example.com/p.png}", "\\includegraphics"], + ["\\htmlClass{evil}{b}", "\\htmlClass"], ["\\htmlId{evil}{b}", "\\htmlId"], + ["\\htmlStyle{color:red}{b}", "\\htmlStyle"], ["\\htmlData{evil=1}{b}", "\\htmlData"]]) { + const html = mathml(draw(src)); + assert.ok(html.includes(`${name}`), src + " is drawn as its own name: " + html.slice(0, 200)); + assert.ok(!/ " + html); + } + for (const src of ["", "\\text{}", "a < b > c \\& d \" '", + "\\text{}", "\\mathrm{javascript:alert(1)}", "x_{}"]) { + const html = draw(src); + // the output may contain the text, but only as text: no tag the model wrote exists + assert.ok(!/<(img|script|svg|iframe|a)\b/i.test(html.replace(/]*>[\s\S]*?<\/annotation>/g, "")), src + " -> " + html); + const tags = (html.match(/<[a-zA-Z][^>]*>/g) || []).join(" "); + assert.ok(!/\son\w+\s*=|javascript:|\ssrc\s*=|\shref\s*=/i.test(tags), "no event handler, link or source in any tag: " + src); + } + // the TeX source is kept in an as escaped text, never as markup + const kept = draw(""); + assert.ok(!kept.includes(" draw("\\def\\a{\\a\\a}\\a"), /expansion|Too many/i, "a macro loop is cut"); + const rule = mathml(draw("\\rule{100em}{100em}")); + assert.ok(rule.includes("20em") && !rule.includes("100em"), "a huge rule is cut to maxSize"); + // macros are not shared between formulas + draw("\\gdef\\foo{1}\\foo"); + assert.throws(() => draw("\\foo"), /Undefined control sequence/); + // and a good formula still draws + assert.match(draw("\\frac{a}{b} + \\sqrt{x}"), /class="katex"/); + }, +}; + +(async () => { + const name = process.argv[2]; + const run = name ? [[name, cases[name]]] : Object.entries(cases); + if (name && !cases[name]) throw new Error("unknown test " + name); + for (const [n, fn] of run) { await fn(); console.log("ok " + n); } +})().catch((e) => { console.error(e); process.exitCode = 1; }); diff --git a/serve/test_web_math.py b/serve/test_web_math.py new file mode 100644 index 00000000..2c5a2b83 --- /dev/null +++ b/serve/test_web_math.py @@ -0,0 +1,107 @@ +"""Chat math on the served page (serve/web/math.js, math-adapter.js, vendor/katex): opt-in, offline, no scripts from the model.""" +from __future__ import annotations + +import hashlib +import json +import re +import shutil +import subprocess +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + +WEB = Path(__file__).parent / "web" +KATEX = WEB / "vendor" / "katex" + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class MathInNode(unittest.TestCase): + def test_delimiters_escaping_drawing_and_hostile_formulas(self): + r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_math.js"))], + capture_output=True, text=True, timeout=120) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +class Vendored(unittest.TestCase): + def test_the_files_are_the_ones_in_provenance(self): + prov = json.loads((KATEX / "PROVENANCE.json").read_text(encoding="utf-8")) + self.assertEqual((prov["package"], prov["version"], prov["license"]), ("katex", "0.19.0", "MIT")) + self.assertTrue(prov["integrity"].startswith("sha512-")) + on_disk = {p.relative_to(KATEX).as_posix() for p in KATEX.rglob("*") if p.is_file() and p.name != "PROVENANCE.json"} + self.assertEqual(on_disk, set(prov["sha256"]), "a file was added or removed without PROVENANCE.json") + for name, digest in prov["sha256"].items(): + with self.subTest(name=name): + self.assertEqual(hashlib.sha256((KATEX / name).read_bytes()).hexdigest(), digest) + self.assertTrue((KATEX / "LICENSE").read_text(encoding="utf-8").startswith("The MIT License")) + + def test_it_works_offline(self): + css = (KATEX / "dist" / "katex.min.css").read_text(encoding="utf-8") + fonts = set(re.findall(r"url\(fonts/([\w-]+\.woff2)\)", css)) + self.assertEqual(len(fonts), 20) + for font in fonts: + self.assertTrue((KATEX / "dist" / "fonts" / font).is_file(), font) + # no address outside this server in anything that loads on the page + for f in (WEB / "math.js", WEB / "math-adapter.js", KATEX / "dist" / "katex.min.css"): + self.assertNotRegex(f.read_text(encoding="utf-8"), r"https?://(?!www\.w3\.org)", f.name) + self.assertNotIn("@import", css) + + def test_the_page_loads_nothing_until_math_is_on(self): + html = (WEB / "index.html").read_text(encoding="utf-8") + js = (WEB / "app.js").read_text(encoding="utf-8") + self.assertIn('src="web/math.js"', html) + self.assertIn('src="web/math-adapter.js"', html) + self.assertNotIn("katex", html.lower().replace("math-adapter", ""), "KaTeX is not named in the page: the adapter loads it") + self.assertIn("math: false", js, "off by default") + self.assertIn('id="s-math"', html) + self.assertIn('aria-checked="false"', re.search(r']*id="s-math"[^>]*>', html).group(0)) + adapter = re.sub(r"^\s*//.*$", "", (WEB / "math-adapter.js").read_text(encoding="utf-8"), flags=re.M) # the code, not its comments + self.assertIn("trust: false", adapter) + self.assertNotIn("innerHTML", adapter) + self.assertNotIn("renderToString", adapter, "KaTeX builds DOM nodes; no HTML string goes into the page") + + +class Served(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def get(self, path): + try: + with urllib.request.urlopen(self.base + path, timeout=10) as r: + return r.status, r.headers.get("Content-Type", ""), r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers.get("Content-Type", ""), e.read() + + def test_scripts_style_and_fonts_are_served(self): + for path, want in (("/web/math.js", "javascript"), ("/web/math-adapter.js", "javascript"), + ("/web/vendor/katex/dist/katex.min.js", "javascript"), + ("/web/vendor/katex/dist/katex.min.css", "text/css"), + ("/web/vendor/katex/dist/fonts/KaTeX_Main-Regular.woff2", "font/woff2")): + with self.subTest(path=path): + code, ctype, body = self.get(path) + self.assertEqual(code, 200) + self.assertIn(want, ctype) + self.assertTrue(body) + + def test_nothing_else_below_vendor(self): + for path in ("/web/vendor/katex/PROVENANCE.json", "/web/vendor/katex/LICENSE", "/web/vendor/katex/dist/fonts/x.ttf", + "/web/vendor/katex/../../app.js", "/web/vendor/", "/web/vendor/katex/dist/fonts", + "/web/vendor/katex/dist/missing.js"): + with self.subTest(path=path): + self.assertEqual(self.get(path)[0], 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css index 1191b041..e899121b 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -221,3 +221,10 @@ main { flex: 1; min-height: 0; display: flex; } .img-results figure{margin:0} .img-results img{max-width:100%;border-radius:var(--st-r-lg);display:block} .img-results figcaption{font-size:var(--st-fs-sm, 13px);color:var(--st-ink-2, inherit);margin-top:4px} + +/* Math (serve/web/math.js): a formula never widens the chat; a long display formula scrolls inside its own box. */ +.chat-math { overflow-wrap: normal; } +.chat-math--display { display: block; text-align: center; overflow-x: auto; max-width: 100%; margin: .6em 0; padding: .25em 0; } +.chat-math--display > * { margin: 0 !important; } +.chat-math[data-math-error] { white-space: pre-wrap; } +.chat-math .katex { font-size: 1.08em; } diff --git a/serve/web/app.js b/serve/web/app.js index b3448d92..ef81c9bb 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -573,7 +573,7 @@ function markdown(text) { // fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking // 0.7 / 0.8 / 20 with a presence penalty). Before 0.1.45 the page sent 0.6 itself; a stored 0.6 with the other two // values untouched counts as "not set" too. -const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true}; +const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false}; const OLD_DEFAULT_TEMPERATURE = 0.6; function samplingUntouched(s) { const t = +s.temperature; @@ -658,16 +658,20 @@ function toolHtml(t, k) { `${icon("chevron", "st-icon st-icon--sm st-chev")}
${body}
`; } // the answer's text with the tool blocks where the model called them +// math (opt-in, serve/web/math.js): formulas become placeholders before the Markdown runs and are drawn after it +function answerMarkdown(text) { + return settings.math ? StrataMath.markdown(text, markdown) : markdown(text); +} function answerHtml(m) { - if (!m.tools || !m.tools.length) return markdown(m.text || ""); + if (!m.tools || !m.tools.length) return answerMarkdown(m.text || ""); let html = "", pos = 0; m.tools.forEach((t, k) => { const at = Math.min(Math.max(t.at || 0, pos), m.text.length); - if (at > pos) html += markdown(m.text.slice(pos, at)); + if (at > pos) html += answerMarkdown(m.text.slice(pos, at)); pos = at; html += toolHtml(t, k); }); - return html + markdown(m.text.slice(pos)); + return html + answerMarkdown(m.text.slice(pos)); } // a tool event from the stream (the `strata_mcp` field of a chunk) function onTool(m, x) { @@ -704,6 +708,7 @@ function updateAssistant(el, m, streaming) { bubble.innerHTML = m.reasoning ? `Writing` : ``; } else { bubble.innerHTML = answerHtml(m); + if (settings.math) StrataMath.hydrate(bubble); if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor"); } el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? "Stopped" : ""); @@ -1013,6 +1018,7 @@ function loadDrawer(s = settings) { for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking)); $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k; $("s-max").value = s.max; $("s-seed").value = s.seed; + $("s-math").setAttribute("aria-checked", String(!!s.math)); $("s-show").setAttribute("aria-checked", String(!!s.show)); $("s-esp").setAttribute("aria-checked", String(s.esp !== false)); $("esp-row").hidden = !projectionLoaded(); @@ -1064,6 +1070,7 @@ function outputs() { } for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs; +$("s-math").onclick = () => $("s-math").setAttribute("aria-checked", String($("s-math").getAttribute("aria-checked") !== "true")); $("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true")); $("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true")); $("s-mcp").onclick = () => $("s-mcp").setAttribute("aria-checked", String($("s-mcp").getAttribute("aria-checked") !== "true")); @@ -1073,10 +1080,16 @@ $("s-apply").onclick = async () => { const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(), + math: $("s-math").getAttribute("aria-checked") === "true", show: $("s-show").getAttribute("aria-checked") === "true", esp: $("s-esp").getAttribute("aria-checked") === "true", mcp: $("s-mcp").getAttribute("aria-checked") === "true"}; store.set("sampling", settings); + StrataMath.reset(); // math on or off: every answer is drawn again + for (const el of $("chat").querySelectorAll(".st-msg--assistant")) { + const m = messages[+el.dataset.i]; + updateAssistant(el, m, !!busy && busy.msg === m); // the element send() holds stays the same while an answer streams + } const share = $("s-share").getAttribute("aria-checked") === "true"; openDrawer(false); if (share || sharedOn) { diff --git a/serve/web/index.html b/serve/web/index.html index 0fdb4e6e..f08271ba 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -248,6 +248,9 @@ +
Render math
draw equations in answers as formulas (works offline)
+
Show thinking
expanded while it streams
+ + diff --git a/serve/web/math-adapter.js b/serve/web/math-adapter.js new file mode 100644 index 00000000..7be74c8f --- /dev/null +++ b/serve/web/math-adapter.js @@ -0,0 +1,34 @@ +// serve/web/math-adapter.js - the KaTeX renderer for math.js (PR #2974 by CC-David-CC). KaTeX 0.19.0 is vendored in +// serve/web/vendor/katex (MIT, see PROVENANCE.json there): no network, no CDN. Nothing is loaded until "Render math" is +// switched on and an answer holds a formula. +// +// What a formula may do: nothing but draw. `trust: false` turns off \href, \url, \includegraphics and \htmlClass-style +// commands, so a formula cannot make a link, load a picture or add an attribute; the macros are not shared between +// formulas; \def loops are cut by maxExpand and a huge \rule or \kern by maxSize. KaTeX builds DOM nodes itself (no +// innerHTML), the result is cloned into the page by math.js, and an error returns the source text instead. +"use strict"; +(function (root) { + const OPTIONS = {output: "htmlAndMathml", trust: false, throwOnError: true, strict: "ignore", maxExpand: 1000, maxSize: 20}; + const adapter = { + OPTIONS, + async initialize() { + if (root.katex && document.querySelector("link[data-katex-ready]")) return; + const css = document.createElement("link"); css.rel = "stylesheet"; + css.href = "web/vendor/katex/dist/katex.min.css"; + const loaded = new Promise((resolve, reject) => { css.onload = resolve; css.onerror = reject; }); + document.head.append(css); + await Promise.all([loaded, root.katex ? Promise.resolve() : root.StrataMath.script("web/vendor/katex/dist/katex.min.js")]); + css.dataset.katexReady = "1"; + }, + async render(source, {display, signal}) { + if (signal.aborted) return {ok: false, reason: "unavailable"}; + const element = document.createElement("span"); + try { + root.katex.render(source, element, {...OPTIONS, displayMode: display, macros: {}}); + return {ok: true, element: element.firstElementChild}; + } catch (_) { return {ok: false, reason: "invalid"}; } + }, + }; + root.StrataMathAdapter = adapter; + if (typeof module !== "undefined" && module.exports) module.exports = adapter; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/serve/web/math.js b/serve/web/math.js new file mode 100644 index 00000000..15e295f5 --- /dev/null +++ b/serve/web/math.js @@ -0,0 +1,142 @@ +// serve/web/math.js - chat math that never changes the source. Engine-independent: a renderer (math-adapter.js) is plugged in. +// Ported from PR #2972 by CC-David-CC. The text of a message stays as the model wrote it (history, copying, the Markdown +// export and the requests all use it); math is only drawn over a placeholder in the page, and a formula that cannot be drawn +// stays as its source text. +"use strict"; +(function (root) { + const escape = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); + const escaped = (s, i) => { let n = 0; while (i > 0 && s[--i] === "\\") n++; return n % 2 === 1; }; + + // split(text) -> [{raw}, {source, display, raw}, {raw, incomplete: true}, ...] + // \( \) and $x$ are inline, \[ \] and $$ $$ are display. Code (fences, `spans`), Markdown link targets and prices ($5 and + // $10) are not math. A formula that is still being written (no closing delimiter yet) stays plain text. + function split(text) { + const parts = []; let start = 0, i = 0; + const push = (end, math) => { if (start < i) parts.push({raw: text.slice(start, i)}); parts.push(math); start = i = end; }; + while (i < text.length) { + // Code takes precedence, including incomplete fences while streaming. + const fence = (i === 0 || text[i - 1] === "\n") && text.slice(i).match(/^ {0,3}(`{3,}|~{3,})[^\n]*\n/); + if (fence) { + const marker = fence[1][0], count = fence[1].length; + const end = new RegExp("^ {0,3}" + marker + "{" + count + ",}[ \\t]*(?:\\n|$)", "m").exec(text.slice(i + fence[0].length)); + i = end ? i + fence[0].length + end.index + end[0].length : text.length; continue; + } + if (text[i] === "`" && !escaped(text, i)) { + const ticks = text.slice(i).match(/^`+/)[0]; let end = text.indexOf(ticks, i + ticks.length); + while (end >= 0 && (text[end - 1] === "`" || text[end + ticks.length] === "`")) end = text.indexOf(ticks, end + ticks.length); + i = end < 0 ? text.length : end + ticks.length; continue; + } + if (escaped(text, i)) { i++; continue; } + // Never inject a math element into a Markdown link's href attribute. + if (text.startsWith("](http", i)) { + const end = text.indexOf(")", i + 2); + i = end < 0 ? text.length : end + 1; continue; + } + let open, close, display; + if (text.startsWith("\\(", i)) { open = "\\("; close = "\\)"; display = false; } + else if (text.startsWith("\\[", i)) { open = "\\["; close = "\\]"; display = true; } + else if (text.startsWith("$$", i)) { open = close = "$$"; display = true; } + else if (text[i] === "$" && !/\s/.test(text[i + 1] || " ") && text[i - 1] !== "$") { open = close = "$"; display = false; } + if (!open) { i++; continue; } + let end = text.indexOf(close, i + open.length); + while (end >= 0 && (escaped(text, end) || (close === "$" && (/\s/.test(text[end - 1]) || /[\d$]/.test(text[end + 1] || ""))))) end = text.indexOf(close, end + close.length); + const source = end >= 0 ? text.slice(i + open.length, end) : text.slice(i + open.length); + // Numeric prices are text, even when separated by a second dollar amount. + if (open === "$" && (/\n/.test(source) || /\$/.test(source) || + /^\d[\d,.]*(?:\s*[A-Za-z]|\s*$)/.test(source))) { i++; continue; } + if (end < 0) { push(text.length, {raw: text.slice(i), incomplete: true}); break; } + push(end + close.length, {source, display, raw: text.slice(i, end + close.length)}); + } + if (start < text.length) parts.push({raw: text.slice(start)}); + return parts; + } + + // markdown(text, format): format() is the page's Markdown, run on the text with every formula swapped for a placeholder + // word, then each word becomes holding the escaped source until it is drawn. + function markdown(text, format) { + let prefix = "STRATAMATHPLACEHOLDER"; while (text.includes(prefix)) prefix += "X"; + const slots = []; + const protectedText = split(text).map((p) => { + if (p.source === undefined && !p.incomplete) return p.raw; + const key = prefix + slots.length + "END"; + slots.push(p); return key; + }).join(""); + let html = format(protectedText); + slots.forEach((p, i) => { + const body = p.incomplete ? escape(p.raw) : `${escape(p.raw)}`; + html = html.replaceAll(prefix + i + "END", () => body); + }); + return html; + } + + // drawing: one formula at a time (an engine may keep state between formulas), 256 results cached, a 10 s deadline for the + // engine to start and 15 s for one formula. A formula over 16 KiB is not drawn. The adapter returns an element that is not + // in the page; the core clones it into the placeholder if that is still on the screen. + const cache = new Map(), done = new Map(); + let initialization = null, queue = Promise.resolve(), epoch = 0; + function reset() { cache.clear(); done.clear(); initialization = null; epoch++; } + const keyOf = (source, display) => JSON.stringify([source, display]); + async function result(source, display) { + if (new TextEncoder().encode(source).length > 16384) return {ok: false, reason: "limit"}; + const key = keyOf(source, display); + if (cache.has(key)) { const hit = cache.get(key); cache.delete(key); cache.set(key, hit); return hit; } + if (cache.size >= 256) { const old = cache.keys().next().value; cache.delete(old); done.delete(old); } + const current = epoch; let work; + const task = queue.then(async () => { + if (epoch !== current || cache.get(key) !== task) return {ok: false, reason: "unavailable"}; + try { + const adapter = root.StrataMathAdapter; + if (!adapter) return {ok: false, reason: "unavailable"}; + initialization ||= Promise.race([adapter.initialize(), new Promise((_, reject) => + setTimeout(() => reject(new Error("Math initialization timed out")), 10000))]); + await initialization; + const signal = AbortSignal.timeout(15000); + let onAbort; + const deadline = new Promise((resolve) => { + onAbort = () => resolve({ok: false, reason: "limit"}); + signal.addEventListener("abort", onAbort, {once: true}); + }); + work = Promise.resolve(adapter.render(source, {display, signal})); + try { return await Promise.race([work, deadline]); } + finally { signal.removeEventListener("abort", onAbort); } + } catch (_) { return {ok: false, reason: "unavailable"}; } + }); + // A browser engine may ignore cancellation. Return source at the deadline, + // but do not overlap conversions that mutate the engine's macro state. + queue = task.then(() => work, () => work).then(() => undefined, () => undefined); + cache.set(key, task); + task.then((r) => { if (cache.get(key) === task) done.set(key, r); }); + return task; + } + + function place(slot, r, tr) { + if (r.ok) slot.replaceChildren(r.element.cloneNode(true)); + else { slot.dataset.mathError = r.reason; slot.title = tr ? tr("math.source", "Math source ({reason})", {reason: r.reason}) : "Math source (" + r.reason + ")"; } + } + // hydrate(container): draw the placeholders in a container. A formula drawn before is placed at once, so a streaming + // answer that is rebuilt on every frame does not flicker back to source text. + function hydrate(container) { + const generation = container._mathGeneration = (container._mathGeneration || 0) + 1; + for (const slot of container.querySelectorAll("[data-math]")) { + const source = decodeURIComponent(slot.dataset.math), display = slot.dataset.display === "1"; + const known = done.get(keyOf(source, display)); + if (known && known.ok) { place(slot, known, root.tr); continue; } + result(source, display).then((r) => { + if (generation !== container._mathGeneration || !container.contains(slot)) return; + place(slot, r, root.tr); + }); + } + } + function script(url) { + return new Promise((resolve, reject) => { + const s = document.createElement("script"); s.src = url; + const timer = setTimeout(() => { s.remove(); reject(new Error("Math script timed out")); }, 10000); + s.onload = () => { clearTimeout(timer); resolve(); }; + s.onerror = () => { clearTimeout(timer); s.remove(); reject(new Error("Math script unavailable")); }; + document.head.append(s); + }); + } + const api = {split, markdown, hydrate, reset, script, result}; + root.StrataMath = api; + if (typeof module !== "undefined" && module.exports) module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/serve/web/vendor/katex/LICENSE b/serve/web/vendor/katex/LICENSE new file mode 100644 index 00000000..37c6433e --- /dev/null +++ b/serve/web/vendor/katex/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2020 Khan Academy and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/serve/web/vendor/katex/PROVENANCE.json b/serve/web/vendor/katex/PROVENANCE.json new file mode 100644 index 00000000..9f713bf8 --- /dev/null +++ b/serve/web/vendor/katex/PROVENANCE.json @@ -0,0 +1,34 @@ +{ + "package": "katex", + "version": "0.19.0", + "url": "https://registry.npmjs.org/katex/-/katex-0.19.0.tgz", + "integrity": "sha512-v6Tznz3zJ7u3niRCoDTsumM2+HA2XXcCu+WAacCeHD2z3p9A9Ks987o5FzfTGBN0e8A0vjEgIDvLbICrXpdw/Q==", + "license": "MIT", + "verified": "the tarball's sha512 was checked against the integrity above when these files were copied from package/dist (2026-10-26)", + "changes": "dist/katex.min.css lost the .woff and .ttf fallbacks of its 20 @font-face rules (every browser that runs this page reads woff2); nothing else was edited. katex.min.js and the 20 woff2 fonts are the package's files unchanged.", + "sha256": { + "LICENSE": "766ccc1f306c885aa45542a9846bbd0a505b27a0374f146778171c2254ce18e3", + "dist/fonts/KaTeX_AMS-Regular.woff2": "0cdd387c9590a1a9f9794560022dbb59654a7d86f187aa0c81495ad42d3a7308", + "dist/fonts/KaTeX_Caligraphic-Bold.woff2": "de7701e42cf1f4cf0b766c03fb27977207eee2f4fd5d76fa82188406da43ea4c", + "dist/fonts/KaTeX_Caligraphic-Regular.woff2": "5d53e70ad607c2352162dec9e0923fb54ecdafaccbf604cd8dcf7d00facb989b", + "dist/fonts/KaTeX_Fraktur-Bold.woff2": "74444efd593c005e3f4573b44524704c0af0a937fe911cca9e94068d0d140d3f", + "dist/fonts/KaTeX_Fraktur-Regular.woff2": "51814d270d06ff0255dba0799994fa4d8c84d11f09951d47595f4abb1f3602dc", + "dist/fonts/KaTeX_Main-Bold.woff2": "0f60d1b897938ec918c8ce073092411baf9438f6739465693ff18b0f9d20b021", + "dist/fonts/KaTeX_Main-BoldItalic.woff2": "99cd42a3c072d918f2f44984a807cf7aa16e13545fd0875fc07c6c65f99e715b", + "dist/fonts/KaTeX_Main-Italic.woff2": "97479ca6cce906abc961ecac96faa5f9ca2e61b8e7670d475826bcdee9a7c267", + "dist/fonts/KaTeX_Main-Regular.woff2": "c2342cd8b869e01752a9321dc17213fc40d4d04c79688c1d43f2cf316abd7866", + "dist/fonts/KaTeX_Math-BoldItalic.woff2": "dc47344dbb6cb5b655c8460d561f4df5f501b90c804ad3c6cec65fe322351ab1", + "dist/fonts/KaTeX_Math-Italic.woff2": "7af58c5ec8f132a2ddde9027c6d7814decce4d3b822a11192a42a20e2e973264", + "dist/fonts/KaTeX_SansSerif-Bold.woff2": "e99ae51144bf1232efcc1bfe5add36262c6866b0faab24fa75740e1b98577a62", + "dist/fonts/KaTeX_SansSerif-Italic.woff2": "00b26ac825e2095056396e0553b8ac26d3f8ad158c3826e28b4c45b385c4714a", + "dist/fonts/KaTeX_SansSerif-Regular.woff2": "68e8c73ef42afd3ccec58bf0fba302cce448938e7fc020a5e31f8a952eee1342", + "dist/fonts/KaTeX_Script-Regular.woff2": "036d4e95149b69ff9bcc0cd55771efeb25ffa3947293e69acd78d5ac328c684b", + "dist/fonts/KaTeX_Size1-Regular.woff2": "6b47c40166b6dbe21a5dfca7718413f2147fd2399be1ba605d8ad39cedf25dfe", + "dist/fonts/KaTeX_Size2-Regular.woff2": "d04c54219f9eaec6d4d4fd42dfb28785975a4794d6b2fc71e566b9cd6db842dd", + "dist/fonts/KaTeX_Size3-Regular.woff2": "73d591271b1604960cb10bb90fee021670af7297017e0e98480b332d11f51995", + "dist/fonts/KaTeX_Size4-Regular.woff2": "a4af7d414440a1c1790825cfb700cf9cf43b0f2c4b04f0ebc523011ad9853ec0", + "dist/fonts/KaTeX_Typewriter-Regular.woff2": "71d517d67827787cfabdf186914cc3358eda539e37931941f2b2fd4a21f68c0b", + "dist/katex.min.css": "864f909fc1f3da0f140321d0e277ac0a444d8909e072cdbf174bcea93b95c089", + "dist/katex.min.js": "103a53763cc033bba8d175bf3f0ba597c3505c9b6747dd3f2c7bc2a6bfcc8ae7" + } +} diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_AMS-Regular.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_AMS-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..0acaaff03d4bb7606de02a827aeee338e5a86910 GIT bin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_7&m zS)oM2>c{G}3Ftw;yx!JfRQ8?A{YDJV$#8$iuyMIOs=Fd;d;T9a596_Id)RU=vNo=l zlVgm8PIfNy1v!4m?pZle^oV(PGE+zFInsi6x*r!s*Yn+E887DbfWjc$;B&3w1$g8w-^4TQ*$WK=;EauvU zZC>+Q&!wIE-_lo2N6)~>#4L@4m5p6`3w_@%88T(bmLr#2o_qxg2h5td>T@`J4p8y| zo{aki2-ZkpRvv* G2<`xUL{2yW literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Caligraphic-Regular.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Caligraphic-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..75344a1f98e37e2c631e178065854c3a81fb842f GIT binary patch literal 6908 zcmV8Fb8N1fhQaGDMf{_aR5Q!Ty=u~ zF9)2+5IRGd_aY*eXu*h4iwC8kb*{C_QN)VA7RMQTu+u)>xr{eg*P|+Ht6ytXr+d(m zZ~p#e2L!$$0|$%oOtI@cwhS2;jT&TD-BQw*ROSFERP599O_J6$GcUwoCkE!d0F$=B3ebZj) z%u2tl(MPUHcVnr%0uq2j$ZD?mW>&vQa*^&_boaZ?MJ~Oeyzo++dtr6}Y?ubX02szi zP*4Emv9VMKu55x7Pupj&vGqTAnT&D>y#d1ekyijf!(aEQSqT*TC&1j-cL)Ens*}5? zPXgozu7BUTz|2A2s#l8S0Ji^=-i#RP8zmtu&neZRA0(Ii3yrZrSlxAws(Hqkb;`{* z>R>b_>h+hM-@KF)45>S=iBNAa{5HRC7)rg~bN2%<09URSqJ=Y{XKexK#T$p9aTxCW zfMVV)pb*Y6X;Za6?`mTJ+yNk09iWQdW&i=IJjein4Vw%ws6B*-E-71rPx9U-XsEPF zmm?rfMCvR9vKSm8 zq$9HmqSC~h)zlKsuL8;5bO!Ba-LHXeIRiMz`dc@Z)3MNyNr{1@gs@BI+wX*usD~DY zPbI0rltnBWa6U%^ibIti;Oq^dR0Nl(5D1CA$j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{Y!4?QY^R+_OTUV|PKgKEAqv9YjP z7^8%(Woe3At!^D|%a~&V)^fGr0K+B?$7$kVv{ew=IR&*I;~1NG)Rd7{gHklieW*|c zm$aDmVy8z3H=aqhT7!E5_T;7GwQJM!%3a>py0xYxUTHYW>>iA}9j(dvs_lZyX-}+7 zoFf$OIk*nx-eB8}bhQCw`;`)c-JI(#jK(22GL&^dfZskZ8U{ zZpm?1v+{19?dAb+K&ka>49`*k+iqC7Pt2=95j`a(ok#2TlS`#p!{thM?>5Fc3f6J| zfn7eOSP-@vO6|dYa~gM8mbvObT)Ued#WJ}*oFe}O#yD*{RqXQ&)dcl z>#WkUD+QDFIIhLYl4U)@;goriI|7?oty?vf+>uSRrXYG+fdBZLWr&xm8$s?~a&)S) z=~n$m^kvi1(eq*8%a6YRMkeMG`n7EW1ql`+lwFu`5h6t$MDMK{E%#qrRLTpuzU~fy z;QaCn{F{BFJ^;}F?i%uYGyh5;Aifzzx)E&ofgNMaOcjRa0;hZ<7~no@b=K~7zvI17 z4mHY9J&pkzn%F31$=u~mVv~R^d}j6K1iCxXAvOZC{a$!SER?`981pokH CFgb+) literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Fraktur-Bold.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Fraktur-Bold.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..395f28beac23c7b0f7f3a1e714bd8dac253dd3bc GIT binary patch literal 11348 zcmV-aEUVLZPew8T0RR9104!7h4gdfE08HQj04x0f0RR9100000000000000000000 z00006U;u#x2s{a#3=s$l=RnhY0X7081A=@Dfj|HRAO(ni2ZA6BfhQYjK}92Ka2^Ov z0o}VqRBm=p{=X$q8M1cpbPUxS0!WG`C@4;IjHc?u&;+W>o%jXepM@BXgT+(Np6`yc z(p7IC8)x~5s#)!;6hBM!$6i|TH+G!ojgVxvwMV<>f6hrZ$wC)-SGcn~DA9)}RnL-z*RWekuPpCacmiMm2|#%vBmjodga!vtbS#zL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0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Main-Italic.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Main-Italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..b50920e138807f385d0b0359f4f0f09891f18406 GIT binary patch literal 16988 zcmV(>K-j-`Pew8T0RR91076^<4gdfE0E4su073x(0RR9100000000000000000000 z00006U;u(d2wDl83=s$lfzV`upmYH?0we>33=4t?00bZfh;j#m7Yuo}gkBMuFlG6J5B*sHHKd(*=umo3RRA1q&Aq{Qq;*?z?Zs zS6lWBvpA{|4kRGzglV7W)AM`dl?u#krjN&WNtdj+pK9tmbDj6g11qm=IR>q4=|=`? zti%rTtj4WAvC1G_rIr^=2^+WshA@nFohl_hT*y>e+7AVqh%8x7!MALuOl3;G|JvJS zZ2pf6{GYmVua&&rfSf~>Q|VHyoWtv{ooO}gpZNn4!G}Ns2Wky}~; z-+Rx%Qf?d6zTgLFWNq{L)|&XtUDJ@rBvM+z<#qC}{~v8;7xR!-65^qpmB9aR)86*I z(Fb`#+6{RXz>gL8A*j+OT~ahDXWkvbdrxCqZx*DH?W|_}L8Ap}LZi^ z0IlqWBQJkKu7V{2mMO|~b$%JDQZ#*va?6C3FLd5So^>i7j8{2goP1iH=I;vx?RqZ+f%D!E1Q}Uf z{0KzZ#6dL*1rA#A#nlOe2*^SaCA87WYSuH!F-~xf7kHOX_>w>4Ow>GI^i|*Yqu$(o zy|edpvIl#l$1ki=Wz?DEGei2WNuq=@I_Sp34KMx$U-n%;?B1Oo?y(DFR2sE^JKR2X z-8G;1*ayx#?E#1FbCY3f%;g&TKkL8!pWgZVe&=t0G8VL%TMb-GT|7;&|I;&j zkM`FvLW;i-j(9}~p?4@p##%xxg#6NNA;2G8NdOw#s3Z)rVoM@GbAqhjDO`sP5rWI` zddKCYp`S4K#-PLrvlAPlH{%u_3>X|uvq!cmzm;uF_#UBueexp|=;6wEg#<-aPj zO2>wF3fYv914sg zp$!>z%#4E66NKB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or/katex/dist/fonts/KaTeX_Main-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..eb24a7ba282b03d830fa6c63ee897d92a5188736 GIT binary patch literal 26272 zcmV)0K+eB+Pew8T0RR910A`>74gdfE0Mb|h0A@!30RR9100000000000000000000 z00006U;u_x2wDl83=s$lg4ZO1h%W&)0we>7bPI$&00bZfh>~Lg>lfqq!H9{pqisKVY-r;FZ|J_}3x%f#O2oVCoLIe_|K;jSrB#_|6tcF#nQYuiY zRK(X+)^(Nr)_--CzcH|L6YOKIgtS zV^e?n{KWzdGz>Uvr3ogO(O4za|Gv{cJ82%+Gi-Qo5zvVr0DLZxboS5QW$DVXQ;r?L zmIH039WJ0HEy6d@pqu?CAy_CO;Dwq|QLaaOJrjSrzwPh3%zqSH-@JXOXu3ou^maSn zD6Y9G97Z4w7UP0&7>6YQ{`#g?zwBT4E;k4aiG}91V;Mr|0QXGWtJ_n;Rp(_G-LZ7X zBgu&ZY&pQNp#j4J@h#fb%-g|!nDK9Z{#y17F$vj|Ow$cw^7Zx5lyr?)4bguwH}XpQ zh^e)Sc&Uh2jvmQxaQ?x06H|Yz6Aq_$_jY?{Yg@O_mO4~aKnjeqsU9vsh70XIBy6)b zDEZG{)L+!>A4obA0Y9^&d{=I z1rQNW-S`)HK@33?1Q_TF+)dX^5`^^cPky~Ft6Q`9TUr!UZBCSJl$f=3h(YRSXRjSf z|1Z&uk0Zv)$I=m0ewE+k>r|MjE&PC~R_Rj!|nOT6qEFfVQj7#Ym zT#(NMmbwG?5(z-e(xsRnh)SU3rz4djk$ndW^Y3v+-m1yqPKC2`3yQvS0RN8Pob@ zd;8b!bXHN=2_&HZ8t7F$c?Gy^Nih!q&MrSe2jI^R0kDYQI<#j9%){aPfS)?x`Q=&T ze;vONSt<60DE_GxGmtaG3@m-&0D!*R0D!`{Qih;{g+tkB+RXlPxk(?CPmP(j+F`GQ zj(Fb(uJ9QTdCD7m7S|H|w>SDl@6XB!CYp(vn%POFc7rMk#lR-EF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FE^bIb( zQ4jJy09T93jzG|o^1~1q+G8C@0KxBnlb~lpVGXmK_Qj9qqse7}!yWiSn=`F^4s$us#6Mcu_;pho0{r bkH82T%!~T~dOL3iZSfI!+IWoKhyte*`46Vs literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Math-BoldItalic.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Math-BoldItalic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..29657023adc09956249f6295746c8ce4469b50d3 GIT binary patch literal 16400 zcmV+rK<~eIPew8T0RR9106-7`4gdfE0D43K06(+<0RR9100000000000000000000 z00006U;u$k2x2I17PZ00bZfi3|sWeGGvz8}4HTsSn}h_&&m_g4$s+7>x}(e0b|zhiFmih3+Y z_JHa$ux;c|a`FyO&iVK5;5haj2M0Us5CRDY31pB2cF2N2#x@CA?hH+IC$1T5oL#Oi zTm8l{f35!3j;S46ZTBB`{Z8%g_kYV-Npt*qbNf{)Q`HU6L<5cyhmJv2>TM?E4I!B; zTrs$#{npsIL(Zb)U1m1L)1HRv;hxQZYYB2DMJ06qtE=2;?F$=%RNirU)ujURtb7>?5s{7KnM;^!<)4(Fm5+BJ{pbl7Y+ig#pY8WtNs@R;Tv}Vb2zWA1jQzm*#o`3DI zY!Lj&klRuUKmwu&j_kk{H`eCp-_vbX8mEgy4^o9{Y;D`8bQQe5ncy0wN9SLFsawuhEI@!jD6#EQ9wi)K3zoxV;?`!a^soM1A0#+O2q9KiRK~gx40mr#h`^il zZVIM5HcJKuSG5?>jK5AE+syVBx&R<)q*ZxDgS_aq3?!Y?rd;$kJ} zznvM-#jF)AbEqu~X<-Qmg2H62$`k9B)$6!d`Tf6NKjrJ0h5H=%>B@|McT8H*%y`vb z(%rk>@RCE*6N6rnrAbrV{r!LUjAD%&0?-v-O(btVFYk|g>A9-v%&i0jKer!j?XGS& z<+bDDY`-WK+F91kb{WD=t*O*|E9?6lh zmQXXHp!8Y@NHBUw0BY;l5r$Z?jtJ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/fonts/KaTeX_Math-Italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..215c143fd7805a5c2b222bd7892a1a2b09610020 GIT binary patch literal 16440 zcmV(}K+wN;Pew8T0RR9106;hZ4gdfE0D72I17PZ00bZfh;j#meGGvz8}?&GBPzE8 z1u0OUJSyttUiBVPluy!d#s9|yDnr%+PdDJI6W~D+hF7dn3876mx~G$_T&rr^uln5x z|BT}}4pu5P3e*HEr8*eDNTG<1F_;U3ZA=tqpJ7vDW=sX5YRKxDB`FY!LZL8@ z!bX`TSd8YAvLOreMkita9aZ$fQ$*@8r}n?8&fXI{KJWmoXc#0=X$40A*07 z&SI0gyJXs?ugX_CC|r4aZcQPu+bcrpYg<7f7bmfQRh4#o+@zM{cG#5I0dklZ z)z<8ItFoM}%JCB=SLYwy?cof?1GGfhVUk-3A3vRct*O30o6@Q!dZh;dM6m*cJeAl!*4z~IaFs+R8AEDeJOU?u3$8JXqZrnAU^RPh+F zU;a;L|F-we${!dyOb=Y9sM9p#JJMP+Bki*!?>>9v2ey3PS!?%!*)SOVy?*)743p>5skoe=iCPWL7}q;e-a9(G+RBfkb0t=i8_N*+ z7_N0U_z$PkZB<@dmg^}j2qDKj_ZiD2E{-^a@MxAp%Lt*{=gz|MvAU+<%dmy%)1*fC9?>djP?CJbUm!@N*vrK|8L#IrzmL7}7602l}4y?RTD= z#6!3r^5Ona!>#G)S?_S5-S-FtfgimK1aUrG4ns(0(V#gV^>8f@hf-*su5ukNasBL{ zgLBnfJJ-)mbL-qOFU-SP%s=z%Z}%T+!EL+v^$fiHW#`{Ax6jd+tNxX~{?eYf=hVw& z*ze|P61T)(fBbU{mHHA0(6Y^eWse?T|L=*6X=cUCf~xpmtLO*gUB^F|M`rr)E7$la zYxyr@6;nP4W&KEj4@Z#n<^!?2U!Fz#w7-M}Qudi}#A94=>6^>8v6fIfp`dgF1SA+- zMF4VjQ4xk%u@w=Z-$gdg7Oo{tgy1r~(YkCMCt-eDf?_AkHuglXmjgUD#^7k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6NHDzr~6!sPJnviyiVP zOQ*ZMi_f6GHV$$AfH8l>0-Xe6=X;+lBtlDacsvlPT9OLxprP0eXCFMaaMvRqXEUgK zX&#U*ivUkEgPlvF>epop3B%@?$Y$;OwMx@%A@igg(&j(Om3Tk#{4W(c+y^=z>**bea`n(V9&rko|US|m)5J_~KM+@*`Ol37}G&|tH$ z??@950jGTJsCN0<z(I{S3PO5uOsC866l1 G>;nKVNojrn literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_SansSerif-Italic.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_SansSerif-Italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..349c06dc609f896392fd5bc8b364d3bc3efc9330 GIT binary patch literal 12028 zcmV659DkbG}7@mjJD1@jO-Eqc8pH1xbNXy>V zuj4@|WLKW95E7|5CLkNL;`-Y+wfA&?GtJ-Z&L(!k4v|`??3CPcqTcL|tNjQ{K536( z{p-EnmtzN&6c7(-?6J;0;$I;9*Or=#CSe6e`Kj!u4Ul0&Ix>QOQ1Y#>s9n_Rs?i!K z`N8}1e;oFIb6U<-O6FuJcnRoEPTZX=aW9wuuhQ&I(s%2$94HMXDG%c+*1)?j&HvPt z{x5f&l`#j}k2io7&=!!w?=Rc&|6fkeUw4gUWm(R$oMkzA?`+>1cE=cO4|J9@oUwe@ zJq9WYEP(~E3>U5e2q**H@Lxant9$O-_qA1~YfFUmMWi9#7(z1*h0+O0B{7{3D{D^4 z+y+H#pL-pvasQi8$-7u`oy}^Vd1cS&h7d}o=09l#K=2N@4Uhmp8_<0KfKAV*4nF{9 zh``OnQviI=2H$)OZk$-3w+A?YOeVo(|CfPQ^gZ}X2Ef)13;=i^x&{D{0emUK0O21D zE;`}h2dxaq;I_*Km7p55ff-;SSPBk+6W{{40nMlsJ&B%0@1SXH7j`GM8{3B+zz$=_ zu#+;rEJr5!|Nnl_4|b>)w1dn}KY^Y`Z=qY*&M}W-CltGC;W3{5am+sQp%1+8mU~@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ju5)&(wnQ)2C=hLXy1LGYTw?$^5o(E?x zDpc)i^RkeI4v~;S0oV6czd%sN{6ds#H;(=Q`!u&&HYV?3wSFCIVBPGE`n2&Ev2vX~ zwU_YGl3FiE%~E=EitxoOATybhK-Eb_T%^vJL{{R(8}E(0q0jp`)~PAhcOapT0q}yf zC36Vfu%tu@ib#yo|CYzYI8{S3uv2{kBjP;mQb>sS(zw8b`c}q zWqI}|(Icoo%XzQmS%6|fNZ<9dnUyoZqp;UA{4gV_NfZAmLFm5|eCL89A)}z8p$o&n z6pkeV8wVFpq$ts1#EQe0C`qyu0;$pnrOP0aDN8mn38@@1x$@*IP^d_;QA(6jP*Tw- zQ?5cKEgd}rBNH=>g_Vt+gOiJ!hgX$qKK{U9kr}SL5FEJZX7CUJLckSQU31Be5Fr#I zL1c&mQ6U;chr%F6n2tDV$T1%q9PR697K@b`87R%k@18Yi?|oa&+}Hw{>>lu%_n3_F(PJ`6#Nt`0$e zVdM667!VJSrU5Md*nBWr3&X?YWO#~TS1HorDI&lFFbZ`;84eT_6+glOnwMmpd*ME$ znCnhRh^EDlqhO1f>8t3&+ewp?=v2^<=Io&TCcf@{Fjiv@!SwVG`7mp=@P$dv*MtxP GG{*pT{>~Tx literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Script-Regular.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Script-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..b3048fc115681ee6c1bc86b0aa158cfbbf59daa3 GIT binary patch literal 9644 zcmV;dB~#jWPew8T0RR91041yd4gdfE06`=G03}%f0RR9100000000000000000000 z00006U;so2FbSLt5eN#^0K-)QHUcCAd<#GT1Rw>82nT2kfhQYDH$_Kij|0iTRZ#qY zNZ@1)o(`sckdP20P$0OrPQ{=ic2J5&*+!ChSkp2Rs1rz~I>ZN2PfZP|%j9GmD|WTN@oMZAt6{_tM4>FlNS+!xZI%6m@k(BVdqZ9U7OrP@-QZ zDBh>VZ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*)n6}V2`la7<$B*n;>qcv*cQut7^em76 zy4$Pyene%)5k6Wbba){>b$0#h_gW*O0)XxdKhfVe(8wwJr*e=loJ$tY_dhq9;@^Mw zYj4E||8_t}laGsB3q@-t1TJWL<`Ad)Q*@id!4CfX5RoZau9F&jBqR=5Lr0ZMp!8^l zn0ZZdW-6>Dsn0FK#k(PP%_JpPZ9{ylDSs8s5y+6ChyNn2oA?^uUNK|zL#9ll${8K; ziu}wImRN*<9w+=CLQTzmk@fuelmU~5W}0CLP@_3GVoh`aB1bx4Y!^BZ9#=b18HMP; z*ox_%_|pznbb|T&%9fiSvl}pIo?%@&bQ&d=p+#ol>u9bZU(Q%)sZq?K%?O9+PZ;J7 z+e8Z&N?CcgPfdj`{#318G>KAB#YCgkk7*^p&peeUQ7Hs98l{p@F_=V1>DggSubA&L z@BuYC62q!$lciLeKe+;8QTLH^x@(w4m86E@$PD;eDkcg`F}jL&P>eZ$KSerf@W zY!uKBNAlrj>iPom9DqSUI})<2_Zvb$j%PVob5S#6SyM9!tt>-7O@$6LFFGa8rk@fQ isFOeq9&M@oI}Pp55h!41eSwD&UH=U4=~t{3ha6jZwt}$$ literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Size1-Regular.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Size1-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..c5a8462fbfe2c39a7c1857b9e296e62500a8a8a5 GIT binary patch literal 5468 zcmV-i6{G5RPew8T0RR9102N#S4gdfE059|a02KrP0RR9100000000000000000000 z00006U;u&y2o4FH3=s$lu0*3V0X7081A#sZVgLjn1&II$f_@Bv92*KLBN4WPw1P)b z3)3bP{M7+ZMOOX{84}{EYouy;ApBw9=Qs{FP0hRc*Aw?6B$@qzw)yYf9S4VSgo05A z7zl`f_8gK{O=qmAg&P)PEyG2}$L+WKk+J>AkO$&keSc`inv`I8;lfZX9KysS(r(}i z*Lpo){eO>B_-D4>9=lQ4Jw;-E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F%!~(?0cIq=^x7MC8vM1&(sfT{Ulb{^<%Z z_CdTjx#liHw%1-KKR67z;4Y}#cL5pmw#5}60w8VqI0*w(-jzf)dupz`HrJS`ou#Ee uC}16e%Gv>UrEUWr7J?uwp6K^lh(`Fkpv`!YL^q7xb{CaG@8Q~cR8|6Fhs$~Z literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Size4-Regular.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Size4-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..680c13085076a2f6c5a7e695935ec3f21cddb65f GIT binary patch literal 4928 zcmV-G6Tj?tPew8T0RR91024p}4gdfE04S^g021l|0RR9100000000000000000000 z00006U;u$M2o4FH3=s$lpb(dJ0X7081A$BnXaEEt1&II$gDMPx92+(xvye7xR)-Qr zuyF+D<2}WHmB5qvtDzk>iwqJnL*(fZs|06Yb!k(1`ETc1I4-BI5fi@^u8fdm)_=e` zdp}9j)YFz0DG~@_Kr>cMHY70C!K^ZDLNTA1b7Br>uDhMiy#E2l3s-l)|7lD20$2hm z@RXnGF4_PYHl#gB*k&mx`PNs|E@~BRiaIk-Yp%L*)p~xqH)tK24LDPq+9^`k`Cgg@ z?wr3yPQ)iMi`0C({fo<{L5l+`f3Eib=1O^!+?5mxbFzfbmnAs&^Jiy+y`4!4(_Cp% zqD;z%tlFv-x2E;!;w zVW0LxIo!N76;gG%@Hb~*66P0cigm@!%!Cno$kKtF{J6eOf$5?ZhZ zGxUV~z5L(+ewzJn*7bz*N{9T6&S$7sY0!Etm|_zlZIG>ifQcfRwh5_SQlHslg9^@7tlD^wLmOxkR|-Rl>&iBW8}oeXg=l3PGl0WW7UOHQ$AH=-*sQ_FPT5-1d5EJQD9Pn$NP z=&ex`C2L6`ubBa-+$U+ol!uAv{MKA*F%G6?$zgGfC`t3*GI6_Eb;)%5MJ*?0ruoG$O;U?7n^){QDYAVGaEVAHLqZB9$dHf<2?`{n zLBa$`NQZCJlm;X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<7&lQCop?gBz@77;ie_dPVir%j-KZ3*88_esm=dk1WcPGAg zto?*Wm=AMA!|Wqb!MEldKGJdgGeJxdqsAN-1>yD|6?!3WhqDhm>PHM>j@5nhx#9SC zj^p2-XK{?-drRD44zlS_--hSvOCM?YJ?{7N{K3&Z!TxDjURSqu!?e!HYXw&1>@L0Z zZ=-jKj*UzCrvgQ_uG{h>He8n&ugf-VTVA_iTHV%la@cN*S^%7Rg7*2Tf+kR*!tk*_@q85UwF!pw(p|nk`ns4bNmF3u!6WrJ!9# zT^44B(E|fR(rr2R^(;aba*?6@{ZjXVY_1F|9y?hWL?q1gppPxAM3zE_WC}8Bbh)$x z{n%R~yGzrnT4THQvNK6vTcWBi$4ecM>e*PrOhhnvRW%Hq7FP?Yee05N4RUnp3c%t4 z38w?h+SS7nbYPivurP_2byCduQ6FY!VI<&E`djO1pk75!^k?zAa`GJs5iIxC+f{{a z7`Rzd#v*CwDlx~hw-hBXRw<4;5_Hl%w*>9g(~%NK%i=IJp!MrN39~R2^?_pyOs5yO z6ge2o{ae&O0u#(|U<%4nfdyzK24CVUVu`~Yq$8g6B#?oOWFj+J$VxU6$xaS(QWUw! zP0CfBZ=4xqAJKL2sICSTTqTeI literal 0 HcmV?d00001 diff --git a/serve/web/vendor/katex/dist/fonts/KaTeX_Typewriter-Regular.woff2 b/serve/web/vendor/katex/dist/fonts/KaTeX_Typewriter-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..771f1af705f5cef5f578b3a1e7d8eff66f9b76b0 GIT binary patch literal 13568 zcmV+bHUG+YPew8T0RR9105t#r4gdfE0Bjrp05qlm0RR9100000000000000000000 z00006U;u$!2wDl83=s$lfunT&H~}^SBm;sB3xWm!1Rw>8CN9CW*AUKZRb(vF-L12^-sRp4kkW?yS(-j4&mT7M`-Mm+~H|D|J~(s zx%geq;*D1(>ArFW~rrE6envo%`l% zO&%1KVbFMCgu$9D>Vhor_p7zu_xgZnQd6^Hr;Yl38vs1CA)z7xl?8(x!j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}8RpUlfSMeYDo)~Pn%b!ioPy+FA=Igdonyr> zddn5~@*@l?7Ly%D*}m?zrvP$*^Z7LsK`I4|IOrYw z%mma?KlxW&tQ{4jgu_m2`QKu8p+*0;IPm|AA2Tp~0zx8U5>hyV42eQxu;dh!RMa%I zqUh)u7@3$^M2itCPW;COo}7PvyA-L?q<`J@XH1rCIdbK3$mitZ=Hca2z^_n|VgV&e zl_^&tD5O%AYBg%rsn?)UlV&Yig|!7{4o_O_Q@4`G|9p`Gi!9+IAN#~@pQX$StE{ok z2AgcL%?`VG)8X{kFCnoNzFO_9xoKwAS?i6?bc^0(v$pf-24xvVl^VTf^vTf{#*Uqy z2?|4BK6K@y51!RkerYBzsY>|D@!>0@POF>sV*j)k?p}&|v)%}_ZsiD^4F!exS-wI4 z&a1bt3V0_?49+3t+y79NTY0JW^O%c+a~}T5DG&LNQM9%p;XJ@uIIA854zN}e-)`N9 z^KD&^4pNLb!qCDvSBysY87J7A0?M0fJ8nOQ(}aI$%AE_+Opl<`rO1C$>3SRP;Zm{g G0ssIW.katex-newline{display:block}.katex .katex-base{position:relative;white-space:nowrap;width:-webkit-min-content;width:-moz-min-content;width:min-content}.katex .katex-base,.katex .katex-strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathboldfrak,.katex .textboldfrak{font-family:KaTeX_Fraktur;font-weight:700}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .mathsfit,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;display:inline-table;table-layout:fixed}.katex .vlist-r{display:table-row}.katex .vlist{display:table-cell;position:relative;vertical-align:bottom}.katex .vlist>span{display:block;height:0;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{overflow:hidden;width:0}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{display:table-cell;font-size:1px;min-width:2px;vertical-align:bottom;width:2px}.katex .katex-vbox{align-items:baseline;display:inline-flex;flex-direction:column}.katex .katex-thinbox{display:inline-flex;flex-direction:row;max-width:0;width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .katex-hdashline,.katex .katex-hline,.katex .katex-overline .overline-line,.katex .katex-rule,.katex .katex-underline .underline-line,.katex .mfrac .frac-line{min-height:1px}.katex .mspace{display:inline-block}.katex .katex-smash{display:inline;line-height:0}.katex .clap,.katex .llap,.katex .rlap{position:relative;width:0}.katex .clap>.katex-inner,.katex .llap>.katex-inner,.katex .rlap>.katex-inner{position:absolute}.katex .clap>.katex-fix,.katex .llap>.katex-fix,.katex .rlap>.katex-fix{display:inline-block}.katex .llap>.katex-inner{right:0}.katex .clap>.katex-inner,.katex .rlap>.katex-inner{left:0}.katex .clap>.katex-inner>span{margin-left:-50%;margin-right:50%}.katex .katex-rule{border:0 solid;display:inline-block;position:relative}.katex .katex-hline,.katex .katex-overline .overline-line,.katex .katex-underline .underline-line{border-bottom-style:solid;display:inline-block;width:100%}.katex .katex-hdashline{border-bottom-style:dashed;display:inline-block;width:100%}.katex .sqrt>.katex-root{margin-left:.2777777778em;margin-right:-.5555555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .katex-sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .katex-sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .katex-sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .katex-sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .katex-sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .katex-sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .katex-sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .katex-sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .katex-sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .katex-sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .katex-sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .katex-sizing.reset-size2.size1{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .katex-sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .katex-sizing.reset-size2.size3{font-size:1.1666666667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .katex-sizing.reset-size2.size4{font-size:1.3333333333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .katex-sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .katex-sizing.reset-size2.size6{font-size:1.6666666667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .katex-sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .katex-sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .katex-sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .katex-sizing.reset-size2.size10{font-size:3.4566666667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .katex-sizing.reset-size2.size11{font-size:4.1466666667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .katex-sizing.reset-size3.size1{font-size:.7142857143em}.katex .fontsize-ensurer.reset-size3.size2,.katex .katex-sizing.reset-size3.size2{font-size:.8571428571em}.katex .fontsize-ensurer.reset-size3.size3,.katex .katex-sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .katex-sizing.reset-size3.size4{font-size:1.1428571429em}.katex .fontsize-ensurer.reset-size3.size5,.katex .katex-sizing.reset-size3.size5{font-size:1.2857142857em}.katex .fontsize-ensurer.reset-size3.size6,.katex .katex-sizing.reset-size3.size6{font-size:1.4285714286em}.katex .fontsize-ensurer.reset-size3.size7,.katex .katex-sizing.reset-size3.size7{font-size:1.7142857143em}.katex .fontsize-ensurer.reset-size3.size8,.katex .katex-sizing.reset-size3.size8{font-size:2.0571428571em}.katex .fontsize-ensurer.reset-size3.size9,.katex .katex-sizing.reset-size3.size9{font-size:2.4685714286em}.katex .fontsize-ensurer.reset-size3.size10,.katex .katex-sizing.reset-size3.size10{font-size:2.9628571429em}.katex .fontsize-ensurer.reset-size3.size11,.katex .katex-sizing.reset-size3.size11{font-size:3.5542857143em}.katex .fontsize-ensurer.reset-size4.size1,.katex .katex-sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .katex-sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .katex-sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .katex-sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .katex-sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .katex-sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .katex-sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .katex-sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .katex-sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .katex-sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .katex-sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .katex-sizing.reset-size5.size1{font-size:.5555555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .katex-sizing.reset-size5.size2{font-size:.6666666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .katex-sizing.reset-size5.size3{font-size:.7777777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .katex-sizing.reset-size5.size4{font-size:.8888888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .katex-sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .katex-sizing.reset-size5.size6{font-size:1.1111111111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .katex-sizing.reset-size5.size7{font-size:1.3333333333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .katex-sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .katex-sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .katex-sizing.reset-size5.size10{font-size:2.3044444444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .katex-sizing.reset-size5.size11{font-size:2.7644444444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .katex-sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .katex-sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .katex-sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .katex-sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .katex-sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .katex-sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .katex-sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .katex-sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .katex-sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .katex-sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .katex-sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .katex-sizing.reset-size7.size1{font-size:.4166666667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .katex-sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .katex-sizing.reset-size7.size3{font-size:.5833333333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .katex-sizing.reset-size7.size4{font-size:.6666666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .katex-sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .katex-sizing.reset-size7.size6{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .katex-sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .katex-sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .katex-sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .katex-sizing.reset-size7.size10{font-size:1.7283333333em}.katex .fontsize-ensurer.reset-size7.size11,.katex .katex-sizing.reset-size7.size11{font-size:2.0733333333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .katex-sizing.reset-size8.size1{font-size:.3472222222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .katex-sizing.reset-size8.size2{font-size:.4166666667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .katex-sizing.reset-size8.size3{font-size:.4861111111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .katex-sizing.reset-size8.size4{font-size:.5555555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .katex-sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .katex-sizing.reset-size8.size6{font-size:.6944444444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .katex-sizing.reset-size8.size7{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .katex-sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .katex-sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .katex-sizing.reset-size8.size10{font-size:1.4402777778em}.katex .fontsize-ensurer.reset-size8.size11,.katex .katex-sizing.reset-size8.size11{font-size:1.7277777778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .katex-sizing.reset-size9.size1{font-size:.2893518519em}.katex .fontsize-ensurer.reset-size9.size2,.katex .katex-sizing.reset-size9.size2{font-size:.3472222222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .katex-sizing.reset-size9.size3{font-size:.4050925926em}.katex .fontsize-ensurer.reset-size9.size4,.katex .katex-sizing.reset-size9.size4{font-size:.462962963em}.katex .fontsize-ensurer.reset-size9.size5,.katex .katex-sizing.reset-size9.size5{font-size:.5208333333em}.katex .fontsize-ensurer.reset-size9.size6,.katex .katex-sizing.reset-size9.size6{font-size:.5787037037em}.katex .fontsize-ensurer.reset-size9.size7,.katex .katex-sizing.reset-size9.size7{font-size:.6944444444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .katex-sizing.reset-size9.size8{font-size:.8333333333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .katex-sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .katex-sizing.reset-size9.size10{font-size:1.2002314815em}.katex .fontsize-ensurer.reset-size9.size11,.katex .katex-sizing.reset-size9.size11{font-size:1.4398148148em}.katex .fontsize-ensurer.reset-size10.size1,.katex .katex-sizing.reset-size10.size1{font-size:.2410800386em}.katex .fontsize-ensurer.reset-size10.size2,.katex .katex-sizing.reset-size10.size2{font-size:.2892960463em}.katex .fontsize-ensurer.reset-size10.size3,.katex .katex-sizing.reset-size10.size3{font-size:.337512054em}.katex .fontsize-ensurer.reset-size10.size4,.katex .katex-sizing.reset-size10.size4{font-size:.3857280617em}.katex .fontsize-ensurer.reset-size10.size5,.katex .katex-sizing.reset-size10.size5{font-size:.4339440694em}.katex .fontsize-ensurer.reset-size10.size6,.katex .katex-sizing.reset-size10.size6{font-size:.4821600771em}.katex .fontsize-ensurer.reset-size10.size7,.katex .katex-sizing.reset-size10.size7{font-size:.5785920926em}.katex .fontsize-ensurer.reset-size10.size8,.katex .katex-sizing.reset-size10.size8{font-size:.6943105111em}.katex .fontsize-ensurer.reset-size10.size9,.katex .katex-sizing.reset-size10.size9{font-size:.8331726133em}.katex .fontsize-ensurer.reset-size10.size10,.katex .katex-sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .katex-sizing.reset-size10.size11{font-size:1.1996142719em}.katex .fontsize-ensurer.reset-size11.size1,.katex .katex-sizing.reset-size11.size1{font-size:.2009646302em}.katex .fontsize-ensurer.reset-size11.size2,.katex .katex-sizing.reset-size11.size2{font-size:.2411575563em}.katex .fontsize-ensurer.reset-size11.size3,.katex .katex-sizing.reset-size11.size3{font-size:.2813504823em}.katex .fontsize-ensurer.reset-size11.size4,.katex .katex-sizing.reset-size11.size4{font-size:.3215434084em}.katex .fontsize-ensurer.reset-size11.size5,.katex .katex-sizing.reset-size11.size5{font-size:.3617363344em}.katex .fontsize-ensurer.reset-size11.size6,.katex .katex-sizing.reset-size11.size6{font-size:.4019292605em}.katex .fontsize-ensurer.reset-size11.size7,.katex .katex-sizing.reset-size11.size7{font-size:.4823151125em}.katex .fontsize-ensurer.reset-size11.size8,.katex .katex-sizing.reset-size11.size8{font-size:.578778135em}.katex .fontsize-ensurer.reset-size11.size9,.katex .katex-sizing.reset-size11.size9{font-size:.6945337621em}.katex .fontsize-ensurer.reset-size11.size10,.katex .katex-sizing.reset-size11.size10{font-size:.8336012862em}.katex .fontsize-ensurer.reset-size11.size11,.katex .katex-sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{display:inline-block;width:.12em}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .katex-accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .katex-accent .accent-body{position:relative}.katex .katex-accent .accent-body:not(.accent-full){width:0}.katex .katex-overlay{display:block}.katex .mtable .vertical-separator{display:inline-block;min-width:1px}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;display:block;height:inherit;position:absolute;width:100%}.katex svg path{stroke:none}.katex svg{fill-rule:nonzero;fill-opacity:1;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1}.katex img{border-style:none;max-height:none;max-width:none;min-height:0;min-width:0}.katex .katex-stretchy{display:block;overflow:hidden;position:relative;width:100%}.katex .katex-stretchy:after,.katex .katex-stretchy:before{content:""}.katex .hide-tail{overflow:hidden;position:relative;width:100%}.katex .halfarrow-left{left:0;overflow:hidden;position:absolute;width:50.2%}.katex .halfarrow-right{overflow:hidden;position:absolute;right:0;width:50.2%}.katex .brace-left{left:0;overflow:hidden;position:absolute;width:25.1%}.katex .brace-center{left:25%;overflow:hidden;position:absolute;width:50%}.katex .brace-right{overflow:hidden;position:absolute;right:0;width:25.1%}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{border:.04em solid;box-sizing:border-box}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .katex-sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{border-right:.049em solid;border-top:.049em solid;box-sizing:border-box;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .reflectbox{display:inline-block;transform:scaleX(-1)}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{display:inline-block;position:absolute;right:calc(50% + .3em);text-align:left}.katex .cd-label-right{display:inline-block;left:calc(50% + .3em);position:absolute;text-align:right}.katex-display{display:block;margin:1em 0;text-align:center}.katex-display>.katex{display:block;text-align:center;white-space:nowrap}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.katex-tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.katex-tag{left:0;right:auto}.katex-display.fleqn>.katex{padding-left:2em;text-align:left}body{counter-reset:katexEqnNo mmlEqnNo} diff --git a/serve/web/vendor/katex/dist/katex.min.js b/serve/web/vendor/katex/dist/katex.min.js new file mode 100644 index 00000000..4a6810d6 --- /dev/null +++ b/serve/web/vendor/katex/dist/katex.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.katex=t():e.katex=t()}("undefined"!=typeof self?self:this,function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return go}});class r extends Error{constructor(e,t){let n,o,s="KaTeX parse error: "+e;const i=t&&t.loc;if(i&&i.start<=i.end){const e=i.lexer.input;n=i.start,o=i.end,n===e.length?s+=" at end of input: ":s+=" at position "+(n+1)+": ";const t=e.slice(n,o).replace(/[^]/g,"$&\u0332");let r,a;r=n>15?"\u2026"+e.slice(n-15,n):e.slice(0,n),a=o+15e.replace(o,"-$1").toLowerCase(),i={"&":"&",">":">","<":"<",'"':""","'":"'"},a=/[&><"']/g,l=e=>String(e).replace(a,e=>i[e]),c=e=>"ordgroup"===e.type||"color"===e.type?1===e.body.length?c(e.body[0]):e:"font"===e.type?c(e.body):e,h=new Set(["mathord","textord","atom"]),m=e=>h.has(c(e).type),u={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format "},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color ",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:e=>"#"+e},macros:{type:"object",cli:"-m, --macro ",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(e,t)=>(t.push(e),t)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:e=>Math.max(0,e),cli:"--min-rule-thickness ",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:e=>Math.max(0,e),cli:"-s, --max-size ",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:e=>Math.max(0,e),cli:"-e, --max-expand ",cliProcessor:e=>"Infinity"===e?1/0:parseInt(e)},globalGroup:{type:"boolean",cli:!1}};function p(e){if(Object.prototype.hasOwnProperty.call(e,"default")&&void 0!==e.default)return e.default;return function(e){if("string"!=typeof e)return e.enum[0];switch(e){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{};default:throw new Error("Unexpected schema type; settings must declare an explicit default.")}}(Array.isArray(e.type)?e.type[0]:e.type)}function d(e,t,r,n){const o=Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0,s=Object.prototype.hasOwnProperty.call(n,"processor")?n.processor:void 0;e[t]=void 0!==o?s?s(o):o:p(n)}class g{constructor(e){void 0===e&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(const t of Object.keys(u)){const r=u[t];r&&d(this,t,e,r)}}isTrusted(e){if("url"in e&&e.url&&!e.protocol){const t=(e=>{const t=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(e);return t?":"!==t[2]?null:/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t[1])?t[1].toLowerCase():null:"_relative"})(e.url);if(null==t)return!1;e.protocol=t}const t="function"==typeof this.trust?this.trust(e):this.trust;return Boolean(t)}}class f{constructor(e,t,r){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=t,this.cramped=r}sup(){return b[y[this.id]]}sub(){return b[x[this.id]]}fracNum(){return b[w[this.id]]}fracDen(){return b[v[this.id]]}cramp(){return b[k[this.id]]}text(){return b[z[this.id]]}isTight(){return this.size>=2}}const b=[new f(0,0,!1),new f(1,0,!0),new f(2,1,!1),new f(3,1,!0),new f(4,2,!1),new f(5,2,!0),new f(6,3,!1),new f(7,3,!0)],y=[4,5,4,5,6,7,6,7],x=[5,5,5,5,7,7,7,7],w=[2,3,4,5,6,7,6,7],v=[3,3,5,5,7,7,7,7],k=[1,1,3,3,5,5,7,7],z=[0,1,2,3,2,3,2,3];var S={DISPLAY:b[0],TEXT:b[2],SCRIPT:b[4],SCRIPTSCRIPT:b[6]};const M=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];const A=[];function T(e){for(let t=0;t=A[t]&&e<=A[t+1])return!0;return!1}M.forEach(e=>e.blocks.forEach(e=>A.push(...e)));const C=e=>e+" "+e,B=80,q={doubleleftarrow:"M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",doublerightarrow:"M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",leftarrow:"M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",leftbrace:"M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",leftbraceunder:"M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",leftgroup:"M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",leftgroupunder:"M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",leftharpoon:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",leftharpoonplus:"M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",leftharpoondown:"M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",leftharpoondownplus:"M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",lefthook:"M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",leftlinesegment:C("M40 281 V428 H0 V94 H40 V241 H400000 v40z"),leftbracketunder:C("M0 0 h120 V290 H399995 v120 H0z"),leftbracketover:C("M0 440 h120 V150 H399995 v-120 H0z"),leftmapsto:C("M40 281 V448H0V74H40V241H400000v40z"),leftToFrom:"M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",longequal:C("M0 50 h400000 v40H0z m0 194h40000v40H0z"),midbrace:"M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",midbraceunder:"M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",oiintSize1:"M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",oiintSize2:"M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",oiiintSize1:"M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",oiiintSize2:"M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",rightarrow:"M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",rightbrace:"M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",rightbraceunder:"M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",rightgroup:"M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",rightgroupunder:"M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",rightharpoon:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",rightharpoonplus:"M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",rightharpoondown:"M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",rightharpoondownplus:"M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",righthook:"M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",rightlinesegment:C("M399960 241 V94 h40 V428 h-40 V281 H0 v-40z"),rightbracketunder:C("M399995 0 h-120 V290 H0 v120 H400000z"),rightbracketover:C("M399995 440 h-120 V150 H0 v-120 H399995z"),rightToFrom:"M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",twoheadleftarrow:"M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",twoheadrightarrow:"M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",tilde1:"M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",tilde2:"M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",tilde3:"M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",tilde4:"M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",vec:"M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",widehat1:"M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",widehat2:"M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat3:"M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widehat4:"M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",widecheck1:"M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",widecheck2:"M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck3:"M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",widecheck4:"M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",baraboveleftarrow:"M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",rightarrowabovebar:"M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",baraboveshortleftharpoon:"M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",rightharpoonaboveshortbar:"M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",shortbaraboveleftharpoon:"M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",shortrightharpoonabovebar:"M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"};class I{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){const e=document.createDocumentFragment();for(let t=0;t{if("toText"in e)return e.toText();throw new Error("Expected MathDomNode with toText, got "+e.constructor.name)}).join("")}}const R={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:1.00375,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:1.00375},O={ex:!0,em:!0,mu:!0},E=function(e){return"string"!=typeof e&&(e=e.unit),e in R||e in O||"ex"===e},H=function(e,t){let r;if(e.unit in R)r=R[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if("mu"===e.unit)r=t.fontMetrics().cssEmPerMu;else{let o;if(o=t.style.isTight()?t.havingStyle(t.style.text()):t,"ex"===e.unit)r=o.fontMetrics().xHeight;else{if("em"!==e.unit)throw new n("Invalid unit: '"+e.unit+"'");r=o.fontMetrics().quad}o!==t&&(r*=o.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*r,t.maxSize)},N=function(e){return+e.toFixed(4)+"em"},D=function(e){return e.filter(e=>e).join(" ")},L=function(e){let t="";for(const r of Object.keys(e)){const n=e[r];void 0!==n&&(t+=s(r)+":"+n+";")}return t},F=function(e,t,r){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=r||{},t){t.style.isTight()&&this.classes.push("mtight");const e=t.getColor();e&&(this.style.color=e)}},P=function(e){const t=document.createElement(e);t.className=D(this.classes),Object.assign(t.style,this.style);for(const e of Object.keys(this.attributes))t.setAttribute(e,this.attributes[e]);for(let e=0;e/=\x00-\x1f]/,G=function(e){let t="<"+e;this.classes.length&&(t+=' class="'+l(D(this.classes))+'"');const r=L(this.style);r&&(t+=' style="'+l(r)+'"');for(const e of Object.keys(this.attributes)){if(V.test(e))throw new n("Invalid attribute name '"+e+"'");t+=" "+e+'="'+l(this.attributes[e])+'"'}t+=">";for(let e=0;e",t};class j{constructor(e,t,r,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,F.call(this,e,r,n),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return P.call(this,"span")}toMarkup(){return G.call(this,"span")}}class U{constructor(e,t,r,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,F.call(this,t,n),this.children=r||[],this.setAttribute("href",e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return P.call(this,"a")}toMarkup(){return G.call(this,"a")}}class Y{constructor(e,t,r){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=["mord"],this.height=0,this.depth=0,this.maxFontSize=0,this.style=r}hasClass(e){return this.classes.includes(e)}toNode(){const e=document.createElement("img");return e.src=this.src,e.alt=this.alt,e.className="mord",Object.assign(e.style,this.style),e}toMarkup(){let e=''+l(this.alt)+'=n[0]&&e<=n[1])return r.name}}return null}(this.text.charCodeAt(0));l&&this.classes.push(l+"_fallback"),/[\xee\xef\xed\xec]/.test(this.text)&&(this.text=X[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){const e=document.createTextNode(this.text);let t=null;return this.italic>0&&(t=document.createElement("span"),t.style.marginRight=N(this.italic)),this.classes.length>0&&(t=t||document.createElement("span"),t.className=D(this.classes)),Object.keys(this.style).length>0&&(t=t||document.createElement("span"),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){let e=!1,t="0&&(r+="margin-right:"+N(this.italic)+";"),r+=L(this.style),r&&(e=!0,t+=' style="'+l(r)+'"');const n=l(this.text);return e?(t+=">",t+=n,t+="",t):n}}class _{constructor(e,t){this.children=void 0,this.attributes=void 0,this.children=e||[],this.attributes=t||{}}toNode(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");for(const t of Object.keys(this.attributes))e.setAttribute(t,this.attributes[t]);for(let t=0;t':''}}class Z{constructor(e){this.attributes=void 0,this.attributes=e||{}}toNode(){const e=document.createElementNS("http://www.w3.org/2000/svg","line");for(const t of Object.keys(this.attributes))e.setAttribute(t,this.attributes[t]);return e}toMarkup(){let e="","\\gt",!0),oe(se,ae,be,"\u2208","\\in",!0),oe(se,ae,be,"\ue020","\\@not"),oe(se,ae,be,"\u2282","\\subset",!0),oe(se,ae,be,"\u2283","\\supset",!0),oe(se,ae,be,"\u2286","\\subseteq",!0),oe(se,ae,be,"\u2287","\\supseteq",!0),oe(se,le,be,"\u2288","\\nsubseteq",!0),oe(se,le,be,"\u2289","\\nsupseteq",!0),oe(se,ae,be,"\u22a8","\\models"),oe(se,ae,be,"\u2190","\\leftarrow",!0),oe(se,ae,be,"\u2264","\\le"),oe(se,ae,be,"\u2264","\\leq",!0),oe(se,ae,be,"<","\\lt",!0),oe(se,ae,be,"\u2192","\\rightarrow",!0),oe(se,ae,be,"\u2192","\\to"),oe(se,le,be,"\u2271","\\ngeq",!0),oe(se,le,be,"\u2270","\\nleq",!0),oe(se,ae,ye,"\xa0","\\ "),oe(se,ae,ye,"\xa0","\\space"),oe(se,ae,ye,"\xa0","\\nobreakspace"),oe(ie,ae,ye,"\xa0","\\ "),oe(ie,ae,ye,"\xa0"," "),oe(ie,ae,ye,"\xa0","\\space"),oe(ie,ae,ye,"\xa0","\\nobreakspace"),oe(se,ae,ye,"","\\nobreak"),oe(se,ae,ye,"","\\allowbreak"),oe(se,ae,fe,",",","),oe(se,ae,fe,";",";"),oe(se,le,he,"\u22bc","\\barwedge",!0),oe(se,le,he,"\u22bb","\\veebar",!0),oe(se,ae,he,"\u2299","\\odot",!0),oe(se,ae,he,"\u2295","\\oplus",!0),oe(se,ae,he,"\u2297","\\otimes",!0),oe(se,ae,xe,"\u2202","\\partial",!0),oe(se,ae,he,"\u2298","\\oslash",!0),oe(se,le,he,"\u229a","\\circledcirc",!0),oe(se,le,he,"\u22a1","\\boxdot",!0),oe(se,ae,he,"\u25b3","\\bigtriangleup"),oe(se,ae,he,"\u25bd","\\bigtriangledown"),oe(se,ae,he,"\u2020","\\dagger"),oe(se,ae,he,"\u22c4","\\diamond"),oe(se,ae,he,"\u22c6","\\star"),oe(se,ae,he,"\u25c3","\\triangleleft"),oe(se,ae,he,"\u25b9","\\triangleright"),oe(se,ae,ge,"{","\\{"),oe(ie,ae,xe,"{","\\{"),oe(ie,ae,xe,"{","\\textbraceleft"),oe(se,ae,me,"}","\\}"),oe(ie,ae,xe,"}","\\}"),oe(ie,ae,xe,"}","\\textbraceright"),oe(se,ae,ge,"{","\\lbrace"),oe(se,ae,me,"}","\\rbrace"),oe(se,ae,ge,"[","\\lbrack",!0),oe(ie,ae,xe,"[","\\lbrack",!0),oe(se,ae,me,"]","\\rbrack",!0),oe(ie,ae,xe,"]","\\rbrack",!0),oe(se,ae,ge,"(","\\lparen",!0),oe(se,ae,me,")","\\rparen",!0),oe(ie,ae,xe,"<","\\textless",!0),oe(ie,ae,xe,">","\\textgreater",!0),oe(se,ae,ge,"\u230a","\\lfloor",!0),oe(se,ae,me,"\u230b","\\rfloor",!0),oe(se,ae,ge,"\u2308","\\lceil",!0),oe(se,ae,me,"\u2309","\\rceil",!0),oe(se,ae,xe,"\\","\\backslash"),oe(se,ae,xe,"\u2223","|"),oe(se,ae,xe,"\u2223","\\vert"),oe(ie,ae,xe,"|","\\textbar",!0),oe(se,ae,xe,"\u2225","\\|"),oe(se,ae,xe,"\u2225","\\Vert"),oe(ie,ae,xe,"\u2225","\\textbardbl"),oe(ie,ae,xe,"~","\\textasciitilde"),oe(ie,ae,xe,"\\","\\textbackslash"),oe(ie,ae,xe,"^","\\textasciicircum"),oe(se,ae,be,"\u2191","\\uparrow",!0),oe(se,ae,be,"\u21d1","\\Uparrow",!0),oe(se,ae,be,"\u2193","\\downarrow",!0),oe(se,ae,be,"\u21d3","\\Downarrow",!0),oe(se,ae,be,"\u2195","\\updownarrow",!0),oe(se,ae,be,"\u21d5","\\Updownarrow",!0),oe(se,ae,de,"\u2210","\\coprod"),oe(se,ae,de,"\u22c1","\\bigvee"),oe(se,ae,de,"\u22c0","\\bigwedge"),oe(se,ae,de,"\u2a04","\\biguplus"),oe(se,ae,de,"\u22c2","\\bigcap"),oe(se,ae,de,"\u22c3","\\bigcup"),oe(se,ae,de,"\u222b","\\int"),oe(se,ae,de,"\u222b","\\intop"),oe(se,ae,de,"\u222c","\\iint"),oe(se,ae,de,"\u222d","\\iiint"),oe(se,ae,de,"\u220f","\\prod"),oe(se,ae,de,"\u2211","\\sum"),oe(se,ae,de,"\u2a02","\\bigotimes"),oe(se,ae,de,"\u2a01","\\bigoplus"),oe(se,ae,de,"\u2a00","\\bigodot"),oe(se,ae,de,"\u222e","\\oint"),oe(se,ae,de,"\u222f","\\oiint"),oe(se,ae,de,"\u2230","\\oiiint"),oe(se,ae,de,"\u2a06","\\bigsqcup"),oe(se,ae,de,"\u222b","\\smallint"),oe(ie,ae,ue,"\u2026","\\textellipsis"),oe(se,ae,ue,"\u2026","\\mathellipsis"),oe(ie,ae,ue,"\u2026","\\ldots",!0),oe(se,ae,ue,"\u2026","\\ldots",!0),oe(se,ae,ue,"\u22ef","\\@cdots",!0),oe(se,ae,ue,"\u22f1","\\ddots",!0),oe(se,ae,xe,"\u22ee","\\varvdots"),oe(ie,ae,xe,"\u22ee","\\varvdots"),oe(se,ae,ce,"\u02ca","\\acute"),oe(se,ae,ce,"\u02cb","\\grave"),oe(se,ae,ce,"\xa8","\\ddot"),oe(se,ae,ce,"~","\\tilde"),oe(se,ae,ce,"\u02c9","\\bar"),oe(se,ae,ce,"\u02d8","\\breve"),oe(se,ae,ce,"\u02c7","\\check"),oe(se,ae,ce,"^","\\hat"),oe(se,ae,ce,"\u20d7","\\vec"),oe(se,ae,ce,"\u02d9","\\dot"),oe(se,ae,ce,"\u02da","\\mathring"),oe(se,ae,pe,"\ue131","\\@imath"),oe(se,ae,pe,"\ue237","\\@jmath"),oe(se,ae,xe,"\u0131","\u0131"),oe(se,ae,xe,"\u0237","\u0237"),oe(ie,ae,xe,"\u0131","\\i",!0),oe(ie,ae,xe,"\u0237","\\j",!0),oe(ie,ae,xe,"\xdf","\\ss",!0),oe(ie,ae,xe,"\xe6","\\ae",!0),oe(ie,ae,xe,"\u0153","\\oe",!0),oe(ie,ae,xe,"\xf8","\\o",!0),oe(ie,ae,xe,"\xc6","\\AE",!0),oe(ie,ae,xe,"\u0152","\\OE",!0),oe(ie,ae,xe,"\xd8","\\O",!0),oe(ie,ae,ce,"\u02ca","\\'"),oe(ie,ae,ce,"\u02cb","\\`"),oe(ie,ae,ce,"\u02c6","\\^"),oe(ie,ae,ce,"\u02dc","\\~"),oe(ie,ae,ce,"\u02c9","\\="),oe(ie,ae,ce,"\u02d8","\\u"),oe(ie,ae,ce,"\u02d9","\\."),oe(ie,ae,ce,"\xb8","\\c"),oe(ie,ae,ce,"\u02da","\\r"),oe(ie,ae,ce,"\u02c7","\\v"),oe(ie,ae,ce,"\xa8",'\\"'),oe(ie,ae,ce,"\u02dd","\\H"),oe(ie,ae,ce,"\u25ef","\\textcircled");const we={"--":!0,"---":!0,"``":!0,"''":!0};oe(ie,ae,xe,"\u2013","--",!0),oe(ie,ae,xe,"\u2013","\\textendash"),oe(ie,ae,xe,"\u2014","---",!0),oe(ie,ae,xe,"\u2014","\\textemdash"),oe(ie,ae,xe,"\u2018","`",!0),oe(ie,ae,xe,"\u2018","\\textquoteleft"),oe(ie,ae,xe,"\u2019","'",!0),oe(ie,ae,xe,"\u2019","\\textquoteright"),oe(ie,ae,xe,"\u201c","``",!0),oe(ie,ae,xe,"\u201c","\\textquotedblleft"),oe(ie,ae,xe,"\u201d","''",!0),oe(ie,ae,xe,"\u201d","\\textquotedblright"),oe(se,ae,xe,"\xb0","\\degree",!0),oe(ie,ae,xe,"\xb0","\\degree"),oe(ie,ae,xe,"\xb0","\\textdegree",!0),oe(se,ae,xe,"\xa3","\\pounds"),oe(se,ae,xe,"\xa3","\\mathsterling",!0),oe(ie,ae,xe,"\xa3","\\pounds"),oe(ie,ae,xe,"\xa3","\\textsterling",!0),oe(se,le,xe,"\u2720","\\maltese"),oe(ie,le,xe,"\u2720","\\maltese");const ve='0123456789/@."';for(let e=0;e<14;e++){const t=ve.charAt(e);oe(se,ae,xe,t,t)}const ke='0123456789!@*()-=+";:?/.,';for(let e=0;e<25;e++){const t=ke.charAt(e);oe(ie,ae,xe,t,t)}const ze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";for(let e=0;e<52;e++){const t=ze.charAt(e);oe(se,ae,pe,t,t),oe(ie,ae,xe,t,t)}let Se;oe(se,le,xe,"C","\u2102"),oe(ie,le,xe,"C","\u2102"),oe(se,le,xe,"H","\u210d"),oe(ie,le,xe,"H","\u210d"),oe(se,le,xe,"N","\u2115"),oe(ie,le,xe,"N","\u2115"),oe(se,le,xe,"P","\u2119"),oe(ie,le,xe,"P","\u2119"),oe(se,le,xe,"Q","\u211a"),oe(ie,le,xe,"Q","\u211a"),oe(se,le,xe,"R","\u211d"),oe(ie,le,xe,"R","\u211d"),oe(se,le,xe,"Z","\u2124"),oe(ie,le,xe,"Z","\u2124"),oe(se,ae,pe,"h","\u210e"),oe(ie,ae,pe,"h","\u210e");for(let e=0;e<52;e++){const t=ze.charAt(e);Se=String.fromCharCode(55349,56320+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56372+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56424+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56580+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56684+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56736+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56788+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56840+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56944+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),e<26&&(Se=String.fromCharCode(55349,56632+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,56476+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se))}Se=String.fromCharCode(55349,56668),oe(se,ae,pe,"k",Se),oe(ie,ae,xe,"k",Se);for(let e=0;e<10;e++){const t=e.toString();Se=String.fromCharCode(55349,57294+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,57314+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,57324+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se),Se=String.fromCharCode(55349,57334+e),oe(se,ae,pe,t,Se),oe(ie,ae,xe,t,Se)}const Me="\xd0\xde\xfe";for(let e=0;e<3;e++){const t=Me.charAt(e);oe(se,ae,pe,t,t),oe(ie,ae,xe,t,t)}const Ae={mathClass:"mathbf",textClass:"textbf",font:"Main-Bold"},Te={mathClass:"mathnormal",textClass:"textit",font:"Math-Italic"},Ce={mathClass:"boldsymbol",textClass:"boldsymbol",font:"Main-BoldItalic"},Be={mathClass:"",textClass:"",font:""},qe={mathClass:"mathfrak",textClass:"textfrak",font:"Fraktur-Regular"},Ie={mathClass:"mathbb",textClass:"textbb",font:"AMS-Regular"},Re={mathClass:"mathboldfrak",textClass:"textboldfrak",font:"Fraktur-Regular"},Oe={mathClass:"mathsf",textClass:"textsf",font:"SansSerif-Regular"},Ee={mathClass:"mathboldsf",textClass:"textboldsf",font:"SansSerif-Bold"},He={mathClass:"mathitsf",textClass:"textitsf",font:"SansSerif-Italic"},Ne={mathClass:"mathtt",textClass:"texttt",font:"Typewriter-Regular"},De=[Ae,Ae,Te,Te,Ce,Ce,{mathClass:"mathscr",textClass:"textscr",font:"Script-Regular"},Be,Be,Be,qe,qe,Ie,Ie,Re,Re,Oe,Oe,Ee,Ee,He,He,Be,Be,Ne,Ne],Le=[Ae,Be,Oe,Ee,Ne];function Fe(e){const t=e.strict,r=e.errorCode,o=e.errorMsg,s=e.token,i=e.report;let a=t;if("function"==typeof t)if(i)a=t(r,o,s);else try{a=t(r,o,s)}catch(e){a="error"}switch(a){case!0:case"error":if(i)throw new n("LaTeX-incompatible input and strict mode is set to 'error': "+o+" ["+r+"]",s);return!0;case!1:case"ignore":if(!i)return!1;break;default:if("undefined"!=typeof console&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+o+" ["+r+"]"),!i)return!1}}const Pe=function(e,t,r){if(ne[r][e]){const t=ne[r][e].replace;t&&(e=t)}return{value:e,metrics:ee(e,t,r)}},Ve=function(e,t,r,n,o){const s=Pe(e,t,r),i=s.metrics;let a;if(e=s.value,i){let t=i.italic;("text"===r||n&&"mathit"===n.font)&&(t=0),a=new W(e,i.height,i.depth,t,i.skew,i.width,o)}else Fe({strict:n.strict,errorCode:"symbolNotInFont",errorMsg:"No character metrics for '"+e+"' in style '"+t+"' and mode '"+r+"'",report:!0}),a=new W(e,0,0,0,0,0,o);a.maxFontSize=n.sizeMultiplier,n.style.isTight()&&a.classes.push("mtight");const l=n.getColor();return l&&(a.style.color=l),a},Ge=function(e,t,r,n){return void 0===n&&(n=[]),"boldsymbol"===r.font&&Pe(e,"Main-Bold",t).metrics?Ve(e,"Main-Bold",t,r,n.concat(["mathbf"])):"\\"===e||"main"===ne[t][e].font?Ve(e,"Main-Regular",t,r,n):Ve(e,"AMS-Regular",t,r,n.concat(["amsrm"]))},je=function(e,t){const r="mathord"===e.type?"mathord":"textord",o=e.mode,s=e.text,i=["mord"],a=t.font,l=t.fontFamily,c=t.fontWeight,h=t.fontShape,m="math"===o||"text"===o&&!!a,u=m?a:l;let p="",d="";if(55349===s.charCodeAt(0)){const e=(e=>{const t=1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320)+65536;if(119808<=t&&t<120484){const e=Math.floor((t-119808)/26);return De[e]}if(120782<=t&&t<=120831){const e=Math.floor((t-120782)/10);return Le[e]}if(120485===t||120486===t)return De[0];if(120486{if(D(e.classes)!==D(t.classes)||e.skew!==t.skew||e.maxFontSize!==t.maxFontSize||0!==e.italic&&e.hasClass("mathnormal"))return!1;if(1===e.classes.length){const t=e.classes[0];if("mbin"===t||"mord"===t)return!1}for(const r of Object.keys(e.style))if(e.style[r]!==t.style[r])return!1;for(const r of Object.keys(t.style))if(e.style[r]!==t.style[r])return!1;return!0},Ye=e=>{for(let t=0;tt&&(t=s.height),s.depth>r&&(r=s.depth),s.maxFontSize>n&&(n=s.maxFontSize)}e.height=t,e.depth=r,e.maxFontSize=n},We=function(e,t,r,n){const o=new j(e,t,r,n);return Xe(o),o},_e=(e,t,r,n)=>new j(e,t,r,n),$e=function(e,t,r){const n=We([e],[],t);return n.height=Math.max(r||t.fontMetrics().defaultRuleThickness,t.minRuleThickness),n.style.borderBottomWidth=N(n.height),n.maxFontSize=1,n},Ze=function(e){const t=new I(e);return Xe(t),t},Ke=function(e,t){return e instanceof I?We([],[e],t):e},Je=function(e,t){const r=function(e){if("individualShift"===e.positionType){const t=e.children,r=[t[0]],n=-t[0].shift-t[0].elem.depth;let o=n;for(let e=1;e{const r=We(["mspace"],[],t),n=H(e,t);return r.style.marginRight=N(n),r},et=(e,t,r)=>{let n,o;switch(e){case"amsrm":n="AMS";break;case"textrm":n="Main";break;case"textsf":n="SansSerif";break;case"texttt":n="Typewriter";break;default:n=e}return o="textbf"===t&&"textit"===r?"BoldItalic":"textbf"===t?"Bold":"textit"===r?"Italic":"Regular",n+"-"+o},tt={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathnormal:{variant:"italic",fontName:"Math-Italic"},mathsfit:{variant:"sans-serif-italic",fontName:"SansSerif-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},rt={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]},nt=function(e,t){const r=rt[e],n=r[0],o=r[1],s=r[2],i=new $(n),a=new _([i],{width:N(o),height:N(s),style:"width:"+N(o),viewBox:"0 0 "+1e3*o+" "+1e3*s,preserveAspectRatio:"xMinYMin"}),l=_e(["katex-overlay"],[a],t);return l.height=s,l.style.height=N(s),l.style.width=N(o),l},ot={number:3,unit:"mu"},st={number:4,unit:"mu"},it={number:5,unit:"mu"},at={mord:{mop:ot,mbin:st,mrel:it,minner:ot},mop:{mord:ot,mop:ot,mrel:it,minner:ot},mbin:{mord:st,mop:st,mopen:st,minner:st},mrel:{mord:it,mop:it,mopen:it,minner:it},mopen:{},mclose:{mop:ot,mbin:st,mrel:it,minner:ot},mpunct:{mord:ot,mop:ot,mrel:it,mopen:ot,mclose:ot,mpunct:ot,minner:ot},minner:{mord:ot,mop:ot,mbin:st,mrel:it,mopen:ot,mpunct:ot,minner:ot}},lt={mord:{mop:ot},mop:{mord:ot,mop:ot},mbin:{},mrel:{},mopen:{},mclose:{mop:ot},mpunct:{},minner:{mop:ot}},ct={},ht={},mt={};function ut(e){const t=e.type,r=e.names,n=e.htmlBuilder,o=e.mathmlBuilder;for(let t=0;t{const r=t.classes[0],n=e.classes[0];"mbin"===r&&bt.has(n)?t.classes[0]="mord":"mbin"===n&&ft.has(r)&&(e.classes[0]="mord")},{node:i},a,l),vt(o,(e,t)=>{var r,n;const o=St(t),i=St(e),a=o&&i?e.hasClass("mtight")?null==(r=lt[o])?void 0:r[i]:null==(n=at[o])?void 0:n[i]:null;if(a)return Qe(a,s)},{node:i},a,l),o},vt=function(e,t,r,n,o){n&&e.push(n);let s=0;for(;sr=>{e.splice(t+1,0,r),s++})(s)}n&&e.pop()},kt=function(e){return e instanceof I||e instanceof U||e instanceof j&&e.hasClass("enclosing")?e:null},zt=function(e,t){const r=kt(e);if(r){const e=r.children;if(e.length){if("right"===t)return zt(e[e.length-1],"right");if("left"===t)return zt(e[0],"left")}}return e},St=function(e,t){if(!e)return null;t&&(e=zt(e,t));const r=e.classes[0];return xt[r]||null},Mt=function(e,t){const r=["nulldelimiter"].concat(e.baseSizingClasses());return We(t.concat(r))},At=function(e,t,r){if(!e)return We();if(ht[e.type]){let n=ht[e.type](e,t);if(r&&t.size!==r.size){n=We(t.sizingClasses(r),[n],t);const e=t.sizeMultiplier/r.sizeMultiplier;n.height*=e,n.depth*=e}return n}throw new n("Got group of unknown type: '"+e.type+"'")};function Tt(e,t){const r=We(["katex-base"],e,t),n=We(["katex-strut"]);return n.style.height=N(r.height+r.depth),r.depth&&(n.style.verticalAlign=N(-r.depth)),r.children.unshift(n),r}function Ct(e,t){let r=null;1===e.length&&"tag"===e[0].type&&(r=e[0].tag,e=e[0].body);const n=wt(e,t,"root");let o;2===n.length&&n[1].hasClass("katex-tag")&&(o=n.pop());const s=[];let i,a=[];for(let e=0;e0&&(s.push(Tt(a,t)),a=[]),s.push(n[e]));a.length>0&&s.push(Tt(a,t)),r?(i=Tt(wt(r,t,!0),t),i.classes=["katex-tag"],s.push(i)):o&&s.push(o);const l=We(["katex-html"],s);if(l.setAttribute("aria-hidden","true"),i){const e=i.children[0];e.style.height=N(l.height+l.depth),l.depth&&(e.style.verticalAlign=N(-l.depth))}return l}function Bt(e){return new I(e)}class qt{constructor(e,t,r){this.type=void 0,this.attributes=void 0,this.children=void 0,this.classes=void 0,this.type=e,this.attributes={},this.children=t||[],this.classes=r||[]}setAttribute(e,t){this.attributes[e]=t}getAttribute(e){return this.attributes[e]}toNode(){const e=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(const t of Object.entries(this.attributes)){const r=t[0],n=t[1];e.setAttribute(r,n)}this.classes.length>0&&(e.className=D(this.classes));for(let t=0;t0&&(e+=' class ="'+l(D(this.classes))+'"'),e+=">";for(let t=0;t",e}toText(){return this.children.map(e=>e.toText()).join("")}}class It{constructor(e){this.text=void 0,this.text=e}toNode(){return document.createTextNode(this.text)}toMarkup(){return l(this.toText())}toText(){return this.text}}class Rt{constructor(e){this.width=void 0,this.character=void 0,this.width=e,this.character=e>=.05555&&e<=.05556?"\u200a":e>=.1666&&e<=.1667?"\u2009":e>=.2222&&e<=.2223?"\u2005":e>=.2777&&e<=.2778?"\u2005\u200a":e>=-.05556&&e<=-.05555?"\u200a\u2063":e>=-.1667&&e<=-.1666?"\u2009\u2063":e>=-.2223&&e<=-.2222?"\u205f\u2063":e>=-.2778&&e<=-.2777?"\u2005\u2063":null}toNode(){if(this.character)return document.createTextNode(this.character);{const e=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return e.setAttribute("width",N(this.width)),e}}toMarkup(){return this.character?""+this.character+"":''}toText(){return this.character?this.character:" "}}const Ot=new Set(["\\imath","\\jmath"]),Et=new Set(["mrow","mtable"]),Ht=function(e,t,r){var n,o;return ne[t][e]&&ne[t][e].replace&&55349!==e.charCodeAt(0)&&(!Object.prototype.hasOwnProperty.call(we,e)||"tt"!==(null==r||null==(n=r.fontFamily)?void 0:n.slice(4,6))&&"tt"!==(null==r||null==(o=r.font)?void 0:o.slice(4,6)))&&(e=ne[t][e].replace),new It(e)},Nt=function(e){return 1===e.length?e[0]:new qt("mrow",e)},Dt={mathit:"italic",boldsymbol:e=>"textord"===e.type?"bold":"bold-italic",mathbf:"bold",mathbb:"double-struck",mathsfit:"sans-serif-italic",mathfrak:"fraktur",mathscr:"script",mathcal:"script",mathsf:"sans-serif",mathtt:"monospace"},Lt=(e,t)=>{if("text"===e.mode){if("texttt"===t.fontFamily)return"monospace";if("textsf"===t.fontFamily)return"textit"===t.fontShape&&"textbf"===t.fontWeight?"sans-serif-bold-italic":"textit"===t.fontShape?"sans-serif-italic":"textbf"===t.fontWeight?"bold-sans-serif":"sans-serif";if("textit"===t.fontShape&&"textbf"===t.fontWeight)return"bold-italic";if("textit"===t.fontShape)return"italic";if("textbf"===t.fontWeight)return"bold"}const r=t.font;if(!r||"mathnormal"===r)return null;const n=e.mode,o=Dt[r];if(o)return"function"==typeof o?o(e):o;let s=e.text;if(Ot.has(s))return null;if(ne[n][s]){const e=ne[n][s].replace;e&&(s=e)}return ee(s,tt[r].fontName,n)?tt[r].variant:null};function Ft(e){if(!e)return!1;if("mi"===e.type&&1===e.children.length){const t=e.children[0];return t instanceof It&&"."===t.text}if("mo"===e.type&&1===e.children.length&&"true"===e.getAttribute("separator")&&"0em"===e.getAttribute("lspace")&&"0em"===e.getAttribute("rspace")){const t=e.children[0];return t instanceof It&&","===t.text}return!1}const Pt=function(e,t,r){if(1===e.length){const n=Gt(e[0],t);return r&&n instanceof qt&&"mo"===n.type&&(n.setAttribute("lspace","0em"),n.setAttribute("rspace","0em")),[n]}const n=[];let o;for(let r=0;r=1&&("mn"===o.type||Ft(o))){const e=s.children[0];e instanceof qt&&"mn"===e.type&&(e.children=[...o.children,...e.children],n.pop())}else if("mi"===o.type&&1===o.children.length){const e=o.children[0];if(e instanceof It&&"\u0338"===e.text&&("mo"===s.type||"mi"===s.type||"mn"===s.type)){const e=s.children[0];e instanceof It&&e.text.length>0&&(e.text=e.text.slice(0,1)+"\u0338"+e.text.slice(1),n.pop())}}}n.push(s),o=s}return n},Vt=function(e,t,r){return Nt(Pt(e,t,r))},Gt=function(e,t){if(!e)return new qt("mrow");if(mt[e.type])return mt[e.type](e,t);throw new n("Got group of unknown type: '"+e.type+"'")};function jt(e,t,r,n,o){const s=Pt(e,r);let i;i=1===s.length&&s[0]instanceof qt&&Et.has(s[0].type)?s[0]:new qt("mrow",s);const a=new qt("annotation",[new It(t)]);a.setAttribute("encoding","application/x-tex");const l=new qt("semantics",[i,a]),c=new qt("math",[l]);c.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML"),n&&c.setAttribute("display","block");return We([o?"katex":"katex-mathml"],[c])}const Ut=[[1,1,1],[2,1,1],[3,1,1],[4,2,1],[5,2,1],[6,3,1],[7,4,2],[8,6,3],[9,7,6],[10,8,7],[11,10,9]],Yt=[.5,.6,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],Xt=function(e,t){return t.size<2?e:Ut[e-1][t.size-1]};class Wt{constructor(e){this.style=void 0,this.color=void 0,this.size=void 0,this.textSize=void 0,this.phantom=void 0,this.font=void 0,this.fontFamily=void 0,this.fontWeight=void 0,this.fontShape=void 0,this.sizeMultiplier=void 0,this.maxSize=void 0,this.minRuleThickness=void 0,this._fontMetrics=void 0,this.strict=void 0,this.style=e.style,this.color=e.color,this.size=e.size||Wt.BASESIZE,this.textSize=e.textSize||this.size,this.phantom=!!e.phantom,this.font=e.font||"",this.fontFamily=e.fontFamily||"",this.fontWeight=e.fontWeight||"",this.fontShape=e.fontShape||"",this.sizeMultiplier=Yt[this.size-1],this.maxSize=e.maxSize,this.minRuleThickness=e.minRuleThickness,this.strict=e.strict,this._fontMetrics=void 0}extend(e){const t={style:this.style,size:this.size,textSize:this.textSize,color:this.color,phantom:this.phantom,font:this.font,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontShape:this.fontShape,maxSize:this.maxSize,minRuleThickness:this.minRuleThickness,strict:this.strict};return Object.assign(t,e),new Wt(t)}havingStyle(e){return this.style===e?this:this.extend({style:e,size:Xt(this.textSize,e)})}havingCrampedStyle(){return this.havingStyle(this.style.cramp())}havingSize(e){return this.size===e&&this.textSize===e?this:this.extend({style:this.style.text(),size:e,textSize:e,sizeMultiplier:Yt[e-1]})}havingBaseStyle(e){e=e||this.style.text();const t=Xt(Wt.BASESIZE,e);return this.size===t&&this.textSize===Wt.BASESIZE&&this.style===e?this:this.extend({style:e,size:t})}havingBaseSizing(){let e;switch(this.style.id){case 4:case 5:e=3;break;case 6:case 7:e=1;break;default:e=6}return this.extend({style:this.style.text(),size:e})}withColor(e){return this.extend({color:e})}withPhantom(){return this.extend({phantom:!0})}withFont(e){return this.extend({font:e})}withTextFontFamily(e){return this.extend({fontFamily:e,font:""})}withTextFontWeight(e){return this.extend({fontWeight:e,font:""})}withTextFontShape(e){return this.extend({fontShape:e,font:""})}sizingClasses(e){return e.size!==this.size?["katex-sizing","reset-size"+e.size,"size"+this.size]:[]}baseSizingClasses(){return this.size!==Wt.BASESIZE?["katex-sizing","reset-size"+this.size,"size"+Wt.BASESIZE]:[]}fontMetrics(){return this._fontMetrics||(this._fontMetrics=function(e){let t;if(t=e>=5?0:e>=3?1:2,!te[t]){const e=te[t]={cssEmPerMu:J.quad[t]/18};for(const r of Object.keys(J))e[r]=J[r][t]}return te[t]}(this.size)),this._fontMetrics}getColor(){return this.phantom?"transparent":this.color}}Wt.BASESIZE=6;var _t=Wt;const $t=e=>new _t({style:e.displayMode?S.DISPLAY:S.TEXT,maxSize:e.maxSize,minRuleThickness:e.minRuleThickness,strict:e.strict}),Zt=function(e,t){if(t.displayMode){const r=["katex-display"];t.leqno&&r.push("leqno"),t.fleqn&&r.push("fleqn"),e=We(r,[e])}return e},Kt=function(e,t,r){const n=$t(r);let o;if("mathml"===r.output)return jt(e,t,n,r.displayMode,!0);if("html"===r.output){const t=Ct(e,n);o=We(["katex"],[t])}else{const s=jt(e,t,n,r.displayMode,!1),i=Ct(e,n);o=We(["katex"],[s,i])}return Zt(o,r)};const Jt={widehat:"^",widecheck:"\u02c7",widetilde:"~",utilde:"~",overleftarrow:"\u2190",underleftarrow:"\u2190",xleftarrow:"\u2190",overrightarrow:"\u2192",underrightarrow:"\u2192",xrightarrow:"\u2192",underbrace:"\u23df",overbrace:"\u23de",underbracket:"\u23b5",overbracket:"\u23b4",overgroup:"\u23e0",undergroup:"\u23e1",overleftrightarrow:"\u2194",underleftrightarrow:"\u2194",xleftrightarrow:"\u2194",Overrightarrow:"\u21d2",xRightarrow:"\u21d2",overleftharpoon:"\u21bc",xleftharpoonup:"\u21bc",overrightharpoon:"\u21c0",xrightharpoonup:"\u21c0",xLeftarrow:"\u21d0",xLeftrightarrow:"\u21d4",xhookleftarrow:"\u21a9",xhookrightarrow:"\u21aa",xmapsto:"\u21a6",xrightharpoondown:"\u21c1",xleftharpoondown:"\u21bd",xrightleftharpoons:"\u21cc",xleftrightharpoons:"\u21cb",xtwoheadleftarrow:"\u219e",xtwoheadrightarrow:"\u21a0",xlongequal:"=",xtofrom:"\u21c4",xrightleftarrows:"\u21c4",xrightequilibrium:"\u21cc",xleftequilibrium:"\u21cb","\\cdrightarrow":"\u2192","\\cdleftarrow":"\u2190","\\cdlongequal":"="},Qt=function(e){const t=new qt("mo",[new It(Jt[e.replace(/^\\/,"")])]);return t.setAttribute("stretchy","true"),t},er={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],"\\cdrightarrow":[["rightarrow"],3,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],"\\cdleftarrow":[["leftarrow"],3,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],"\\cdlongequal":[["longequal"],3,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overbracket:[["leftbracketover","rightbracketover"],1.6,440],underbracket:[["leftbracketunder","rightbracketunder"],1.6,410],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},tr=new Set(["widehat","widecheck","widetilde","utilde"]),rr=function(e,t){const r=function(){let r=4e5;const n=e.label.slice(1);if(tr.has(n)&&"base"in e){const o="ordgroup"===e.base.type?e.base.body.length:1;let s,i,a;if(o>5)"widehat"===n||"widecheck"===n?(s=420,r=2364,a=.42,i=n+"4"):(s=312,r=2340,a=.34,i="tilde4");else{const e=[1,1,2,2,3,3][o];"widehat"===n||"widecheck"===n?(r=[0,1062,2364,2364,2364][e],s=[0,239,300,360,420][e],a=[0,.24,.3,.3,.36,.42][e],i=n+e):(r=[0,600,1033,2339,2340][e],s=[0,260,286,306,312][e],a=[0,.26,.286,.3,.306,.34][e],i="tilde"+e)}const l=new $(i),c=new _([l],{width:"100%",height:N(a),viewBox:"0 0 "+r+" "+s,preserveAspectRatio:"none"});return{span:_e([],[c],t),minWidth:0,height:a}}{const e=[],o=er[n];if(!o)throw new Error('No SVG data for "'+n+'".');const s=o[0],i=o[1],a=o[2],l=a/1e3,c=s.length;let h,m;if(1===c){if(4!==o.length)throw new Error('Expected 4-tuple for single-path SVG data "'+n+'".');h=["hide-tail"],m=[o[3]]}else if(2===c)h=["halfarrow-left","halfarrow-right"],m=["xMinYMin","xMaxYMin"];else{if(3!==c)throw new Error("Correct katexImagesData or update code here to support\n "+c+" children.");h=["brace-left","brace-center","brace-right"],m=["xMinYMin","xMidYMin","xMaxYMin"]}for(let n=0;n0&&(n.style.minWidth=N(o)),n},nr=new Set(["bin","close","inner","open","punct","rel"]),or=new Set(["accent-token","mathord","op-token","spacing","textord"]);function sr(e,t){if(!e||e.type!==t)throw new Error("Expected node of type "+t+", but got "+(e?"node of type "+e.type:String(e)));return e}function ir(e){const t=ar(e);if(!t)throw new Error("Expected node of symbol group type, but got "+(e?"node of type "+e.type:String(e)));return t}function ar(e){return"atom"===e.type||or.has(e.type)?e:null}function lr(e,t,r){let o="";for(const s of e.body)if("textord"===s.type)o+=s.text;else{if(!r||"spacing"!==s.type||" "!==s.text)throw new n(t,e);o+=" "}return o}const cr=e=>{return e instanceof W?e:((t=e)instanceof j||t instanceof U||t instanceof I)&&1===e.children.length?cr(e.children[0]):void 0;var t},hr=(e,t)=>{let r,n,o;e&&"supsub"===e.type?(n=sr(e.base,"accent"),r=n.base,e.base=r,o=function(e){if(e instanceof j)return e;throw new Error("Expected span but got "+String(e)+".")}(At(e,t)),e.base=n):(n=sr(e,"accent"),r=n.base);const s=At(r,t.havingCrampedStyle());let i=0;var a,l;n.isShifty&&m(r)&&(i=null!=(a=null==(l=cr(s))?void 0:l.skew)?a:0);const c="\\c"===n.label;let h,u=c?s.height+s.depth:Math.min(s.height,t.fontMetrics().xHeight);if(n.isStretchy)h=rr(n,t),h=Je({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"elem",elem:h,wrapperClasses:["svg-align"],wrapperStyle:i>0?{width:"calc(100% - "+N(2*i)+")",marginLeft:N(2*i)}:void 0}]});else{let e,r;"\\vec"===n.label?(e=nt("vec",t),r=rt.vec[1]):(e=je({type:"textord",mode:n.mode,text:n.label},t),e=function(e){if(e instanceof W)return e;throw new Error("Expected symbolNode but got "+String(e)+".")}(e),e.italic=0,r=e.width,c&&(u+=e.depth)),h=We(["accent-body"],[e]);const o="\\textcircled"===n.label;o&&(h.classes.push("accent-full"),u=s.height);let a=i;o||(a-=r/2),h.style.left=N(a),"\\textcircled"===n.label&&(h.style.top=".2em"),h=Je({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:-u},{type:"elem",elem:h}]})}const p=We(["mord","katex-accent"],[h],t);return o?(o.children[0]=p,o.height=Math.max(p.height,o.height),o.classes[0]="mord",o):p},mr=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(e=>"\\"+e).join("|"));ut({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],numArgs:1,handler:(e,t)=>{const r=dt(t[0]),n=!mr.test(e.funcName),o=!n||"\\widehat"===e.funcName||"\\widetilde"===e.funcName||"\\widecheck"===e.funcName;return{type:"accent",mode:e.parser.mode,label:e.funcName,isStretchy:n,isShifty:o,base:r}},htmlBuilder:hr,mathmlBuilder:(e,t)=>{const r=e.isStretchy?Qt(e.label):new qt("mo",[Ht(e.label,e.mode)]),n=new qt("mover",[Gt(e.base,t),r]);return n.setAttribute("accent","true"),n}}),ut({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\c","\\r","\\H","\\v","\\textcircled"],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["primitive"],handler:(e,t)=>{const r=t[0];let n=e.parser.mode;return"math"===n&&(Fe({strict:e.parser.settings.strict,errorCode:"mathVsTextAccents",errorMsg:"LaTeX's accent "+e.funcName+" works only in text mode",report:!0}),n="text"),{type:"accent",mode:n,label:e.funcName,isStretchy:!1,isShifty:!0,base:r}}}),ut({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],numArgs:1,handler:(e,t)=>{let r=e.parser,n=e.funcName;const o=t[0];return{type:"accentUnder",mode:r.mode,label:n,base:o}},htmlBuilder:(e,t)=>{const r=At(e.base,t),n=rr(e,t),o="\\utilde"===e.label?.12:0,s=Je({positionType:"top",positionData:r.height,children:[{type:"elem",elem:n,wrapperClasses:["svg-align"]},{type:"kern",size:o},{type:"elem",elem:r}]});return We(["mord","accentunder"],[s],t)},mathmlBuilder:(e,t)=>{const r=Qt(e.label),n=new qt("munder",[Gt(e.base,t),r]);return n.setAttribute("accentunder","true"),n}});const ur=e=>{const t=new qt("mpadded",e?[e]:[]);return t.setAttribute("width","+0.6em"),t.setAttribute("lspace","0.3em"),t};ut({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium","\\\\cdrightarrow","\\\\cdleftarrow","\\\\cdlongequal"],numArgs:1,numOptionalArgs:1,handler(e,t,r){let n=e.parser,o=e.funcName;return{type:"xArrow",mode:n.mode,label:o,body:t[0],below:r[0]}},htmlBuilder(e,t){const r=t.style;let n=t.havingStyle(r.sup());const o=Ke(At(e.body,n,t),t),s="\\x"===e.label.slice(0,2)?"x":"cd";let i;o.classes.push(s+"-arrow-pad"),e.below&&(n=t.havingStyle(r.sub()),i=Ke(At(e.below,n,t),t),i.classes.push(s+"-arrow-pad"));const a=rr(e,t),l=-t.fontMetrics().axisHeight+.5*a.height;let c,h=-t.fontMetrics().axisHeight-.5*a.height-.111;if((o.depth>.25||"\\xleftequilibrium"===e.label)&&(h-=o.depth),i){const e=-t.fontMetrics().axisHeight+i.height+.5*a.height+.111;c=Je({positionType:"individualShift",children:[{type:"elem",elem:o,shift:h},{type:"elem",elem:a,shift:l,wrapperClasses:["svg-align"]},{type:"elem",elem:i,shift:e}]})}else c=Je({positionType:"individualShift",children:[{type:"elem",elem:o,shift:h},{type:"elem",elem:a,shift:l,wrapperClasses:["svg-align"]}]});return We(["mrel","x-arrow"],[c],t)},mathmlBuilder(e,t){const r=Qt(e.label);let n;if(r.setAttribute("minsize","x"===e.label.charAt(0)?"1.75em":"3.0em"),e.body){const o=ur(Gt(e.body,t));if(e.below){const s=ur(Gt(e.below,t));n=new qt("munderover",[r,s,o])}else n=new qt("mover",[r,o])}else if(e.below){const o=ur(Gt(e.below,t));n=new qt("munder",[r,o])}else n=ur(),n=new qt("mover",[r,n]);return n}}),ut({type:"mclass",names:["\\mathord","\\mathbin","\\mathrel","\\mathopen","\\mathclose","\\mathpunct","\\mathinner"],numArgs:1,primitive:!0,handler(e,t){let r=e.parser,n=e.funcName;const o=t[0];return{type:"mclass",mode:r.mode,mclass:"m"+n.slice(5),body:gt(o),isCharacterBox:m(o)}},htmlBuilder:function(e,t){const r=wt(e.body,t,!0);return We([e.mclass],r,t)},mathmlBuilder:function(e,t){let r;const n=Pt(e.body,t);return"minner"===e.mclass?r=new qt("mpadded",n):"mord"===e.mclass?e.isCharacterBox?(r=n[0],r.type="mi"):r=new qt("mi",n):(e.isCharacterBox?(r=n[0],r.type="mo"):r=new qt("mo",n),"mbin"===e.mclass?(r.attributes.lspace="0.22em",r.attributes.rspace="0.22em"):"mpunct"===e.mclass?(r.attributes.lspace="0em",r.attributes.rspace="0.17em"):"mopen"!==e.mclass&&"mclose"!==e.mclass||(r.attributes.lspace="0em",r.attributes.rspace="0em")),r}});const pr=e=>{const t="ordgroup"===e.type&&e.body.length?e.body[0]:e;return"atom"!==t.type||"bin"!==t.family&&"rel"!==t.family?"mord":"m"+t.family};ut({type:"mclass",names:["\\@binrel"],numArgs:2,handler(e,t){return{type:"mclass",mode:e.parser.mode,mclass:pr(t[0]),body:gt(t[1]),isCharacterBox:m(t[1])}}}),ut({type:"mclass",names:["\\stackrel","\\overset","\\underset"],numArgs:2,handler(e,t){let r=e.parser,n=e.funcName;const o=t[1],s=t[0];let i;i="\\stackrel"!==n?pr(o):"mrel";const a={type:"op",mode:o.mode,limits:!0,alwaysHandleSupSub:!0,parentIsSupSub:!1,symbol:!1,suppressBaseShift:"\\stackrel"!==n,body:gt(o)},l="\\underset"===n?{type:"supsub",mode:s.mode,base:a,sub:s}:{type:"supsub",mode:s.mode,base:a,sup:s};return{type:"mclass",mode:r.mode,mclass:i,body:[l],isCharacterBox:m(l)}}}),ut({type:"pmb",names:["\\pmb"],numArgs:1,allowedInText:!0,handler(e,t){return{type:"pmb",mode:e.parser.mode,mclass:pr(t[0]),body:gt(t[0])}},htmlBuilder(e,t){const r=wt(e.body,t,!0),n=We([e.mclass],r,t);return n.style.textShadow="0.02em 0.01em 0.04px",n},mathmlBuilder(e,t){const r=Pt(e.body,t),n=new qt("mstyle",r);return n.setAttribute("style","text-shadow: 0.02em 0.01em 0.04px"),n}});const dr={">":"\\\\cdrightarrow","<":"\\\\cdleftarrow","=":"\\\\cdlongequal",A:"\\uparrow",V:"\\downarrow","|":"\\Vert",".":"no arrow"},gr=()=>({type:"styling",body:[],mode:"math",style:"display",resetFont:!0}),fr=e=>"textord"===e.type&&"@"===e.text,br=(e,t)=>("mathord"===e.type||"atom"===e.type)&&e.text===t;function yr(e,t,r){const n=dr[e];switch(n){case"\\\\cdrightarrow":case"\\\\cdleftarrow":return r.callFunction(n,[t[0]],[t[1]]);case"\\uparrow":case"\\downarrow":{const e={type:"atom",text:n,mode:"math",family:"rel"},o={type:"ordgroup",mode:"math",body:[r.callFunction("\\\\cdleft",[t[0]],[]),r.callFunction("\\Big",[e],[]),r.callFunction("\\\\cdright",[t[1]],[])]};return r.callFunction("\\\\cdparent",[o],[])}case"\\\\cdlongequal":return r.callFunction("\\\\cdlongequal",[],[]);case"\\Vert":{const e={type:"textord",text:"\\Vert",mode:"math"};return r.callFunction("\\Big",[e],[])}default:return{type:"textord",text:" ",mode:"math"}}}ut({type:"cdlabel",names:["\\\\cdleft","\\\\cdright"],numArgs:1,handler(e,t){let r=e.parser,n=e.funcName;return{type:"cdlabel",mode:r.mode,side:n.slice(4),label:t[0]}},htmlBuilder(e,t){const r=t.havingStyle(t.style.sup()),n=Ke(At(e.label,r,t),t);return n.classes.push("cd-label-"+e.side),n.style.bottom=N(.8-n.depth),n.height=0,n.depth=0,n},mathmlBuilder(e,t){let r=new qt("mrow",[Gt(e.label,t)]);return r=new qt("mpadded",[r]),r.setAttribute("width","0"),"left"===e.side&&r.setAttribute("lspace","-1width"),r.setAttribute("voffset","0.7em"),r=new qt("mstyle",[r]),r.setAttribute("displaystyle","false"),r.setAttribute("scriptlevel","1"),r}}),ut({type:"cdlabelparent",names:["\\\\cdparent"],numArgs:1,handler(e,t){return{type:"cdlabelparent",mode:e.parser.mode,fragment:t[0]}},htmlBuilder(e,t){const r=Ke(At(e.fragment,t),t);return r.classes.push("cd-vert-arrow"),r},mathmlBuilder(e,t){return new qt("mrow",[Gt(e.fragment,t)])}}),ut({type:"textord",names:["\\@char"],numArgs:1,allowedInText:!0,handler(e,t){let r=e.parser;const o=lr(sr(t[0],"ordgroup"),"\\@char has non-numeric argument");let s,i=parseInt(o);if(isNaN(i))throw new n("\\@char has non-numeric argument "+o);if(i<0||i>1114111)throw new n("\\@char with invalid code point "+o);return i<=65535?s=String.fromCharCode(i):(i-=65536,s=String.fromCharCode(55296+(i>>10),56320+(1023&i))),{type:"textord",mode:r.mode,text:s}}});ut({type:"color",names:["\\textcolor"],numArgs:2,allowedInText:!0,argTypes:["color","original"],handler(e,t){let r=e.parser;const n=sr(t[0],"color-token").color,o=t[1];return{type:"color",mode:r.mode,color:n,body:gt(o)}},htmlBuilder:(e,t)=>{const r=wt(e.body,t.withColor(e.color),!1);return Ze(r)},mathmlBuilder:(e,t)=>{const r=Pt(e.body,t.withColor(e.color)),n=new qt("mstyle",r);return n.setAttribute("mathcolor",e.color),n}}),ut({type:"color",names:["\\color"],numArgs:1,allowedInText:!0,argTypes:["color"],handler(e,t){let r=e.parser,n=e.breakOnTokenText;const o=sr(t[0],"color-token").color;r.gullet.macros.set("\\current@color",o);const s=r.parseExpression(!0,n);return{type:"color",mode:r.mode,color:o,body:s}}}),ut({type:"cr",names:["\\\\"],numArgs:0,numOptionalArgs:0,allowedInText:!0,handler(e){let t=e.parser;const r="["===t.gullet.future().text?t.parseSizeGroup(!0):null,n=!t.settings.displayMode||!Fe({strict:t.settings.strict,errorCode:"newLineInDisplayMode",errorMsg:"In LaTeX, \\\\ or \\newline does nothing in display mode",report:!1});return{type:"cr",mode:t.mode,newLine:n,size:r&&sr(r,"size").value}},htmlBuilder(e,t){const r=We(["mspace"],[],t);return e.newLine&&(r.classes.push("katex-newline"),e.size&&(r.style.marginTop=N(H(e.size,t)))),r},mathmlBuilder(e,t){const r=new qt("mspace");return e.newLine&&(r.setAttribute("linebreak","newline"),e.size&&r.setAttribute("height",N(H(e.size,t)))),r}});const xr={"\\global":"\\global","\\long":"\\\\globallong","\\\\globallong":"\\\\globallong","\\def":"\\gdef","\\gdef":"\\gdef","\\edef":"\\xdef","\\xdef":"\\xdef","\\let":"\\\\globallet","\\futurelet":"\\\\globalfuture"},wr=e=>{const t=e.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(t))throw new n("Expected a control sequence",e);return t},vr=(e,t,r,n)=>{let o=e.gullet.macros.get(r.text);null==o&&(r.noexpand=!0,o={tokens:[r],numArgs:0,unexpandable:!e.gullet.isExpandable(r.text)}),e.gullet.macros.set(t,o,n)};ut({type:"internal",names:["\\global","\\long","\\\\globallong"],numArgs:0,allowedInText:!0,handler(e){let t=e.parser,r=e.funcName;t.consumeSpaces();const o=t.fetch();if(xr[o.text])return"\\global"!==r&&"\\\\globallong"!==r||(o.text=xr[o.text]),sr(t.parseFunction(),"internal");throw new n("Invalid token after macro prefix",o)}}),ut({type:"internal",names:["\\def","\\gdef","\\edef","\\xdef"],numArgs:0,allowedInText:!0,primitive:!0,handler(e){let t=e.parser,r=e.funcName,o=t.gullet.popToken();const s=o.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(s))throw new n("Expected a control sequence",o);let i,a=0;const l=[[]];for(;"{"!==t.gullet.future().text;)if(o=t.gullet.popToken(),"#"===o.text){if("{"===t.gullet.future().text){i=t.gullet.future(),l[a].push("{");break}if(o=t.gullet.popToken(),!/^[1-9]$/.test(o.text))throw new n('Invalid argument number "'+o.text+'"');if(parseInt(o.text)!==a+1)throw new n('Argument number "'+o.text+'" out of order');a++,l.push([])}else{if("EOF"===o.text)throw new n("Expected a macro definition");l[a].push(o.text)}let c=t.gullet.consumeArg().tokens;return i&&c.unshift(i),"\\edef"!==r&&"\\xdef"!==r||(c=t.gullet.expandTokens(c),c.reverse()),t.gullet.macros.set(s,{tokens:c,numArgs:a,delimiters:l},r===xr[r]),{type:"internal",mode:t.mode}}}),ut({type:"internal",names:["\\let","\\\\globallet"],numArgs:0,allowedInText:!0,primitive:!0,handler(e){let t=e.parser,r=e.funcName;const n=wr(t.gullet.popToken());t.gullet.consumeSpaces();const o=(e=>{let t=e.gullet.popToken();return"="===t.text&&(t=e.gullet.popToken()," "===t.text&&(t=e.gullet.popToken())),t})(t);return vr(t,n,o,"\\\\globallet"===r),{type:"internal",mode:t.mode}}}),ut({type:"internal",names:["\\futurelet","\\\\globalfuture"],numArgs:0,allowedInText:!0,primitive:!0,handler(e){let t=e.parser,r=e.funcName;const n=wr(t.gullet.popToken()),o=t.gullet.popToken(),s=t.gullet.popToken();return vr(t,n,s,"\\\\globalfuture"===r),t.gullet.pushToken(s),t.gullet.pushToken(o),{type:"internal",mode:t.mode}}});const kr=function(e,t,r){const n=ee(ne.math[e]&&ne.math[e].replace||e,t,r);if(!n)throw new Error("Unsupported symbol "+e+" and font size "+t+".");return n},zr=function(e,t,r,n){const o=r.havingBaseStyle(t),s=We(n.concat(o.sizingClasses(r)),[e],r),i=o.sizeMultiplier/r.sizeMultiplier;return s.height*=i,s.depth*=i,s.maxFontSize=o.sizeMultiplier,s},Sr=function(e,t,r){const n=t.havingBaseStyle(r),o=(1-t.sizeMultiplier/n.sizeMultiplier)*t.fontMetrics().axisHeight;e.classes.push("delimcenter"),e.style.top=N(o),e.height-=o,e.depth+=o},Mr=function(e,t,r,n,o,s){const i=function(e,t,r,n){return Ve(e,"Size"+t+"-Regular",r,n)}(e,t,o,n),a=zr(We(["delimsizing","size"+t],[i],n),S.TEXT,n,s);return r&&Sr(a,n,S.TEXT),a},Ar=function(e,t,r,n){let o;o="Size1-Regular"===t?"delim-size1":"delim-size4";return{type:"elem",elem:We(["delimsizinginner",o],[We([],[Ve(e,t,r,n)])])}},Tr=function(e,t,r){const n=K["Size4-Regular"][e.charCodeAt(0)]?K["Size4-Regular"][e.charCodeAt(0)][4]:K["Size1-Regular"][e.charCodeAt(0)][4],o=new $("inner",function(e,t){switch(e){case"\u239c":return C("M291 0 H417 V"+t+" H291z");case"\u2223":return C("M145 0 H188 V"+t+" H145z");case"\u2225":return C("M145 0 H188 V"+t+" H145z")+C("M367 0 H410 V"+t+" H367z");case"\u239f":return C("M457 0 H583 V"+t+" H457z");case"\u23a2":return C("M319 0 H403 V"+t+" H319z");case"\u23a5":return C("M263 0 H347 V"+t+" H263z");case"\u23aa":return C("M384 0 H504 V"+t+" H384z");case"\u23d0":return C("M312 0 H355 V"+t+" H312z");case"\u2016":return C("M257 0 H300 V"+t+" H257z")+C("M478 0 H521 V"+t+" H478z");default:return""}}(e,Math.round(1e3*t))),s=new _([o],{width:N(n),height:N(t),style:"width:"+N(n),viewBox:"0 0 "+1e3*n+" "+Math.round(1e3*t),preserveAspectRatio:"xMinYMin"}),i=_e([],[s],r);return i.height=t,i.style.height=N(t),i.style.width=N(n),{type:"elem",elem:i}},Cr={type:"kern",size:-.008},Br=new Set(["|","\\lvert","\\rvert","\\vert"]),qr=new Set(["\\|","\\lVert","\\rVert","\\Vert"]),Ir=function(e,t,r,n,o,s){let i,a,l,c,h="",m=0;i=l=c=e,a=null;let u="Size1-Regular";"\\uparrow"===e?l=c="\u23d0":"\\Uparrow"===e?l=c="\u2016":"\\downarrow"===e?i=l="\u23d0":"\\Downarrow"===e?i=l="\u2016":"\\updownarrow"===e?(i="\\uparrow",l="\u23d0",c="\\downarrow"):"\\Updownarrow"===e?(i="\\Uparrow",l="\u2016",c="\\Downarrow"):Br.has(e)?(l="\u2223",h="vert",m=333):qr.has(e)?(l="\u2225",h="doublevert",m=556):"["===e||"\\lbrack"===e?(i="\u23a1",l="\u23a2",c="\u23a3",u="Size4-Regular",h="lbrack",m=667):"]"===e||"\\rbrack"===e?(i="\u23a4",l="\u23a5",c="\u23a6",u="Size4-Regular",h="rbrack",m=667):"\\lfloor"===e||"\u230a"===e?(l=i="\u23a2",c="\u23a3",u="Size4-Regular",h="lfloor",m=667):"\\lceil"===e||"\u2308"===e?(i="\u23a1",l=c="\u23a2",u="Size4-Regular",h="lceil",m=667):"\\rfloor"===e||"\u230b"===e?(l=i="\u23a5",c="\u23a6",u="Size4-Regular",h="rfloor",m=667):"\\rceil"===e||"\u2309"===e?(i="\u23a4",l=c="\u23a5",u="Size4-Regular",h="rceil",m=667):"("===e||"\\lparen"===e?(i="\u239b",l="\u239c",c="\u239d",u="Size4-Regular",h="lparen",m=875):")"===e||"\\rparen"===e?(i="\u239e",l="\u239f",c="\u23a0",u="Size4-Regular",h="rparen",m=875):"\\{"===e||"\\lbrace"===e?(i="\u23a7",a="\u23a8",c="\u23a9",l="\u23aa",u="Size4-Regular"):"\\}"===e||"\\rbrace"===e?(i="\u23ab",a="\u23ac",c="\u23ad",l="\u23aa",u="Size4-Regular"):"\\lgroup"===e||"\u27ee"===e?(i="\u23a7",c="\u23a9",l="\u23aa",u="Size4-Regular"):"\\rgroup"===e||"\u27ef"===e?(i="\u23ab",c="\u23ad",l="\u23aa",u="Size4-Regular"):"\\lmoustache"===e||"\u23b0"===e?(i="\u23a7",c="\u23ad",l="\u23aa",u="Size4-Regular"):"\\rmoustache"!==e&&"\u23b1"!==e||(i="\u23ab",c="\u23a9",l="\u23aa",u="Size4-Regular");const p=kr(i,u,o),d=p.height+p.depth,g=kr(l,u,o),f=g.height+g.depth,b=kr(c,u,o),y=b.height+b.depth;let x=0,w=1;if(null!==a){const e=kr(a,u,o);x=e.height+e.depth,w=2}const v=d+y+x,k=v+Math.max(0,Math.ceil((t-v)/(w*f)))*w*f;let z=n.fontMetrics().axisHeight;r&&(z*=n.sizeMultiplier);const M=k/2-z,A=[];if(h.length>0){const e=k-d-y,t=Math.round(1e3*k),r=function(e,t){switch(e){case"lbrack":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+" v1759 v84 h347 v-84\nH403z M403 1759 V0 H319 V1759 v"+t+" v1759 v84 h84z";case"rbrack":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+" v1759 H0 v84 H347z\nM347 1759 V0 H263 V1759 v"+t+" v1759 h84z";case"vert":return"M145 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v"+t+" v585 h43z";case"doublevert":return"M145 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v"+t+" v585 h43z\nM367 15 v585 v"+t+" v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v"+-t+" v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M410 15 H367 v585 v"+t+" v585 h43z";case"lfloor":return"M319 602 V0 H403 V602 v"+t+" v1715 h263 v84 H319z\nMM319 602 V0 H403 V602 v"+t+" v1715 H319z";case"rfloor":return"M319 602 V0 H403 V602 v"+t+" v1799 H0 v-84 H319z\nMM319 602 V0 H403 V602 v"+t+" v1715 H319z";case"lceil":return"M403 1759 V84 H666 V0 H319 V1759 v"+t+" v602 h84z\nM403 1759 V0 H319 V1759 v"+t+" v602 h84z";case"rceil":return"M347 1759 V0 H0 V84 H263 V1759 v"+t+" v602 h84z\nM347 1759 V0 h-84 V1759 v"+t+" v602 h84z";case"lparen":return"M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1\nc-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,\n-36,557 l0,"+(t+84)+"c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,\n949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9\nc0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,\n-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189\nl0,-"+(t+92)+"c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,\n-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z";case"rparen":return"M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,\n63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5\nc11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,"+(t+9)+"\nc-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664\nc-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11\nc0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17\nc242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558\nl0,-"+(t+144)+"c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,\n-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z";default:throw new Error("Unknown stretchy delimiter.")}}(h,Math.round(1e3*e)),o=new $(h,r),s=N(m/1e3),i=N(t/1e3),a=new _([o],{width:s,height:i,viewBox:"0 0 "+m+" "+t}),l=_e([],[a],n);l.height=t/1e3,l.style.width=s,l.style.height=i,A.push({type:"elem",elem:l})}else{if(A.push(Ar(c,u,o,n)),A.push(Cr),null===a){const e=k-d-y+.016;A.push(Tr(l,e,n))}else{const e=(k-d-y-x)/2+.016;A.push(Tr(l,e,n)),A.push(Cr),A.push(Ar(a,u,o,n)),A.push(Cr),A.push(Tr(l,e,n))}A.push(Cr),A.push(Ar(i,u,o,n))}const T=n.havingBaseStyle(S.TEXT),C=Je({positionType:"bottom",positionData:M,children:A});return zr(We(["delimsizing","mult"],[C],T),S.TEXT,n,s)},Rr=.08,Or=function(e,t,r,n,o){const s=function(e,t,r){t*=1e3;let n="";switch(e){case"sqrtMain":n=function(e,t){return"M95,"+(622+e+t)+"\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl"+e/2.075+" -"+e+"\nc5.3,-9.3,12,-14,20,-14\nH400000v"+(40+e)+"H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM"+(834+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,B);break;case"sqrtSize1":n=function(e,t){return"M263,"+(601+e+t)+"c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl"+e/2.084+" -"+e+"\nc4.7,-7.3,11,-11,19,-11\nH40000v"+(40+e)+"H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM"+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,B);break;case"sqrtSize2":n=function(e,t){return"M983 "+(10+e+t)+"\nl"+e/3.13+" -"+e+"\nc4,-6.7,10,-10,18,-10 H400000v"+(40+e)+"\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM"+(1001+e)+" "+t+"h400000v"+(40+e)+"h-400000z"}(t,B);break;case"sqrtSize3":n=function(e,t){return"M424,"+(2398+e+t)+"\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl"+e/4.223+" -"+e+"c4,-6.7,10,-10,18,-10 H400000\nv"+(40+e)+"H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M"+(1001+e)+" "+t+"\nh400000v"+(40+e)+"h-400000z"}(t,B);break;case"sqrtSize4":n=function(e,t){return"M473,"+(2713+e+t)+"\nc339.3,-1799.3,509.3,-2700,510,-2702 l"+e/5.298+" -"+e+"\nc3.3,-7.3,9.3,-11,18,-11 H400000v"+(40+e)+"H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM"+(1001+e)+" "+t+"h400000v"+(40+e)+"H1017.7z"}(t,B);break;case"sqrtTall":n=function(e,t,r){return"M702 "+(e+t)+"H400000"+(40+e)+"\nH742v"+(r-54-t-e)+"l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 "+t+"H400000v"+(40+e)+"H742z"}(t,B,r)}return n}(e,n,r),i=new $(e,s),a=new _([i],{width:"400em",height:N(t),viewBox:"0 0 400000 "+r,preserveAspectRatio:"xMinYMin slice"});return _e(["hide-tail"],[a],o)},Er=new Set(["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230a","\u230b","\\lceil","\\rceil","\u2308","\u2309","\\surd"]),Hr=new Set(["\\uparrow","\\downarrow","\\updownarrow","\\Uparrow","\\Downarrow","\\Updownarrow","|","\\|","\\vert","\\Vert","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27ee","\u27ef","\\lmoustache","\\rmoustache","\u23b0","\u23b1"]),Nr=new Set(["<",">","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"]),Dr=[0,1.2,1.8,2.4,3],Lr=function(e,t,r,o,s){if("<"===e||"\\lt"===e||"\u27e8"===e?e="\\langle":">"!==e&&"\\gt"!==e&&"\u27e9"!==e||(e="\\rangle"),Er.has(e)||Nr.has(e))return Mr(e,t,!1,r,o,s);if(Hr.has(e))return Ir(e,Dr[t],!1,r,o,s);throw new n("Illegal delimiter: '"+e+"'")},Fr=[{type:"small",style:S.SCRIPTSCRIPT},{type:"small",style:S.SCRIPT},{type:"small",style:S.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],Pr=[{type:"small",style:S.SCRIPTSCRIPT},{type:"small",style:S.SCRIPT},{type:"small",style:S.TEXT},{type:"stack"}],Vr=[{type:"small",style:S.SCRIPTSCRIPT},{type:"small",style:S.SCRIPT},{type:"small",style:S.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],Gr=function(e){if("small"===e.type)return"Main-Regular";if("large"===e.type)return"Size"+e.size+"-Regular";if("stack"===e.type)return"Size4-Regular";{const t=e.type;throw new Error("Add support for delim type '"+t+"' here.")}},jr=function(e,t,r,n){for(let o=Math.min(2,3-n.style.size);ot)return s}return r[r.length-1]},Ur=function(e,t,r,n,o,s){let i;"<"===e||"\\lt"===e||"\u27e8"===e?e="\\langle":">"!==e&&"\\gt"!==e&&"\u27e9"!==e||(e="\\rangle"),i=Nr.has(e)?Fr:Er.has(e)?Vr:Pr;const a=jr(e,t,i,n);return"small"===a.type?function(e,t,r,n,o,s){const i=Ve(e,"Main-Regular",o,n),a=zr(i,t,n,s);return r&&Sr(a,n,t),a}(e,a.style,r,n,o,s):"large"===a.type?Mr(e,a.size,r,n,o,s):Ir(e,t,r,n,o,s)},Yr=function(e,t,r,n,o,s){const i=n.fontMetrics().axisHeight*n.sizeMultiplier,a=5/n.fontMetrics().ptPerEm,l=Math.max(t-i,r+i),c=Math.max(l/500*901,2*l-a);return Ur(e,c,!0,n,o,s)},Xr={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},Wr=new Set(["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230a","\u230b","\\lceil","\\rceil","\u2308","\u2309","<",">","\\langle","\u27e8","\\rangle","\u27e9","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27ee","\u27ef","\\lmoustache","\\rmoustache","\u23b0","\u23b1","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."]);function _r(e){return"isMiddle"in e}function $r(e,t){const r=ar(e);if(r&&Wr.has(r.text))return r;throw new n(r?"Invalid delimiter '"+r.text+"' after '"+t.funcName+"'":"Invalid delimiter type '"+e.type+"'",e)}function Zr(e){if(!e.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}ut({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],numArgs:1,argTypes:["primitive"],handler:(e,t)=>{const r=$r(dt(t[0]),e);return{type:"delimsizing",mode:e.parser.mode,size:Xr[e.funcName].size,mclass:Xr[e.funcName].mclass,delim:r.text}},htmlBuilder:(e,t)=>"."===e.delim?We([e.mclass]):Lr(e.delim,e.size,t,e.mode,[e.mclass]),mathmlBuilder:e=>{const t=[];"."!==e.delim&&t.push(Ht(e.delim,e.mode));const r=new qt("mo",t);"mopen"===e.mclass||"mclose"===e.mclass?r.setAttribute("fence","true"):r.setAttribute("fence","false"),r.setAttribute("stretchy","true");const n=N(Dr[e.size]);return r.setAttribute("minsize",n),r.setAttribute("maxsize",n),r}}),ut({type:"leftright-right",names:["\\right"],numArgs:1,primitive:!0,handler:(e,t)=>{const r=e.parser.gullet.macros.get("\\current@color");if(r&&"string"!=typeof r)throw new n("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:e.parser.mode,delim:$r(t[0],e).text,color:r}}}),ut({type:"leftright",names:["\\left"],numArgs:1,primitive:!0,handler:(e,t)=>{const r=$r(t[0],e),n=e.parser;++n.leftrightDepth;const o=n.parseExpression(!1);--n.leftrightDepth,n.expect("\\right",!1);const s=sr(n.parseFunction(),"leftright-right");return{type:"leftright",mode:n.mode,body:o,left:r.text,right:s.delim,rightColor:s.color}},htmlBuilder:(e,t)=>{Zr(e);const r=wt(e.body,t,!0,["mopen","mclose"]);let n,o,s=0,i=0,a=!1;for(let e=0;e{Zr(e);const r=Pt(e.body,t);if("."!==e.left){const t=new qt("mo",[Ht(e.left,e.mode)]);t.setAttribute("fence","true"),r.unshift(t)}if("."!==e.right){const t=new qt("mo",[Ht(e.right,e.mode)]);t.setAttribute("fence","true"),e.rightColor&&t.setAttribute("mathcolor",e.rightColor),r.push(t)}return Nt(r)}}),ut({type:"middle",names:["\\middle"],numArgs:1,primitive:!0,handler:(e,t)=>{const r=$r(t[0],e);if(!e.parser.leftrightDepth)throw new n("\\middle without preceding \\left",r);return{type:"middle",mode:e.parser.mode,delim:r.text}},htmlBuilder:(e,t)=>{let r;return"."===e.delim?r=Mt(t,[]):(r=Lr(e.delim,1,t,e.mode,[]),r.isMiddle={delim:e.delim,options:t}),r},mathmlBuilder:(e,t)=>{const r="\\vert"===e.delim||"|"===e.delim?Ht("|","text"):Ht(e.delim,e.mode),n=new qt("mo",[r]);return n.setAttribute("fence","true"),n.setAttribute("lspace","0.05em"),n.setAttribute("rspace","0.05em"),n}});ut({type:"enclose",names:["\\colorbox"],numArgs:2,allowedInText:!0,argTypes:["color","hbox"],handler(e,t,r){let n=e.parser,o=e.funcName;const s=sr(t[0],"color-token").color,i=t[1];return{type:"enclose",mode:n.mode,label:o,backgroundColor:s,body:i}},htmlBuilder:(e,t)=>{const r=Ke(At(e.body,t),t),n=e.label.slice(1);let o,s,i=t.sizeMultiplier;const a=m(e.body);if("sout"===n)o=We(["katex-stretchy","katex-sout"]),o.height=t.fontMetrics().defaultRuleThickness/i,s=-.5*t.fontMetrics().xHeight;else if("phase"===n){const e=H({number:.6,unit:"pt"},t),n=H({number:.35,unit:"ex"},t);i/=t.havingBaseSizing().sizeMultiplier;const a=r.height+r.depth+e+n;r.style.paddingLeft=N(a/2+e);const c=Math.floor(1e3*a*i),h="M400000 "+(l=c)+" H0 L"+l/2+" 0 l65 45 L145 "+(l-80)+" H400000z",m=new _([new $("phase",h)],{width:"400em",height:N(c/1e3),viewBox:"0 0 400000 "+c,preserveAspectRatio:"xMinYMin slice"});o=_e(["hide-tail"],[m],t),o.style.height=N(a),s=r.depth+e+n}else{let i,l;/cancel/.test(n)?a||r.classes.push("cancel-pad"):"angl"===n?r.classes.push("anglpad"):r.classes.push("boxpad");let c=0;/box/.test(n)?(c=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness),i=t.fontMetrics().fboxsep+("colorbox"===n?0:c),l=i):"angl"===n?(c=Math.max(t.fontMetrics().defaultRuleThickness,t.minRuleThickness),i=4*c,l=Math.max(0,.25-r.depth)):(i=a?.2:0,l=i),o=function(e,t,r,n,o){let s;const i=e.height+e.depth+r+n;if(/fbox|color|angl/.test(t)){if(s=We(["katex-stretchy",t],[],o),"fbox"===t){const e=o.color&&o.getColor();e&&(s.style.borderColor=e)}}else{const e=[];/^[bx]cancel$/.test(t)&&e.push(new Z({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(t)&&e.push(new Z({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));const r=new _(e,{width:"100%",height:N(i)});s=_e([],[r],o)}return s.height=i,s.style.height=N(i),s}(r,n,i,l,t),/fbox|boxed|fcolorbox/.test(n)?(o.style.borderStyle="solid",o.style.borderWidth=N(c)):"angl"===n&&.049!==c&&(o.style.borderTopWidth=N(c),o.style.borderRightWidth=N(c)),s=r.depth+l,e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor,e.borderColor&&(o.style.borderColor=e.borderColor))}var l;let c;if(e.backgroundColor)c=Je({positionType:"individualShift",children:[{type:"elem",elem:o,shift:s},{type:"elem",elem:r,shift:0}]});else{const e=/cancel|phase/.test(n)?["svg-align"]:[];c=Je({positionType:"individualShift",children:[{type:"elem",elem:r,shift:0},{type:"elem",elem:o,shift:s,wrapperClasses:e}]})}return/cancel/.test(n)&&(c.height=r.height,c.depth=r.depth),/cancel/.test(n)&&!a?We(["mord","cancel-lap"],[c],t):We(["mord"],[c],t)},mathmlBuilder:(e,t)=>{let r;const n=new qt(e.label.includes("colorbox")?"mpadded":"menclose",[Gt(e.body,t)]);switch(e.label){case"\\cancel":n.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":n.setAttribute("notation","downdiagonalstrike");break;case"\\phase":n.setAttribute("notation","phasorangle");break;case"\\sout":n.setAttribute("notation","horizontalstrike");break;case"\\fbox":n.setAttribute("notation","box");break;case"\\angl":n.setAttribute("notation","actuarial");break;case"\\fcolorbox":case"\\colorbox":if(r=t.fontMetrics().fboxsep*t.fontMetrics().ptPerEm,n.setAttribute("width","+"+2*r+"pt"),n.setAttribute("height","+"+2*r+"pt"),n.setAttribute("lspace",r+"pt"),n.setAttribute("voffset",r+"pt"),"\\fcolorbox"===e.label){const r=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness);n.setAttribute("style","border: "+N(r)+" solid "+e.borderColor)}break;case"\\xcancel":n.setAttribute("notation","updiagonalstrike downdiagonalstrike")}return e.backgroundColor&&n.setAttribute("mathbackground",e.backgroundColor),n}}),ut({type:"enclose",names:["\\fcolorbox"],numArgs:3,allowedInText:!0,argTypes:["color","color","hbox"],handler(e,t,r){let n=e.parser,o=e.funcName;const s=sr(t[0],"color-token").color,i=sr(t[1],"color-token").color,a=t[2];return{type:"enclose",mode:n.mode,label:o,backgroundColor:i,borderColor:s,body:a}}}),ut({type:"enclose",names:["\\fbox"],numArgs:1,argTypes:["hbox"],allowedInText:!0,handler(e,t){return{type:"enclose",mode:e.parser.mode,label:"\\fbox",body:t[0]}}}),ut({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\phase"],numArgs:1,handler(e,t){let r=e.parser,n=e.funcName;const o=t[0];return{type:"enclose",mode:r.mode,label:n,body:o}}}),ut({type:"enclose",names:["\\sout"],numArgs:1,allowedInText:!0,handler(e,t){let r=e.parser,n=e.funcName;"math"===r.mode&&Fe({strict:r.settings.strict,errorCode:"mathVsSout",errorMsg:"LaTeX's \\sout works only in text mode",report:!0});const o=t[0];return{type:"enclose",mode:r.mode,label:n,body:o}}}),ut({type:"enclose",names:["\\angl"],numArgs:1,argTypes:["hbox"],allowedInText:!1,handler(e,t){return{type:"enclose",mode:e.parser.mode,label:"\\angl",body:t[0]}}});const Kr={};function Jr(e){let t=e.type,r=e.names,n=e.props,o=e.handler,s=e.htmlBuilder,i=e.mathmlBuilder;const a={type:t,numArgs:n.numArgs||0,allowedInText:!1,numOptionalArgs:0,handler:o};for(let e=0;e{if(!e.parser.settings.displayMode)throw new n("{"+e.envName+"} can be used only in display mode.")},sn=new Set(["gather","gather*"]);function an(e){if(!e.includes("ed"))return!e.includes("*")}function ln(e,t,r){let o=t.hskipBeforeAndAfter,s=t.addJot,i=t.cols,a=t.arraystretch,l=t.colSeparationType,c=t.autoTag,h=t.singleRow,m=t.emptySingleRow,u=t.maxNumCols,p=t.leqno;if(e.gullet.beginGroup(),h||e.gullet.macros.set("\\cr","\\\\\\relax"),!a){const t=e.gullet.expandMacroAsText("\\arraystretch");if(null==t)a=1;else if(a=parseFloat(t),!a||a<0)throw new n("Invalid \\arraystretch: "+t)}e.gullet.beginGroup();let d=[];const g=[d],f=[],b=[],y=null!=c?[]:void 0;function x(){c&&e.gullet.macros.set("\\@eqnsw","1",!0)}function w(){y&&(e.gullet.macros.get("\\df@tag")?(y.push(e.subparse([new rn("\\df@tag")])),e.gullet.macros.set("\\df@tag",void 0,!0)):y.push(Boolean(c)&&"1"===e.gullet.macros.get("\\@eqnsw")))}for(x(),b.push(nn(e));;){const t=e.parseExpression(!1,h?"\\end":"\\\\");e.gullet.endGroup(),e.gullet.beginGroup();let o={type:"ordgroup",mode:e.mode,body:t};r&&(o={type:"styling",mode:e.mode,style:r,resetFont:!0,body:[o]}),d.push(o);const s=e.fetch().text;if("&"===s){if(u&&d.length===u){if(h||l)throw new n("Too many tab characters: &",e.nextToken);Fe({strict:e.settings.strict,errorCode:"textEnv",errorMsg:"Too few columns specified in the {array} column argument.",report:!0})}e.consume()}else{if("\\end"===s){w(),1!==d.length||"styling"!==o.type||1!==o.body.length||"ordgroup"!==o.body[0].type||0!==o.body[0].body.length||!(g.length>1)&&m||Array.isArray(null==y?void 0:y[y.length-1])||c&&!0===(null==y?void 0:y[y.length-1])||g.pop(),b.length0&&(y+=.25),c.push({pos:y,isDashed:e[t]})}for(x(i[0]),r=0;r0&&(u+=b,ce))for(r=0;r=a)continue;var B,q;if(o>0||e.hskipBeforeAndAfter)i=null!=(B=null==(q=c)?void 0:q.pregap)?B:u,0!==i&&(z=We(["arraycolsep"],[]),z.style.width=N(i),k.push(z));const p=[];for(r=0;r0){const e=$e("katex-hline",t,h),r=$e("katex-hdashline",t,h),n=[{type:"elem",elem:O,shift:0}];for(;c.length>0;){const t=c.pop(),o=t.pos-w;t.isDashed?n.push({type:"elem",elem:r,shift:o}):n.push({type:"elem",elem:e,shift:o})}O=Je({positionType:"individualShift",children:n})}if(0===A.length)return We(["mord"],[O],t);{const e=Je({positionType:"individualShift",children:A}),r=We(["katex-tag"],[e],t);return Ze([O,r])}},mn={c:"center ",l:"left ",r:"right "},un=function(e,t){const r=[],n=new qt("mtd",[],["mtr-glue"]),o=new qt("mtd",[],["mml-eqn-num"]);for(let s=0;s0){const t=e.cols;let r="",n=!1,o=0,i=t.length;"separator"===t[0].type&&(a+="top ",o=1),"separator"===t[t.length-1].type&&(a+="bottom ",i-=1);for(let e=o;e0?"left ":"",a+=h[h.length-1].length>0?"right ":"";for(let e=1;e0&&c&&(n=1),r[e]={type:"align",align:t,pregap:n,postgap:0}}return s.colSeparationType=c?"align":"alignat",s};Jr({type:"array",names:["array","darray"],props:{numArgs:1},handler(e,t){const r=(ar(t[0])?[t[0]]:sr(t[0],"ordgroup").body).map(function(e){const t=ir(e).text;if("lcr".includes(t))return{type:"align",align:t};if("|"===t)return{type:"separator",separator:"|"};if(":"===t)return{type:"separator",separator:":"};throw new n("Unknown column alignment: "+t,e)}),o={cols:r,hskipBeforeAndAfter:!0,maxNumCols:r.length};return ln(e.parser,o,cn(e.envName))},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],props:{numArgs:0},handler(e){const t={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[e.envName.replace("*","")];let r="c";const o={hskipBeforeAndAfter:!1,cols:[{type:"align",align:r}]};if("*"===e.envName.charAt(e.envName.length-1)){const t=e.parser;if(t.consumeSpaces(),"["===t.fetch().text){if(t.consume(),t.consumeSpaces(),r=t.fetch().text,!"lcr".includes(r))throw new n("Expected l or c or r",t.nextToken);t.consume(),t.consumeSpaces(),t.expect("]"),t.consume(),o.cols=[{type:"align",align:r}]}}const s=ln(e.parser,o,cn(e.envName)),i=Math.max(0,...s.body.map(e=>e.length));return s.cols=new Array(i).fill({type:"align",align:r}),t?{type:"leftright",mode:e.mode,body:[s],left:t[0],right:t[1],rightColor:void 0}:s},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["smallmatrix"],props:{numArgs:0},handler(e){const t=ln(e.parser,{arraystretch:.5},"script");return t.colSeparationType="small",t},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["subarray"],props:{numArgs:1},handler(e,t){const r=(ar(t[0])?[t[0]]:sr(t[0],"ordgroup").body).map(function(e){const t=ir(e).text;if("lc".includes(t))return{type:"align",align:t};throw new n("Unknown column alignment: "+t,e)});if(r.length>1)throw new n("{subarray} can contain only one column");const o={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5},s=ln(e.parser,o,"script");if(s.body.length>0&&s.body[0].length>1)throw new n("{subarray} can contain only one column");return s},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["cases","dcases","rcases","drcases"],props:{numArgs:0},handler(e){const t=ln(e.parser,{arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},cn(e.envName));return{type:"leftright",mode:e.mode,body:[t],left:e.envName.includes("r")?".":"\\{",right:e.envName.includes("r")?"\\}":".",rightColor:void 0}},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["align","align*","aligned","split"],props:{numArgs:0},handler:pn,htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["gathered","gather","gather*"],props:{numArgs:0},handler(e){sn.has(e.envName)&&on(e);const t={cols:[{type:"align",align:"c"}],addJot:!0,colSeparationType:"gather",autoTag:an(e.envName),emptySingleRow:!0,leqno:e.parser.settings.leqno};return ln(e.parser,t,"display")},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["alignat","alignat*","alignedat"],props:{numArgs:1},handler:pn,htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["equation","equation*"],props:{numArgs:0},handler(e){on(e);const t={autoTag:an(e.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:e.parser.settings.leqno};return ln(e.parser,t,"display")},htmlBuilder:hn,mathmlBuilder:un}),Jr({type:"array",names:["CD"],props:{numArgs:0},handler(e){return on(e),function(e){const t=[];for(e.gullet.beginGroup(),e.gullet.macros.set("\\cr","\\\\\\relax"),e.gullet.beginGroup();;){t.push(e.parseExpression(!1,"\\\\")),e.gullet.endGroup(),e.gullet.beginGroup();const r=e.fetch().text;if("&"!==r&&"\\\\"!==r){if("\\end"===r){0===t[t.length-1].length&&t.pop();break}throw new n("Expected \\\\ or \\cr or \\end",e.nextToken)}e.consume()}let r=[];const o=[r];for(let s=0;sAV".includes(o))throw new n('Expected one of "<>AV=|." after @',i[t]);for(let e=0;e<2;e++){let r=!0;for(let a=t+1;a{let r=e.parser,n=e.funcName;const o=dt(t[0]),s=n in gn?gn[n]:n;return{type:"font",mode:r.mode,font:s.slice(1),body:o}},htmlBuilder:(e,t)=>{const r=e.font,n=t.withFont(r);return At(e.body,n)},mathmlBuilder:(e,t)=>{const r=e.font,n=t.withFont(r);return Gt(e.body,n)}}),ut({type:"mclass",names:["\\boldsymbol","\\bm"],numArgs:1,handler:(e,t)=>{let r=e.parser;const n=t[0];return{type:"mclass",mode:r.mode,mclass:pr(n),body:[{type:"font",mode:r.mode,font:"boldsymbol",body:n}],isCharacterBox:m(n)}}}),ut({type:"font",names:["\\rm","\\sf","\\tt","\\bf","\\it","\\cal"],numArgs:0,allowedInText:!0,handler:(e,t)=>{let r=e.parser,n=e.funcName,o=e.breakOnTokenText;const s=r.mode,i=r.parseExpression(!0,o);return{type:"font",mode:s,font:"math"+n.slice(1),body:{type:"ordgroup",mode:r.mode,body:i}}}});const fn=(e,t)=>{if(!t)return e;return{type:"styling",mode:e.mode,style:t,body:[e]}};ut({type:"genfrac",names:["\\cfrac","\\dfrac","\\frac","\\tfrac","\\dbinom","\\binom","\\tbinom","\\\\atopfrac","\\\\bracefrac","\\\\brackfrac"],numArgs:2,allowedInArgument:!0,handler:(e,t)=>{let r=e.parser,n=e.funcName;const o=t[0],s=t[1];let i,a=null,l=null;switch(n){case"\\cfrac":case"\\dfrac":case"\\frac":case"\\tfrac":i=!0;break;case"\\\\atopfrac":i=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":i=!1,a="(",l=")";break;case"\\\\bracefrac":i=!1,a="\\{",l="\\}";break;case"\\\\brackfrac":i=!1,a="[",l="]";break;default:throw new Error("Unrecognized genfrac command")}const c="\\cfrac"===n;let h=null;return c||n.startsWith("\\d")?h="display":n.startsWith("\\t")&&(h="text"),fn({type:"genfrac",mode:r.mode,numer:o,denom:s,continued:c,hasBarLine:i,leftDelim:a,rightDelim:l,barSize:null},h)},htmlBuilder:(e,t)=>{const r=t.style,n=r.fracNum(),o=r.fracDen();let s;s=t.havingStyle(n);const i=At(e.numer,s,t);if(e.continued){const e=8.5/t.fontMetrics().ptPerEm,r=3.5/t.fontMetrics().ptPerEm;i.height=i.height0?3*h:7*h,p=t.fontMetrics().denom1):(c>0?(m=t.fontMetrics().num2,u=h):(m=t.fontMetrics().num3,u=3*h),p=t.fontMetrics().denom2),l){const e=t.fontMetrics().axisHeight;m-i.depth-(e+.5*c){const r=new qt("mfrac",[Gt(e.numer,t),Gt(e.denom,t)]);if(e.hasBarLine){if(e.barSize){const n=H(e.barSize,t);r.setAttribute("linethickness",N(n))}}else r.setAttribute("linethickness","0px");if(null!=e.leftDelim||null!=e.rightDelim){const t=[];if(null!=e.leftDelim){const r=new qt("mo",[new It(e.leftDelim.replace("\\",""))]);r.setAttribute("fence","true"),t.push(r)}if(t.push(r),null!=e.rightDelim){const r=new qt("mo",[new It(e.rightDelim.replace("\\",""))]);r.setAttribute("fence","true"),t.push(r)}return Nt(t)}return r}}),ut({type:"infix",names:["\\over","\\choose","\\atop","\\brace","\\brack"],numArgs:0,infix:!0,handler(e){let t,r=e.parser,n=e.funcName,o=e.token;switch(n){case"\\over":t="\\frac";break;case"\\choose":t="\\binom";break;case"\\atop":t="\\\\atopfrac";break;case"\\brace":t="\\\\bracefrac";break;case"\\brack":t="\\\\brackfrac";break;default:throw new Error("Unrecognized infix genfrac command")}return{type:"infix",mode:r.mode,replaceWith:t,token:o}}});const bn=["display","text","script","scriptscript"],yn=function(e){let t=null;return e.length>0&&(t=e,t="."===t?null:t),t};ut({type:"genfrac",names:["\\genfrac"],numArgs:6,allowedInArgument:!0,argTypes:["math","math","size","text","math","math"],handler(e,t){let r=e.parser;const n=t[4],o=t[5],s=dt(t[0]),i="atom"===s.type&&"open"===s.family?yn(s.text):null,a=dt(t[1]),l="atom"===a.type&&"close"===a.family?yn(a.text):null,c=sr(t[2],"size");let h,m=null;c.isBlank?h=!0:(m=c.value,h=m.number>0);let u=null,p=t[3];if("ordgroup"===p.type){if(p.body.length>0){const e=sr(p.body[0],"textord");u=bn[Number(e.text)]}}else p=sr(p,"textord"),u=bn[Number(p.text)];return fn({type:"genfrac",mode:r.mode,numer:n,denom:o,continued:!1,hasBarLine:h,barSize:m,leftDelim:i,rightDelim:l},u)}}),ut({type:"infix",names:["\\above"],numArgs:1,argTypes:["size"],infix:!0,handler(e,t){let r=e.parser,n=(e.funcName,e.token);return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:sr(t[0],"size").value,token:n}}}),ut({type:"genfrac",names:["\\\\abovefrac"],numArgs:3,argTypes:["math","size","math"],handler:(e,t)=>{let r=e.parser;e.funcName;const n=t[0],o=sr(t[1],"infix").size;if(!o)throw new Error("\\\\abovefrac expected size, but got "+String(o));const s=t[2],i=o.number>0;return{type:"genfrac",mode:r.mode,numer:n,denom:s,continued:!1,hasBarLine:i,barSize:o,leftDelim:null,rightDelim:null}}});const xn=(e,t)=>{const r=t.style;let n,o;"supsub"===e.type?(n=e.sup?At(e.sup,t.havingStyle(r.sup()),t):At(e.sub,t.havingStyle(r.sub()),t),o=sr(e.base,"horizBrace")):o=sr(e,"horizBrace");const s=At(o.base,t.havingBaseStyle(S.DISPLAY)),i=rr(o,t);let a;if(a=o.isOver?Je({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:i,wrapperClasses:["svg-align"]}]}):Je({positionType:"bottom",positionData:s.depth+.1+i.height,children:[{type:"elem",elem:i,wrapperClasses:["svg-align"]},{type:"kern",size:.1},{type:"elem",elem:s}]}),n){const e=We(["minner",o.isOver?"mover":"munder"],[a],t);a=o.isOver?Je({positionType:"firstBaseline",children:[{type:"elem",elem:e},{type:"kern",size:.2},{type:"elem",elem:n}]}):Je({positionType:"bottom",positionData:e.depth+.2+n.height+n.depth,children:[{type:"elem",elem:n},{type:"kern",size:.2},{type:"elem",elem:e}]})}return We(["minner",o.isOver?"mover":"munder"],[a],t)};ut({type:"horizBrace",names:["\\overbrace","\\underbrace","\\overbracket","\\underbracket"],numArgs:1,handler(e,t){let r=e.parser,n=e.funcName;return{type:"horizBrace",mode:r.mode,label:n,isOver:n.includes("\\over"),base:t[0]}},htmlBuilder:xn,mathmlBuilder:(e,t)=>{const r=Qt(e.label);return new qt(e.isOver?"mover":"munder",[Gt(e.base,t),r])}}),ut({type:"href",names:["\\href"],numArgs:2,argTypes:["url","original"],allowedInText:!0,handler:(e,t)=>{let r=e.parser;const n=t[1],o=sr(t[0],"url").url;return r.settings.isTrusted({command:"\\href",url:o})?{type:"href",mode:r.mode,href:o,body:gt(n)}:r.formatUnsupportedCmd("\\href")},htmlBuilder:(e,t)=>{const r=wt(e.body,t,!1);return function(e,t,r,n){const o=new U(e,t,r,n);return Xe(o),o}(e.href,[],r,t)},mathmlBuilder:(e,t)=>{let r=Vt(e.body,t);return r instanceof qt||(r=new qt("mrow",[r])),r.setAttribute("href",e.href),r}}),ut({type:"href",names:["\\url"],numArgs:1,argTypes:["url"],allowedInText:!0,handler:(e,t)=>{let r=e.parser;const n=sr(t[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:n}))return r.formatUnsupportedCmd("\\url");const o=[];for(let e=0;e{let r=e.parser,o=e.funcName;e.token;const s=sr(t[0],"raw").string,i=t[1];let a;r.settings.strict&&Fe({strict:r.settings.strict,errorCode:"htmlExtension",errorMsg:"HTML extension is disabled on strict mode",report:!0});const l={};switch(o){case"\\htmlClass":l.class=s,a={command:"\\htmlClass",class:s};break;case"\\htmlId":l.id=s,a={command:"\\htmlId",id:s};break;case"\\htmlStyle":l.style=s,a={command:"\\htmlStyle",style:s};break;case"\\htmlData":{const e="{,}",t=[];let r="";for(let n=0;n{const r=wt(e.body,t,!1),n=["enclosing"];e.attributes.class&&n.push(...e.attributes.class.trim().split(/\s+/));const o=We(n,r,t);for(const t of Object.entries(e.attributes)){const e=t[0],r=t[1];"class"!==e&&o.setAttribute(e,r)}return o},mathmlBuilder:(e,t)=>Vt(e.body,t)}),ut({type:"htmlmathml",names:["\\html@mathml"],numArgs:2,allowedInArgument:!0,allowedInText:!0,handler:(e,t)=>({type:"htmlmathml",mode:e.parser.mode,html:gt(t[0]),mathml:gt(t[1])}),htmlBuilder:(e,t)=>{const r=wt(e.html,t,!1);return Ze(r)},mathmlBuilder:(e,t)=>Vt(e.mathml,t)});const wn=function(e){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(e))return{number:+e,unit:"bp"};{const t=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e);if(!t)throw new n("Invalid size: '"+e+"' in \\includegraphics");const r={number:+(t[1]+t[2]),unit:t[3]};if(!E(r))throw new n("Invalid unit: '"+r.unit+"' in \\includegraphics.");return r}};ut({type:"includegraphics",names:["\\includegraphics"],numArgs:1,numOptionalArgs:1,argTypes:["raw","url"],allowedInText:!1,handler:(e,t,r)=>{let o=e.parser,s={number:0,unit:"em"},i={number:.9,unit:"em"},a={number:0,unit:"em"},l="";if(r[0]){const e=sr(r[0],"raw").string.split(",");for(let t=0;t{const r=H(e.height,t);let n=0;e.totalheight.number>0&&(n=H(e.totalheight,t)-r);let o=0;e.width.number>0&&(o=H(e.width,t));const s={height:N(r+n)};o>0&&(s.width=N(o)),n>0&&(s.verticalAlign=N(-n));const i=new Y(e.src,e.alt,s);return i.height=r,i.depth=n,i},mathmlBuilder:(e,t)=>{const r=new qt("mglyph",[]);r.setAttribute("alt",e.alt);const n=H(e.height,t);let o=0;if(e.totalheight.number>0&&(o=H(e.totalheight,t)-n,r.setAttribute("valign",N(-o))),r.setAttribute("height",N(n+o)),e.width.number>0){const n=H(e.width,t);r.setAttribute("width",N(n))}return r.setAttribute("src",e.src),r}}),ut({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],numArgs:1,argTypes:["size"],primitive:!0,allowedInText:!0,handler(e,t){let r=e.parser,n=e.funcName;const o=sr(t[0],"size");if(r.settings.strict){const e="m"===n[1],t="mu"===o.value.unit;e?(t||Fe({strict:r.settings.strict,errorCode:"mathVsTextUnits",errorMsg:"LaTeX's "+n+" supports only mu units, not "+o.value.unit+" units",report:!0}),"math"!==r.mode&&Fe({strict:r.settings.strict,errorCode:"mathVsTextUnits",errorMsg:"LaTeX's "+n+" works only in math mode",report:!0})):t&&Fe({strict:r.settings.strict,errorCode:"mathVsTextUnits",errorMsg:"LaTeX's "+n+" doesn't support mu units",report:!0})}return{type:"kern",mode:r.mode,dimension:o.value}},htmlBuilder(e,t){return Qe(e.dimension,t)},mathmlBuilder(e,t){const r=H(e.dimension,t);return new Rt(r)}}),ut({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],numArgs:1,allowedInText:!0,handler:(e,t)=>{let r=e.parser,n=e.funcName;const o=t[0];return{type:"lap",mode:r.mode,alignment:n.slice(5),body:o}},htmlBuilder:(e,t)=>{let r;"clap"===e.alignment?(r=We([],[At(e.body,t)]),r=We(["katex-inner"],[r],t)):r=We(["katex-inner"],[At(e.body,t)]);const n=We(["katex-fix"],[]);let o=We([e.alignment],[r,n],t);const s=We(["katex-strut"]);return s.style.height=N(o.height+o.depth),o.depth&&(s.style.verticalAlign=N(-o.depth)),o.children.unshift(s),o=We(["katex-thinbox"],[o],t),We(["mord","katex-vbox"],[o],t)},mathmlBuilder:(e,t)=>{const r=new qt("mpadded",[Gt(e.body,t)]);if("rlap"!==e.alignment){const t="llap"===e.alignment?"-1":"-0.5";r.setAttribute("lspace",t+"width")}return r.setAttribute("width","0px"),r}}),ut({type:"styling",names:["\\(","$"],numArgs:0,allowedInText:!0,allowedInMath:!1,handler(e,t){let r=e.funcName,n=e.parser;const o=n.mode;n.switchMode("math");const s="\\("===r?"\\)":"$",i=n.parseExpression(!1,s);return n.expect(s),n.switchMode(o),{type:"styling",mode:n.mode,style:"text",resetFont:!0,body:i}}}),ut({type:"text",names:["\\)","\\]"],numArgs:0,allowedInText:!0,allowedInMath:!1,handler(e,t){throw new n("Mismatched "+e.funcName)}});const vn=(e,t)=>{switch(t.style.size){case S.DISPLAY.size:return e.display;case S.TEXT.size:return e.text;case S.SCRIPT.size:return e.script;case S.SCRIPTSCRIPT.size:return e.scriptscript;default:return e.text}};ut({type:"mathchoice",names:["\\mathchoice"],numArgs:4,primitive:!0,handler:(e,t)=>({type:"mathchoice",mode:e.parser.mode,display:gt(t[0]),text:gt(t[1]),script:gt(t[2]),scriptscript:gt(t[3])}),htmlBuilder:(e,t)=>{const r=vn(e,t),n=wt(r,t,!1);return Ze(n)},mathmlBuilder:(e,t)=>{const r=vn(e,t);return Vt(r,t)}});const kn=(e,t,r,n,o,s,i)=>{e=We([],[e]);const a=r&&m(r);let l,c,h;if(t){const e=At(t,n.havingStyle(o.sup()),n);c={elem:e,kern:Math.max(n.fontMetrics().bigOpSpacing1,n.fontMetrics().bigOpSpacing3-e.depth)}}if(r){const e=At(r,n.havingStyle(o.sub()),n);l={elem:e,kern:Math.max(n.fontMetrics().bigOpSpacing2,n.fontMetrics().bigOpSpacing4-e.height)}}if(c&&l){const t=n.fontMetrics().bigOpSpacing5+l.elem.height+l.elem.depth+l.kern+e.depth+i;h=Je({positionType:"bottom",positionData:t,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:l.elem,marginLeft:N(-s)},{type:"kern",size:l.kern},{type:"elem",elem:e},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:N(s)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]})}else if(l){const t=e.height-i;h=Je({positionType:"top",positionData:t,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:l.elem,marginLeft:N(-s)},{type:"kern",size:l.kern},{type:"elem",elem:e}]})}else{if(!c)return e;{const t=e.depth+i;h=Je({positionType:"bottom",positionData:t,children:[{type:"elem",elem:e},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:N(s)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]})}}const u=[h];if(l&&0!==s&&!a){const e=We(["mspace"],[],n);e.style.marginRight=N(s),u.unshift(e)}return We(["mop","op-limits"],u,n)},zn=new Set(["\\smallint"]),Sn=(e,t)=>{let r,n,o,s=!1;"supsub"===e.type?(r=e.sup,n=e.sub,o=sr(e.base,"op"),s=!0):o=sr(e,"op");const i=t.style;let a,l,c=!1;if(i.size===S.DISPLAY.size&&o.symbol&&!zn.has(o.name)&&(c=!0),o.symbol){const e=c?"Size2-Regular":"Size1-Regular";let r="";if("\\oiint"!==o.name&&"\\oiiint"!==o.name||(r=o.name.slice(1),o.name="oiint"===r?"\\iint":"\\iiint"),a=Ve(o.name,e,"math",t,["mop","op-symbol",c?"large-op":"small-op"]),l=a.italic,r.length>0){const e=nt(r+"Size"+(c?"2":"1"),t);a=Je({positionType:"individualShift",children:[{type:"elem",elem:a,shift:0},{type:"elem",elem:e,shift:c?.08:0}]}),o.name="\\"+r,a.classes.unshift("mop"),a.italic=l}}else if(o.body){const e=wt(o.body,t,!0);1===e.length&&e[0]instanceof W?(a=e[0],a.classes[0]="mop"):a=We(["mop"],e,t)}else{const e=[];for(let r=1;r{let r=e.parser,n=e.funcName;return 1===n.length&&(n=Mn[n]),{type:"op",mode:r.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:n}},htmlBuilder:Sn,mathmlBuilder:(e,t)=>{let r;if(e.symbol)r=new qt("mo",[Ht(e.name,e.mode)]),zn.has(e.name)&&r.setAttribute("largeop","false");else if(e.body)r=new qt("mo",Pt(e.body,t));else{r=new qt("mi",[new It(e.name.slice(1))]);const t=new qt("mo",[Ht("\u2061","text")]);r=e.parentIsSupSub?new qt("mrow",[r,t]):Bt([r,t])}return r}}),ut({type:"op",names:["\\mathop"],numArgs:1,primitive:!0,handler:(e,t)=>{let r=e.parser;const n=t[0];return{type:"op",mode:r.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:gt(n)}}});const An={"\u222b":"\\int","\u222c":"\\iint","\u222d":"\\iiint","\u222e":"\\oint","\u222f":"\\oiint","\u2230":"\\oiiint"};ut({type:"op",names:["\\arcsin","\\arccos","\\arctan","\\arctg","\\arcctg","\\arg","\\ch","\\cos","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\deg","\\dim","\\exp","\\hom","\\ker","\\lg","\\ln","\\log","\\sec","\\sin","\\sinh","\\sh","\\tan","\\tanh","\\tg","\\th"],numArgs:0,handler(e){let t=e.parser,r=e.funcName;return{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:r}}}),ut({type:"op",names:["\\det","\\gcd","\\inf","\\lim","\\max","\\min","\\Pr","\\sup"],numArgs:0,handler(e){let t=e.parser,r=e.funcName;return{type:"op",mode:t.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:r}}}),ut({type:"op",names:["\\int","\\iint","\\iiint","\\oint","\\oiint","\\oiiint","\u222b","\u222c","\u222d","\u222e","\u222f","\u2230"],numArgs:0,allowedInArgument:!0,handler(e){let t=e.parser,r=e.funcName;return 1===r.length&&(r=An[r]),{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:r}}});const Tn=(e,t)=>{let r,n,o,s,i=!1;if("supsub"===e.type?(r=e.sup,n=e.sub,o=sr(e.base,"operatorname"),i=!0):o=sr(e,"operatorname"),o.body.length>0){const e=o.body.map(e=>{const t="text"in e?e.text:void 0;return"string"==typeof t?{type:"textord",mode:e.mode,text:t}:e}),r=wt(e,t.withFont("mathrm"),!0);for(let e=0;e{let r=e.parser,n=e.funcName;const o=t[0];return{type:"operatorname",mode:r.mode,body:gt(o),alwaysHandleSupSub:"\\operatornamewithlimits"===n,limits:!1,parentIsSupSub:!1}},htmlBuilder:Tn,mathmlBuilder:(e,t)=>{let r=Pt(e.body,t.withFont("mathrm")),n=!0;for(let e=0;ee.toText()).join("");r=[new It(e)]}const o=new qt("mi",r);o.setAttribute("mathvariant","normal");const s=new qt("mo",[Ht("\u2061","text")]);return e.parentIsSupSub?new qt("mrow",[o,s]):Bt([o,s])}}),en("\\operatorname","\\@ifstar\\operatornamewithlimits\\operatorname@"),pt({type:"ordgroup",htmlBuilder(e,t){return e.semisimple?Ze(wt(e.body,t,!1)):We(["mord"],wt(e.body,t,!0),t)},mathmlBuilder(e,t){return Vt(e.body,t,!0)}}),ut({type:"overline",names:["\\overline"],numArgs:1,handler(e,t){let r=e.parser;const n=t[0];return{type:"overline",mode:r.mode,body:n}},htmlBuilder(e,t){const r=At(e.body,t.havingCrampedStyle()),n=$e("overline-line",t),o=t.fontMetrics().defaultRuleThickness,s=Je({positionType:"firstBaseline",children:[{type:"elem",elem:r},{type:"kern",size:3*o},{type:"elem",elem:n},{type:"kern",size:o}]});return We(["mord","katex-overline"],[s],t)},mathmlBuilder(e,t){const r=new qt("mo",[new It("\u203e")]);r.setAttribute("stretchy","true");const n=new qt("mover",[Gt(e.body,t),r]);return n.setAttribute("accent","true"),n}}),ut({type:"phantom",names:["\\phantom"],numArgs:1,allowedInText:!0,handler:(e,t)=>{let r=e.parser;const n=t[0];return{type:"phantom",mode:r.mode,body:gt(n)}},htmlBuilder:(e,t)=>{const r=wt(e.body,t.withPhantom(),!1);return Ze(r)},mathmlBuilder:(e,t)=>{const r=Pt(e.body,t);return new qt("mphantom",r)}}),en("\\hphantom","\\smash{\\phantom{#1}}"),ut({type:"vphantom",names:["\\vphantom"],numArgs:1,allowedInText:!0,handler:(e,t)=>{let r=e.parser;const n=t[0];return{type:"vphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{const r=We(["katex-inner"],[At(e.body,t.withPhantom())]),n=We(["katex-fix"],[]);return We(["mord","rlap"],[r,n],t)},mathmlBuilder:(e,t)=>{const r=Pt(gt(e.body),t),n=new qt("mphantom",r),o=new qt("mpadded",[n]);return o.setAttribute("width","0px"),o}}),ut({type:"raisebox",names:["\\raisebox"],numArgs:2,argTypes:["size","hbox"],allowedInText:!0,handler(e,t){let r=e.parser;const n=sr(t[0],"size").value,o=t[1];return{type:"raisebox",mode:r.mode,dy:n,body:o}},htmlBuilder(e,t){const r=At(e.body,t),n=H(e.dy,t);return Je({positionType:"shift",positionData:-n,children:[{type:"elem",elem:r}]})},mathmlBuilder(e,t){const r=new qt("mpadded",[Gt(e.body,t)]),n=e.dy.number+e.dy.unit;return r.setAttribute("voffset",n),r}});const Cn=(e,t)=>({type:"reflectbox",mode:e.parser.mode,body:t[0]});function Bn(e,t,r){const n=wt(e,t,!1),o=t.sizeMultiplier/r.sizeMultiplier;for(let e=0;e=0?a.setAttribute("height",N(o)):(a.setAttribute("height",N(o)),a.setAttribute("depth",N(-o))),a.setAttribute("voffset",N(o)),a}});const qn=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"];ut({type:"sizing",names:qn,numArgs:0,allowedInText:!0,handler:(e,t)=>{let r=e.breakOnTokenText,n=e.funcName,o=e.parser;const s=o.parseExpression(!1,r);return{type:"sizing",mode:o.mode,size:qn.indexOf(n)+1,body:s}},htmlBuilder:(e,t)=>{const r=t.havingSize(e.size);return Bn(e.body,r,t)},mathmlBuilder:(e,t)=>{const r=t.havingSize(e.size),n=Pt(e.body,r),o=new qt("mstyle",n);return o.setAttribute("mathsize",N(r.sizeMultiplier)),o}}),ut({type:"smash",names:["\\smash"],numArgs:1,numOptionalArgs:1,allowedInText:!0,handler:(e,t,r)=>{let n=e.parser,o=!1,s=!1;const i=r[0]&&sr(r[0],"ordgroup");if(i){let e;for(let t=0;t{const r=We([],[At(e.body,t)]);if(!e.smashHeight&&!e.smashDepth)return r;if(e.smashHeight&&(r.height=0),e.smashDepth&&(r.depth=0),e.smashHeight&&e.smashDepth)return We(["mord","katex-smash"],[r],t);if(r.children)for(let t=0;t{const r=new qt("mpadded",[Gt(e.body,t)]);return e.smashHeight&&r.setAttribute("height","0px"),e.smashDepth&&r.setAttribute("depth","0px"),r}}),ut({type:"sqrt",names:["\\sqrt"],numArgs:1,numOptionalArgs:1,handler(e,t,r){let n=e.parser;const o=r[0],s=t[0];return{type:"sqrt",mode:n.mode,body:s,index:o}},htmlBuilder(e,t){let r=At(e.body,t.havingCrampedStyle());0===r.height&&(r.height=t.fontMetrics().xHeight),r=Ke(r,t);const n=t.fontMetrics().defaultRuleThickness;let o=n;t.style.idr.height+r.depth+s&&(s=(s+h-r.height-r.depth)/2);const m=a.height-r.height-s-l;r.style.paddingLeft=N(c);const u=Je({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+m)},{type:"elem",elem:a},{type:"kern",size:l}]});if(e.index){const r=t.havingStyle(S.SCRIPTSCRIPT),n=At(e.index,r,t),o=.6*(u.height-u.depth),s=Je({positionType:"shift",positionData:-o,children:[{type:"elem",elem:n}]}),i=We(["katex-root"],[s]);return We(["mord","sqrt"],[i,u],t)}return We(["mord","sqrt"],[u],t)},mathmlBuilder(e,t){const r=e.body,n=e.index;return n?new qt("mroot",[Gt(r,t),Gt(n,t)]):new qt("msqrt",[Gt(r,t)])}});const In={display:S.DISPLAY,text:S.TEXT,script:S.SCRIPT,scriptscript:S.SCRIPTSCRIPT};ut({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],numArgs:0,allowedInText:!0,primitive:!0,handler(e,t){let r=e.breakOnTokenText,n=e.funcName,o=e.parser;const s=o.parseExpression(!0,r),i=n.slice(1,n.length-5);if(!(i in In))throw new Error("Unknown style: "+i);return{type:"styling",mode:o.mode,style:i,body:s}},htmlBuilder(e,t){const r=In[e.style];let n=t.havingStyle(r);return e.resetFont&&(n=n.withFont("")),Bn(e.body,n,t)},mathmlBuilder(e,t){const r=In[e.style];let n=t.havingStyle(r);e.resetFont&&(n=n.withFont(""));const o=Pt(e.body,n),s=new qt("mstyle",o),i={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]}[e.style];return s.setAttribute("scriptlevel",i[0]),s.setAttribute("displaystyle",i[1]),s}});pt({type:"supsub",htmlBuilder(e,t){const r=function(e,t){const r=e.base;if(r)return"op"===r.type?r.limits&&(t.style.size===S.DISPLAY.size||r.alwaysHandleSupSub)?Sn:null:"operatorname"===r.type?r.alwaysHandleSupSub&&(t.style.size===S.DISPLAY.size||r.limits)?Tn:null:"accent"===r.type?m(r.base)?hr:null:"horizBrace"===r.type&&!e.sub===r.isOver?xn:null;return null}(e,t);if(r)return r(e,t);const n=e.base,o=e.sup,s=e.sub,i=At(n,t);let a,l;const c=t.fontMetrics();let h=0,u=0;const p=n&&m(n);if(o){const e=t.havingStyle(t.style.sup());a=At(o,e,t),p||(h=i.height-e.fontMetrics().supDrop*e.sizeMultiplier/t.sizeMultiplier)}if(s){const e=t.havingStyle(t.style.sub());l=At(s,e,t),p||(u=i.depth+e.fontMetrics().subDrop*e.sizeMultiplier/t.sizeMultiplier)}let d;d=t.style===S.DISPLAY?c.sup1:t.style.cramped?c.sup3:c.sup2;const g=t.sizeMultiplier,f=N(.5/c.ptPerEm/g);let b,y=null;if(l){const t=e.base&&"op"===e.base.type&&e.base.name&&("\\oiint"===e.base.name||"\\oiiint"===e.base.name);var x;if(i instanceof W||t)y=N(-(null!=(x=i.italic)?x:0))}if(a&&l){h=Math.max(h,d,a.depth+.25*c.xHeight),u=Math.max(u,c.sub2);const e=4*c.defaultRuleThickness;if(h-a.depth-(l.height-u)0&&(h+=t,u-=t)}b=Je({positionType:"individualShift",children:[{type:"elem",elem:l,shift:u,marginRight:f,marginLeft:y},{type:"elem",elem:a,shift:-h,marginRight:f}]})}else if(l){u=Math.max(u,c.sub1,l.height-.8*c.xHeight);b=Je({positionType:"shift",positionData:u,children:[{type:"elem",elem:l,marginLeft:y,marginRight:f}]})}else{if(!a)throw new Error("supsub must have either sup or sub.");h=Math.max(h,d,a.depth+.25*c.xHeight),b=Je({positionType:"shift",positionData:-h,children:[{type:"elem",elem:a,marginRight:f}]})}const w=St(i,"right")||"mord";return We([w],[i,We(["msupsub"],[b])],t)},mathmlBuilder(e,t){let r,n,o=!1;e.base&&"horizBrace"===e.base.type&&(n=!!e.sup,n===e.base.isOver&&(o=!0,r=e.base.isOver)),!e.base||"op"!==e.base.type&&"operatorname"!==e.base.type||(e.base.parentIsSupSub=!0);const s=[Gt(e.base,t)];let i;if(e.sub&&s.push(Gt(e.sub,t)),e.sup&&s.push(Gt(e.sup,t)),o)i=r?"mover":"munder";else if(e.sub)if(e.sup){const r=e.base;i=r&&"op"===r.type&&r.limits&&t.style===S.DISPLAY||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(t.style===S.DISPLAY||r.limits)?"munderover":"msubsup"}else{const r=e.base;i=r&&"op"===r.type&&r.limits&&(t.style===S.DISPLAY||r.alwaysHandleSupSub)||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(r.limits||t.style===S.DISPLAY)?"munder":"msub"}else{const r=e.base;i=r&&"op"===r.type&&r.limits&&(t.style===S.DISPLAY||r.alwaysHandleSupSub)||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(r.limits||t.style===S.DISPLAY)?"mover":"msup"}return new qt(i,s)}}),pt({type:"atom",htmlBuilder(e,t){return Ge(e.text,e.mode,t,["m"+e.family])},mathmlBuilder(e,t){const r=new qt("mo",[Ht(e.text,e.mode)]);if("bin"===e.family){const n=Lt(e,t);"bold-italic"===n&&r.setAttribute("mathvariant",n)}else"punct"===e.family?r.setAttribute("separator","true"):"open"!==e.family&&"close"!==e.family||r.setAttribute("stretchy","false");return r}});const Rn={mi:"italic",mn:"normal",mtext:"normal"};pt({type:"mathord",htmlBuilder(e,t){return je(e,t)},mathmlBuilder(e,t){const r=new qt("mi",[Ht(e.text,e.mode,t)]),n=Lt(e,t)||"italic";return n!==Rn[r.type]&&r.setAttribute("mathvariant",n),r}}),pt({type:"textord",htmlBuilder(e,t){return je(e,t)},mathmlBuilder(e,t){const r=Ht(e.text,e.mode,t),n=Lt(e,t)||"normal";let o;return o="text"===e.mode?new qt("mtext",[r]):/[0-9]/.test(e.text)?new qt("mn",[r]):"\\prime"===e.text?new qt("mo",[r]):new qt("mi",[r]),n!==Rn[o.type]&&o.setAttribute("mathvariant",n),o}});const On=new Map([["\\nobreak","nobreak"],["\\allowbreak","allowbreak"]]),En=new Map([[" ",{}],["\\ ",{}],["~",{className:"nobreak"}],["\\space",{}],["\\nobreakspace",{className:"nobreak"}]]);pt({type:"spacing",htmlBuilder(e,t){const r=En.get(e.text),o=On.get(e.text);if(r){const n=r.className||"";if("text"===e.mode){const r=je(e,t);return r.classes.push(n),r}return We(["mspace",n],[Ge(e.text,e.mode,t)],t)}if(o)return We(["mspace",o],[],t);throw new n('Unknown type of space "'+e.text+'"')},mathmlBuilder(e,t){let r;if(!En.has(e.text)){if(On.has(e.text))return new qt("mspace");throw new n('Unknown type of space "'+e.text+'"')}return r=new qt("mtext",[new It("\xa0")]),r}});const Hn=()=>{const e=new qt("mtd",[]);return e.setAttribute("width","50%"),e};pt({type:"tag",mathmlBuilder(e,t){const r=new qt("mtable",[new qt("mtr",[Hn(),new qt("mtd",[Vt(e.body,t)]),Hn(),new qt("mtd",[Vt(e.tag,t)])])]);return r.setAttribute("width","100%"),r}});const Nn={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},Dn={"\\textbf":"textbf","\\textmd":"textmd"},Ln={"\\textit":"textit","\\textup":"textup"},Fn=(e,t)=>{const r=e.font;return r?Nn[r]?t.withTextFontFamily(Nn[r]):Dn[r]?t.withTextFontWeight(Dn[r]):"\\emph"===r?"textit"===t.fontShape?t.withTextFontShape("textup"):t.withTextFontShape("textit"):t.withTextFontShape(Ln[r]):t};ut({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup","\\emph"],numArgs:1,argTypes:["text"],allowedInArgument:!0,allowedInText:!0,handler(e,t){let r=e.parser,n=e.funcName;const o=t[0];return{type:"text",mode:r.mode,body:gt(o),font:n}},htmlBuilder(e,t){const r=Fn(e,t),n=wt(e.body,r,!0);return We(["mord","text"],n,r)},mathmlBuilder(e,t){const r=Fn(e,t);return Vt(e.body,r)}}),ut({type:"underline",names:["\\underline"],numArgs:1,allowedInText:!0,handler(e,t){return{type:"underline",mode:e.parser.mode,body:t[0]}},htmlBuilder(e,t){const r=At(e.body,t),n=$e("underline-line",t),o=t.fontMetrics().defaultRuleThickness,s=Je({positionType:"top",positionData:r.height,children:[{type:"kern",size:o},{type:"elem",elem:n},{type:"kern",size:3*o},{type:"elem",elem:r}]});return We(["mord","katex-underline"],[s],t)},mathmlBuilder(e,t){const r=new qt("mo",[new It("\u203e")]);r.setAttribute("stretchy","true");const n=new qt("munder",[Gt(e.body,t),r]);return n.setAttribute("accentunder","true"),n}}),ut({type:"vcenter",names:["\\vcenter"],numArgs:1,argTypes:["original"],allowedInText:!1,handler(e,t){return{type:"vcenter",mode:e.parser.mode,body:t[0]}},htmlBuilder(e,t){const r=At(e.body,t),n=t.fontMetrics().axisHeight,o=.5*(r.height-n-(r.depth+n));return Je({positionType:"shift",positionData:o,children:[{type:"elem",elem:r}]})},mathmlBuilder(e,t){const r=new qt("mpadded",[Gt(e.body,t)],["vcenter"]);return new qt("mrow",[r])}}),ut({type:"verb",names:["\\verb"],numArgs:0,allowedInText:!0,handler(e,t,r){throw new n("\\verb ended by end of line instead of matching delimiter")},htmlBuilder(e,t){const r=Pn(e),n=[],o=t.havingStyle(t.style.text());for(let t=0;te.body.replace(/ /g,e.star?"\u2423":"\xa0");var Vn=ct;const Gn="[ \r\n\t]",jn="(\\\\[a-zA-Z@]+)"+Gn+"*",Un="[\u0300-\u036f]",Yn=new RegExp(Un+"+$"),Xn="("+Gn+"+)|\\\\(\n|[ \r\t]+\n?)[ \r\t]*|([!-\\[\\]-\u2027\u202a-\ud7ff\uf900-\uffff]"+Un+"*|[\ud800-\udbff][\udc00-\udfff]"+Un+"*|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5|"+jn+"|\\\\[^\ud800-\udfff])";class Wn{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(Xn,"g"),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){const e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new rn("EOF",new tn(this,t,t));const r=this.tokenRegex.exec(e);if(null===r||r.index!==t)throw new n("Unexpected character: '"+e[t]+"'",new rn(e[t],new tn(this,t,t+1)));const o=r[6]||r[3]||(r[2]?"\\ ":" ");if(14===this.catcodes[o]){const t=e.indexOf("\n",this.tokenRegex.lastIndex);return-1===t?(this.tokenRegex.lastIndex=e.length,Fe({strict:this.settings.strict,errorCode:"commentAtEnd",errorMsg:"% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)",report:!0})):this.tokenRegex.lastIndex=t+1,this.lex()}return new rn(o,new tn(this,t,this.tokenRegex.lastIndex))}}class _n{constructor(e,t){void 0===e&&(e={}),void 0===t&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(0===this.undefStack.length)throw new n("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");const e=this.undefStack.pop();for(const t of Object.keys(e))void 0===e[t]?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){return Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:Object.prototype.hasOwnProperty.call(this.builtins,e)?this.builtins[e]:void 0}set(e,t,r){if(void 0===r&&(r=!1),r){for(let t=0;t0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{const t=this.undefStack[this.undefStack.length-1];t&&!Object.prototype.hasOwnProperty.call(t,e)&&(t[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}null==t?delete this.current[e]:this.current[e]=t}}var $n=Qr;en("\\noexpand",function(e){const t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),en("\\expandafter",function(e){const t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),en("\\@firstoftwo",function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),en("\\@secondoftwo",function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),en("\\@ifnextchar",function(e){const t=e.consumeArgs(3);e.consumeSpaces();const r=e.future();return 1===t[0].length&&t[0][0].text===r.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),en("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),en("\\TextOrMath",function(e){const t=e.consumeArgs(2);return"text"===e.mode?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});const Zn={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};en("\\char",function(e){let t,r=e.popToken(),o=0;if("'"===r.text)t=8,r=e.popToken();else if('"'===r.text)t=16,r=e.popToken();else if("`"===r.text)if(r=e.popToken(),"\\"===r.text[0])o=r.text.charCodeAt(1);else{if("EOF"===r.text)throw new n("\\char` missing argument");o=r.text.charCodeAt(0)}else t=10;if(t){if(o=Zn[r.text],null==o||o>=t)throw new n("Invalid base-"+t+" digit "+r.text);let s;for(;null!=(s=Zn[e.future().text])&&s{let s=e.consumeArg().tokens;if(1!==s.length)throw new n("\\newcommand's first argument must be a macro name");const i=s[0].text,a=e.isDefined(i);if(a&&!t)throw new n("\\newcommand{"+i+"} attempting to redefine "+i+"; use \\renewcommand");if(!a&&!r)throw new n("\\renewcommand{"+i+"} when command "+i+" does not yet exist; use \\newcommand");let l=0;if(s=e.consumeArg().tokens,1===s.length&&"["===s[0].text){let t="",r=e.expandNextToken();for(;"]"!==r.text&&"EOF"!==r.text;)t+=r.text,r=e.expandNextToken();if(!t.match(/^\s*[0-9]+\s*$/))throw new n("Invalid number of arguments: "+t);l=parseInt(t),s=e.consumeArg().tokens}return a&&o||e.macros.set(i,{tokens:s,numArgs:l}),""};en("\\newcommand",e=>Kn(e,!1,!0,!1)),en("\\renewcommand",e=>Kn(e,!0,!1,!1)),en("\\providecommand",e=>Kn(e,!0,!0,!0)),en("\\message",e=>{const t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join("")),""}),en("\\errmessage",e=>{const t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join("")),""}),en("\\show",e=>{const t=e.popToken(),r=t.text;return console.log(t,e.macros.get(r),Vn[r],ne.math[r],ne.text[r]),""}),en("\\bgroup","{"),en("\\egroup","}"),en("~","\\nobreakspace"),en("\\lq","`"),en("\\rq","'"),en("\\aa","\\r a"),en("\\AA","\\r A"),en("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`\xa9}"),en("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}"),en("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`\xae}"),en("\u212c","\\mathscr{B}"),en("\u2130","\\mathscr{E}"),en("\u2131","\\mathscr{F}"),en("\u210b","\\mathscr{H}"),en("\u2110","\\mathscr{I}"),en("\u2112","\\mathscr{L}"),en("\u2133","\\mathscr{M}"),en("\u211b","\\mathscr{R}"),en("\u212d","\\mathfrak{C}"),en("\u210c","\\mathfrak{H}"),en("\u2128","\\mathfrak{Z}"),en("\\Bbbk","\\Bbb{k}"),en("\\llap","\\mathllap{\\textrm{#1}}"),en("\\rlap","\\mathrlap{\\textrm{#1}}"),en("\\clap","\\mathclap{\\textrm{#1}}"),en("\\mathstrut","\\vphantom{(}"),en("\\underbar","\\underline{\\text{#1}}"),en("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}'),en("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`\u2260}}"),en("\\ne","\\neq"),en("\u2260","\\neq"),en("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`\u2209}}"),en("\u2209","\\notin"),en("\u2258","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`\u2258}}"),en("\u2259","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}"),en("\u225a","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225a}}"),en("\u225b","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`\u225b}}"),en("\u225d","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`\u225d}}"),en("\u225e","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`\u225e}}"),en("\u225f","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225f}}"),en("\u27c2","\\perp"),en("\u203c","\\mathclose{!\\mkern-0.8mu!}"),en("\u220c","\\notni"),en("\u231c","\\ulcorner"),en("\u231d","\\urcorner"),en("\u231e","\\llcorner"),en("\u231f","\\lrcorner"),en("\xa9","\\copyright"),en("\xae","\\textregistered"),en("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}'),en("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}'),en("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}'),en("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}'),en("\\vdots","{\\varvdots\\rule{0pt}{15pt}}"),en("\u22ee","\\vdots"),en("\\varGamma","\\mathit{\\Gamma}"),en("\\varDelta","\\mathit{\\Delta}"),en("\\varTheta","\\mathit{\\Theta}"),en("\\varLambda","\\mathit{\\Lambda}"),en("\\varXi","\\mathit{\\Xi}"),en("\\varPi","\\mathit{\\Pi}"),en("\\varSigma","\\mathit{\\Sigma}"),en("\\varUpsilon","\\mathit{\\Upsilon}"),en("\\varPhi","\\mathit{\\Phi}"),en("\\varPsi","\\mathit{\\Psi}"),en("\\varOmega","\\mathit{\\Omega}"),en("\\substack","\\begin{subarray}{c}#1\\end{subarray}"),en("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax"),en("\\boxed","\\fbox{$\\displaystyle{#1}$}"),en("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;"),en("\\implies","\\DOTSB\\;\\Longrightarrow\\;"),en("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;"),en("\\dddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}"),en("\\ddddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");const Jn={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"},Qn=new Set(["bin","rel"]);en("\\dots",function(e){let t="\\dotso";const r=e.expandAfterFuture().text;return r in Jn?t=Jn[r]:("\\not"===r.slice(0,4)||r in ne.math&&Qn.has(ne.math[r].group))&&(t="\\dotsb"),t});const eo={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};en("\\dotso",function(e){return e.future().text in eo?"\\ldots\\,":"\\ldots"}),en("\\dotsc",function(e){const t=e.future().text;return t in eo&&","!==t?"\\ldots\\,":"\\ldots"}),en("\\cdots",function(e){return e.future().text in eo?"\\@cdots\\,":"\\@cdots"}),en("\\dotsb","\\cdots"),en("\\dotsm","\\cdots"),en("\\dotsi","\\!\\cdots"),en("\\dotsx","\\ldots\\,"),en("\\DOTSI","\\relax"),en("\\DOTSB","\\relax"),en("\\DOTSX","\\relax"),en("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"),en("\\,","\\tmspace+{3mu}{.1667em}"),en("\\thinspace","\\,"),en("\\>","\\mskip{4mu}"),en("\\:","\\tmspace+{4mu}{.2222em}"),en("\\medspace","\\:"),en("\\;","\\tmspace+{5mu}{.2777em}"),en("\\thickspace","\\;"),en("\\!","\\tmspace-{3mu}{.1667em}"),en("\\negthinspace","\\!"),en("\\negmedspace","\\tmspace-{4mu}{.2222em}"),en("\\negthickspace","\\tmspace-{5mu}{.277em}"),en("\\enspace","\\kern.5em "),en("\\enskip","\\hskip.5em\\relax"),en("\\quad","\\hskip1em\\relax"),en("\\qquad","\\hskip2em\\relax"),en("\\tag","\\@ifstar\\tag@literal\\tag@paren"),en("\\tag@paren","\\tag@literal{({#1})}"),en("\\tag@literal",e=>{if(e.macros.get("\\df@tag"))throw new n("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"}),en("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"),en("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"),en("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}"),en("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"),en("\\newline","\\\\\\relax"),en("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");const to=N(K["Main-Regular"]["T".charCodeAt(0)][1]-.7*K["Main-Regular"]["A".charCodeAt(0)][1]);en("\\LaTeX","\\textrm{\\html@mathml{L\\kern-.36em\\raisebox{"+to+"}{\\scriptstyle A}\\kern-.15em\\TeX}{LaTeX}}"),en("\\KaTeX","\\textrm{\\html@mathml{K\\kern-.17em\\raisebox{"+to+"}{\\scriptstyle A}\\kern-.15em\\TeX}{KaTeX}}"),en("\\hspace","\\@ifstar\\@hspacer\\@hspace"),en("\\@hspace","\\hskip #1\\relax"),en("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax"),en("\\ordinarycolon",":"),en("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}"),en("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}'),en("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}'),en("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}'),en("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}'),en("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}'),en("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}'),en("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}'),en("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}'),en("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}'),en("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}'),en("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}'),en("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}'),en("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}'),en("\u2237","\\dblcolon"),en("\u2239","\\eqcolon"),en("\u2254","\\coloneqq"),en("\u2255","\\eqqcolon"),en("\u2a74","\\Coloneqq"),en("\\ratio","\\vcentcolon"),en("\\coloncolon","\\dblcolon"),en("\\colonequals","\\coloneqq"),en("\\coloncolonequals","\\Coloneqq"),en("\\equalscolon","\\eqqcolon"),en("\\equalscoloncolon","\\Eqqcolon"),en("\\colonminus","\\coloneq"),en("\\coloncolonminus","\\Coloneq"),en("\\minuscolon","\\eqcolon"),en("\\minuscoloncolon","\\Eqcolon"),en("\\coloncolonapprox","\\Colonapprox"),en("\\coloncolonsim","\\Colonsim"),en("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),en("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"),en("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),en("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"),en("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220c}}"),en("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}"),en("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}"),en("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}"),en("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}"),en("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}"),en("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}"),en("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}"),en("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}"),en("\\gvertneqq","\\html@mathml{\\@gvertneqq}{\u2269}"),en("\\lvertneqq","\\html@mathml{\\@lvertneqq}{\u2268}"),en("\\ngeqq","\\html@mathml{\\@ngeqq}{\u2271}"),en("\\ngeqslant","\\html@mathml{\\@ngeqslant}{\u2271}"),en("\\nleqq","\\html@mathml{\\@nleqq}{\u2270}"),en("\\nleqslant","\\html@mathml{\\@nleqslant}{\u2270}"),en("\\nshortmid","\\html@mathml{\\@nshortmid}{\u2224}"),en("\\nshortparallel","\\html@mathml{\\@nshortparallel}{\u2226}"),en("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{\u2288}"),en("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{\u2289}"),en("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{\u228a}"),en("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{\u2acb}"),en("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{\u228b}"),en("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{\u2acc}"),en("\\imath","\\html@mathml{\\@imath}{\u0131}"),en("\\jmath","\\html@mathml{\\@jmath}{\u0237}"),en("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27e6}}"),en("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27e7}}"),en("\u27e6","\\llbracket"),en("\u27e7","\\rrbracket"),en("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}"),en("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}"),en("\u21a4","\\mapsfrom"),en("\\mapsfrom","\\html@mathml{\\mathrel{\\mathreflectbox{\\mapsto}}}{\\mathrel{\\char`\u21a4}}"),en("\u2983","\\lBrace"),en("\u2984","\\rBrace"),en("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`\u29b5}}"),en("\u29b5","\\minuso"),en("\\darr","\\downarrow"),en("\\dArr","\\Downarrow"),en("\\Darr","\\Downarrow"),en("\\lang","\\langle"),en("\\rang","\\rangle"),en("\\uarr","\\uparrow"),en("\\uArr","\\Uparrow"),en("\\Uarr","\\Uparrow"),en("\\N","\\mathbb{N}"),en("\\R","\\mathbb{R}"),en("\\Z","\\mathbb{Z}"),en("\\alef","\\aleph"),en("\\alefsym","\\aleph"),en("\\Alpha","\\mathrm{A}"),en("\\Beta","\\mathrm{B}"),en("\\bull","\\bullet"),en("\\Chi","\\mathrm{X}"),en("\\clubs","\\clubsuit"),en("\\cnums","\\mathbb{C}"),en("\\Complex","\\mathbb{C}"),en("\\Dagger","\\ddagger"),en("\\diamonds","\\diamondsuit"),en("\\empty","\\emptyset"),en("\\Epsilon","\\mathrm{E}"),en("\\Eta","\\mathrm{H}"),en("\\exist","\\exists"),en("\\harr","\\leftrightarrow"),en("\\hArr","\\Leftrightarrow"),en("\\Harr","\\Leftrightarrow"),en("\\hearts","\\heartsuit"),en("\\image","\\Im"),en("\\infin","\\infty"),en("\\Iota","\\mathrm{I}"),en("\\isin","\\in"),en("\\Kappa","\\mathrm{K}"),en("\\larr","\\leftarrow"),en("\\lArr","\\Leftarrow"),en("\\Larr","\\Leftarrow"),en("\\lrarr","\\leftrightarrow"),en("\\lrArr","\\Leftrightarrow"),en("\\Lrarr","\\Leftrightarrow"),en("\\Mu","\\mathrm{M}"),en("\\natnums","\\mathbb{N}"),en("\\Nu","\\mathrm{N}"),en("\\Omicron","\\mathrm{O}"),en("\\plusmn","\\pm"),en("\\rarr","\\rightarrow"),en("\\rArr","\\Rightarrow"),en("\\Rarr","\\Rightarrow"),en("\\real","\\Re"),en("\\reals","\\mathbb{R}"),en("\\Reals","\\mathbb{R}"),en("\\Rho","\\mathrm{P}"),en("\\sdot","\\cdot"),en("\\sect","\\S"),en("\\spades","\\spadesuit"),en("\\sub","\\subset"),en("\\sube","\\subseteq"),en("\\supe","\\supseteq"),en("\\Tau","\\mathrm{T}"),en("\\thetasym","\\vartheta"),en("\\weierp","\\wp"),en("\\Zeta","\\mathrm{Z}"),en("\\argmin","\\DOTSB\\operatorname*{arg\\,min}"),en("\\argmax","\\DOTSB\\operatorname*{arg\\,max}"),en("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits"),en("\\bra","\\mathinner{\\langle{#1}|}"),en("\\ket","\\mathinner{|{#1}\\rangle}"),en("\\braket","\\mathinner{\\langle{#1}\\rangle}"),en("\\Bra","\\left\\langle#1\\right|"),en("\\Ket","\\left|#1\\right\\rangle");const ro=e=>t=>{const r=t.consumeArg().tokens,n=t.consumeArg().tokens,o=t.consumeArg().tokens,s=t.consumeArg().tokens,i=t.macros.get("|"),a=t.macros.get("\\|");t.macros.beginGroup();const l=t=>r=>{e&&(r.macros.set("|",i),o.length&&r.macros.set("\\|",a));let s=t;if(!t&&o.length){"|"===r.future().text&&(r.popToken(),s=!0)}return{tokens:s?o:n,numArgs:0}};t.macros.set("|",l(!1)),o.length&&t.macros.set("\\|",l(!0));const c=t.consumeArg().tokens,h=t.expandTokens([...s,...c,...r]);return t.macros.endGroup(),{tokens:h.reverse(),numArgs:0}};en("\\bra@ket",ro(!1)),en("\\bra@set",ro(!0)),en("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}"),en("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}"),en("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}"),en("\\angln","{\\angl n}"),en("\\blue","\\textcolor{##6495ed}{#1}"),en("\\orange","\\textcolor{##ffa500}{#1}"),en("\\pink","\\textcolor{##ff00af}{#1}"),en("\\red","\\textcolor{##df0030}{#1}"),en("\\green","\\textcolor{##28ae7b}{#1}"),en("\\gray","\\textcolor{gray}{#1}"),en("\\purple","\\textcolor{##9d38bd}{#1}"),en("\\blueA","\\textcolor{##ccfaff}{#1}"),en("\\blueB","\\textcolor{##80f6ff}{#1}"),en("\\blueC","\\textcolor{##63d9ea}{#1}"),en("\\blueD","\\textcolor{##11accd}{#1}"),en("\\blueE","\\textcolor{##0c7f99}{#1}"),en("\\tealA","\\textcolor{##94fff5}{#1}"),en("\\tealB","\\textcolor{##26edd5}{#1}"),en("\\tealC","\\textcolor{##01d1c1}{#1}"),en("\\tealD","\\textcolor{##01a995}{#1}"),en("\\tealE","\\textcolor{##208170}{#1}"),en("\\greenA","\\textcolor{##b6ffb0}{#1}"),en("\\greenB","\\textcolor{##8af281}{#1}"),en("\\greenC","\\textcolor{##74cf70}{#1}"),en("\\greenD","\\textcolor{##1fab54}{#1}"),en("\\greenE","\\textcolor{##0d923f}{#1}"),en("\\goldA","\\textcolor{##ffd0a9}{#1}"),en("\\goldB","\\textcolor{##ffbb71}{#1}"),en("\\goldC","\\textcolor{##ff9c39}{#1}"),en("\\goldD","\\textcolor{##e07d10}{#1}"),en("\\goldE","\\textcolor{##a75a05}{#1}"),en("\\redA","\\textcolor{##fca9a9}{#1}"),en("\\redB","\\textcolor{##ff8482}{#1}"),en("\\redC","\\textcolor{##f9685d}{#1}"),en("\\redD","\\textcolor{##e84d39}{#1}"),en("\\redE","\\textcolor{##bc2612}{#1}"),en("\\maroonA","\\textcolor{##ffbde0}{#1}"),en("\\maroonB","\\textcolor{##ff92c6}{#1}"),en("\\maroonC","\\textcolor{##ed5fa6}{#1}"),en("\\maroonD","\\textcolor{##ca337c}{#1}"),en("\\maroonE","\\textcolor{##9e034e}{#1}"),en("\\purpleA","\\textcolor{##ddd7ff}{#1}"),en("\\purpleB","\\textcolor{##c6b9fc}{#1}"),en("\\purpleC","\\textcolor{##aa87ff}{#1}"),en("\\purpleD","\\textcolor{##7854ab}{#1}"),en("\\purpleE","\\textcolor{##543b78}{#1}"),en("\\mintA","\\textcolor{##f5f9e8}{#1}"),en("\\mintB","\\textcolor{##edf2df}{#1}"),en("\\mintC","\\textcolor{##e0e5cc}{#1}"),en("\\grayA","\\textcolor{##f6f7f7}{#1}"),en("\\grayB","\\textcolor{##f0f1f2}{#1}"),en("\\grayC","\\textcolor{##e3e5e6}{#1}"),en("\\grayD","\\textcolor{##d6d8da}{#1}"),en("\\grayE","\\textcolor{##babec2}{#1}"),en("\\grayF","\\textcolor{##888d93}{#1}"),en("\\grayG","\\textcolor{##626569}{#1}"),en("\\grayH","\\textcolor{##3b3e40}{#1}"),en("\\grayI","\\textcolor{##21242c}{#1}"),en("\\kaBlue","\\textcolor{##314453}{#1}"),en("\\kaGreen","\\textcolor{##71B307}{#1}");const no={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0};class oo{constructor(e,t,r){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new _n($n,t.macros),this.mode=r,this.stack=[]}feed(e){this.lexer=new Wn(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return 0===this.stack.length&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){let t,r,n;if(e){if(this.consumeSpaces(),"["!==this.future().text)return null;t=this.popToken();var o=this.consumeArg(["]"]);n=o.tokens,r=o.end}else{var s=this.consumeArg();n=s.tokens,t=s.start,r=s.end}return this.pushToken(new rn("EOF",r.loc)),this.pushTokens(n),new rn("",tn.range(t,r))}consumeSpaces(){for(;;){if(" "!==this.future().text)break;this.stack.pop()}}consumeArg(e){const t=[],r=e&&e.length>0;r||this.consumeSpaces();const o=this.future();let s,i=0,a=0;do{if(s=this.popToken(),t.push(s),"{"===s.text)++i;else if("}"===s.text){if(--i,-1===i)throw new n("Extra }",s)}else if("EOF"===s.text)throw new n("Unexpected end of input in a macro argument, expected '"+(e&&r?e[a]:"}")+"'",s);if(e&&r)if((0===i||1===i&&"{"===e[a])&&s.text===e[a]){if(++a,a===e.length){t.splice(-a,a);break}}else a=0}while(0!==i||r);return"{"===o.text&&"}"===t[t.length-1].text&&(t.pop(),t.shift()),t.reverse(),{tokens:t,start:o,end:s}}consumeArgs(e,t){if(t){if(t.length!==e+1)throw new n("The length of delimiters doesn't match the number of args!");const r=t[0];for(let e=0;ethis.settings.maxExpand)throw new n("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(e){const t=this.popToken(),r=t.text,o=t.noexpand?null:this._getExpansion(r);if(null==o||e&&o.unexpandable){if(e&&null==o&&"\\"===r[0]&&!this.isDefined(r))throw new n("Undefined control sequence: "+r);return this.pushToken(t),!1}this.countExpansion(1);let s=o.tokens;const i=this.consumeArgs(o.numArgs,o.delimiters);if(o.numArgs){s=s.slice();for(let e=s.length-1;e>=0;--e){let t=s[e];if("#"===t.text){if(0===e)throw new n("Incomplete placeholder at end of macro body",t);if(t=s[--e],"#"===t.text)s.splice(e+1,1);else{if(!/^[1-9]$/.test(t.text))throw new n("Not a valid argument number",t);s.splice(e,2,...i[+t.text-1])}}}}return this.pushTokens(s),s.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(!1===this.expandOnce()){const e=this.stack.pop();return e.treatAsRelax&&(e.text="\\relax"),e}}expandMacro(e){return this.macros.has(e)?this.expandTokens([new rn(e)]):void 0}expandTokens(e){const t=[],r=this.stack.length;for(this.pushTokens(e);this.stack.length>r;)if(!1===this.expandOnce(!0)){const e=this.stack.pop();e.treatAsRelax&&(e.noexpand=!1,e.treatAsRelax=!1),t.push(e)}return this.countExpansion(t.length),t}expandMacroAsText(e){const t=this.expandMacro(e);return t?t.map(e=>e.text).join(""):t}_getExpansion(e){const t=this.macros.get(e);if(null==t)return t;if(1===e.length){const t=this.lexer.catcodes[e];if(null!=t&&13!==t)return}const r="function"==typeof t?t(this):t;if("string"==typeof r){let e=0;if(r.includes("#")){const t=r.replace(/##/g,"");for(;t.includes("#"+(e+1));)++e}const t=new Wn(r,this.settings),n=[];let o=t.lex();for(;"EOF"!==o.text;)n.push(o),o=t.lex();n.reverse();return{tokens:n,numArgs:e}}return r}isDefined(e){return this.macros.has(e)||Object.prototype.hasOwnProperty.call(Vn,e)||Object.prototype.hasOwnProperty.call(ne.math,e)||Object.prototype.hasOwnProperty.call(ne.text,e)||Object.prototype.hasOwnProperty.call(no,e)}isExpandable(e){const t=this.macros.get(e);return null!=t?"string"==typeof t||"function"==typeof t||!t.unexpandable:Object.prototype.hasOwnProperty.call(Vn,e)&&!Vn[e].primitive}}const so=/^[\u208a\u208b\u208c\u208d\u208e\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2090\u2091\u2095\u1d62\u2c7c\u2096\u2097\u2098\u2099\u2092\u209a\u1d63\u209b\u209c\u1d64\u1d65\u2093\u1d66\u1d67\u1d68\u1d69\u1d6a]/,io=Object.freeze({"\u208a":"+","\u208b":"-","\u208c":"=","\u208d":"(","\u208e":")","\u2080":"0","\u2081":"1","\u2082":"2","\u2083":"3","\u2084":"4","\u2085":"5","\u2086":"6","\u2087":"7","\u2088":"8","\u2089":"9","\u2090":"a","\u2091":"e","\u2095":"h","\u1d62":"i","\u2c7c":"j","\u2096":"k","\u2097":"l","\u2098":"m","\u2099":"n","\u2092":"o","\u209a":"p","\u1d63":"r","\u209b":"s","\u209c":"t","\u1d64":"u","\u1d65":"v","\u2093":"x","\u1d66":"\u03b2","\u1d67":"\u03b3","\u1d68":"\u03c1","\u1d69":"\u03d5","\u1d6a":"\u03c7","\u207a":"+","\u207b":"-","\u207c":"=","\u207d":"(","\u207e":")","\u2070":"0","\xb9":"1","\xb2":"2","\xb3":"3","\u2074":"4","\u2075":"5","\u2076":"6","\u2077":"7","\u2078":"8","\u2079":"9","\u1d2c":"A","\u1d2e":"B","\u1d30":"D","\u1d31":"E","\u1d33":"G","\u1d34":"H","\u1d35":"I","\u1d36":"J","\u1d37":"K","\u1d38":"L","\u1d39":"M","\u1d3a":"N","\u1d3c":"O","\u1d3e":"P","\u1d3f":"R","\u1d40":"T","\u1d41":"U","\u2c7d":"V","\u1d42":"W","\u1d43":"a","\u1d47":"b","\u1d9c":"c","\u1d48":"d","\u1d49":"e","\u1da0":"f","\u1d4d":"g","\u02b0":"h","\u2071":"i","\u02b2":"j","\u1d4f":"k","\u02e1":"l","\u1d50":"m","\u207f":"n","\u1d52":"o","\u1d56":"p","\u02b3":"r","\u02e2":"s","\u1d57":"t","\u1d58":"u","\u1d5b":"v","\u02b7":"w","\u02e3":"x","\u02b8":"y","\u1dbb":"z","\u1d5d":"\u03b2","\u1d5e":"\u03b3","\u1d5f":"\u03b4","\u1d60":"\u03d5","\u1d61":"\u03c7","\u1dbf":"\u03b8"}),ao={"\u0301":{text:"\\'",math:"\\acute"},"\u0300":{text:"\\`",math:"\\grave"},"\u0308":{text:'\\"',math:"\\ddot"},"\u0303":{text:"\\~",math:"\\tilde"},"\u0304":{text:"\\=",math:"\\bar"},"\u0306":{text:"\\u",math:"\\breve"},"\u030c":{text:"\\v",math:"\\check"},"\u0302":{text:"\\^",math:"\\hat"},"\u0307":{text:"\\.",math:"\\dot"},"\u030a":{text:"\\r",math:"\\mathring"},"\u030b":{text:"\\H"},"\u0327":{text:"\\c"}},lo={"\xe1":"a\u0301","\xe0":"a\u0300","\xe4":"a\u0308","\u01df":"a\u0308\u0304","\xe3":"a\u0303","\u0101":"a\u0304","\u0103":"a\u0306","\u1eaf":"a\u0306\u0301","\u1eb1":"a\u0306\u0300","\u1eb5":"a\u0306\u0303","\u01ce":"a\u030c","\xe2":"a\u0302","\u1ea5":"a\u0302\u0301","\u1ea7":"a\u0302\u0300","\u1eab":"a\u0302\u0303","\u0227":"a\u0307","\u01e1":"a\u0307\u0304","\xe5":"a\u030a","\u01fb":"a\u030a\u0301","\u1e03":"b\u0307","\u0107":"c\u0301","\u1e09":"c\u0327\u0301","\u010d":"c\u030c","\u0109":"c\u0302","\u010b":"c\u0307","\xe7":"c\u0327","\u010f":"d\u030c","\u1e0b":"d\u0307","\u1e11":"d\u0327","\xe9":"e\u0301","\xe8":"e\u0300","\xeb":"e\u0308","\u1ebd":"e\u0303","\u0113":"e\u0304","\u1e17":"e\u0304\u0301","\u1e15":"e\u0304\u0300","\u0115":"e\u0306","\u1e1d":"e\u0327\u0306","\u011b":"e\u030c","\xea":"e\u0302","\u1ebf":"e\u0302\u0301","\u1ec1":"e\u0302\u0300","\u1ec5":"e\u0302\u0303","\u0117":"e\u0307","\u0229":"e\u0327","\u1e1f":"f\u0307","\u01f5":"g\u0301","\u1e21":"g\u0304","\u011f":"g\u0306","\u01e7":"g\u030c","\u011d":"g\u0302","\u0121":"g\u0307","\u0123":"g\u0327","\u1e27":"h\u0308","\u021f":"h\u030c","\u0125":"h\u0302","\u1e23":"h\u0307","\u1e29":"h\u0327","\xed":"i\u0301","\xec":"i\u0300","\xef":"i\u0308","\u1e2f":"i\u0308\u0301","\u0129":"i\u0303","\u012b":"i\u0304","\u012d":"i\u0306","\u01d0":"i\u030c","\xee":"i\u0302","\u01f0":"j\u030c","\u0135":"j\u0302","\u1e31":"k\u0301","\u01e9":"k\u030c","\u0137":"k\u0327","\u013a":"l\u0301","\u013e":"l\u030c","\u013c":"l\u0327","\u1e3f":"m\u0301","\u1e41":"m\u0307","\u0144":"n\u0301","\u01f9":"n\u0300","\xf1":"n\u0303","\u0148":"n\u030c","\u1e45":"n\u0307","\u0146":"n\u0327","\xf3":"o\u0301","\xf2":"o\u0300","\xf6":"o\u0308","\u022b":"o\u0308\u0304","\xf5":"o\u0303","\u1e4d":"o\u0303\u0301","\u1e4f":"o\u0303\u0308","\u022d":"o\u0303\u0304","\u014d":"o\u0304","\u1e53":"o\u0304\u0301","\u1e51":"o\u0304\u0300","\u014f":"o\u0306","\u01d2":"o\u030c","\xf4":"o\u0302","\u1ed1":"o\u0302\u0301","\u1ed3":"o\u0302\u0300","\u1ed7":"o\u0302\u0303","\u022f":"o\u0307","\u0231":"o\u0307\u0304","\u0151":"o\u030b","\u1e55":"p\u0301","\u1e57":"p\u0307","\u0155":"r\u0301","\u0159":"r\u030c","\u1e59":"r\u0307","\u0157":"r\u0327","\u015b":"s\u0301","\u1e65":"s\u0301\u0307","\u0161":"s\u030c","\u1e67":"s\u030c\u0307","\u015d":"s\u0302","\u1e61":"s\u0307","\u015f":"s\u0327","\u1e97":"t\u0308","\u0165":"t\u030c","\u1e6b":"t\u0307","\u0163":"t\u0327","\xfa":"u\u0301","\xf9":"u\u0300","\xfc":"u\u0308","\u01d8":"u\u0308\u0301","\u01dc":"u\u0308\u0300","\u01d6":"u\u0308\u0304","\u01da":"u\u0308\u030c","\u0169":"u\u0303","\u1e79":"u\u0303\u0301","\u016b":"u\u0304","\u1e7b":"u\u0304\u0308","\u016d":"u\u0306","\u01d4":"u\u030c","\xfb":"u\u0302","\u016f":"u\u030a","\u0171":"u\u030b","\u1e7d":"v\u0303","\u1e83":"w\u0301","\u1e81":"w\u0300","\u1e85":"w\u0308","\u0175":"w\u0302","\u1e87":"w\u0307","\u1e98":"w\u030a","\u1e8d":"x\u0308","\u1e8b":"x\u0307","\xfd":"y\u0301","\u1ef3":"y\u0300","\xff":"y\u0308","\u1ef9":"y\u0303","\u0233":"y\u0304","\u0177":"y\u0302","\u1e8f":"y\u0307","\u1e99":"y\u030a","\u017a":"z\u0301","\u017e":"z\u030c","\u1e91":"z\u0302","\u017c":"z\u0307","\xc1":"A\u0301","\xc0":"A\u0300","\xc4":"A\u0308","\u01de":"A\u0308\u0304","\xc3":"A\u0303","\u0100":"A\u0304","\u0102":"A\u0306","\u1eae":"A\u0306\u0301","\u1eb0":"A\u0306\u0300","\u1eb4":"A\u0306\u0303","\u01cd":"A\u030c","\xc2":"A\u0302","\u1ea4":"A\u0302\u0301","\u1ea6":"A\u0302\u0300","\u1eaa":"A\u0302\u0303","\u0226":"A\u0307","\u01e0":"A\u0307\u0304","\xc5":"A\u030a","\u01fa":"A\u030a\u0301","\u1e02":"B\u0307","\u0106":"C\u0301","\u1e08":"C\u0327\u0301","\u010c":"C\u030c","\u0108":"C\u0302","\u010a":"C\u0307","\xc7":"C\u0327","\u010e":"D\u030c","\u1e0a":"D\u0307","\u1e10":"D\u0327","\xc9":"E\u0301","\xc8":"E\u0300","\xcb":"E\u0308","\u1ebc":"E\u0303","\u0112":"E\u0304","\u1e16":"E\u0304\u0301","\u1e14":"E\u0304\u0300","\u0114":"E\u0306","\u1e1c":"E\u0327\u0306","\u011a":"E\u030c","\xca":"E\u0302","\u1ebe":"E\u0302\u0301","\u1ec0":"E\u0302\u0300","\u1ec4":"E\u0302\u0303","\u0116":"E\u0307","\u0228":"E\u0327","\u1e1e":"F\u0307","\u01f4":"G\u0301","\u1e20":"G\u0304","\u011e":"G\u0306","\u01e6":"G\u030c","\u011c":"G\u0302","\u0120":"G\u0307","\u0122":"G\u0327","\u1e26":"H\u0308","\u021e":"H\u030c","\u0124":"H\u0302","\u1e22":"H\u0307","\u1e28":"H\u0327","\xcd":"I\u0301","\xcc":"I\u0300","\xcf":"I\u0308","\u1e2e":"I\u0308\u0301","\u0128":"I\u0303","\u012a":"I\u0304","\u012c":"I\u0306","\u01cf":"I\u030c","\xce":"I\u0302","\u0130":"I\u0307","\u0134":"J\u0302","\u1e30":"K\u0301","\u01e8":"K\u030c","\u0136":"K\u0327","\u0139":"L\u0301","\u013d":"L\u030c","\u013b":"L\u0327","\u1e3e":"M\u0301","\u1e40":"M\u0307","\u0143":"N\u0301","\u01f8":"N\u0300","\xd1":"N\u0303","\u0147":"N\u030c","\u1e44":"N\u0307","\u0145":"N\u0327","\xd3":"O\u0301","\xd2":"O\u0300","\xd6":"O\u0308","\u022a":"O\u0308\u0304","\xd5":"O\u0303","\u1e4c":"O\u0303\u0301","\u1e4e":"O\u0303\u0308","\u022c":"O\u0303\u0304","\u014c":"O\u0304","\u1e52":"O\u0304\u0301","\u1e50":"O\u0304\u0300","\u014e":"O\u0306","\u01d1":"O\u030c","\xd4":"O\u0302","\u1ed0":"O\u0302\u0301","\u1ed2":"O\u0302\u0300","\u1ed6":"O\u0302\u0303","\u022e":"O\u0307","\u0230":"O\u0307\u0304","\u0150":"O\u030b","\u1e54":"P\u0301","\u1e56":"P\u0307","\u0154":"R\u0301","\u0158":"R\u030c","\u1e58":"R\u0307","\u0156":"R\u0327","\u015a":"S\u0301","\u1e64":"S\u0301\u0307","\u0160":"S\u030c","\u1e66":"S\u030c\u0307","\u015c":"S\u0302","\u1e60":"S\u0307","\u015e":"S\u0327","\u0164":"T\u030c","\u1e6a":"T\u0307","\u0162":"T\u0327","\xda":"U\u0301","\xd9":"U\u0300","\xdc":"U\u0308","\u01d7":"U\u0308\u0301","\u01db":"U\u0308\u0300","\u01d5":"U\u0308\u0304","\u01d9":"U\u0308\u030c","\u0168":"U\u0303","\u1e78":"U\u0303\u0301","\u016a":"U\u0304","\u1e7a":"U\u0304\u0308","\u016c":"U\u0306","\u01d3":"U\u030c","\xdb":"U\u0302","\u016e":"U\u030a","\u0170":"U\u030b","\u1e7c":"V\u0303","\u1e82":"W\u0301","\u1e80":"W\u0300","\u1e84":"W\u0308","\u0174":"W\u0302","\u1e86":"W\u0307","\u1e8c":"X\u0308","\u1e8a":"X\u0307","\xdd":"Y\u0301","\u1ef2":"Y\u0300","\u0178":"Y\u0308","\u1ef8":"Y\u0303","\u0232":"Y\u0304","\u0176":"Y\u0302","\u1e8e":"Y\u0307","\u0179":"Z\u0301","\u017d":"Z\u030c","\u1e90":"Z\u0302","\u017b":"Z\u0307","\u03ac":"\u03b1\u0301","\u1f70":"\u03b1\u0300","\u1fb1":"\u03b1\u0304","\u1fb0":"\u03b1\u0306","\u03ad":"\u03b5\u0301","\u1f72":"\u03b5\u0300","\u03ae":"\u03b7\u0301","\u1f74":"\u03b7\u0300","\u03af":"\u03b9\u0301","\u1f76":"\u03b9\u0300","\u03ca":"\u03b9\u0308","\u0390":"\u03b9\u0308\u0301","\u1fd2":"\u03b9\u0308\u0300","\u1fd1":"\u03b9\u0304","\u1fd0":"\u03b9\u0306","\u03cc":"\u03bf\u0301","\u1f78":"\u03bf\u0300","\u03cd":"\u03c5\u0301","\u1f7a":"\u03c5\u0300","\u03cb":"\u03c5\u0308","\u03b0":"\u03c5\u0308\u0301","\u1fe2":"\u03c5\u0308\u0300","\u1fe1":"\u03c5\u0304","\u1fe0":"\u03c5\u0306","\u03ce":"\u03c9\u0301","\u1f7c":"\u03c9\u0300","\u038e":"\u03a5\u0301","\u1fea":"\u03a5\u0300","\u03ab":"\u03a5\u0308","\u1fe9":"\u03a5\u0304","\u1fe8":"\u03a5\u0306","\u038f":"\u03a9\u0301","\u1ffa":"\u03a9\u0300"};class co{constructor(e,t){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new oo(e,t,this.mode),this.settings=t,this.leftrightDepth=0,this.nextToken=null}expect(e,t){if(void 0===t&&(t=!0),this.fetch().text!==e)throw new n("Expected '"+e+"', got '"+this.fetch().text+"'",this.fetch());t&&this.consume()}consume(){this.nextToken=null}fetch(){return null==this.nextToken&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{const e=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){const t=this.nextToken;this.consume(),this.gullet.pushToken(new rn("}")),this.gullet.pushTokens(e);const r=this.parseExpression(!1);return this.expect("}"),this.nextToken=t,r}parseExpression(e,t){const r=[];for(;;){"math"===this.mode&&this.consumeSpaces();const n=this.fetch();if(co.endOfExpression.has(n.text))break;if(t&&n.text===t)break;if(e&&Vn[n.text]&&Vn[n.text].infix)break;const o=this.parseAtom(t);if(!o)break;"internal"!==o.type&&r.push(o)}return"text"===this.mode&&this.formLigatures(r),this.handleInfixNodes(r)}handleInfixNodes(e){let t,r=-1;for(let o=0;o=128))return null;this.settings.strict&&(T(t.charCodeAt(0))?"math"===this.mode&&Fe({strict:this.settings.strict,errorCode:"unicodeTextInMathMode",errorMsg:'Unicode text character "'+t[0]+'" used in math mode',report:!0,token:e}):Fe({strict:this.settings.strict,errorCode:"unknownSymbol",errorMsg:'Unrecognized Unicode character "'+t[0]+'" ('+t.charCodeAt(0)+")",report:!0,token:e})),o={type:"textord",mode:"text",loc:tn.range(e),text:t}}var s;if(this.consume(),r)for(let t=0;t Date: Mon, 26 Oct 2026 19:05:34 +0100 Subject: [PATCH 133/177] prefill: opt-in fused int8 prompt experts for the native Q2_0 pack on sm_80+, STRATA_PF_FUSED_Q2N=1 (#3809) A PC whose CPU lacks the AVX-512 set that setup checks for gets the native Q2_0 pack. On a CUDA card of sm_80 or newer its Q2_0 / Q2_0 prompt experts run through MMQ, although the fused int8 kernel for that format (#2145) is in the binary and set up only on a Turing card (b6443f3ae). STRATA_PF_FUSED_Q2N=1 sets that kernel up on any sm_80+ card and takes it for the Q2_0 / Q2_0 layers, under its own variable so that STRATA_PF_FUSED=1 keeps its bits. STRATA_PF_FUSED=0 and STRATA_PF_FUSED_NATIVE=0 still turn it off. A failed setup leaves the occupancy as it was and the layers on MMQ. - moe_fused_iq.cu: DevInfo.q2n; dev_info() sets up Q2_0 gate/up when the switch is set; gu_covered() and native_supported() take the pair only when q2n is set (a Q2_0 gate with another down type is refused, as on Turing). - tests/cuda/prefill_fused_iq_test.cpp: --unset-pf-fused leaves STRATA_PF_FUSED unset (the engine's default) and skips below sm_80; CMakeLists.txt: the ctest entry prefill_fused_iq_test_q2n runs the Q2_0 / Q2_0 pair with the switch alone (exit 77 = skipped without an sm_80+ card; CUDA branch only). - docs/DETAILS.md: one section in the author's measured numbers (RTX 5080) and the A4000 caveat below. Unset (the default), nothing changes: dev_info() reads the variable once and sets nothing up, gu_covered() and native_supported() return what they returned. Read line by line against base: the Turing path (t75) and the HIP path are untouched. Set, the prompt arithmetic changes (first-token KL against FP16 0.0110, MMQ 0.0112, the author's figure) and the fused path's smaller buffers let --prefill auto pick a larger chunk, which is most of the author's 16K gain; the generated text can change. Not verified: an RTX A4000 (sm_86). The kernel was taken on every CUDA card in #2145 and then kept to Turing after an A4000 no longer matched the old output and read 4K prompts 4.5% slower; the PR does not repeat that run. Merge note: #3277 and #3779 change dev_info() and native_supported() in the same file. Tests: prefill_fused_iq_test_q2n and prefill_fused_iq_test pass on an RTX A4000 (sm_86, synthetic data); on the Q2_0 / Q2_0 layer the fused kernel is 1.76x / 1.30x / 1.24x the MMQ path at 2048 / 4864 / 8192 tokens with the same relative RMS against FP32. Builds on CUDA sm_86 (Linux) and sm_120 (MSVC). Not covered: no model run; the engine-level A4000 check is the gate. --- CMakeLists.txt | 4 ++++ docs/DETAILS.md | 23 ++++++++++++++++++++++- src/prefill/moe_fused_iq.cu | 13 +++++++++++-- tests/cuda/prefill_fused_iq_test.cpp | 23 ++++++++++++++++++----- 4 files changed, 55 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e1aa9ffe..89b2f620 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2055,6 +2055,10 @@ if(STRATA_NATIVE_EXPERTS) 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 opt-in STRATA_PF_FUSED_Q2N=1 on its own (the test leaves STRATA_PF_FUSED unset): the native Q2_0 pack's Q2_0 / Q2_0 + # layers on sm_80+ (77 below sm_80 and without a card) + add_test(NAME prefill_fused_iq_test_q2n COMMAND prefill_fused_iq_test "--only=Q2_0 / Q2_0" --unset-pf-fused) + set_tests_properties(prefill_fused_iq_test_q2n PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_Q2N=1" 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) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index a6e35c0b..22bd4b65 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -947,7 +947,28 @@ that wins in both directions: `STRATA_SM75_IL`, `STRATA_SM75_EXP`, `STRATA_GR_UP `STRATA_TOPK_SPLIT`, `STRATA_TOPK_SAMPLE`, `STRATA_ATTN_V3`, `STRATA_Q2_WARP`, `STRATA_FUSE_WAIT=2`, `STRATA_QIL`, `STRATA_TC_SM75`, `STRATA_PA_V1_PREFETCH`, `STRATA_SCORES_THREAD` (a thread-per-head block scorer; `=1` works on any CUDA card). Options that change answers stay separate: `STRATA_SELECT_SIMT=1|2`, `STRATA_PA_V2T=1`, `STRATA_PF_FUSED=1 STRATA_PF_FUSED_SM75=1` -(Q2_0 pack, 7.5 card only) and `STRATA_BF16_TC=1` with `STRATA_XN_F16`. +(Q2_0 pack, 7.5 card only), `STRATA_PF_FUSED_Q2N=1` (the native Q2_0 pack's prompt experts on sm_80+, below) and +`STRATA_BF16_TC=1` with `STRATA_XN_F16`. + +### The native Q2_0 pack's prompt experts on the fused int8 kernels (`STRATA_PF_FUSED_Q2N=1`, opt-in, sm_80+) + +A PC whose CPU lacks the AVX-512 set that setup looks for gets the native Q2_0 pack. On a CUDA card of sm_80 or newer its +Q2_0 / Q2_0 layers read prompts through MMQ's Q2_0 kernel; the fused int8 kernel for that format (#2145) is set up only on a +7.5 card. `STRATA_PF_FUSED_Q2N=1` sets it up on any sm_80+ card and takes it for those layers. It has its own variable, so +`STRATA_PF_FUSED=1` keeps its bits, and `STRATA_PF_FUSED=0` or `STRATA_PF_FUSED_NATIVE=0` still turn it off. Unset, the engine +is unchanged (first-token logits byte-identical to v0.2.2 on 40 prompts of 1-5K tokens, the author's check). With the switch +the prompt arithmetic changes and the generated text can change. + +The author measured it on an RTX 5080 16 GB (sm_120, Linux, CUDA 13.0), i9-14900K, 2,100 experts in VRAM, CPU prompt share off, +against the same build unset. At the same 4,864-token chunk (4 interleaved rounds) the 4K, 16K and 23K prompts read 2-3.5% +faster (4/4 rounds each). With `--prefill auto` (5 rounds) the fused path's smaller buffers make the chunk 5,632 tokens instead of +4,864 and the 16K prompt reads 32-33% faster (2,592 -> 3,438 tok/s), the 23K one 14%, a 4K one 0-2%; so most of the gain is the +larger chunk, not the kernel. One layer (`prefill_fused_iq_test`, Q2_0 / Q2_0) runs at 1.92x / 1.37x / 1.30x the MMQ path at +2,048 / 4,864 / 8,192 tokens. First-token KL against the FP16 prompt path over 30 prompts of 1.5-4.6K tokens: 0.0110 (MMQ +0.0112), top-1 agreement 28/30 (MMQ 29/30). Not measured: a card that holds every expert, other sm_80+ cards, Windows, the +generated text. On an RTX A4000 the same kernel in #2145 stopped matching the old output and read 4K prompts 4.5% slower, so +Ampere is not verified. The ctest entry `prefill_fused_iq_test_q2n` runs the Q2_0 / Q2_0 layer with the switch alone (it skips +below sm_80 and without a card). --- diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index de272681..d239972f 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -1188,6 +1188,7 @@ struct DevInfo { bool done = false, ok = false; bool w12 = false; // gfx12 (RDNA4): the native kernels only - the Q2_0 pack's (moe_fused.cu) are not ported there bool t75 = false; // Turing (STRATA_PF_FUSED_SM75): the Q2_0 / Q2_0 layers only (what was set up and checked there) + bool q2n = false; // sm_80+ with STRATA_PF_FUSED_Q2N=1: the native Q2_0 pack's Q2_0 gate/up is set up as well (opt-in) bool s120 = false; // compute capability 12.0 (sm120_series.hpp): the default for the formats measured there int sms = 0, occ = 1; }; @@ -1308,7 +1309,12 @@ const DevInfo& dev_info() { } d.ok = setup_one(occ) && setup_one(occ) && setup_one(occ) && setup_one(occ) && setup_one(occ) && setup_one(occ) && - setup_one(occ) && setup_one(occ); // (Q2_0 gate/up is the Turing opt-in's only) + setup_one(occ) && setup_one(occ); // (Q2_0 gate/up: the Turing opt-in's, or below) + // STRATA_PF_FUSED_Q2N=1: the native Q2_0 pack's Q2_0 gate/up on these kernels here too (what #2145 took with + // STRATA_PF_FUSED=1 on every CUDA card until b6443f3a kept it to Turing). Its own variable, so STRATA_PF_FUSED=1 keeps + // its bits: unset, the kernel is not set up and the Q2_0 layers keep MMQ. A failed setup leaves occ as it was. + static const bool q2n = [] { const char* v = std::getenv("STRATA_PF_FUSED_Q2N"); return v != nullptr && v[0] == '1'; }(); + if (int o2 = occ; q2n && d.ok && setup_one(o2)) { d.q2n = true; occ = o2; } d.occ = d.ok ? occ : 1; cudaGetLastError(); #endif @@ -1332,7 +1338,7 @@ bool f16_d(int t) { return t == T_Q2_0 || t == T_IQ4_NL || t == T_Q8_0; } bool gu_covered(int t) { return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS #if !defined(__HIPCC__) - || (t == T_Q2_0 && dev_info().t75) // the canonical Q2_0 pack's gate/up: Turing opt-in only (sm_80+ keeps MMQ for it) + || (t == T_Q2_0 && (dev_info().t75 || dev_info().q2n)) // Q2_0 gate/up: the Turing opt-in, or STRATA_PF_FUSED_Q2N=1 on sm_80+ #endif #if defined(__HIPCC__) || (t == T_Q2_0 && dev_info().w12) // gfx12: the native Q2_0 pack's gate/up on native_w11_kernel (64-value blocks) @@ -1411,12 +1417,15 @@ bool native_supported(int gu_type, int d_type) { // agent, needles, CJK and tool calls the same). IQ2_XXS / IQ2_XS gate/up (the IQ3_XXS and IQ2_XS packs) keep MMQ until // measured. Every other CUDA card: opt-in as before. if (env < 0) { + // the native Q2_0 pack's Q2_0 / Q2_0 layers: only with STRATA_PF_FUSED_Q2N=1 (d.q2n), on any sm_80+ card + if (gu_type == T_Q2_0) { const DevInfo& d = dev_info(); return d.ok && d.q2n && d_type == T_Q2_0 && d_covered_on(d_type, d); } if (gu_type != T_IQ2_S && gu_type != T_IQ3_XXS && gu_type != T_IQ3_S && gu_type != T_IQ4_XS) return false; const DevInfo& d = dev_info(); // 12.0 cards with 80+ SMs only (RTX PRO 5000 / 6000, RTX 5080 / 5090): on an RTX 5070 (48 SMs, IQ2_XS pack, experts // partly in RAM) the fused kernels were 4.7% slower on 20K prompts (0/6 pairs) - it keeps MMQ unless STRATA_PF_FUSED=1 return d.ok && d.s120 && d.sms >= 80 && !d.t75 && d_covered_on(d_type, d); } + if (gu_type == T_Q2_0 && d_type != T_Q2_0) return false; // the opt-in (STRATA_PF_FUSED=1 as well) takes the Q2_0 / Q2_0 pair only #endif // default: only these three; the Q2_0 one (148-amd) is on Linux only: on Windows it is opt-in (STRATA_PF_FUSED=1) until tested there if (env < 0 && gu_type != T_IQ3_S && gu_type != T_IQ3_XXS && !(gu_type == T_Q2_0 && strata::core::kGfx12PromptDefaultsOn)) return false; diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp index e07051e8..aba76925 100644 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -13,7 +13,9 @@ // different expert ranges. Part 2 (timing): one layer at the engine's chunks (2048, 3584, 8192 tokens; 512 experts, // top 10) on both paths and on MMQ's products alone (no gathers), for the IQ2_XS, IQ3_XXS and IQ3_S packs' most // common layers, with the grouping checked and a sample of rows against the reference. --no-ref, --no-timing, -// --only=NAME, --chunks=A,B. Exit 77 without a CUDA device of sm_80 or newer. +// --only=NAME, --chunks=A,B, --unset-pf-fused (STRATA_PF_FUSED left unset instead of set to 1: the engine's default, for the +// STRATA_PF_FUSED_Q2N=1 ctest entry). Exit 77 without a CUDA device of sm_80 or newer. +#include "strata/core/emulate.hpp" #include "strata/prefill/moe_fused_iq.hpp" #include "strata/prefill/moe_mmq.hpp" @@ -643,10 +645,15 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { int main(int argc, char** argv) { try { + // --unset-pf-fused: STRATA_PF_FUSED unset, as the engine's default (the ctest entry for the opt-in STRATA_PF_FUSED_Q2N=1, + // whose Q2_0 / Q2_0 pair the engine takes with the old variable unset or at 1) + bool unset_pf = false; + for (int i = 1; i < argc; ++i) + if (std::strcmp(argv[i], "--unset-pf-fused") == 0) unset_pf = true; #ifdef _WIN32 - _putenv_s("STRATA_PF_FUSED", "1"); + if (unset_pf) _putenv_s("STRATA_PF_FUSED", ""); else _putenv_s("STRATA_PF_FUSED", "1"); // (an empty value removes it) #else - setenv("STRATA_PF_FUSED", "1", 1); + if (unset_pf) unsetenv("STRATA_PF_FUSED"); else setenv("STRATA_PF_FUSED", "1", 1); setenv("STRATA_PF_FUSED_KQ", "1", 1); // (the HIP build's Q4_K / Q5_K / Q5_1 / Q8_0 pairs) #endif int n = 0; @@ -656,6 +663,12 @@ int main(int argc, char** argv) { std::printf("the fused kernels need sm_80 or newer (or gfx11 / gfx12 matrix cores): skipped\n"); return 77; } + // with STRATA_PF_FUSED unset nothing is set up below sm_80 (Turing's pair is STRATA_PF_FUSED=1 STRATA_PF_FUSED_SM75=1's) + if (unset_pf) { + int major = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0); + if (strata::cc_major_of(major) < 8) { std::printf("STRATA_PF_FUSED unset: nothing is set up below sm_80 (skipped)\n"); return 77; } + } if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } const std::vector pairs = { {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, @@ -691,8 +704,8 @@ int main(int argc, char** argv) { for (const Pair& p : pairs) { if (only ? std::string(p.name).find(only) == std::string::npos : p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K) continue; if (!fused::native_supported((int) p.gu, (int) p.d)) { - // the canonical Q2_0 pack's Q2_0 gate/up is the Turing opt-in's (STRATA_PF_FUSED_SM75=1), and on Turing that is - // the only pair set up: skip what this device does not take (--only=NAME still insists) + // the Q2_0 / Q2_0 pair is the Turing opt-in's (STRATA_PF_FUSED_SM75=1; the only pair set up there) or, on sm_80+, + // STRATA_PF_FUSED_Q2N=1's: skip what this device does not take (--only=NAME still insists) const bool turing_pair = p.gu == GGML_TYPE_Q2_0 && p.d == GGML_TYPE_Q2_0; int major = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0); From 0aa64b2de39e26ad5368e630c36fb2f3ed08bf8c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 19:57:56 +0100 Subject: [PATCH 134/177] Web chat: preview a generated svg or html block in a sandboxed frame (#1628) A complete ```svg or ```html block in an answer gets a Preview button. The block's own code is drawn in an iframe (srcdoc) that is cut off from the page: sandbox="" (an opaque origin: no access to the page's DOM, storage, cookies or server, no scripts, forms, popups, downloads or navigation of the page), a CSP in the frame's document (default-src 'none': no network, fonts, frames or media; styles inline, pictures as data: only; no , no form target), no referrer and no permissions. A well-formed svg is shown as an with a data: URL: an image runs no script, loads nothing and animates in every browser. The frame takes the page's light or dark colours and is built again when the theme changes. A page (html) can also be run WITH scripts, one block at a time, after a warning that is shown every time: sandbox="allow-scripts" only (still an opaque origin), the CSP allows the block's inline script and no address; closing the preview ends it. What the sandbox flags alone do not stop is a link or inside the model's html loading a web page into the frame. The browser test shows it does (tools/webtest/browser_test.mjs, with and without the header). So the page is served with Content-Security-Policy: frame-src 'none' (nothing else: a srcdoc frame inherits the page's policy, and the script preview needs its inline script), and a in a previewed page is dropped. tools/webtest holds the mock server (the page's own files, scripted answers, no model) and the browser tests; serve/test_web_preview.js checks the documents, flags and frames, serve/test_web_preview.py the header and that the page never listens for a frame's postMessage. Ported by hand from PR #1628 by thoives. Co-authored-by: Thomas Ivesdal-Tronstad <325436323+thoives@users.noreply.github.com> --- serve/server.py | 9 ++ serve/test_web_preview.js | 104 ++++++++++++++++++ serve/test_web_preview.py | 79 ++++++++++++++ serve/web/app.css | 13 +++ serve/web/app.js | 60 +++++++++-- serve/web/index.html | 1 + serve/web/preview.js | 81 +++++++++++++++ tools/webtest/browser_test.mjs | 185 +++++++++++++++++++++++++++++++++ tools/webtest/lib.mjs | 77 ++++++++++++++ tools/webtest/mock.mjs | 129 +++++++++++++++++++++++ 10 files changed, 732 insertions(+), 6 deletions(-) create mode 100644 serve/test_web_preview.js create mode 100644 serve/test_web_preview.py create mode 100644 serve/web/preview.js create mode 100644 tools/webtest/browser_test.mjs create mode 100644 tools/webtest/lib.mjs create mode 100644 tools/webtest/mock.mjs diff --git a/serve/server.py b/serve/server.py index ad0e10a9..ba92ffba 100644 --- a/serve/server.py +++ b/serve/server.py @@ -449,6 +449,11 @@ class GpuBusy(RuntimeError): self.retry_after = retry_after +# The page's only CSP directive: its preview frames (srcdoc) may not load any address. Other directives are left out +# on purpose: a frame made from srcdoc inherits the page's policy, and the opt-in "run scripts" preview needs its own inline script. +PAGE_CSP = "frame-src 'none'" + + def unload_wait(value, default: float) -> float: """#1997: the `wait` of POST /unload?wait=...: absent / 0 / false: 0 (answer "busy" at once, as before); 1 / true / yes: `default` seconds; a number of seconds above 1: that long (at most an hour).""" @@ -6646,6 +6651,10 @@ def make_handler(svc: Service): body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") + if not path: + # the chat's svg/html preview is a sandboxed frame; this keeps it from navigating away to a web page + # (a link or inside a model's html), which no sandbox flag does (serve/web/preview.js) + self.send_header("Content-Security-Policy", PAGE_CSP) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) diff --git a/serve/test_web_preview.js b/serve/test_web_preview.js new file mode 100644 index 00000000..7c1dad15 --- /dev/null +++ b/serve/test_web_preview.js @@ -0,0 +1,104 @@ +// The svg/html preview (serve/web/preview.js), run in Node. The real browser behaviour (what a sandboxed frame can and +// cannot reach) is tested in tools/webtest/browser_test.mjs; here the documents and frames that are built are checked. +// node serve/test_web_preview.js (serve/test_web_preview.py runs it too and skips when node is missing) +"use strict"; +const assert = require("node:assert/strict"); +const path = require("node:path"); +const P = require(path.join(__dirname, "web", "preview.js")); + +const light = {dark: false, ink: "#221e1f"}, dark = {dark: true, ink: "#eef1f3"}; +const cspOf = (doc) => /Content-Security-Policy" content="([^"]*)"/.exec(doc)[1]; +const noImage = {DOMParser: undefined}; // no DOMParser: the inline svg path + +const cases = { + can_preview() { + assert.ok(P.canPreview("svg", "") && P.canPreview("SVG", " ")); + assert.ok(P.canPreview("html", "

x

") && P.canPreview("htm", "") && P.canPreview("HTML", "

")); + assert.ok(!P.canPreview("python", "") && !P.canPreview("html", "plain words") && !P.canPreview("svg", "

not svg

")); + assert.ok(!P.canPreview("", "

x

") && !P.canPreview("svgx", ""), "the fence's language decides"); + }, + sandbox_flags_are_minimal() { + assert.equal(P.SANDBOX.static, "", "no flags: no scripts, forms, popups, downloads, modals or navigation"); + assert.equal(P.SANDBOX.scripts, "allow-scripts", "scripts only"); + for (const v of Object.values(P.SANDBOX)) assert.ok(!/same-origin|top-navigation|popups|forms|modals|downloads|storage|pointer-lock|presentation/.test(v)); + }, + csp_has_no_network() { + const off = P.csp(false), on = P.csp(true); + for (const c of [off, on]) { + assert.match(c, /^default-src 'none'; /, "everything is off unless listed"); + assert.ok(!/connect-src|frame-src|font-src|media-src|object-src|https?:|\*/.test(c), "no network source: " + c); + assert.match(c, /img-src data:/); assert.match(c, /base-uri 'none'/); assert.match(c, /form-action 'none'/); + } + assert.ok(!off.includes("script-src"), "off: scripts fall back to default-src 'none'"); + assert.match(on, /script-src 'unsafe-inline'/, "on: the block's own inline script, and no source"); + assert.ok(!/script-src[^;]*(https?:|\*|'self'|data:)/.test(on)); + }, + html_documents() { + const frag = P.previewDoc("html", "

hi

", false, light); + assert.ok(frag.startsWith("hi

") && frag.endsWith("")); + assert.match(frag, /color-scheme:light/); + const full = P.previewDoc("html", "tx", false, dark); + assert.ok(full.indexOf("Content-Security-Policy") < full.indexOf(""), "our CSP is before the page's head"); + assert.equal((full.match(/<!doctype/gi) || []).length, 1, "one doctype"); + assert.match(full, /color-scheme:dark/); + assert.equal(cspOf(full), P.csp(false)); + assert.equal(cspOf(P.previewDoc("html", "<p>x</p>", true, light)), P.csp(true)); + assert.equal(P.previewDoc("html", "just words", false, light), null); + assert.equal(P.previewDoc("python", "<p>x</p>", false, light), null); + }, + a_page_cannot_redirect_itself() { + for (const meta of ['<meta http-equiv="refresh" content="0;url=http://evil.example/">', "<meta http-equiv=refresh content='0; url=http://evil.example'>", + '<META HTTP-EQUIV = "Refresh" CONTENT="1;URL=http://evil.example">', '<meta content="0;url=http://evil.example" http-equiv="refresh">']) { + const doc = P.previewDoc("html", `<!doctype html><html><head>${meta}</head><body>x</body></html>`, false, light); + assert.ok(!/refresh/i.test(doc.replace(/Content-Security-Policy[^>]*>/, "")), meta + " -> " + doc); + assert.ok(!/<meta\b[^>]*refresh/i.test(P.previewDoc("html", `<p>x</p>${meta}`, true, light)), "also in a fragment and with scripts"); + } + }, + svg_documents() { + const doc = P.previewDoc("svg", '<svg width="10" height="10"><circle r="4"/></svg>', false, light, noImage); + assert.ok(doc.includes("<svg width=\"10\"") && doc.includes("display:flex"), "an svg that cannot be an image is inline"); + assert.equal(cspOf(doc), P.csp(false), "inline svg: scripts and handlers are still blocked by the CSP"); + assert.equal(P.previewDoc("svg", "<p>no</p>", false, light), null); + // as an image: with a parser, the svg goes in as a data: URL, with the page's ink as currentColor + const env = { + DOMParser: class { parseFromString(s) { + const style = {textContent: ""}, root = {namespaceURI: "http://www.w3.org/2000/svg", localName: "svg", firstChild: null, + insertBefore(n) { this.style = n; }, hasAttribute: () => false}; + return {documentElement: root, querySelector: () => null, createElementNS: () => style, src: s}; + } }, + XMLSerializer: class { serializeToString(d) { return "<svg>" + (d.documentElement.style ? d.documentElement.style.textContent : "") + "</svg>"; } }, + }; + const img = P.previewDoc("svg", '<svg><script>x</script></svg>', false, {dark: false, ink: "#123456"}, env); + assert.match(img, /<img alt="" style="width:100%;height:100%;object-fit:contain" src="data:image\/svg\+xml;charset=utf-8,/); + assert.ok(decodeURIComponent(/src="data:image\/svg\+xml;charset=utf-8,([^"]*)"/.exec(img)[1]).includes("svg{color:#123456}")); + assert.ok(!img.includes("<svg><script>"), "the svg is not in the document, only its encoded image"); + // with scripts requested for an svg, the markup is inline (an image cannot run anything) + assert.ok(P.previewDoc("svg", "<svg></svg>", true, light, env).includes("<body><svg></svg>")); + }, + the_theme_cannot_inject() { + const evil = {dark: false, ink: "red;}</style><script>parent.x=1</script><style>"}; + assert.ok(!P.previewDoc("html", "<p>x</p>", false, evil).includes("<script>parent.x"), "the ink goes into CSS only after a check"); + assert.match(P.previewDoc("html", "<p>x</p>", false, evil), /color:CanvasText/); + assert.match(P.previewDoc("html", "<p>x</p>", false, {dark: true, ink: "rgb(1, 2, 3)"}), /color:rgb\(1, 2, 3\)/); + }, + frames_are_built_cut_off() { + class Frame { constructor() { this.attrs = {}; this.dataset = {}; } setAttribute(k, v) { this.attrs[k] = v; } } + const env = {document: {createElement: (t) => { assert.equal(t, "iframe"); return new Frame(); }}}; + const f = P.makeFrame("<p>x</p>", {scripts: false, title: "Page preview", lang: "html"}, env); + assert.deepEqual(f.attrs, {sandbox: "", referrerpolicy: "no-referrer", allow: ""}); + assert.equal(f.srcdoc, "<p>x</p>"); assert.equal(f.dataset.opened, "1"); assert.equal(f.dataset.scripts, undefined); + const run = P.makeFrame("<p>x</p>", {scripts: true}, env); + assert.equal(run.attrs.sandbox, "allow-scripts"); assert.equal(run.dataset.scripts, "1"); + const blank = P.makeFrame(null, {}, env); + assert.equal(blank.srcdoc, undefined); assert.equal(blank.dataset.opened, undefined, "an empty frame holds nothing"); + assert.equal(blank.attrs.sandbox, "", "a blank frame is as closed as a static one"); + }, +}; + +(async () => { + const name = process.argv[2]; + const run = name ? [[name, cases[name]]] : Object.entries(cases); + if (name && !cases[name]) throw new Error("unknown test " + name); + for (const [n, fn] of run) { await fn(); console.log("ok " + n); } +})().catch((e) => { console.error(e); process.exitCode = 1; }); diff --git a/serve/test_web_preview.py b/serve/test_web_preview.py new file mode 100644 index 00000000..b61acd80 --- /dev/null +++ b/serve/test_web_preview.py @@ -0,0 +1,79 @@ +"""The chat's svg/html preview: sandboxed, no network, no way to the page (serve/web/preview.js).""" +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import unittest +import urllib.request +from pathlib import Path + +from serve.frontend import ChatTemplate +from serve.server import PAGE_CSP, ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] +WEB = Path(__file__).parent / "web" + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class PreviewInNode(unittest.TestCase): + def test_documents_frames_and_flags(self): + r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_preview.js"))], + capture_output=True, text=True, timeout=60) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +class ThePageSource(unittest.TestCase): + def test_no_way_for_a_frame_to_reach_the_page(self): + scripts = {p.name: p.read_text(encoding="utf-8") for p in WEB.glob("*.js")} + for name, src in scripts.items(): + with self.subTest(name=name): + self.assertNotIn("allow-same-origin", src.replace("no allow-same-origin", ""), "a frame with the page's origin is the page") + self.assertNotRegex(src, r"allow-(top-navigation|popups|forms|modals|downloads)") + # the page never listens for what a frame posts to it + self.assertNotRegex(scripts["app.js"], r"addEventListener\(\s*[\"']message[\"']") + self.assertNotRegex(scripts["app.js"], r"\bonmessage\b") + # every iframe starts closed, and is only ever made by preview.js + for tag in re.findall(r"<iframe\b[^>]*>", scripts["app.js"]): + self.assertIn('sandbox=""', tag) + self.assertNotIn("createElement(\"iframe\")", scripts["app.js"]) + self.assertIn("srcdoc", scripts["preview.js"]) + self.assertNotRegex(scripts["preview.js"], r"\.src\s*=") + + +class TheHeader(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def test_the_page_forbids_a_frame_to_load_an_address(self): + with urllib.request.urlopen(self.base + "/", timeout=10) as r: + self.assertEqual(r.headers.get("Content-Security-Policy"), PAGE_CSP) + self.assertEqual(PAGE_CSP, "frame-src 'none'", + "only this directive: a srcdoc frame inherits the page's policy, and the opt-in script preview needs its inline script") + + def test_other_files_do_not_carry_it(self): + with urllib.request.urlopen(self.base + "/web/app.js", timeout=10) as r: + self.assertIsNone(r.headers.get("Content-Security-Policy")) + + +@unittest.skipUnless(os.environ.get("WEBTEST_MODULES") and shutil.which("node"), + "set WEBTEST_MODULES (a folder with node_modules/puppeteer-core) to run the browser tests") +class InABrowser(unittest.TestCase): + def test_sandbox_in_chrome(self): + r = subprocess.run([shutil.which("node"), str(ROOT / "tools" / "webtest" / "browser_test.mjs"), "preview"], + capture_output=True, text=True, timeout=300) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css index e899121b..fb17d537 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -228,3 +228,16 @@ main { flex: 1; min-height: 0; display: flex; } .chat-math--display > * { margin: 0 !important; } .chat-math[data-math-error] { white-space: pre-wrap; } .chat-math .katex { font-size: 1.08em; } + +/* svg/html preview (serve/web/preview.js): the frame is sandboxed and carries the page's colours, so it is transparent on the + theme's surface; the code and the preview swap places inside the same box. */ +.st-code__btns { display: flex; gap: 4px; } +.st-code .st-btn--icon[aria-pressed="true"] { background: rgba(255, 255, 255, .12); color: #fff; } +.st-code__preview { display: none; } +.st-code[data-preview="true"] > pre { display: none; } +.st-code[data-preview="true"] .st-code__preview { display: block; height: min(340px, 60vh); background: var(--st-surface-2); } +.st-code [data-preview-scripts] { display: none; } +.st-code[data-preview="true"] [data-preview-scripts] { display: inline-flex; } +.st-code .st-btn--icon[data-preview-scripts][aria-pressed="true"] { background: var(--st-warn-tint); color: var(--st-warn-text); } +.st-code--run .st-code__preview { outline: 2px solid var(--st-warn-text); outline-offset: -2px; } +.st-code__preview iframe { display: block; width: 100%; height: 100%; border: 0; background: transparent; } diff --git a/serve/web/app.js b/serve/web/app.js index ef81c9bb..310c0b90 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -60,6 +60,7 @@ function setTheme(t, save) { if (save) try { localStorage.setItem("strata.theme", t); } catch (e) { /* ignore */ } $("theme-icon").setAttribute("href", `${SPRITE}#i-${t === "dark" ? "sun" : "moon"}`); $("dark-toggle").setAttribute("aria-checked", String(t === "dark")); + refreshPreviews(); // the preview frames carry the page's colours } const flipTheme = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark", true); $("theme-btn").onclick = flipTheme; @@ -512,10 +513,36 @@ function inline(s) { .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'); return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code class="inline">${esc(codes[+i])}</code>`); } -function codeBlock(lang, code) { - return `<div class="st-code"><div class="st-code__head"><span>${esc(lang || "code")}</span>` + - `<button class="st-btn st-btn--icon" data-code-copy aria-label="Copy code">${icon("copy")}</button></div>` + - `<pre><code>${esc(code)}</code></pre></div>`; +// An ```svg or ```html block that is complete gets a Preview button (serve/web/preview.js): the block's own code in a sandboxed +// frame, built when it is first opened and again when the theme changes. The state lives on the box (data-preview), so it +// resets if the answer is rebuilt. A page (html) can also be run WITH scripts, after a warning, one block at a time. +function pageTheme() { + const root = document.documentElement; + return {dark: root.dataset.theme === "dark", ink: getComputedStyle(root).getPropertyValue("--st-ink").trim()}; +} +function fillPreview(fr, scripts, blank) { + const box = fr.closest(".st-code"); + const doc = blank ? null : StrataPreview.previewDoc(fr.dataset.lang, box.querySelector("pre").textContent, scripts, pageTheme(), window); + const nf = StrataPreview.makeFrame(doc, {scripts, title: fr.title, lang: fr.dataset.lang}); + fr.replaceWith(nf); + box.classList.toggle("st-code--run", !!(doc && scripts)); + const rb = box.querySelector("[data-preview-scripts]"); + if (rb) { + rb.setAttribute("aria-pressed", String(!!(doc && scripts))); + rb.setAttribute("aria-label", doc && scripts ? tr("preview.stopScripts", "Stop scripts") : tr("preview.runScripts", "Run scripts")); + } +} +function refreshPreviews() { for (const fr of document.querySelectorAll("iframe[data-opened]")) fillPreview(fr, fr.dataset.scripts === "1"); } +function codeBlock(lang, code, complete) { + const ok = complete && StrataPreview.canPreview(lang || "", code); + const kind = ok ? StrataPreview.kindOf(lang) : null; + const label = kind === "svg" ? tr("preview.showSvg", "Preview the picture") : tr("preview.showPage", "Preview the page"); + const head = `<div class="st-code__head"><span>${esc(lang || tr("code.label", "code"))}</span><span class="st-code__btns">` + + (kind === "page" ? `<button class="st-btn st-btn--icon" data-preview-scripts aria-label="${esc(tr("preview.runScripts", "Run scripts"))}" aria-pressed="false" title="${esc(tr("preview.runScripts", "Run scripts"))}">${icon("warning")}</button>` : "") + + (ok ? `<button class="st-btn st-btn--icon" data-preview-toggle data-preview-label="${esc(label)}" aria-label="${esc(label)}" title="${esc(label)}" aria-pressed="false">${icon("image")}</button>` : "") + + `<button class="st-btn st-btn--icon" data-code-copy aria-label="${esc(tr("code.copy", "Copy code"))}">${icon("copy")}</button></span></div>`; + const prev = ok ? `<div class="st-code__preview"><iframe sandbox="" title="${esc(kind === "svg" ? tr("preview.titleSvg", "Picture preview") : tr("preview.titlePage", "Page preview"))}" data-lang="${esc(lang)}"></iframe></div>` : ""; + return `<div class="st-code">${head}<pre><code>${esc(code)}</code></pre>${prev}</div>`; } function blocks(text) { const out = [], lines = text.split("\n"); @@ -561,8 +588,8 @@ function markdown(text) { html += blocks(rest.slice(0, m.index)); rest = rest.slice(m.index + m[0].length); const end = rest.match(/(^|\n)```[ \t]*(\n|$)/); - if (!end) { html += codeBlock(m[2].trim(), rest); break; } // still streaming - html += codeBlock(m[2].trim(), rest.slice(0, end.index)); + if (!end) { html += codeBlock(m[2].trim(), rest, false); break; } // still streaming: no preview of a half-written block + html += codeBlock(m[2].trim(), rest.slice(0, end.index), true); rest = rest.slice(end.index + end[0].length); } return html; @@ -727,6 +754,27 @@ function scrollDown(force) { const s = $("chat-scroll"); if (force || nearBottom $("chat").addEventListener("click", (e) => { const cc = e.target.closest("[data-code-copy]"); if (cc) { copyText(cc.closest(".st-code").querySelector("pre").textContent, cc); return; } + // an svg/html block: flip between its code and its sandboxed preview. Closing the preview also turns scripts off. + const pv = e.target.closest("[data-preview-toggle]"); + if (pv) { + const box = pv.closest(".st-code"); + const on = box.dataset.preview === "true"; + if (on) delete box.dataset.preview; else box.dataset.preview = "true"; + pv.setAttribute("aria-pressed", String(!on)); + pv.setAttribute("aria-label", on ? pv.dataset.previewLabel : tr("preview.showCode", "Show the code")); + const fr = box.querySelector("iframe"); + if (on) fillPreview(fr, false, true); + else if (!fr.dataset.opened) fillPreview(fr, false); + return; + } + const rs = e.target.closest("[data-preview-scripts]"); + if (rs) { + const fr = rs.closest(".st-code").querySelector("iframe"); + const run = fr.dataset.scripts !== "1"; + if (run && !confirm(tr("preview.confirm", "Run this code with scripts?\n\nIt runs in your browser, cut off from this chat and from the network, but it can still freeze the tab, and it is code the model wrote.\n\nOnly this block, and only until you close the preview."))) return; + fillPreview(fr, run); + return; + } const mc = e.target.closest("[data-msg-copy]"); if (mc) { const i = +mc.closest(".st-msg").dataset.i; copyText(messages[i].text, mc); return; } // a tool block: its open state lives in the message (the answer is rebuilt while it streams), so the click sets it diff --git a/serve/web/index.html b/serve/web/index.html index f08271ba..704417c7 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -271,6 +271,7 @@ <div class="scrim" id="scrim" hidden></div> <div class="st-toasts" id="toasts" aria-live="polite"></div> <script src="web/i18n.js"></script> +<script src="web/preview.js"></script> <script src="web/math.js"></script> <script src="web/math-adapter.js"></script> <script src="web/app.js"></script> diff --git a/serve/web/preview.js b/serve/web/preview.js new file mode 100644 index 00000000..b6d26fb9 --- /dev/null +++ b/serve/web/preview.js @@ -0,0 +1,81 @@ +// serve/web/preview.js - the preview of an ```svg or ```html block in an answer (PR #1628 by thoives). +// +// A block is shown in an <iframe srcdoc> that is cut off from the page: +// - sandbox="" : an opaque origin, so no access to the page's DOM, storage, cookies or the server; no scripts, no forms, +// no popups, no navigation of the page, no downloads; +// - a CSP in the frame's own document: default-src 'none' (no network, no fonts, no frames, no media), styles inline and +// pictures as data: only, no <base>, no form target; +// - the page's own header CSP frame-src 'none' (serve/server.py) stops the frame from navigating away to a web page +// (a link, or <meta refresh>), which no sandbox flag can. +// An svg is shown as an <img> with a data: URL where it parses as XML: an image runs no scripts and loads nothing, and it +// animates in every browser. The user can run ONE html block with scripts, after a warning, never remembered: the frame then +// has sandbox="allow-scripts" (still an opaque origin, still no network), and the CSP allows its inline script. +// +// This file builds strings and frames only; app.js decides when. Nothing in it touches the page's own DOM. +"use strict"; +(function (root) { + // no allow-same-origin: that would give the frame the page's origin and with it the page itself + const SANDBOX = {static: "", scripts: "allow-scripts"}; + const csp = (scripts) => "default-src 'none'; " + (scripts ? "script-src 'unsafe-inline'; " : "") + + "style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'"; + const metaCsp = (scripts) => `<meta http-equiv="Content-Security-Policy" content="${csp(scripts)}">`; + const SVG_NS = "http://www.w3.org/2000/svg"; + + // theme = {dark: bool, ink: "#rrggbb"}: the frame carries the page's colours, so it is transparent on the page's surface + const safeInk = (ink) => (/^[#\w(),.\s%-]{1,40}$/.test(ink || "") ? ink : "CanvasText"); + const themeCss = (theme) => `html{color-scheme:${theme && theme.dark ? "dark" : "light"};color:${safeInk(theme && theme.ink)}}`; + const frameHead = (css, scripts, theme) => `<!doctype html><html><head>${metaCsp(scripts)}<style>${themeCss(theme)}html,body{background:transparent;margin:0;height:100%}${css}</style></head><body>`; + + // a plain svg as an <img> with a data: URL, or null when it is not well-formed XML (then the inline svg is used) + function svgImage(s, theme, env = root) { + try { + const doc = new env.DOMParser().parseFromString(/^<svg\b[^>]*\sxmlns\s*=/i.test(s) ? s : s.replace(/^<svg\b/i, `<svg xmlns="${SVG_NS}"`), "image/svg+xml"); + const r = doc.documentElement; + if (doc.querySelector("parsererror") || r.namespaceURI !== SVG_NS || r.localName !== "svg") return null; + const st = doc.createElementNS(SVG_NS, "style"); // an image has no page around it: give currentColor the page's ink + st.textContent = `svg{color:${safeInk(theme && theme.ink)}}`; + r.insertBefore(st, r.firstChild); + const fill = !r.hasAttribute("width") && !r.hasAttribute("height"); + return `<img alt="" ${fill ? 'style="width:100%;height:100%;object-fit:contain" ' : ""}src="data:image/svg+xml;charset=utf-8,${encodeURIComponent(new env.XMLSerializer().serializeToString(doc))}">`; + } catch (e) { return null; } + } + + // the document for a block, or null when the block is not a previewable svg or html (lang is the fence's language) + function previewDoc(lang, code, scripts, theme, env) { + let s = String(code).trim(); + if (/^svg\b/i.test(lang) && /^<svg[\s>]/i.test(s)) { + const img = scripts ? null : svgImage(s, theme, env); + return frameHead("body{display:flex;align-items:center;justify-content:center}" + (img ? "img" : "svg") + "{max-width:100%;max-height:100%}", scripts, theme) + + (img || s) + "</body></html>"; + } + if (/^html?$/i.test(lang) && /^<[/a-z!]/i.test(s)) { + s = s.replace(/<meta\b[^>]*\bhttp-equiv\s*=\s*["']?\s*refresh\b[^>]*>/gi, ""); // a page that redirects itself would leave the sandbox's document + // a complete document: our CSP and theme come first, then the page without its doctype (its own html and head tags merge + // into ours, and its own CSS still wins); nothing of the page can run before the CSP is in force + if (/^<!doctype\s+html/i.test(s)) return `<!doctype html><html><head>${metaCsp(scripts)}<style>${themeCss(theme)}</style></head>` + s.replace(/^<!doctype[^>]*>/i, ""); + return frameHead("", scripts, theme) + s + "</body></html>"; // a fragment: wrap in a minimal document + } + return null; + } + const kindOf = (lang) => (/^svg\b/i.test(lang) ? "svg" : "page"); + // cheap: can this block be previewed at all (the same test as previewDoc, without building anything) + const canPreview = (lang, code) => { + const s = String(code).trim(); + return (/^svg\b/i.test(lang) && /^<svg[\s>]/i.test(s)) || (/^html?$/i.test(lang) && /^<[/a-z!]/i.test(s)); + }; + + // a new frame holding the document (the sandbox attribute only counts when a frame is created, so a frame is never reused) + function makeFrame(doc, {scripts = false, title = "", lang = ""} = {}, env = root) { + const f = env.document.createElement("iframe"); + f.setAttribute("sandbox", scripts ? SANDBOX.scripts : SANDBOX.static); + f.setAttribute("referrerpolicy", "no-referrer"); + f.setAttribute("allow", ""); + f.title = title; f.dataset.lang = lang; + if (doc) { f.dataset.opened = "1"; if (scripts) f.dataset.scripts = "1"; f.srcdoc = doc; } + return f; + } + + const api = {SANDBOX, csp, metaCsp, previewDoc, svgImage, kindOf, canPreview, makeFrame, themeCss}; + root.StrataPreview = api; + if (typeof module !== "undefined" && module.exports) module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/tools/webtest/browser_test.mjs b/tools/webtest/browser_test.mjs new file mode 100644 index 00000000..8fe01ec2 --- /dev/null +++ b/tools/webtest/browser_test.mjs @@ -0,0 +1,185 @@ +// Browser tests of the served web page (serve/web) in headless Chrome or Edge, against the mock server in mock.mjs. +// No model, no GPU. Optional: the normal test run (serve/test_web_*.py, node serve/test_web_*.js) does not need a browser. +// +// WEBTEST_MODULES=<folder with node_modules/puppeteer-core> [CHROME_BIN=<chrome>] node tools/webtest/browser_test.mjs [name] +import assert from "node:assert/strict"; +import { startMock } from "./mock.mjs"; +import { launch, openPage, say, idle, sleep, runner } from "./lib.mjs"; + +const { test, run } = runner("web page browser tests"); + +const turn = (role, text, extra = {}) => ({ role, text, time: 1, ...extra }); +const fence = (lang, code) => "```" + lang + "\n" + code + "\n```\n"; + +// ------------------------------------------------------------------------------------------------ preview (#1628) +const hostilePage = (base) => `<!doctype html><html><head><meta http-equiv="refresh" content="0;url=${base}/exfil-refresh"></head><body> +<pre id="out">static</pre><a id="l" href="${base}/exfil-link">link</a> +<form id="f" action="${base}/exfil-form" method="post"><button id="s">go</button></form> +<script> +const out = []; +const log = (k, v) => { out.push(k + ": " + v); document.getElementById("out").textContent = out.join("\\n"); }; +try { log("parent.document", typeof parent.document.title); } catch (e) { log("parent.document", "blocked " + e.name); } +try { log("top.document", typeof top.document.title); } catch (e) { log("top.document", "blocked " + e.name); } +try { log("localStorage", localStorage.length); } catch (e) { log("localStorage", "blocked " + e.name); } +try { log("cookie", document.cookie.length); } catch (e) { log("cookie", "blocked " + e.name); } +try { top.location = "${base}/exfil-top"; log("top.location=", "no error"); } catch (e) { log("top.location=", "blocked " + e.name); } +try { const w = window.open("${base}/exfil-open"); log("window.open", w ? "opened" : "blocked"); } catch (e) { log("window.open", "blocked"); } +try { parent.postMessage("hello", "*"); log("postMessage", "sent"); } catch (e) { log("postMessage", "blocked"); } +fetch("${base}/exfil-fetch").then(() => log("fetch", "went out"), () => log("fetch", "blocked")); +const x = new XMLHttpRequest(); x.open("GET", "${base}/exfil-xhr"); x.onerror = () => log("xhr", "blocked"); x.onload = () => log("xhr", "went out"); try { x.send(); } catch (e) { log("xhr", "blocked"); } +new Image().src = "${base}/exfil-img"; +const s = document.createElement("script"); s.src = "${base}/exfil-script.js"; document.head.appendChild(s); +try { new WebSocket("ws://127.0.0.1:9/exfil-ws"); } catch (e) { log("websocket", "blocked"); } +log("ran", "yes"); +</script></body></html>`; + +async function hostileChat(mock) { + return { chat: [turn("user", "page please"), turn("assistant", "Here:\n\n" + fence("html", hostilePage(mock.url)))] }; +} +const exfil = (mock) => mock.state.calls.filter((c) => c.includes("exfil")); + +test("preview: an svg block previews as a picture, with no script and no network", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: { chat: [turn("user", "draw"), turn("assistant", "x\n\n" + fence("svg", + '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80"><script>parent.__pwned=1</script><image href="' + mock.url + '/exfil-svg-img"/><circle cx="40" cy="40" r="30" fill="red" onload="parent.__pwned=2"/></svg>'))] } }); + await page.click("[data-preview-toggle]"); + const frame = await page.$("iframe"); + assert.equal(await frame.evaluate((f) => f.getAttribute("sandbox")), "", "the sandbox has no flags at all"); + assert.equal(await frame.evaluate((f) => f.getAttribute("referrerpolicy")), "no-referrer"); + const doc = await frame.evaluate((f) => f.srcdoc); + assert.match(doc, /Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'"/); + assert.match(doc, /<img [^>]*src="data:image\/svg\+xml/, "a well-formed svg is shown as an image: images run no script"); + await sleep(400); + assert.equal(await page.evaluate(() => window.__pwned), undefined); + assert.deepEqual(exfil(mock), []); + await page.close(); +}); + +test("preview: a page does not run scripts, load addresses or leave the sandbox until asked", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: await hostileChat(mock) }); + const title = await page.title(), url = page.url(); + await page.click("[data-preview-toggle]"); + await sleep(600); + const frame = await (await page.$("iframe")).contentFrame(); + assert.equal(await frame.evaluate(() => document.getElementById("out").textContent), "static", "the script did not run"); + assert.equal(await (await page.$("iframe")).evaluate((f) => f.getAttribute("sandbox")), ""); + assert.equal(page.lastDialog, undefined, "no dialog without the run button"); + await frame.click("#l").catch(() => {}); // a link in the page + await frame.click("#s").catch(() => {}); // a form in the page + await sleep(500); + assert.deepEqual(exfil(mock), [], "no request left the preview"); + assert.equal(page.url(), url); assert.equal(await page.title(), title); + await page.close(); +}); + +test("preview: run with scripts keeps the page and the network out of reach", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: await hostileChat(mock) }); + const url = page.url(), title = await page.title(); + const messages = []; + await page.evaluate(() => { window.addEventListener("message", (e) => { window.__message = e.data; }); }); + await page.click("[data-preview-toggle]"); + await page.click("[data-preview-scripts]"); + assert.match(page.lastDialog, /Run this code with scripts/, "a warning comes first"); + const iframe = await page.$("iframe"); + assert.equal(await iframe.evaluate((f) => f.getAttribute("sandbox")), "allow-scripts", "scripts, and nothing else"); + await sleep(1200); + const frame = await iframe.contentFrame(); + const out = await frame.evaluate(() => document.getElementById("out").textContent); + for (const line of ["ran: yes", "parent.document: blocked SecurityError", "top.document: blocked SecurityError", + "localStorage: blocked SecurityError", "cookie: blocked SecurityError", "fetch: blocked", "xhr: blocked", "window.open: blocked"]) { + assert.ok(out.includes(line), `${line}\n--- got:\n${out}`); + } + await frame.click("#l").catch(() => {}); + await frame.click("#s").catch(() => {}); + await sleep(800); + assert.deepEqual(exfil(mock), [], "no address was reached from the preview: " + exfil(mock)); + assert.equal(page.url(), url, "the page did not navigate"); + assert.equal(await page.title(), title); + assert.equal(await page.evaluate(() => document.querySelectorAll("iframe").length), 1, "no frame was added to the page"); + assert.equal(await page.evaluate(() => typeof localStorage.getItem("strata.chat")), "string", "the page's own store is untouched"); + // a message to the page is the only thing that can cross; the page has no listener of its own, so nothing happens with it + assert.ok(!(await page.evaluate(() => /addEventListener\(["']message["']/.test(document.scripts[document.scripts.length - 1].textContent || "")))); + // closing the preview ends the script + await page.click("[data-preview-toggle]"); + assert.equal(await page.$eval(".st-code", (b) => b.classList.contains("st-code--run")), false); + assert.equal(await page.$eval("iframe", (f) => f.getAttribute("sandbox")), ""); + assert.equal(await page.$eval("iframe", (f) => f.getAttribute("srcdoc")), null); + await page.close(); +}); + +test("preview: the page's CSP header is what keeps a link inside the preview from loading a web page", async ({ browser }) => { + const link = (m) => ({ chat: [turn("user", "x"), turn("assistant", fence("html", `<a id="l" href="${m.url}/exfil-link">go</a>`))] }); + for (const csp of [false, true]) { + const m = await startMock({ csp }); + const page = await openPage(browser, m, { seed: link(m) }); + await page.click("[data-preview-toggle]"); + await sleep(300); + await (await (await page.$("iframe")).contentFrame()).click("#l"); + await sleep(700); + const went = exfil(m).length; + assert.equal(went, csp ? 0 : 1, csp ? "with the header the link goes nowhere" : "without it the sandbox alone does let a link load a page (why the header exists)"); + await page.close(); + await m.stop(); + } +}); + +test("preview: declining the warning runs nothing", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: await hostileChat(mock), dialogs: "dismiss" }); + await page.click("[data-preview-toggle]"); + await page.click("[data-preview-scripts]"); + assert.ok(page.lastDialog); + assert.equal(await page.$eval("iframe", (f) => f.getAttribute("sandbox")), ""); + assert.equal(await (await (await page.$("iframe")).contentFrame()).evaluate(() => document.getElementById("out").textContent), "static"); + await page.close(); +}); + +test("preview: not offered for a half-written block, other languages or text that is not markup", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: { chat: [turn("user", "x"), + turn("assistant", fence("python", "<svg></svg>") + fence("html", "just words") + fence("svg", "not an svg") + "```html\n<p>unfinished")] } }); + assert.equal(await page.$$eval("[data-preview-toggle]", (e) => e.length), 0); + await page.close(); +}); + +test("preview: follows the theme and shows the code again", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { dark: false, seed: { chat: [turn("user", "x"), turn("assistant", fence("html", "<p>hello</p>"))] } }); + await page.click("[data-preview-toggle]"); + const doc = () => page.$eval("iframe", (f) => f.srcdoc); + assert.match(await doc(), /color-scheme:light/); + await page.click("#theme-btn"); + assert.match(await doc(), /color-scheme:dark/, "the frame is built again when the theme changes"); + assert.equal(await page.$eval("pre", (p) => getComputedStyle(p).display), "none"); + await page.click("[data-preview-toggle]"); + assert.notEqual(await page.$eval("pre", (p) => getComputedStyle(p).display), "none"); + await page.close(); +}); + +test("preview: from a streamed answer, only once the block is complete", async ({ browser, mock }) => { + const page = await openPage(browser, mock); + await say(page, "#svg draw a circle"); + await idle(page); + assert.equal(await page.$$eval("[data-preview-toggle]", (e) => e.length), 1); + await page.click("[data-preview-toggle]"); + const w = await (await page.$("iframe")).evaluate((f) => f.getBoundingClientRect().width); + assert.ok(w > 100, "the frame has room"); + await page.close(); +}); + +// ------------------------------------------------------------------------------------------------ math (#2972, #2974) +test("math: off by default, drawn when switched on, source kept", async ({ browser, mock }) => { + const page = await openPage(browser, mock); + await say(page, "#math please"); + await idle(page); + assert.equal(await page.$$eval(".katex", (e) => e.length), 0, "off: the model's text as written"); + await page.evaluate(() => { settings.math = true; renderChat(); }); + await page.waitForSelector(".katex"); + assert.equal(await page.$$eval(".katex", (e) => e.length), 3, "the inline, the display and the blocked-command formula"); + const requestText = await page.evaluate(() => JSON.stringify(apiMessages())); + assert.ok(requestText.includes("\\\\pi r^2") && requestText.includes("\\\\frac{n(n+1)}{2}"), "the request keeps the source"); + assert.equal(await page.$$eval("#chat a[href], #chat .chat-math img", (e) => e.length), 0, "no link or picture from a formula"); + assert.deepEqual(exfil(mock), []); + assert.equal(await page.evaluate(() => messages.at(-1).text.includes("$\\pi r^2$")), true); + await page.close(); +}); + +const mock = await startMock(); +const browser = await launch(); +await run(async () => ({ browser, mock, close: async () => { await browser.close(); await mock.stop(); } })); diff --git a/tools/webtest/lib.mjs b/tools/webtest/lib.mjs new file mode 100644 index 00000000..e7cce3cd --- /dev/null +++ b/tools/webtest/lib.mjs @@ -0,0 +1,77 @@ +// Shared bits for the browser tests and the screenshot script of the served web page (serve/web): a headless Chromium, +// a page against the mock server, small helpers. puppeteer-core is not a dependency of the repo: install it anywhere and +// point WEBTEST_MODULES at that folder (the one that holds node_modules); CHROME_BIN is the Chrome or Edge to drive. +import { createRequire } from "node:module"; +import path from "node:path"; +import fs from "node:fs"; + +const req = createRequire(path.join(process.env.WEBTEST_MODULES || process.cwd(), "noop.js")); +export const puppeteer = req("puppeteer-core"); + +const CANDIDATES = [process.env.CHROME_BIN, "C:/Program Files/Google/Chrome/Application/chrome.exe", + "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser", + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].filter(Boolean); +export const chrome = () => { + const found = CANDIDATES.find((p) => fs.existsSync(p)); + if (!found) throw new Error("no Chrome or Edge found; set CHROME_BIN"); + return found; +}; +export const launch = () => puppeteer.launch({ executablePath: chrome(), headless: true, args: ["--no-sandbox", "--disable-gpu"] }); + +// a page with a seeded browser store (localStorage values are JSON, as the page's own store writes them), console errors collected +export async function openPage(browser, mock, { width = 1280, height = 800, seed = {}, query = "", dark = false, hash = "", dialogs = "accept" } = {}) { + const context = await browser.createBrowserContext(); + const page = await context.newPage(); + page.errors = []; + page.on("pageerror", (e) => page.errors.push("pageerror: " + e.message)); + page.on("console", (m) => { if (m.type() === "error") page.errors.push("console: " + m.text()); }); + page.on("dialog", async (d) => { page.lastDialog = d.message(); if (dialogs === "accept") await d.accept(); else await d.dismiss(); }); + await page.setViewport({ width, height }); + await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: dark ? "dark" : "light" }]); + await page.evaluateOnNewDocument((s) => { + if (window !== window.top) return; // not in the preview frames: they have no storage + if (sessionStorage.getItem("seeded")) return; + sessionStorage.setItem("seeded", "1"); + for (const [k, v] of Object.entries(s)) localStorage.setItem("strata." + k, JSON.stringify(v)); + }, seed); + await page.goto(mock.url + "/" + query + hash, { waitUntil: "networkidle0" }); + return page; +} + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +// the page's own `busy` is a top-level let of app.js: reachable by name from page.evaluate +export const idle = (page, timeout = 15000) => page.waitForFunction(() => busy === null, { timeout }); +export async function say(page, text) { + await page.click("#input"); + await page.type("#input", text); + await page.keyboard.press("Enter"); +} +export const assistantText = (page, i = -1) => page.evaluate((n) => { const a = messages.filter((m) => m.role === "assistant"); return a.at(n).text; }, i); +export const shot = async (page, dir, name, opts = {}) => { + fs.mkdirSync(dir, { recursive: true }); + const file = path.join(dir, name + ".png"); + await page.screenshot({ path: file, ...opts }); + return file; +}; + +// tiny test runner: node file.mjs [name-substring] +export function runner(title) { + const tests = []; + const only = process.argv[2]; + return { + test: (name, fn) => tests.push([name, fn]), + async run(setup) { + const ctx = await setup(); + let failed = 0; + for (const [name, fn] of tests) { + if (only && !name.includes(only)) continue; + const t = Date.now(); + try { await fn(ctx); console.log(`ok ${name} (${Date.now() - t} ms)`); } + catch (e) { failed++; console.log(`FAIL ${name}\n ${String(e.stack || e).split("\n").slice(0, 6).join("\n ")}`); } + } + await ctx.close(); + console.log(failed ? `${title}: ${failed} failed` : `${title}: all passed`); + process.exitCode = failed ? 1 : 0; + }, + }; +} diff --git a/tools/webtest/mock.mjs b/tools/webtest/mock.mjs new file mode 100644 index 00000000..6c343c21 --- /dev/null +++ b/tools/webtest/mock.mjs @@ -0,0 +1,129 @@ +// A stand-in for the Strata server for tests of the served web page (serve/web): it serves the page's own files and +// answers the few calls the page makes with scripted text. No model, no GPU, no Python. Used by browser_test.mjs and shots.mjs. +// +// import { startMock } from "./mock.mjs"; +// const mock = await startMock(); // { url, state, stop() } +// +// What the page asks and what it gets: GET /health /metrics /mcp /settings /config, POST /load /unload, +// POST /v1/chat/completions (streamed). The reply depends on a word in the last user message: +// #math inline and display formulas, a price #svg / #html a fenced svg / html block #think reasoning first +// #long a slow answer (about 6 s) to interrupt #hold never ends until the page stops it #tool an MCP tool call, then text +// #error a 500 anything else: "Mock answer N." +import http from "node:http"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +export const WEB = path.resolve(here, "..", "..", "serve", "web"); +const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", + ".svg": "image/svg+xml", ".json": "application/json; charset=utf-8", ".woff2": "font/woff2" }; + +// the one header the real server puts on the page (serve/server.py, PAGE_CSP): read from the source so the two cannot drift +const PAGE_CSP = (/^PAGE_CSP = "(.*)"$/m.exec(fs.readFileSync(path.join(here, "..", "..", "serve", "server.py"), "utf8")) || [])[1] || ""; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const lastUser = (messages) => { + for (let i = messages.length - 1; i >= 0; i--) { + if (messages[i].role !== "user") continue; + const c = messages[i].content; + return typeof c === "string" ? c : (c.find((p) => p.type === "text") || {}).text || ""; + } + return ""; +}; + +const MATH = "The area is $\\pi r^2$ and the sum is\n\n$$\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2}$$\n\nIt costs $5 or $10, and `$x$` is code.\n\n" + + "A bad one: $\\frac{1}{$ and a link-ish \\href{javascript:alert(1)}{click}: $\\href{javascript:alert(1)}{click}$."; +const SVG = "Here is a circle:\n\n```svg\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 100\" width=\"120\" height=\"120\">" + + "<circle cx=\"50\" cy=\"50\" r=\"40\" fill=\"#10b981\"/><text x=\"50\" y=\"56\" text-anchor=\"middle\" fill=\"white\" font-size=\"18\">SVG</text></svg>\n```\n"; +const HTML = "A small page:\n\n```html\n<!doctype html><html><body style=\"font-family:sans-serif\"><h2>Hello</h2>" + + "<p id=\"p\">Static text.</p><script>document.getElementById('p').textContent='Script ran.'</script></body></html>\n```\n"; + +export async function startMock({ port = 0, root = WEB, loaded = true, csp = true } = {}) { + const state = { requests: [], aborted: 0, completed: 0, loaded, calls: [], answers: 0 }; + const server = http.createServer(async (req, res) => { + const url = new URL(req.url, "http://x"); + const p = url.pathname.replace(/\/+$/, ""); + state.calls.push(`${req.method} ${p}`); + const json = (code, body) => { res.writeHead(code, { "Content-Type": "application/json" }); res.end(JSON.stringify(body)); }; + if (req.method === "GET") { + if (p === "") return file(res, path.join(root, "index.html"), undefined, csp && PAGE_CSP ? { "Content-Security-Policy": PAGE_CSP } : {}); + if (p.startsWith("/web/")) return file(res, path.join(root, p.slice(5)), root); + if (p.startsWith("/fonts/")) return file(res, path.join(root, "fonts", p.slice(7)), root); + if (p === "/health") return json(200, { status: "ok", max_context: 32768, model: "Mock-Model", images: true, image_generation: false, loaded: state.loaded, service: "strata" }); + if (p === "/metrics") return json(200, metrics(state)); + if (p === "/mcp") return json(200, { servers: [], tools: 0 }); + if (p === "/settings") return json(200, { shared: false, defaults: null }); + return json(404, { error: { message: "not found" } }); + } + let body = ""; + for await (const part of req) body += part; + if (p === "/unload") { await sleep(150); state.loaded = false; return json(200, { status: "unloaded" }); } + if (p === "/load") { await sleep(300); state.loaded = true; return json(200, { status: "loaded" }); } + if (p === "/settings") return json(200, { shared: false }); + if (p !== "/v1/chat/completions") return json(404, { error: { message: "not found" } }); + const b = JSON.parse(body || "{}"); + state.requests.push(b); + const text = lastUser(b.messages || []); + if (text.includes("#error")) return json(500, { error: { message: "The mock engine failed on purpose." } }); + state.loaded = true; + res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + let closed = false; + res.on("close", () => { if (!res.writableEnded) { closed = true; state.aborted++; } }); + const send = (o) => { if (!closed) res.write("data: " + JSON.stringify(o) + "\n\n"); }; + const say = async (s, ms = 0, step = 6) => { + for (let i = 0; i < s.length && !closed; i += step) { send({ choices: [{ delta: { content: s.slice(i, i + step) } }] }); if (ms) await sleep(ms); } + }; + state.answers++; + if (text.includes("#think")) { + for (const w of ["Let me think ", "about this ", "for a moment."]) { send({ choices: [{ delta: { reasoning_content: w } }] }); await sleep(30); } + await say("Thought through. The answer is 42."); + } else if (text.includes("#math")) await say(MATH, 4); + else if (text.includes("#svg")) await say(SVG, 2); + else if (text.includes("#html")) await say(HTML, 2); + else if (text.includes("#hold")) { await say("Working on it", 20); while (!closed) await sleep(50); return; } + else if (text.includes("#long")) { await say("This is a long answer that goes on for a while so that it can be interrupted. ".repeat(3), 40, 4); } + else if (text.includes("#tool")) { + await say("Let me look that up. ", 5); + const id = "call-1"; + send({ strata_mcp: { event: "call", id, name: "fs__read", server: "fs", tool: "read", arguments: { path: "notes.txt" }, round: 0 } }); + await sleep(900); + send({ strata_mcp: { event: "result", id, text: "The file says hello.", ok: true, chars: 20, ms: 900 } }); + await say("The file says hello.", 5); + } else await say(`Mock answer ${state.answers}.`, 5); + if (!closed) { + send({ choices: [{ delta: {}, finish_reason: "stop" }], usage: { completion_tokens: 12 } }); + res.write("data: [DONE]\n\n"); + res.end(); + state.completed++; + } + }); + await new Promise((r) => server.listen(port, "127.0.0.1", r)); + return { url: `http://127.0.0.1:${server.address().port}`, state, stop: () => new Promise((r) => { server.closeAllConnections?.(); server.close(r); }) }; +} + +function file(res, f, root, extra = {}) { + const resolved = path.resolve(f); + if (root && !resolved.startsWith(path.resolve(root) + path.sep)) { res.writeHead(404); return res.end(); } + fs.readFile(resolved, (err, data) => { + if (err) { res.writeHead(404, { "Content-Type": "application/json" }); return res.end('{"error":{"message":"not found"}}'); } + res.writeHead(200, { "Content-Type": TYPES[path.extname(resolved)] || "application/octet-stream", "Cache-Control": "no-cache", ...extra }); + res.end(data); + }); +} + +function metrics(state) { + const spark = Array.from({ length: 30 }, (_, i) => 20 + 10 * Math.sin(i / 3)); + return { + live: { state: state.loaded ? "idle" : "unloaded", queued: 0 }, + engine: { model: "Mock-Model", version: "0.0", max_context: 32768, expert_slots: 1200, expert_cache_mib: 9000 }, + hardware: { gpu_util: 35, gpu_mem_used: 9e9, gpu_mem_total: 12e9, gpu_temp: 61, gpu_power: 140, cpu: 22, ram_total: 64e9, ram_used: 30e9, disk_read_mb: 5 }, + hardware_static: { gpu_name: "Mock GPU", cpu_name: "Mock CPU", threads: 16, cores: 8, psutil: true }, + history: { tok_s: spark, gpu_util: spark, gpu_mem_used: spark, gpu_temp: spark, gpu_power: spark, cpu: spark, disk_read_mb: spark, gpu_pcie_rx_mb: spark, prefill_tok_s_mean: spark }, + requests: [], totals: null, requests_kept: 0, conversation_cache: null, + }; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const mock = await startMock({ port: Number(process.argv[2] || 0) }); + console.log("mock server on " + mock.url); +} From bcdb92ac6875beb7e0418c1447701ce9440f2f9f Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:59:54 +0100 Subject: [PATCH 135/177] Web page: Load and Unload in the header (#3550) One button in the header of every tab: Load while the model is unloaded, Unload otherwise. It calls POST /load and POST /unload (the server already had both, for its own page only). Unload asks first and never interrupts a turn: the button is off while an answer is being written, an image is made or a request is queued. The pill and the Monitor say Unloaded / Loading / Unloading, a message or an image on an unloaded model shows Loading, and a poll that started before the POST cannot flip the button back (the POST's state is held until a later poll agrees). On a phone the pill's text is the first thing the header row gives up (it measures the row, not a fixed width), so Load/Unload and the theme button stay on the screen from 320 px. Browser tests (tools/webtest/browser_test.mjs): unload with its question, load back, declining, not while answering, a message that loads, the header at 320 to 640 px. Ported by hand from PR #3550 by Sakurai Momoka (sakuumomo); the texts now go through the page's translation catalog. Co-authored-by: Sakurai Momoka <159397306+sakuumomo@users.noreply.github.com> --- serve/test_web_load_unload.py | 68 +++++++++++ serve/web/app.css | 22 +++- serve/web/app.js | 214 +++++++++++++++++++++++++++++++-- serve/web/index.html | 2 + tools/webtest/browser_test.mjs | 73 +++++++++++ 5 files changed, 363 insertions(+), 16 deletions(-) create mode 100644 serve/test_web_load_unload.py diff --git a/serve/test_web_load_unload.py b/serve/test_web_load_unload.py new file mode 100644 index 00000000..f6118e7d --- /dev/null +++ b/serve/test_web_load_unload.py @@ -0,0 +1,68 @@ +"""serve/test_web_load_unload.py - the web page's header carries the Load / Unload control (#3550, by sakuumomo). + +Pins, as text: index.html holds the header button and the Monitor's "Unloaded" badge; app.js wires the button to POST /load +and POST /unload, holds the POST's state until a later poll agrees, answers a 401 with the key copy, and refits the header +row only when its text changed (the per-second poll does not force a layout). The behaviour itself, in a real browser, is in +tools/webtest/browser_test.mjs ("load/unload: ..."). + + python -m unittest serve.test_web_load_unload -v +""" +from __future__ import annotations + +import shutil +import subprocess +import unittest +from pathlib import Path + +WEB = Path(__file__).resolve().parent / "web" + + +class WebLoadUnloadMarkup(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.html = (WEB / "index.html").read_text(encoding="utf-8") + cls.js = (WEB / "app.js").read_text(encoding="utf-8") + cls.css = (WEB / "app.css").read_text(encoding="utf-8") + + def test_header_button_and_monitor_badge(self): + self.assertIn('id="unload-btn"', self.html) + self.assertIn('data-s="unloaded"', self.html) + self.assertLess(self.html.index('id="unload-btn"'), self.html.index('id="theme-btn"')) # in the header row + + def test_button_posts_load_and_unload(self): + self.assertIn('$("unload-btn").onclick', self.js) + self.assertIn('fetch(loadingNow ? "load" : "unload", {method: "POST", headers: headers(true), body: "{}"})', self.js) + + def test_unload_asks_first_and_never_interrupts_a_turn(self): + self.assertIn("confirm(tr(\"model.confirmUnload\"", self.js) + self.assertIn("turnBlocksUnload(live)", self.js) + self.assertIn("function turnBlocksUnload(live)", self.js) + + def test_401_gets_the_key_copy(self): + # The control POST answers a 401 the way poll and send do, not with a bare HTTP line. + self.assertIn('r.status === 401 ? tr("toast.keyAbout2"', self.js) + + def test_poll_hold_until_a_poll_agrees(self): + self.assertIn("metricsHold = {state, after: metricsEpoch};", self.js) + self.assertIn("function metricsAgree(live, state)", self.js) + + def test_header_refits_only_on_changed_text(self): + # The per-second poll re-sets the pill; the fit runs when its text actually changed. + self.assertIn("if (text !== lastPillText) { lastPillText = text; fitHeader(); }", self.js) + + def test_the_header_row_keeps_the_buttons_on_a_phone(self): + self.assertIn("#unload-btn", self.css) + self.assertIn(".st-header--clip #pill-text", self.css) + for width in ("955px", "457px", "382px"): + self.assertIn(f"@media (max-width: {width})", self.css) + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class WebLoadUnloadParses(unittest.TestCase): + def test_app_js_parses(self): + r = subprocess.run(["node", "--check", str(WEB / "app.js")], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css index fb17d537..9c40e420 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -11,6 +11,8 @@ main { flex: 1; min-height: 0; display: flex; } .card-title { font-weight: var(--st-fw-bold); font-size: var(--st-fs-base); color: var(--st-ink); } .st-header { position: relative; z-index: 2; flex: none; } .st-header .st-tabs { margin-left: var(--st-s-4); } +#unload-btn { flex: none; height: 32px; padding: 0 12px; min-width: 7.75rem; } +.st-header--clip #pill-text { display: none; } #drawer-close .st-icon { transform: rotate(-90deg); } /* ---------------------------------------------------------------- chat */ @@ -181,12 +183,26 @@ main { flex: 1; min-height: 0; display: flex; } @media (max-width: 900px) { .monitor-row { grid-template-columns: minmax(0, 1fr); } } -@media (max-width: 640px) { +/* The tab strip keeps a width it can scroll. The pill's text hides only when the header row overflows (fitHeader in app.js). + Load / Unload (PR #3550) sits in the row: 9rem of tabs plus its 7.75rem fit from 458px; below that the tighter floors keep + it and the theme button in the viewport. */ +@media (max-width: 955px) { .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } - .st-header .st-tabs { margin-left: 0; } + .st-header__brand, #theme-btn, #pill, #unload-btn { flex: none; } + .st-header .st-tabs { margin-left: 0; flex: 1 1 auto; min-width: 9rem; overflow-x: auto; } .st-tab { padding: 0 10px; } .st-tab .st-icon { display: none; } - #pill-text { display: none; } +} +@media (max-width: 457px) { + #unload-btn { min-width: 0; padding: 0 8px; } + .st-header .st-tabs { min-width: 5.5rem; } +} +/* the name plus "Unloading…" still overflows at 374px in Firefox 158 */ +@media (max-width: 382px) { + .st-header__brand { display: none; } + .st-header .st-tabs { min-width: 4.75rem; } +} +@media (max-width: 640px) { .chat { padding: var(--st-s-5) var(--st-s-4); } .composer-wrap { padding: 0 var(--st-s-3) var(--st-s-3); } .monitor, .about { padding: var(--st-s-4); } diff --git a/serve/web/app.js b/serve/web/app.js index 310c0b90..4b0477fd 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -164,22 +164,38 @@ function setMetric(key, value, unit, sub) { } let lastMetrics = null, metricsFailures = 0, keyWarned = false, mcpTick = 0; +let metricsEpoch = 0; +// After Load or Unload returns, a poll that started earlier can still say the opposite. Hold the POST's state until a later +// poll agrees, or until the first poll that started after the POST arrives. (PR #3550 by sakuumomo) +let metricsHold = null; let reqShowAll = false; // the Monitor's request table: the last 12, or every one the server keeps (issue #35) +function metricsAgree(live, state) { + const s = (live && live.state) || ""; + if (state === "unloaded") return s === "unloaded"; + return s !== "" && s !== "unloaded"; +} async function poll() { + const epoch = ++metricsEpoch; try { const r = await fetch(reqShowAll ? "metrics?requests=all" : "metrics", {headers: headers()}); if (r.status === 401) { - setPill("error", "API key needed"); - if (!keyWarned) { keyWarned = true; toast("warn", "API key needed", "This server needs a key: add it under About > Settings.", 6000); } + setPill("error", tr("pill.keyNeeded", "API key needed")); + if (!keyWarned) { keyWarned = true; toast("warn", tr("pill.keyNeeded", "API key needed"), tr("toast.keyAbout", "This server needs a key: add it under About > Settings."), 6000); } } else if (r.ok) { - lastMetrics = await r.json(); + const m = await r.json(); + if (metricsHold && epoch <= metricsHold.after && !metricsAgree(m.live, metricsHold.state)) { + setTimeout(poll, 1000); + return; + } + if (metricsHold && (metricsAgree(m.live, metricsHold.state) || epoch > metricsHold.after)) metricsHold = null; + lastMetrics = m; metricsFailures = 0; render(lastMetrics); } else { throw new Error(`HTTP ${r.status}`); } } catch (e) { - if (++metricsFailures === 3) setPill("error", "Server not reachable"); + if (++metricsFailures === 3) setPill("error", tr("pill.unreachable", "Server not reachable")); } if (tab === "monitor" && ++mcpTick % 10 === 0) loadMcp(); // server states change rarely: every 10 s setTimeout(poll, 1000); @@ -188,21 +204,164 @@ async function poll() { function setPill(state, text) { $("pill").dataset.state = state === "error" ? "queued" : state; $("pill-text").textContent = text; + // a poll re-sets the sentence every second; refit only when its text changed + if (text !== lastPillText) { lastPillText = text; fitHeader(); } } +let lastPillText = null; +// The pill's sentence is the first thing the header row can spare when it runs out of room. +function fitHeader() { + const header = document.querySelector(".st-header"); + if (!header) return; + header.classList.remove("st-header--clip"); + if (header.scrollWidth > header.clientWidth) header.classList.add("st-header--clip"); +} +window.addEventListener("resize", fitHeader); + +// ------------------------------------------------------------------ Load / Unload (POST /load, /unload: the header button) +// Metrics stay "unloaded" until the engine is READY, so a turn or an image job on this page has to paint Loading itself. +// modelOp covers the button's own POST, which returns before the next poll can agree. +let modelOp = null; +let imageBusy = false; +function pageBusy() { return busy != null || imageBusy; } +// "generating an image" is the job a refresh can see. imageBusy is this page's POST before that phase is published. A chat +// phase already on the metrics wins, because Stop still stops that reply. +function imageLive(live) { + if (live && live.phase === "generating an image") return true; + const state = live && live.state; + if (state === "reading" || state === "generating") return false; + return imageBusy; +} +function paintLive() { if (lastMetrics) render(lastMetrics); } +function turnBlocksUnload(live) { + const state = (live && live.state) || ""; + return pageBusy() || state === "reading" || state === "generating" || (live && live.queued > 0); +} +function setModelButton(text, title, disabled) { + const btn = $("unload-btn"); + btn.textContent = text; btn.title = title; btn.disabled = disabled; + fitHeader(); +} +function modelButton(live) { + if (modelOp === "load") return setModelButton(tr("model.loading", "Loading…"), tr("model.loadingTitle", "The model is loading"), true); + if (modelOp === "unload") return setModelButton(tr("model.unloading", "Unloading…"), tr("model.unloadingTitle", "The model is unloading"), true); + const state = (live && live.state) || ""; + const metricsBusy = state === "reading" || state === "generating" || (live && live.queued > 0); + const imageNow = imageLive(live); + const unload = tr("model.unload", "Unload"); + if (state === "unloaded") { + if (imageNow) return setModelButton(tr("model.loading", "Loading…"), tr("model.imageLoading", "An image is already loading the model"), true); + if (pageBusy()) return setModelButton(tr("model.loading", "Loading…"), tr("model.replyLoading", "A reply is already loading the model"), true); + return setModelButton(tr("model.load", "Load"), tr("model.loadTitle", "Load the model now. A message also loads it."), false); + } + if (imageNow) return setModelButton(unload, tr("model.imageBusy", "An image is generating. It finishes on its own."), true); + if (!state) return setModelButton("…", tr("model.waiting", "Waiting for the server"), true); + if (metricsBusy || pageBusy()) return setModelButton(unload, tr("model.stopFirst", "Stop the reply, then unload"), true); + return setModelButton(unload, tr("model.unloadTitle", "Unload the model and free the GPU"), false); +} +$("unload-btn").onclick = async () => { + if (modelOp) return; + const live = (lastMetrics && lastMetrics.live) || {}; + const loading = live.state === "unloaded"; + const busyCopy = (sample, stillLoading) => stillLoading + ? (imageLive(sample) ? tr("model.imageLoadingDot", "An image is already loading the model.") : tr("model.replyLoadingDot", "A reply is already loading the model.")) + : (imageLive(sample) ? tr("model.imageBusy", "An image is generating. It finishes on its own.") : tr("model.stopFirstDot", "Stop the reply, then unload.")); + if (loading ? pageBusy() : turnBlocksUnload(live)) { + toast("warn", tr("model.busy", "Model is busy"), busyCopy(live, loading)); + return; + } + if (!loading && !confirm(tr("model.confirmUnload", "Unload the model and free the GPU? Load, or the next message, brings it back."))) return; + // confirm() blocks the poll. Yield so a sample that arrived during the dialog is applied. A confirmed Unload stays an unload. + if (!loading) { + modelOp = "unload"; + modelButton(live); + await new Promise((resolve) => setTimeout(resolve, 0)); + } + const now = (lastMetrics && lastMetrics.live) || {}; + const loadingNow = loading; + if (loadingNow ? pageBusy() : turnBlocksUnload(now)) { + modelOp = null; + if (lastMetrics) render(lastMetrics); else modelButton(now); + toast("warn", tr("model.busy", "Model is busy"), busyCopy(now, loadingNow)); + return; + } + modelOp = loadingNow ? "load" : "unload"; + modelButton(now); + if (loadingNow) toast("info", tr("model.loadingToast", "Loading the model"), tr("model.fewMinutes", "This can take a few minutes.")); + const remember = (state) => { + if (!lastMetrics) lastMetrics = {}; + lastMetrics.live = Object.assign({}, lastMetrics.live, {state, queued: 0}); + metricsHold = {state, after: metricsEpoch}; + }; + try { + const r = await fetch(loadingNow ? "load" : "unload", {method: "POST", headers: headers(true), body: "{}"}); + let body = {}; + try { body = await r.json(); } catch (e) { /* the connection dropped */ } + const status = body.status || ""; + const msg = (body.error && body.error.message) || + (r.status === 401 ? tr("toast.keyAbout2", "API key needed: add it under About > Settings.") : tr("toast.httpAnswer", "The server answered HTTP {code}.", {code: r.status})); + const failTitle = loadingNow ? tr("model.loadFailed", "Load failed") : tr("model.unloadFailed", "Unload failed"); + if (loadingNow) { + if (r.ok && status === "loaded") { + remember("idle"); + toast("success", tr("model.loaded", "Model loaded"), tr("model.gpuInUse", "The GPU is in use.")); + } else { + toast("error", failTitle, msg); + } + } else if (status === "unloaded" || status === "not loaded") { + remember("unloaded"); + toast(status === "unloaded" ? "success" : "info", + status === "unloaded" ? tr("model.unloaded", "Model unloaded") : tr("model.alreadyUnloaded", "Already unloaded"), + tr("model.gpuFree", "The GPU is free. Load, or the next message, brings it back.")); + } else if (r.status === 409 || status === "busy") { + let sample = (lastMetrics && lastMetrics.live) || {}; + try { + const mr = await fetch("metrics", {headers: headers()}); + if (mr.ok) { + const m = await mr.json(); + if (m && m.live) { sample = m.live; lastMetrics = m; } + } + } catch (e) { /* the 409 body has no phase */ } + toast("warn", tr("model.busy", "Model is busy"), imageLive(sample) + ? tr("model.imageBusy", "An image is generating. It finishes on its own.") : tr("model.stopFirstDot", "Stop the reply, then unload.")); + } else if (status === "unsupported") { + toast("error", tr("model.unsupported", "Unload is not available"), ""); + } else { + toast("error", failTitle, msg); + } + } catch (e) { + toast("error", loadingNow ? tr("model.loadFailed", "Load failed") : tr("model.unloadFailed", "Unload failed"), tr("model.noAnswer", "The server did not answer.")); + } finally { + modelOp = null; + if (lastMetrics) render(lastMetrics); else modelButton({}); + } +}; function render(m) { const live = m.live || {}, hw = m.hardware || {}, st = m.hardware_static || {}, eng = m.engine || {}, h = m.history || {}; const last = (m.requests || [])[0]; - // the header pill - if (live.state === "reading") { + // the header pill. modelOp and a local load win over "N queued": with parallel requests, queued stays up through + // ensure_loaded(), and metrics stay "unloaded" until the engine is READY. An image POST in that window is still a load. + const localLoad = live.state === "unloaded" && (busy != null || imageBusy); + if (modelOp === "load") { + setPill("idle", tr("model.loading", "Loading…")); + } else if (modelOp === "unload") { + setPill("idle", tr("model.unloading", "Unloading…")); + } else if (localLoad) { + setPill("idle", tr("model.loading", "Loading…")); + } else if (imageLive(live)) { + setPill("reading", tr("pill.image", "Generating image…")); + } else if (live.state === "reading") { const pct = live.prompt_total ? Math.round((100 * live.prompt_read) / live.prompt_total) : null; - setPill("reading", pct != null ? `Reading prompt · ${pct}%` : "Reading prompt"); + setPill("reading", pct != null ? tr("pill.readingPct", "Reading prompt · {pct}%", {pct}) : tr("pill.reading", "Reading prompt")); } else if (live.state === "generating") { - setPill("generating", `Generating · ${fmt(live.tok_s, 1)} tok/s`); + setPill("generating", tr("pill.generating", "Generating · {rate} tok/s", {rate: fmt(live.tok_s, 1)})); + } else if (live.state === "unloaded") { + setPill("idle", tr("pill.unloaded", "Unloaded")); } else { - setPill("idle", "Idle"); + setPill("idle", tr("pill.idle", "Idle")); } - if (live.queued > 0) setPill("queued", `${live.queued} queued`); + modelButton(live); + if (!modelOp && !localLoad && live.queued > 0) setPill("queued", tr("pill.queued", "{n} queued", {n: live.queued})); if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept); if (tab === "monitor") renderConvCache(m.conversation_cache); if (tab === "about") renderAbout(eng, hw, st); @@ -252,11 +411,29 @@ function renderTotals(t) { } function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { // model state - const on = live.queued > 0 ? "queued" : live.state; - for (const b of document.querySelectorAll("#state-badges .st-badge")) b.classList.toggle("on", b.dataset.s === on || b.dataset.s === live.state); + // A local turn keeps metrics on "unloaded" for the whole engine start. + const imageNow = imageLive(live); + const starting = modelOp === "load" || imageNow || (busy != null && live.state === "unloaded"); + const on = !modelOp && live.queued > 0 ? "queued" : live.state; + for (const b of document.querySelectorAll("#state-badges .st-badge")) { + const lit = (b.dataset.s === on || b.dataset.s === live.state) && !(starting && b.dataset.s === "unloaded"); + b.classList.toggle("on", lit); + } const prog = $("state-progress"); let label = "Waiting for a request", detail = "", pct = 0; - if (live.state === "reading") { + if (modelOp === "load" || (busy != null && live.state === "unloaded" && !imageNow)) { + label = "Loading"; + delete prog.dataset.tone; + detail = "The model is loading."; + } else if (imageNow && (live.state === "unloaded" || live.state === "reading" || live.state === "generating" || live.state === "idle")) { + label = live.state === "unloaded" ? "Loading" : "Generating image"; + delete prog.dataset.tone; + detail = live.state === "unloaded" ? "The model is loading." : "An image is generating. It finishes on its own."; + } else if (modelOp === "unload") { + label = "Unloading"; + delete prog.dataset.tone; + detail = "Freeing the GPU."; + } else if (live.state === "reading") { label = "Reading prompt"; prog.dataset.tone = "info"; if (live.prompt_total) { @@ -270,6 +447,10 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { delete prog.dataset.tone; pct = live.max_tokens ? Math.min(100, (100 * live.generated) / live.max_tokens) : 0; detail = `${fmt(live.generated)} tokens · ${fmt(live.tok_s, 1)} tok/s`; + } else if (live.state === "unloaded") { + label = "Unloaded"; + delete prog.dataset.tone; + detail = "Load brings it back. A message does too."; } else if (last) { delete prog.dataset.tone; detail = `last: ${fmt(last.output_tokens)} tokens${last.decode_tok_s ? ` at ${fmt(last.decode_tok_s, 1)} tok/s` : ""}`; @@ -859,6 +1040,7 @@ async function send() { const controller = new AbortController(); busy = {controller, msg: m}; setBusy(true); + paintLive(); const body = {model: health.model, messages: apiMessages(), stream: true, reasoning_effort: settings.thinking}; @@ -937,6 +1119,7 @@ async function send() { if (m.limit) m.meta = `${m.meta || ""} · stopped at the limit of ${m.limit} tool rounds (mcp.max_rounds)`; busy = null; setBusy(false); + paintLive(); if (frame) cancelAnimationFrame(frame); updateAssistant(el, m, false); saveChat(); @@ -1184,6 +1367,7 @@ async function start() { loadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } }); showTab(location.hash.slice(1) || "chat"); poll(); + requestAnimationFrame(fitHeader); } start(); @@ -1194,7 +1378,9 @@ $("img-form").onsubmit = async (ev) => { if (!prompt) return; const body = {prompt, size: $("img-size").value, response_format: "b64_json"}; if ($("img-seed").value !== "") body.seed = Number($("img-seed").value); + imageBusy = true; $("img-go").disabled = true; + paintLive(); const t0 = performance.now(); $("img-hint").textContent = "Generating\u2026 (a minute or more on a small GPU)"; try { @@ -1216,6 +1402,8 @@ $("img-form").onsubmit = async (ev) => { $("img-hint").textContent = ""; toast("error", "No image", String(e.message || e), 8000); } finally { + imageBusy = false; $("img-go").disabled = false; + paintLive(); } }; diff --git a/serve/web/index.html b/serve/web/index.html index 704417c7..be6f6d36 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -33,6 +33,7 @@ <span class="st-header__spacer"></span> <span class="st-pill" id="pill" data-state="idle" role="status" aria-live="polite"> <span class="st-pill__dot"></span><span id="pill-text">Connecting…</span></span> + <button class="st-btn st-btn--secondary" id="unload-btn" type="button" title="Waiting for the server" disabled>…</button> <button class="st-btn st-btn--icon" id="theme-btn" title="Light / dark" aria-label="Switch between light and dark"> <svg class="st-icon"><use id="theme-icon" href="web/sprite.svg#i-moon"/></svg></button> </header> @@ -102,6 +103,7 @@ <span class="card-title">Model state</span> <span class="badges" id="state-badges"> <span class="st-badge" data-s="idle">Idle</span> + <span class="st-badge" data-s="unloaded">Unloaded</span> <span class="st-badge st-badge--reading" data-s="reading">Reading</span> <span class="st-badge st-badge--generating" data-s="generating">Generating</span> <span class="st-badge st-badge--queued" data-s="queued">Queued</span> diff --git a/tools/webtest/browser_test.mjs b/tools/webtest/browser_test.mjs index 8fe01ec2..5949db2e 100644 --- a/tools/webtest/browser_test.mjs +++ b/tools/webtest/browser_test.mjs @@ -180,6 +180,79 @@ test("math: off by default, drawn when switched on, source kept", async ({ brows await page.close(); }); +// ------------------------------------------------------------------------------------------------ load / unload (#3550) +const btnText = (page) => page.$eval("#unload-btn", (b) => b.textContent); +const waitBtn = (page, text) => page.waitForFunction((t) => document.getElementById("unload-btn").textContent === t, { timeout: 8000 }, text); +const posts = (mock, what) => mock.state.calls.filter((c) => c === "POST " + what).length; + +test("load/unload: the header button unloads after a confirmation and loads again", async ({ browser, mock }) => { + mock.state.loaded = true; mock.state.calls.length = 0; + const page = await openPage(browser, mock); + await waitBtn(page, "Unload"); + await page.click("#unload-btn"); + assert.match(page.lastDialog, /Unload the model and free the GPU/); + await waitBtn(page, "Load"); + assert.equal(posts(mock, "/unload"), 1); + assert.equal(await page.$eval("#pill-text", (e) => e.textContent), "Unloaded"); + await sleep(2500); // the poll must agree, not flip the button back + assert.equal(await btnText(page), "Load"); + await page.click("#unload-btn"); + await waitBtn(page, "Unload"); + assert.equal(posts(mock, "/load"), 1); + assert.equal(await page.$eval("#pill-text", (e) => e.textContent), "Idle"); + await page.close(); +}); + +test("load/unload: declining the question changes nothing", async ({ browser, mock }) => { + mock.state.loaded = true; mock.state.calls.length = 0; + const page = await openPage(browser, mock, { dialogs: "dismiss" }); + await waitBtn(page, "Unload"); + await page.click("#unload-btn"); + await sleep(500); + assert.equal(posts(mock, "/unload"), 0); + assert.equal(await btnText(page), "Unload"); + await page.close(); +}); + +test("load/unload: not while an answer is being written", async ({ browser, mock }) => { + mock.state.loaded = true; + const page = await openPage(browser, mock); + await waitBtn(page, "Unload"); + await say(page, "#hold please"); + await page.waitForFunction(() => busy !== null); + assert.equal(await page.$eval("#unload-btn", (b) => b.disabled), true); + assert.match(await page.$eval("#unload-btn", (b) => b.title), /Stop the reply/); + await page.click("#stop-btn"); + await idle(page); + await page.waitForFunction(() => !document.getElementById("unload-btn").disabled, { timeout: 8000 }); + await page.close(); +}); + +test("load/unload: an unloaded model is loaded by a message and the button follows", async ({ browser, mock }) => { + mock.state.loaded = false; + const page = await openPage(browser, mock); + await waitBtn(page, "Load"); + await say(page, "hello"); + await idle(page); + await waitBtn(page, "Unload"); + await page.close(); +}); + +test("load/unload: the header fits a phone", async ({ browser, mock }) => { + mock.state.loaded = true; + for (const width of [320, 360, 390, 640]) { + const page = await openPage(browser, mock, { width, height: 700 }); + await waitBtn(page, "Unload"); + const r = await page.evaluate(() => { + const box = (id) => { const b = document.getElementById(id).getBoundingClientRect(); return [b.left, b.right]; }; + return { unload: box("unload-btn"), theme: box("theme-btn"), scroll: document.documentElement.scrollWidth, width: innerWidth }; + }); + for (const [l, rt] of [r.unload, r.theme]) assert.ok(l >= 0 && rt <= r.width, `${width}px: ${JSON.stringify(r)}`); + assert.ok(r.scroll <= r.width, `${width}px: the page scrolls sideways: ${JSON.stringify(r)}`); + await page.close(); + } +}); + const mock = await startMock(); const browser = await launch(); await run(async () => ({ browser, mock, close: async () => { await browser.close(); await mock.stop(); } })); From 0acba452ec6aa61150fff79fa5811566521aae3b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:06:26 +0100 Subject: [PATCH 136/177] Test: app-ui 'Quit works once' waits for the shutdown callback (polling, up to 5 s) instead of a fixed 20 ms sleep, so a busy PC cannot fail it (test only) --- apps/host/tests/app-ui.test.mjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/host/tests/app-ui.test.mjs b/apps/host/tests/app-ui.test.mjs index 5b04c8c3..e0aac186 100644 --- a/apps/host/tests/app-ui.test.mjs +++ b/apps/host/tests/app-ui.test.mjs @@ -12,6 +12,8 @@ import { checkComponentUpdates } from '../server/updates.mjs'; const root = fileURLToPath(new URL('..', import.meta.url)); const delay = ms => new Promise(r => setTimeout(r, ms)); +/** Wait until `done()` is true, polling every 10 ms for up to `ms` (a busy PC can hold a timer back by far more than a fixed 20 ms sleep). */ +const until = async (done, ms = 5000) => { const end = Date.now() + ms; while (!done() && Date.now() < end) await delay(10); return done(); }; const bridgeEnv = { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:5555', STRATA_SHELL_TOKEN: 'a'.repeat(32) }; test('a host nobody started has no window mode, no Quit and no updater', () => { @@ -40,7 +42,8 @@ test('browser mode (chosen): Quit works once and the app updater says why it is assert.equal(ui.updater.unavailable, BROWSER_UPDATE_MESSAGE); await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE && error.message === BROWSER_UPDATE_MESSAGE); assert.equal(ui.quit().status, 202); - await delay(20); + assert.ok(await until(() => stopped >= 1), 'the shutdown callback ran'); + await delay(50); // and only once assert.equal(stopped, 1); }); From fcd3cdbcd7cd591262238f8ffc8c1030db50ac88 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:14:14 +0100 Subject: [PATCH 137/177] Web chat: one chat-history design - saved chats, edit and rewind, branch, send while answering (#1787, #2615, #3823, #4004) Five overlapping proposals, one set of controls (Chat settings > Chats, all off by default; off, the page is the page from before: one chat, New chat clears it with an Undo, Send is off while an answer is written, no new request field). - Saved chats list (#1787): the chats kept in this browser (IndexedDB, one record per chat, names of attachments only), a list with day groups, search over titles and text, rename, delete with Undo, collapse; a private window or full store keeps the list in memory and says so once. Nothing goes to the server. The list has the New chat button, so the composer's one is hidden while it is on. - Edit and rewind messages (#2615 + #3823): under each message, Regenerate (a new answer to the same question), Edit answer (its text only: thinking and tool calls go, no request) and Rewind to here. Rewind asks, as #3823 proposes: "Edit and send again here" hides this message and the ones after it, puts the question and its attachments in the box and keeps one Undo bar ("2 messages hidden"); "Branch from here" starts a new saved chat with the messages before it and leaves this one alone. A branch keeps a title that says where it came from ("Branch of ...", also at the very first message) and links back. One control does what #2615 had as Edit on a question and as Remove from here. - Send while answering (#4004, for the web page): "Wait" (default, as before), "Send after" (the message waits and goes when the answer is done) or "Interrupt" (the answer stops where it is, what is written stays and is marked interrupted, the message goes at once; a running tool finishes first). One message waits; Take back returns it to the box; Stop keeps it for you to send. The pure logic is serve/web/history.js, the store serve/web/chatstore.js, the page's part serve/web/chats-ui.js. Tests: serve/test_web_history.js (Node, with the IndexedDB stub and cases of #1787), serve/test_web_history.py, and 17 browser tests (tools/webtest/browser_test.mjs). Screenshots: tools/webtest/shots.mjs. Also: the Sampling drawer is now Chat settings (its button says so), a wide window lets a message use the column (#3176 widened only the column). Ported by hand and merged: #1787 by Scotty Hudson, #2615 by Joyer Huang (uppet), issues #3823 and #4004 by xvcezrqpbxtpzblrt (their proposals, for the desktop app, carried to the web page). Co-authored-by: Scotty Hudson <14501954+Scotty-Hudson@users.noreply.github.com> Co-authored-by: Joyer Huang <110209+uppet@users.noreply.github.com> Co-authored-by: xvcezrqpbxtpzblrt <333138892+xvcezrqpbxtpzblrt@users.noreply.github.com> --- serve/test_web_history.js | 222 ++++++++++++++++ serve/test_web_history.py | 119 +++++++++ serve/web/app.css | 78 ++++++ serve/web/app.js | 230 +++++++++++++---- serve/web/chats-ui.js | 450 +++++++++++++++++++++++++++++++++ serve/web/chatstore.js | 66 +++++ serve/web/history.js | 90 +++++++ serve/web/index.html | 142 +++++++---- serve/web/sprite.svg | 1 + tools/webtest/browser_test.mjs | 348 +++++++++++++++++++++++++ tools/webtest/shots.mjs | 142 +++++++++++ 11 files changed, 1786 insertions(+), 102 deletions(-) create mode 100644 serve/test_web_history.js create mode 100644 serve/test_web_history.py create mode 100644 serve/web/chats-ui.js create mode 100644 serve/web/chatstore.js create mode 100644 serve/web/history.js create mode 100644 tools/webtest/shots.mjs diff --git a/serve/test_web_history.js b/serve/test_web_history.js new file mode 100644 index 00000000..74658c24 --- /dev/null +++ b/serve/test_web_history.js @@ -0,0 +1,222 @@ +// The chat history's logic (serve/web/history.js) and the browser store behind the saved-chats list (serve/web/chatstore.js), +// run in Node. The store runs against a small stub of IndexedDB that is faithful where the code depends on it: a read's result +// is on the request and not on the store; a write the browser refuses fires abort on the transaction; a blocked open never +// resolves by itself; a database already at version 1 does not run onupgradeneeded; requests answer on a later tick. +// (The stub and its cases are from PR #1787 by Scotty-Hudson, rebuilt for the split modules.) +// node serve/test_web_history.js (serve/test_web_history.py runs it too and skips when node is missing) +"use strict"; +const assert = require("node:assert/strict"); +const path = require("node:path"); +const H = require(path.join(__dirname, "web", "history.js")); +const {createChatStore} = require(path.join(__dirname, "web", "chatstore.js")); + +const user = (text, extra = {}) => ({role: "user", text, time: 1, ...extra}); +const bot = (text, extra = {}) => ({role: "assistant", text, time: 2, ...extra}); +const tool = {id: "t1", name: "fs__read", result: "secret result", state: "done", round: 0, at: 0}; +const convo = () => [user("q1", {images: [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], files: [{kind: "file", name: "n.txt", text: "notes"}]}), + bot("a1", {reasoning: "thoughts", tools: [tool], meta: "12 tokens", stopped: true, error: "x"}), user("q2"), bot("a2")]; + +const cases = { + titles_and_groups() { + assert.equal(H.chatTitle({title: "Mine", messages: []}), "Mine"); + assert.equal(H.chatTitle({title: "", messages: [user(" first line\nsecond")]}), "first line"); + assert.equal(H.chatTitle({title: "", messages: [user("x".repeat(100))]}).length, H.TITLE_MAX); + assert.equal(H.chatTitle({title: "", messages: []}), "New chat"); + assert.equal(H.chatTitle({title: "", messages: []}, "Neuer Chat"), "Neuer Chat", "the caller's word for an unnamed chat"); + const now = Date.UTC(2026, 9, 26, 12), day = 86400000; + const keys = [0, 0.4, 1.5, 5, 20, 40].map((d) => H.groupKey(now - d * day, now)); + assert.deepEqual(keys, ["today", "today", "yesterday", "week", "month", "older"]); + const a = H.newChat(1, 0.5), b = H.newChat(2, 0.5); + assert.notEqual(a.id, b.id); assert.deepEqual(a.messages, []); + }, + filter_searches_titles_and_text() { + const chats = [{id: "a", title: "the garden", time: 3, messages: [user("watering the tomatoes")]}, + {id: "b", title: "a chat about code", time: 2, messages: [user("nothing here")]}, + {id: "c", title: "tomatoes again", time: 1, messages: [user("a different question")]}]; + assert.deepEqual(H.filterChats(chats, "").map((c) => c.id), ["a", "b", "c"], "newest first"); + assert.deepEqual(H.filterChats(chats, " TOMATOES ").map((c) => c.id), ["a", "c"], "title or text, any case"); + assert.deepEqual(H.filterChats(chats, "nothing here").map((c) => c.id), ["b"]); + assert.deepEqual(H.filterChats(chats, "zzz"), []); + assert.deepEqual(chats.map((c) => c.id), ["a", "b", "c"], "the caller's list is not reordered"); + }, + clean_keeps_names_only() { + const clean = H.cleanMessages(convo()); + assert.deepEqual(clean[0].images, [{name: "a.png"}]); + assert.deepEqual(clean[0].files, [{name: "n.txt"}]); + assert.ok(!JSON.stringify(clean).includes("data:image") && !JSON.stringify(clean).includes("notes"), "no contents in the browser's store"); + assert.equal(clean[1].text, "a1", "the text stays"); + assert.deepEqual(convo()[0].files, [{kind: "file", name: "n.txt", text: "notes"}], "a copy: the screen keeps its contents"); + }, + rewind_a_question() { + const m = convo(); + const plan = H.rewind(m, 2); + assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"]); + assert.equal(plan.hidden, 2, "the question and its answer"); + assert.equal(plan.draft.text, "q2"); assert.equal(plan.draft.lost, 0); + const first = H.rewind(m, 0); + assert.deepEqual(first.keep, [], "the first question: nothing stays, the question goes to the box"); + assert.equal(first.draft.text, "q1"); assert.equal(first.hidden, 4); + assert.deepEqual(first.draft.images, [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], "attachments with contents come back"); + assert.deepEqual(first.draft.files, [{kind: "file", name: "n.txt", text: "notes"}]); + assert.equal(m.length, 4, "the list itself is not changed"); + }, + rewind_an_answer() { + const plan = H.rewind(convo(), 1); + assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"], "the answer stays and the list ends with it"); + assert.equal(plan.draft, null); assert.equal(plan.hidden, 2); + assert.equal(H.rewind(convo(), 3).hidden, 0, "the last answer: nothing to hide"); + assert.equal(H.rewind(convo(), 9), null); + }, + lost_attachments_are_counted() { + const reloaded = H.cleanMessages(convo()); + assert.equal(H.lostAttachments(reloaded[0]), 2); + assert.equal(H.lostAttachments(convo()[0]), 0); + const plan = H.rewind(reloaded, 0); + assert.equal(plan.draft.lost, 2); assert.deepEqual(plan.draft.images, []); assert.deepEqual(plan.draft.files, []); + assert.equal(plan.draft.text, "q1", "the text still comes back"); + }, + regenerate_from_the_question() { + const m = convo(); + assert.deepEqual(H.regenerate(m, 1).keep.map((x) => x.text), ["q1"]); + assert.equal(H.regenerate(m, 1).hidden, 3); + assert.deepEqual(H.regenerate(m, 3).keep.map((x) => x.text), ["q1", "a1", "q2"]); + assert.deepEqual(H.regenerate(m, 2).keep.map((x) => x.text), ["q1", "a1", "q2"], "on the last question itself"); + assert.equal(H.regenerate([bot("orphan")], 0), null, "no question before it"); + }, + edit_an_answer() { + const plan = H.editAnswer(convo(), 1, "corrected", "Edited"); + assert.equal(plan.keep.length, 2); assert.equal(plan.hidden, 2); + const a = plan.keep[1]; + assert.deepEqual(a, {role: "assistant", text: "corrected", time: 2, meta: "Edited"}, "no thinking, tools, error, stop mark or stats"); + assert.equal(H.editAnswer(convo(), 0, "x"), null, "only an answer can be edited"); + }, + branch_is_a_copy_with_a_title_that_stays() { + const original = {id: "c1", title: "", time: 1, messages: convo()}; + const plan = H.rewind(original.messages, 2); + const b = H.branch(original, plan.keep, plan.keep.length, "Branch of q1", 5, 0.25); + assert.deepEqual(b.messages.map((x) => x.text), ["q1", "a1"]); + assert.equal(b.title, "Branch of q1"); assert.deepEqual(b.parent, {id: "c1", title: "q1"}); + assert.notEqual(b.id, "c1"); + b.messages[0].text = "changed"; b.messages[1].tools[0].result = "changed"; + assert.equal(original.messages[0].text, "q1", "the original is untouched"); + assert.equal(original.messages[1].tools[0].result, "secret result"); + assert.equal(H.chatTitle(H.branch(original, [], 0, "Branch of q1"), "x"), "Branch of q1", "a branch at the first message keeps its title"); + }, +}; + +// ---------------------------------------------------------------- the stub IndexedDB +function makeIdb(hooks = {}, seed = {}) { + const data = Object.assign({}, seed), stores = {}, calls = {upgradeneeded: 0, createObjectStore: 0}; + let current = null; + const request = () => ({result: null, error: null, transaction: current, onsuccess: null, onerror: null}); + const store = { + put(value) { + const req = request(); + queueMicrotask(() => { + if (hooks.quota) { req.error = {name: "QuotaExceededError"}; req.onerror && req.onerror(); return; } + if (hooks.abort) return; + data[value.id] = value; req.result = value; req.onsuccess && req.onsuccess(); + }); + return req; + }, + delete(key) { + const req = request(); + queueMicrotask(() => { if (hooks.quota || hooks.abort) return; delete data[key]; req.result = true; req.onsuccess && req.onsuccess(); }); + return req; + }, + getAll() { + const req = request(); + queueMicrotask(() => { if (hooks.abort) return; req.result = Object.values(data); req.onsuccess && req.onsuccess(); }); + return req; + }, + }; + const transaction = () => { + const t = {error: null, oncomplete: null, onerror: null, onabort: null, objectStore: () => store}; + current = t; + queueMicrotask(() => { + if (hooks.quota || hooks.abort) { t.error = {name: hooks.quota ? "QuotaExceededError" : hooks.abort}; t.onabort && t.onabort(); } + else if (t.oncomplete) t.oncomplete(); + }); + return t; + }; + const db = {objectStoreNames: {contains: (n) => n in stores}, createObjectStore: (n) => { calls.createObjectStore++; stores[n] = store; }, transaction}; + return {open: () => { + if (hooks.throws) throw new Error("private mode"); + const r = {result: db, error: null, onupgradeneeded: null, onsuccess: null, onerror: null, onblocked: null}; + queueMicrotask(() => { + if (hooks.blocked) { r.onblocked && r.onblocked(); return; } + if (hooks.newDatabase !== false) { calls.upgradeneeded++; r.onupgradeneeded && r.onupgradeneeded(); } + r.result = db; r.onsuccess && r.onsuccess(); + }); + return r; + }, records: data, calls}; +} +const wait = () => new Promise((r) => setTimeout(r, 10)); +const mk = (hooks, seed) => { + const idb = makeIdb(hooks, seed), problems = []; + return {idb, problems, store: createChatStore({indexedDB: idb, onProblem: (k) => problems.push(k)})}; +}; +const chat = (id, extra = {}) => ({id, title: id, time: 1, messages: [user("hi " + id)], ...extra}); + +Object.assign(cases, { + async store_fresh_database_creates_the_store_and_reads() { + const a = mk({}, {c0: chat("c0"), c1: chat("c1")}); + assert.equal(await a.store.start(), true); + assert.equal(a.idb.calls.upgradeneeded, 1); assert.equal(a.idb.calls.createObjectStore, 1); + assert.deepEqual((await a.store.all()).map((c) => c.id).sort(), ["c0", "c1"], "the result is read from the request"); + assert.deepEqual(a.problems, []); + }, + async store_put_and_remove_touch_one_record() { + const a = mk({}, {c0: chat("c0")}); + await a.store.start(); + a.store.put(chat("c1", {title: "renamed"})); await wait(); + assert.equal(a.idb.records.c1.title, "renamed"); assert.ok(a.idb.records.c0, "the other record is not rewritten"); + a.store.remove("c0"); await wait(); + assert.ok(!("c0" in a.idb.records)); + }, + async store_private_mode_is_memory_only_and_says_so_once() { + const a = mk({throws: true}); + assert.equal(await a.store.start(), false); + assert.deepEqual(a.problems, ["memory"]); + assert.deepEqual(await a.store.all(), []); + a.store.put(chat("x")); a.store.remove("x"); // no store: nothing to do, nothing thrown + await a.store.start(); + assert.deepEqual(a.problems, ["memory"], "told once, not on every try"); + }, + async store_missing_object_store_is_memory_only() { + const a = mk({newDatabase: false}); // a database already at version 1: no upgrade, no store + assert.equal(await a.store.start(), false); + assert.equal(a.idb.calls.createObjectStore, 0); + assert.deepEqual(a.problems, ["memory"]); + }, + async store_blocked_open_does_not_hang() { + const a = mk({blocked: true}); + assert.equal(await a.store.start(), false); + assert.deepEqual(a.problems, ["memory"]); + }, + async store_full_storage_warns_once_with_its_own_message() { + const a = mk({quota: true}); + await a.store.start(); + a.store.put(chat("big")); await wait(); + a.store.put(chat("big2")); await wait(); + assert.deepEqual(a.problems, ["quota"], "one warning, the quota one"); + }, + async store_another_failure_is_not_called_quota() { + const a = mk({abort: "DataError"}); + await a.store.start(); + a.store.put(chat("bad")); await wait(); + assert.deepEqual(a.problems, ["failed"]); + }, + async store_a_read_that_aborts_answers_empty() { + const a = mk({abort: "DataError"}, {c0: chat("c0")}); + await a.store.start(); + assert.deepEqual(await a.store.all(), [], "no hang, no records"); + }, +}); + +(async () => { + const name = process.argv[2]; + const run = name ? [[name, cases[name]]] : Object.entries(cases); + if (name && !cases[name]) throw new Error("unknown test " + name); + for (const [n, fn] of run) { await fn(); console.log("ok " + n); } +})().catch((e) => { console.error(e); process.exitCode = 1; }); diff --git a/serve/test_web_history.py b/serve/test_web_history.py new file mode 100644 index 00000000..15854f2e --- /dev/null +++ b/serve/test_web_history.py @@ -0,0 +1,119 @@ +"""The web page's chat history: saved chats in the browser (#1787), edit / regenerate / rewind with an Undo (#2615), the rewind +choice between "here" and a branch (#3823), and sending while an answer is written (#4004). One design, opt-in, off by default. + +The logic runs in Node (serve/test_web_history.js); what the page does in a real browser is in tools/webtest/browser_test.mjs +(run here when WEBTEST_MODULES is set). These checks read the sources for what must hold whatever the code looks like: +off is the page from before, and nothing about a chat goes to the server.""" +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] +WEB = Path(__file__).parent / "web" + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class HistoryInNode(unittest.TestCase): + def test_messages_titles_branches_and_the_browser_store(self): + r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_history.js"))], + capture_output=True, text=True, timeout=60) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +class OffIsThePageFromBefore(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.html = (WEB / "index.html").read_text(encoding="utf-8") + cls.app = (WEB / "app.js").read_text(encoding="utf-8") + cls.ui = (WEB / "chats-ui.js").read_text(encoding="utf-8") + cls.store = (WEB / "chatstore.js").read_text(encoding="utf-8") + + def test_the_three_switches_start_off(self): + self.assertIn('chatList: false, chatEdit: false, whileBusy: "wait"', self.app) + for el in ("s-list", "s-edit"): + self.assertIn('aria-checked="false"', re.search(rf'<button[^>]*id="{el}"[^>]*>', self.html).group(0)) + self.assertIn('data-v="wait"', self.html) + self.assertRegex(self.html, r'<aside class="chat-sidebar"[^>]*\bhidden>') # no list until it is switched on + + def test_the_browser_store_is_opened_only_for_the_list(self): + self.assertEqual(self.ui.count("chatStore.start()"), 1) + self.assertRegex(self.ui, r"async function openChats\(fromScreen\) \{\s*await chatStore\.start\(\);") + self.assertEqual(len(re.findall(r"\bopenChats\(", self.ui)), 2) # its definition and the one call, in setChatList + self.assertNotIn("indexedDB", self.app, "the page's main script never touches the store") + self.assertIn("if (settings.chatList) await setChatList(true, false);", self.app) + + def test_with_the_list_off_one_chat_is_kept_as_before(self): + self.assertIn('if (!listOn) { store.set("chat", H.cleanMessages(messages)); return; }', self.ui) + self.assertIn('$("new-btn").hidden = on;', self.ui) # only the list's own New chat shows while it is on + + def test_pictures_and_files_are_kept_as_names_only(self): + self.assertIn("chatStore.put(H.cleanChat(chat))", self.ui) + self.assertNotIn("chatStore.put(chat)", self.ui) + + def test_nothing_about_a_chat_goes_to_the_server(self): + for name, src in (("app.js", self.app), ("chats-ui.js", self.ui), ("chatstore.js", self.store)): + for call in re.findall(r'fetch\(\s*([^,)]+)', src): + if call != '"v1/chat/completions"': # the question itself, as ever + self.assertNotRegex(call, r"chat|histor", f"{name}: {call}") + + def test_the_edit_controls_wait_for_a_finished_answer(self): + self.assertIn("const historyLocked = () => !!busy || !!panel || !!pending;", self.ui) + self.assertIn("$(\"s-list\").disabled = $(\"s-edit\").disabled = !!busy || !!panel;", self.app) + + def test_an_interrupted_answer_keeps_what_was_written(self): + self.assertIn("if (cut) m.interrupted = true;", self.app) + self.assertIn("busy.cutAfterTool = true; return; } // let the tool finish", self.app) + self.assertIn("settlePending(cut, !m.stopped && !m.error);", self.app) + + def test_sending_while_busy_parks_nothing_unless_asked(self): + self.assertIn('const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject";', self.app) + self.assertIn("if (!parksWhileBusy()) return;", self.app) + + +class NothingOnTheServer(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def test_the_scripts_are_served_and_there_is_no_chat_endpoint(self): + for name in ("history.js", "chatstore.js", "chats-ui.js"): + with urllib.request.urlopen(f"{self.base}/web/{name}", timeout=10) as r: + self.assertEqual(r.status, 200) + for path in ("/chats", "/api/chats", "/history", "/api/history"): + with self.subTest(path=path): + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(self.base + path, timeout=10) + self.assertEqual(e.exception.code, 404) + + +@unittest.skipUnless(os.environ.get("WEBTEST_MODULES") and shutil.which("node"), + "set WEBTEST_MODULES (a folder with node_modules/puppeteer-core) to run the browser tests") +class InABrowser(unittest.TestCase): + def test_history_in_chrome(self): + for name in ("history", "list", "rewind", "branch", "regenerate", "edit answer", "while answering"): + with self.subTest(name=name): + r = subprocess.run([shutil.which("node"), str(ROOT / "tools" / "webtest" / "browser_test.mjs"), name], + capture_output=True, text=True, timeout=300) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css index 9c40e420..0873b269 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -257,3 +257,81 @@ main { flex: 1; min-height: 0; display: flex; } .st-code .st-btn--icon[data-preview-scripts][aria-pressed="true"] { background: var(--st-warn-tint); color: var(--st-warn-text); } .st-code--run .st-code__preview { outline: 2px solid var(--st-warn-text); outline-offset: -2px; } .st-code__preview iframe { display: block; width: 100%; height: 100%; border: 0; background: transparent; } + +/* ---------------------------------------------------------------- chat history (chats-ui.js) + The saved-chats list (PR #1787 by Scotty-Hudson), edit / regenerate / rewind (PR #2615 by uppet) and the Chat settings button. */ +.view--chat { flex-direction: row; } +.chat-main { flex: 1; min-width: 0; display: flex; flex-direction: column; } +.chat-sidebar { flex: none; width: 260px; display: flex; flex-direction: column; gap: var(--st-s-3); + padding: var(--st-s-4); background: var(--st-surface); border-right: 1px solid var(--st-line); } +.sidebar-head { display: flex; align-items: center; gap: var(--st-s-2); } +.sidebar-head .card-title { flex: 1; } +#sidebar-toggle .st-icon { transform: rotate(90deg); transition: transform var(--st-dur) var(--st-ease); } +.chat-sidebar[data-open="false"] { width: 60px; } +.chat-sidebar[data-open="false"] .sidebar-head { flex-direction: column; } +.chat-sidebar[data-open="false"] #sidebar-toggle .st-icon { transform: rotate(-90deg); } +.chat-sidebar[data-open="false"] .sidebar-title, .chat-sidebar[data-open="false"] .sidebar-search, +.chat-sidebar[data-open="false"] .sidebar-list, .chat-sidebar[data-open="false"] .sidebar-foot { display: none; } +.sidebar-search { height: 36px; font-size: var(--st-fs-sm); } +.sidebar-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; } +.sidebar-group { margin: 0; padding: var(--st-s-3) 8px var(--st-s-1); font-size: var(--st-fs-xs); + font-weight: var(--st-fw-bold); letter-spacing: .04em; text-transform: uppercase; color: var(--st-ink-muted); } +.chat-item { display: flex; align-items: center; gap: 2px; border-radius: var(--st-r-md); } +.chat-item.on { background: var(--st-surface-2); } +.chat-item__title { flex: 1; min-width: 0; border: 0; background: transparent; cursor: pointer; text-align: left; + padding: 8px; color: var(--st-ink-soft); font: 500 var(--st-fs-sm)/1.35 var(--st-font); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.chat-item:hover .chat-item__title { color: var(--st-ink); } +.chat-item.on .chat-item__title { color: var(--st-ink); font-weight: var(--st-fw-bold); } +.chat-item__actions { display: flex; gap: 2px; flex: none; opacity: 0; } /* the buttons come up on hover or focus */ +.chat-item:hover .chat-item__actions, .chat-item:focus-within .chat-item__actions { opacity: 1; } +.chat-item__actions .st-btn--icon { width: 30px; height: 30px; } +.chat-item__actions .st-btn--icon .st-icon { width: 16px; height: 16px; } +.chat-item__input { flex: 1; min-width: 0; height: 34px; font-size: var(--st-fs-sm); } +.sidebar-empty { margin: 0; padding: var(--st-s-2) 8px; } +.sidebar-foot { margin: 0; } +.chat-parent { display: flex; align-items: center; justify-content: center; gap: var(--st-s-3); flex-wrap: wrap; padding: var(--st-s-2) var(--st-s-4); + border-bottom: 1px solid var(--st-line-soft); font-size: var(--st-fs-sm); } +.chat-parent .st-btn { height: 30px; padding: 0 12px; font-size: var(--st-fs-xs); } + +/* the buttons under a message, the open panel / editor, and the bars above the box (Undo, a waiting message) */ +.history-actions, .history-editor__actions, .history-undo, .pending { display: flex; flex-wrap: wrap; gap: var(--st-s-2); align-items: center; } +.history-actions .st-btn, .history-undo .st-btn, .pending .st-btn, .history-panel .st-btn { height: 30px; padding: 0 10px; font-size: var(--st-fs-xs); } +.history-actions { margin-top: var(--st-s-1); } +.st-msg--user .history-actions { justify-content: flex-end; } +.history-panel, .history-editor { width: 100%; display: flex; flex-direction: column; gap: var(--st-s-2); padding: var(--st-s-3); + border: 1px solid var(--st-line); border-radius: var(--st-r-md); background: var(--st-surface-2); } +.history-choice { display: flex; align-items: center; gap: var(--st-s-3); flex-wrap: wrap; } +.history-choice > .muted { flex: 1 1 14rem; min-width: 0; } +.history-panel > .st-btn { align-self: flex-start; } +.history-editor textarea { width: 100%; min-height: 140px; max-height: 50vh; resize: vertical; font: inherit; height: auto; padding: 10px 14px; } +.history-editor p, .history-panel p { margin: 0; } +.st-msg[data-editing="true"] > .st-bubble { display: none; } +.history-undo, .pending { max-width: min(100%, 1100px); margin: 0 auto var(--st-s-2); color: var(--st-ink-muted); font-size: var(--st-fs-sm); } +.pending { justify-content: space-between; padding: 6px 10px; border: 1px solid var(--st-line); border-radius: var(--st-r-md); background: var(--st-surface); } +.pending__text { flex: 1 1 12rem; min-width: 0; overflow-wrap: anywhere; color: var(--st-ink-soft); } +.pending__actions { display: flex; gap: var(--st-s-2); } + +/* Chat settings: the button says what it is, and the drawer groups the chat switches */ +.chat-settings-button { height: 36px; padding: 0 10px; gap: 6px; white-space: nowrap; font-size: var(--st-fs-sm); } +.chat-settings-short { display: none; } +.drawer-group { display: flex; flex-direction: column; gap: var(--st-s-4); padding-top: var(--st-s-4); border-top: 1px solid var(--st-line); } +.drawer-group__title { margin: 0; font-size: var(--st-fs-base); font-weight: var(--st-fw-bold); color: var(--st-ink); } +.seg--3 { grid-template-columns: repeat(3, 1fr); } +.seg--3 button { padding: 0 4px; } +#lang { width: 100%; } +@media (max-width: 640px) { + .chat-settings-label, .composer-hint { display: none; } + .chat-settings-short { display: inline; } + .st-btn--send { margin-left: auto; } +} +@media (max-width: 760px) { + /* the list is an overlay here: the chat keeps the whole width when it is closed to its rail */ + .view--chat { position: relative; } + .chat-sidebar[data-open="true"] { position: absolute; top: 0; left: 0; bottom: 0; z-index: 30; box-shadow: var(--st-sh-pop); } + .chat-sidebar { padding: var(--st-s-3); } +} + +/* a message may use the room a wide window gives the chat column (#3176 widened the column; the kit's 720px kept the messages narrow in it) */ +.st-msg { max-width: min(100%, 900px); } +.st-toast .st-btn { white-space: nowrap; } diff --git a/serve/web/app.js b/serve/web/app.js index 4b0477fd..e0ad80aa 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -781,7 +781,8 @@ function markdown(text) { // fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking // 0.7 / 0.8 / 20 with a presence penalty). Before 0.1.45 the page sent 0.6 itself; a stored 0.6 with the other two // values untouched counts as "not set" too. -const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false}; +const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false, + chatList: false, chatEdit: false, whileBusy: "wait"}; const OLD_DEFAULT_TEMPERATURE = 0.6; function samplingUntouched(s) { const t = +s.temperature; @@ -789,14 +790,10 @@ function samplingUntouched(s) { } let settings = {...DEFAULTS, ...store.get("sampling", {})}; if (samplingUntouched(settings)) settings.temperature = DEFAULTS.temperature; -let messages = store.get("chat", []); +let messages = store.get("chat", []); // the open chat's messages (chats-ui.js: with the saved-chats list on, also that chat's own) let attachments = []; // {name, url} -let busy = null; // {controller, msg} - -function saveChat() { - store.set("chat", messages.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})), - files: (m.files || []).map((f) => ({name: f.name}))}))); -} +let busy = null; // {controller, msg, cut, cutAfterTool} +let pending = null; // a message parked while an answer is written: {text, images, files, mode} function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); } function msgEl(m, i) { @@ -840,6 +837,8 @@ function msgEl(m, i) { `<button class="st-btn st-btn--icon" data-msg-copy aria-label="Copy the answer" title="Copy">${icon("copy")}</button></div>`; updateAssistant(el, m, false); } + const actions = msgActions(m, i); // edit / regenerate / rewind (chats-ui.js), when switched on + if (actions) el.appendChild(actions); return el; } // One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and @@ -927,6 +926,9 @@ function renderChat() { chat.querySelectorAll(".st-msg").forEach((e) => e.remove()); $("chat-empty").hidden = messages.length > 0; messages.forEach((m, i) => chat.appendChild(msgEl(m, i))); + renderSidebar(); + renderParent(); + renderUndoBar(); scrollDown(true); } function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; } @@ -1018,27 +1020,122 @@ function assistantMessages(m) { return out; } +function busyHint() { + const mode = settings.whileBusy; + return mode === "queue" ? tr("composer.hintQueue", "Enter sends when the answer is done") + : mode === "interject" ? tr("composer.hintInterject", "Enter stops the answer here and sends now") : ""; +} +// While an answer is written, Send is off ("wait", as always) or parks the message ("queue", "interject": Chat settings) +const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject"; function setBusy(on) { $("stop-btn").hidden = !on; - $("send-btn").disabled = on; - $("composer-hint").textContent = on ? "" : "Shift+Enter: new line"; + $("send-btn").disabled = (on && !parksWhileBusy()) || !!panel; + $("input").disabled = !!panel; + $("composer-hint").textContent = panel ? tr("composer.finishOpen", "Save or cancel what is open above to continue") + : on ? busyHint() : tr("composer.newline", "Shift+Enter: new line"); + if (settings.chatEdit) syncActions(); // the buttons follow the state: none under the answer being written + $("s-list").disabled = $("s-edit").disabled = !!busy || !!panel; // they change the messages on the screen + renderUndoBar(); + renderPending(); } -async function send() { - const text = $("input").value.trim(); - if ((!text && !attachments.length) || busy) return; - messages.push({role: "user", text, images: attachments.filter((a) => a.kind !== "file"), - files: attachments.filter((a) => a.kind === "file"), time: Date.now()}); - attachments = []; - renderAttachments(); - $("input").value = ""; - autosize(); +// A message sent while an answer is being written (#4004). "queue": it waits and goes when the answer is done. "interject": the +// answer stops where it is (what is written stays, marked interrupted) and the message goes at once; if a tool is running, the +// tool finishes first. Only one message waits. Off by default: with "wait" the page does nothing, as before. +function park(p, own) { + if (!parksWhileBusy()) return; + if (pending) { toast("warn", tr("pending.one", "A message is already waiting"), tr("pending.oneText", "Take it back or wait until it is sent.")); return; } + pending = {...p, mode: settings.whileBusy}; + if (own) { attachments = []; renderAttachments(); $("input").value = ""; autosize(); } + if (pending.mode === "interject") requestCut(); + setBusy(!!busy); +} +function requestCut() { + if (!busy || busy.cut) return; + if ((busy.msg.tools || []).some((t) => t.state === "running")) { busy.cutAfterTool = true; return; } // let the tool finish + busy.cut = true; + busy.controller.abort(); +} +function renderPending() { + let el = $("pending"); + if (!pending) { if (el) el.remove(); return; } + if (!el) { + el = node("div", "pending"); + el.id = "pending"; + el.setAttribute("role", "status"); + el.innerHTML = "<span class=\"pending__text\"></span><span class=\"pending__actions\"><button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-now></button>" + + "<button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-back></button></span>"; + el.querySelector("[data-pending-now]").onclick = pendingNow; + el.querySelector("[data-pending-back]").onclick = releasePending; + $("composer").before(el); + } + const quote = (pending.text || (pending.files[0] || pending.images[0] || {}).name || "").replace(/\s+/g, " ").slice(0, 70); + const text = !busy ? tr("pending.ready", "Not sent yet: “{text}”", {text: quote}) + : pending.mode === "queue" ? tr("pending.queued", "Sends when this answer is done: “{text}”", {text: quote}) + : busy.cutAfterTool ? tr("pending.afterTool", "Waiting for the tool to finish, then sending: “{text}”", {text: quote}) + : tr("pending.cutting", "Stopping the answer, then sending: “{text}”", {text: quote}); + el.querySelector(".pending__text").textContent = text; + const now = el.querySelector("[data-pending-now]"); + now.textContent = busy ? tr("pending.sendNow", "Send now") : tr("pending.send", "Send"); + now.hidden = !!busy && pending.mode === "interject"; // already on its way + el.querySelector("[data-pending-back]").textContent = tr("pending.takeBack", "Take back"); +} +function pendingNow() { + if (!pending) return; + if (busy) { pending.mode = "interject"; requestCut(); setBusy(true); return; } + const p = pending; + pending = null; + setBusy(false); + send(p); +} +// the waiting message goes back into the message box (a chat switch or a new chat must not lose it) +function releasePending() { + if (!pending) return; + const p = pending; + pending = null; + if (!$("input").value.trim()) $("input").value = p.text; + else $("input").value = `${p.text}\n\n${$("input").value}`; + attachments = [...p.images, ...p.files, ...attachments]; + renderAttachments(); autosize(); + setBusy(!!busy); +} +// after an answer: an interrupted one sends an interjection, a finished one sends a queued message +function settlePending(cut, finished) { + if (!pending) return; + if ((pending.mode === "interject" && cut) || (pending.mode === "queue" && finished)) { + const p = pending; + pending = null; + setBusy(false); + send(p); + } +} + +// the message box (or a parked message, `payload`) becomes a user turn and a reply is asked for +async function send(payload) { + const own = !payload; + const p = payload || {text: $("input").value.trim(), images: attachments.filter((a) => a.kind !== "file"), + files: attachments.filter((a) => a.kind === "file")}; + if (!p.text && !p.images.length && !p.files.length) return; + if (panel) return; // something is open above (an edit): finish it first + if (busy) { park(p, own); return; } + clearUndo(); + messages.push({role: "user", text: p.text, images: p.images, files: p.files, time: Date.now()}); + if (own) { + attachments = []; + renderAttachments(); + $("input").value = ""; + autosize(); + } + return generateReply(); +} +// an answer for the messages as they are: the last one is a user turn +async function generateReply() { const m = {role: "assistant", text: "", reasoning: "", time: Date.now()}; messages.push(m); renderChat(); const el = $("chat").lastElementChild; const controller = new AbortController(); - busy = {controller, msg: m}; + busy = {controller, msg: m, cut: false, cutAfterTool: false}; setBusy(true); paintLive(); @@ -1062,7 +1159,7 @@ async function send() { if (!r.ok) { let msg = `HTTP ${r.status}`; try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ } - if (r.status === 401) msg = "This server needs an API key: add it under About > Settings."; + if (r.status === 401) msg = tr("toast.keyNeeded", "This server needs an API key: add it under About > Settings."); throw new Error(msg); } const reader = r.body.getReader(), dec = new TextDecoder(); @@ -1080,9 +1177,13 @@ async function send() { if (data === "[DONE]") continue; let j; try { j = JSON.parse(data); } catch (e) { continue; } - if (j.error) throw new Error(j.error.message || "the engine reported an error"); + if (j.error) throw new Error(j.error.message || tr("toast.engineError", "the engine reported an error")); if (j.usage) usage = j.usage; - if (j.strata_mcp) onTool(m, j.strata_mcp); + if (j.strata_mcp) { + onTool(m, j.strata_mcp); + // an interjection waited for a running tool: it has its result now, so the answer can stop + if (busy.cutAfterTool && !busy.cut && !(m.tools || []).some((t) => t.state === "running")) { busy.cut = true; controller.abort(); } + } const d = (j.choices && j.choices[0] && j.choices[0].delta) || {}; const lastTool = m.tools && m.tools.length ? m.tools[m.tools.length - 1] : null; // a new round after a tool if (d.reasoning_content) { @@ -1102,21 +1203,24 @@ async function send() { } } catch (e) { if (e.name === "AbortError") m.stopped = true; - else { m.error = e.message || String(e); toast("error", "The request failed", m.error, 6000); } + else { m.error = e.message || String(e); toast("error", tr("toast.requestFailed", "The request failed"), m.error, 6000); } } + const cut = busy.cut; // an interjection ended it: kept as written, marked interrupted + if (cut) m.interrupted = true; if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; const n = usage ? usage.completion_tokens : null; + const ended = cut ? tr("chat.interruptedLower", "interrupted") : tr("chat.stoppedLower", "stopped"); if (n && firstAt) { const secs = (performance.now() - firstAt) / 1000; - m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}` + - (projectionLoaded() ? (settings.esp ? " · projection on" : " · projection off") : ""); + m.meta = tr("chat.tokens", "{n} tokens", {n: fmt(n)}) + (secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : "") + (m.stopped ? ` · ${ended}` : "") + + (projectionLoaded() ? (settings.esp ? ` · ${tr("chat.projectionOn", "projection on")}` : ` · ${tr("chat.projectionOff", "projection off")}`) : ""); } else if (m.stopped) { - m.meta = "Stopped"; + m.meta = cut ? tr("chat.interrupted", "Interrupted") : tr("chat.stopped", "Stopped"); } for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; } const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length; - if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${ran} tool call${ran > 1 ? "s" : ""}`; - if (m.limit) m.meta = `${m.meta || ""} · stopped at the limit of ${m.limit} tool rounds (mcp.max_rounds)`; + if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${tr("chat.toolCalls", {one: "{n} tool call", other: "{n} tool calls"}, {n: ran})}`; + if (m.limit) m.meta = `${m.meta || ""} · ${tr("chat.toolLimit", "stopped at the limit of {n} tool rounds (mcp.max_rounds)", {n: m.limit})}`; busy = null; setBusy(false); paintLive(); @@ -1124,6 +1228,7 @@ async function send() { updateAssistant(el, m, false); saveChat(); scrollDown(); + settlePending(cut, !m.stopped && !m.error); } $("composer").onsubmit = (e) => { e.preventDefault(); send(); }; @@ -1134,14 +1239,21 @@ $("input").addEventListener("keydown", (e) => { function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; } $("input").addEventListener("input", autosize); +// one chat, as before: New chat clears it, with an Undo (with the saved-chats list on, its own New chat button does this job) $("new-btn").onclick = () => { - if (busy) { toast("warn", "Still writing", "Stop the answer first."); return; } + if (busy) { stillWriting(); return; } + if (panel) { closePanel(); } + clearUndo(); + releasePending(); if (!messages.length) return; const backup = messages; messages = []; saveChat(); renderChat(); - toast("info", "New chat", "The last one was cleared.", 6000, {label: "Undo", run: () => { messages = backup; saveChat(); renderChat(); }}); + toast("info", tr("chat.newToast", "New chat"), tr("chat.clearedToast", "The last one was cleared."), 6000, {label: tr("undo", "Undo"), run: () => { + if (busy || messages.length) return; // a new question since: the cleared chat is not put back over it + messages = backup; saveChat(); renderChat(); + }}); }; $("export-btn").onclick = () => { if (!messages.length) { toast("info", "Nothing to save yet"); return; } @@ -1238,13 +1350,15 @@ $("input").addEventListener("paste", (e) => { if (files.length) { e.preventDefault(); addFiles(files); } }); -// ------------------------------------------------------------------ the sampling drawer +// ------------------------------------------------------------------ the chat settings drawer function openDrawer(open) { $("drawer").dataset.open = String(open); $("drawer").setAttribute("aria-hidden", String(!open)); $("scrim").hidden = !open; if (open) { loadDrawer(); loadShared(); loadMcp(); } } +const checked = (id) => $(id).getAttribute("aria-checked") === "true"; +const segValue = (id) => { const b = [...$(id).children].find((x) => x.getAttribute("aria-checked") === "true"); return b ? b.dataset.v : null; }; function loadDrawer(s = settings) { for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking)); $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k; @@ -1255,6 +1369,9 @@ function loadDrawer(s = settings) { $("esp-row").hidden = !projectionLoaded(); $("s-mcp").setAttribute("aria-checked", String(s.mcp !== false)); $("s-share").setAttribute("aria-checked", String(sharedOn)); + $("s-list").setAttribute("aria-checked", String(!!s.chatList)); + $("s-edit").setAttribute("aria-checked", String(!!s.chatEdit)); + for (const b of $("s-busy").children) b.setAttribute("aria-checked", String(b.dataset.v === (s.whileBusy || "wait"))); outputs(); } // "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings) @@ -1292,48 +1409,57 @@ function projectionLoaded() { } function outputs() { const t = +$("s-temp").value; - $("o-temp").textContent = t === 0 ? "0 · greedy" : t.toFixed(2); + $("o-temp").textContent = t === 0 ? tr("drawer.greedy", "0 · greedy") : t.toFixed(2); $("o-topp").textContent = (+$("s-topp").value).toFixed(2); $("o-topk").textContent = $("s-topk").value; - const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); - $("o-thinking").textContent = sel ? {none: "answers right away", low: "short", medium: "medium", high: "thorough (default)"}[sel.dataset.v] : ""; + const sel = segValue("s-thinking"); + $("o-thinking").textContent = sel ? {none: tr("drawer.thinkNone", "answers right away"), low: tr("drawer.thinkLow", "short"), + medium: tr("drawer.thinkMedium", "medium"), high: tr("drawer.thinkHigh", "thorough (default)")}[sel] : ""; + const busyMode = segValue("s-busy"); + $("o-busy").textContent = {wait: tr("drawer.busyWaitNote", "Send is off until the answer is done, as before."), + queue: tr("drawer.busyQueueNote", "Your message waits and goes as soon as the answer is done."), + interject: tr("drawer.busyInterjectNote", "The answer stops where it is (what is written stays) and your message goes at once. A tool that is running finishes first.")}[busyMode] || ""; for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0; } for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; +for (const b of $("s-busy").children) b.onclick = () => { for (const x of $("s-busy").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs; -$("s-math").onclick = () => $("s-math").setAttribute("aria-checked", String($("s-math").getAttribute("aria-checked") !== "true")); -$("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true")); -$("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true")); -$("s-mcp").onclick = () => $("s-mcp").setAttribute("aria-checked", String($("s-mcp").getAttribute("aria-checked") !== "true")); -$("s-share").onclick = () => $("s-share").setAttribute("aria-checked", String($("s-share").getAttribute("aria-checked") !== "true")); +for (const id of ["s-math", "s-show", "s-esp", "s-mcp", "s-share", "s-list", "s-edit"]) { + $(id).onclick = () => $(id).setAttribute("aria-checked", String($(id).getAttribute("aria-checked") !== "true")); +} $("s-reset").onclick = () => loadDrawer(DEFAULTS); $("s-apply").onclick = async () => { - const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); - settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, + const prev = settings; + // the list and the edit controls change the messages on the screen: not while an answer is written or something is open + const locked = !!busy || !!panel; + settings = {thinking: segValue("s-thinking") || "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(), - math: $("s-math").getAttribute("aria-checked") === "true", - show: $("s-show").getAttribute("aria-checked") === "true", - esp: $("s-esp").getAttribute("aria-checked") === "true", - mcp: $("s-mcp").getAttribute("aria-checked") === "true"}; + math: checked("s-math"), show: checked("s-show"), esp: checked("s-esp"), mcp: checked("s-mcp"), + chatList: locked ? !!prev.chatList : checked("s-list"), chatEdit: locked ? !!prev.chatEdit : checked("s-edit"), + whileBusy: segValue("s-busy") || "wait"}; store.set("sampling", settings); StrataMath.reset(); // math on or off: every answer is drawn again + if (settings.chatList !== !!prev.chatList) await setChatList(settings.chatList, true); + if (settings.chatEdit !== !!prev.chatEdit) { clearUndo(); syncActions(); } + if (settings.whileBusy === "wait" && pending) releasePending(); // "wait" parks nothing: a waiting message goes back to the box + setBusy(!!busy); for (const el of $("chat").querySelectorAll(".st-msg--assistant")) { const m = messages[+el.dataset.i]; updateAssistant(el, m, !!busy && busy.msg === m); // the element send() holds stays the same while an answer streams } - const share = $("s-share").getAttribute("aria-checked") === "true"; + const share = checked("s-share"); openDrawer(false); if (share || sharedOn) { try { await saveShared(share, settings); - toast("success", "Sampling saved", share ? "Other apps (omp, API clients) use these settings from their next request." - : "Other apps use their own settings again."); + toast("success", tr("drawer.saved", "Chat settings saved"), share ? tr("drawer.savedShared", "Other apps (omp, API clients) use these settings from their next request.") + : tr("drawer.savedOwn", "Other apps use their own settings again.")); } catch (e) { - toast("error", "Saved here, but not for other apps", e.message, 6000); + toast("error", tr("drawer.savedHere", "Saved here, but not for other apps"), e.message, 6000); } return; } - toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : ""); + toast("success", tr("drawer.saved", "Chat settings saved"), settings.temperature === 0 ? tr("drawer.savedGreedy", "Greedy: the same question gives the same answer.") : ""); }; $("sampling-btn").onclick = () => openDrawer(true); $("drawer-close").onclick = () => openDrawer(false); @@ -1360,6 +1486,8 @@ $("lang").onchange = async () => { async function start() { await StrataI18n.setLanguage(urlLang || store.get("lang", "en")); $("lang").value = StrataI18n.lang; + initChats(); + if (settings.chatList) await setChatList(true, false); // the saved-chats list is read before the first draw setBusy(false); renderChat(); const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut) diff --git a/serve/web/chats-ui.js b/serve/web/chats-ui.js new file mode 100644 index 00000000..f15d7869 --- /dev/null +++ b/serve/web/chats-ui.js @@ -0,0 +1,450 @@ +// serve/web/chats-ui.js - the chat history on the page: the saved-chats list, and edit / regenerate / go back / branch / undo. +// One design for the proposals in PRs #1787 (list), #2615 (edit, regenerate, undo) and issue #3823 (rewind asks: here or a branch); +// the pure part is serve/web/history.js, the browser store is serve/web/chatstore.js. +// +// Both are opt-in (Chat settings > Chats) and off by default: off, the page keeps the one chat it always had, with "New chat" +// clearing it (and an Undo). Nothing here goes to the server. +// +// This file is loaded before app.js and uses its globals when its functions run: $, esc, icon, node, toast, store, settings, +// messages, attachments, busy, pending, setBusy, renderChat, renderAttachments, autosize, generateReply, releasePending. +// app.js calls initChats() once, from start(). +"use strict"; + +const H = StrataHistory; +const untitled = () => tr("chat.untitled", "New chat"); +const node = (tag, cls, text) => { + const n = document.createElement(tag); + if (cls) n.className = cls; + if (text != null) n.textContent = text; + return n; +}; + +// ------------------------------------------------------------------ state +let listOn = false; // the saved-chats list is on +let chats = [], chat = null, chatId = ""; +let sidebarQuery = "", sidebarOpen = true; +let undoState = null; // one change, in memory until a new question, another chat or a reload +let panel = null; // the open "Rewind to here" panel or answer editor: {kind, index, el} +const chatStore = StrataChatStore.createChatStore({ + onProblem(kind) { + toast("warn", tr("store.title", "Chat list not saved"), kind === "memory" + ? tr("store.memory", "This browser will not keep the chat list. It stays in memory until you close the page.") + : kind === "quota" ? tr("store.quota", "This browser cannot keep more. The chats on the screen are still there.") + : tr("store.failed", "The chat list could not be saved. The chats on the screen are still there."), 6000); + }, +}); + +// the open chat's messages are the page's `messages`; with the list on they are also the chat's, the same array +function setMessages(next) { + messages = next; + if (chat) chat.messages = next; +} +function saveChat() { + if (!listOn) { store.set("chat", H.cleanMessages(messages)); return; } // off: one chat, as before + chat.time = Date.now(); + chatStore.put(H.cleanChat(chat)); + renderSidebar(); +} +function stillWriting() { toast("warn", tr("busy.stillWriting", "Still writing"), tr("busy.stopFirst", "Stop the answer first.")); } + +// ------------------------------------------------------------------ the saved-chats list (#1787) +// Turning the list on: the chat on the screen becomes the first record. Only when the switch is flipped in this visit: on a page +// load the list is the list, so a fresh chat stays empty and the single chat of before ("strata.chat") is read once, when the +// store is empty. +async function openChats(fromScreen) { + await chatStore.start(); + chats = await chatStore.all(); + if (!chats.length) { + const old = fromScreen ? messages : store.get("chat", []); + if (old.length) { + const c = {...H.newChat(), messages: old, time: old[old.length - 1].time || Date.now()}; + chats = [c]; + chatStore.put(H.cleanChat(c)); // the migrated chat is a record like the others + } + } + chat = chats.find((c) => c.id === store.get("chatId", "")) || chats[0] || H.newChat(); + if (!chats.includes(chat)) chats.push(chat); + chatId = chat.id; + setMessages(chat.messages); +} +async function setChatList(on, fromScreen) { + listOn = on; + $("sidebar").hidden = !on; + $("new-btn").hidden = on; // the list has its own New chat + if (!on) { // off writes the single chat, so a reload shows the chat you were in + if (chat) messages = chat.messages; + chat = null; + store.set("chat", H.cleanMessages(messages)); + renderChat(); + return; + } + await openChats(fromScreen); + renderChat(); +} + +function groupName(key) { + return {today: tr("group.today", "Today"), yesterday: tr("group.yesterday", "Yesterday"), week: tr("group.week", "Previous 7 days"), + month: tr("group.month", "Previous 30 days"), older: tr("group.older", "Older")}[key]; +} +function chatItem(c) { + const t = H.chatTitle(c, untitled()); + const row = node("div", `chat-item${c.id === chatId ? " on" : ""}`); + row.dataset.id = c.id; + row.innerHTML = `<button class="chat-item__title" data-open-chat title="${esc(t)}">${esc(t)}</button>` + + `<span class="chat-item__actions">` + + `<button class="st-btn st-btn--icon" data-rename aria-label="${esc(tr("sidebar.rename", "Rename this chat"))}" title="${esc(tr("sidebar.renameShort", "Rename"))}">${icon("edit")}</button>` + + `<button class="st-btn st-btn--icon" data-delete aria-label="${esc(tr("sidebar.delete", "Delete this chat"))}" title="${esc(tr("sidebar.deleteShort", "Delete"))}">${icon("trash")}</button>` + + `</span>`; + return row; +} +function renderSidebar() { + if (!listOn) return; + // the search reads every chat's message text, so the whole store is in memory after the first load + const list = H.filterChats(chats, sidebarQuery, untitled()); + const box = $("sidebar-list"); + box.innerHTML = ""; + if (!list.length) { + box.appendChild(node("p", "muted small sidebar-empty", sidebarQuery.trim() ? tr("sidebar.noMatch", "No chat matches") : tr("sidebar.none", "No chats yet"))); + } else { + let group = ""; + for (const c of list) { + const g = H.groupKey(c.time); + if (g !== group) { group = g; box.appendChild(node("p", "sidebar-group", groupName(g))); } + box.appendChild(chatItem(c)); + } + } + $("sidebar-foot").textContent = tr("sidebar.foot", {one: "{n} chat · kept in this browser", other: "{n} chats · kept in this browser"}, {n: chats.length}); +} + +function showChat(c) { + clearUndo(); + chat = c; chatId = c.id; messages = c.messages; + store.set("chatId", chatId); + chatStore.put(H.cleanChat(chat)); // renderChat renders the list, so the write here does not render it again + renderChat(); +} +function openChat(id) { + if (busy) { stillWriting(); return; } + const c = chats.find((x) => x.id === id); + if (!c || c === chat) return; + releasePending(); + closePanel(); + showChat(c); +} +function startChat() { + if (busy) { stillWriting(); return; } + if (!messages.length && !chat.parent) { $("input").focus(); return; } // already a fresh chat + releasePending(); + closePanel(); + const prev = chatId, c = H.newChat(); + chats.push(c); + showChat(c); + $("input").focus(); + toast("info", tr("chat.newToast", "New chat"), tr("chat.newToastText", "The one you were in is in the list on the left."), 6000, + {label: tr("undo", "Undo"), run: () => openChat(prev)}); +} +function deleteChat(c) { + if (busy && c.id === chatId) { stillWriting(); return; } + const i = chats.indexOf(c), wasOpen = c.id === chatId; + if (i < 0) return; // the list only ever passes a chat it holds + chats.splice(i, 1); + chatStore.remove(c.id); // the record; the Undo puts it back + if (wasOpen) { + releasePending(); + closePanel(); + const next = chats[0] || H.newChat(); + if (!chats.includes(next)) chats.push(next); + showChat(next); + } else renderSidebar(); + toast("info", tr("chat.deleted", "Chat deleted"), H.chatTitle(c, untitled()), 6000, {label: tr("undo", "Undo"), run: () => { + if (chats.includes(c)) return; // already put back + chats.splice(Math.min(i, chats.length), 0, c); // the display is sorted by time, so only the index matters + if (wasOpen) showChat(c); else { chatStore.put(H.cleanChat(c)); renderSidebar(); } + }}); +} +// rename: the row turns into a field; Enter or a click outside keeps the name, Escape gives it up +function renameChat(row, c) { + const title = row.querySelector(".chat-item__title"); + const input = node("input", "st-input chat-item__input"); + input.value = H.chatTitle(c, untitled()); + input.setAttribute("aria-label", tr("sidebar.nameFor", "Name for this chat")); + title.replaceWith(input); + input.focus(); input.select(); + let done = false; + const finish = (keep) => { + if (done) return; + done = true; + if (keep) { c.title = input.value.trim(); chatStore.put(H.cleanChat(c)); } + renderSidebar(); + }; + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") { e.preventDefault(); finish(true); } + else if (e.key === "Escape") { e.preventDefault(); finish(false); } + }); + input.addEventListener("blur", () => finish(true)); +} +function setSidebar(open, save) { + sidebarOpen = open; + $("sidebar").dataset.open = String(open); + const t = open ? tr("sidebar.collapse", "Collapse the chat list") : tr("sidebar.expand", "Open the chat list"); + $("sidebar-toggle").title = t; $("sidebar-toggle").setAttribute("aria-label", t); + $("sidebar-toggle").setAttribute("aria-expanded", String(open)); + if (save) store.set("sidebar", open); +} + +// a chat that was branched from another says so, and links back while the original is still in the list +function renderParent() { + const bar = $("chat-parent"); + const p = listOn && chat ? chat.parent : null; + bar.hidden = !p; + if (!p) return; + const alive = chats.some((c) => c.id === p.id); + bar.innerHTML = ""; + bar.appendChild(node("span", "muted", tr("branch.from", "Branched from “{title}”", {title: p.title}))); + if (alive) { + const b = node("button", "st-btn st-btn--secondary", tr("branch.open", "Open the original")); + b.type = "button"; + b.onclick = () => openChat(p.id); + bar.appendChild(b); + } +} + +// ------------------------------------------------------------------ edit, regenerate, go back (#2615, #3823) +// Every change keeps the messages it replaced for one Undo: a new question, another chat or a reload ends it. The controls +// are off while an answer is written (stop it first), while something is open, and while a message waits to be sent. +const historyLocked = () => !!busy || !!panel || !!pending; +function clearUndo() { undoState = null; renderUndoBar(); } +function renderUndoBar() { + let el = $("history-undo"); + if (!settings.chatEdit || !undoState) { if (el) el.remove(); return; } + if (!el) { + el = node("div", "history-undo"); + el.id = "history-undo"; + el.setAttribute("role", "status"); + el.innerHTML = "<span></span><button type=\"button\" class=\"st-btn st-btn--secondary\"></button>"; + el.querySelector("button").onclick = undoHistory; + $("composer").before(el); + } + el.querySelector("span").textContent = undoState.text; + el.querySelector("button").textContent = tr("undo", "Undo"); + el.querySelector("button").disabled = historyLocked(); +} +// replace the messages with `next`; text says what happened, for the Undo bar +function commit(next, text) { + undoState = {messages, text, inserted: undefined, draftBefore: null}; + setMessages(next); + saveChat(); + renderChat(); + return undoState; +} +function undoHistory() { + if (!settings.chatEdit || !undoState || historyLocked()) return false; + const u = undoState; + setMessages(u.messages); + if (u.inserted !== undefined && $("input").value === u.inserted && u.draftBefore) { // the box still holds what the rewind put there + $("input").value = u.draftBefore.text; + attachments = u.draftBefore.attachments; + renderAttachments(); autosize(); + } + undoState = null; + saveChat(); + renderChat(); + $("input").focus(); + return true; +} +const hiddenText = (n) => tr("hist.hidden", {one: "{n} message hidden", other: "{n} messages hidden"}, {n}); + +function msgActions(m, i) { + if (!settings.chatEdit) return null; + if (busy && busy.msg === m) return null; // the answer being written has no buttons until it is done + const row = node("div", "history-actions"); + const lock = historyLocked(); + const add = (label, title, run) => { + const b = node("button", "st-btn st-btn--secondary", label); + b.type = "button"; b.title = title; b.disabled = lock; b.onclick = run; + row.appendChild(b); + }; + const last = i === messages.length - 1; + if (m.role === "assistant" || last) { + add(tr("hist.regenerate", "Regenerate"), tr("hist.regenerateTitle", "Ask for a new answer to this question. Tools may run again."), () => regenerateAt(i)); + } + if (m.role === "assistant") add(tr("hist.editAnswer", "Edit answer"), tr("hist.editAnswerTitle", "Correct the answer's text. No request is sent."), () => editAnswerAt(i)); + add(tr("hist.rewind", "Rewind to here"), tr("hist.rewindTitle", "Go back to this point in the chat"), () => openRewind(i)); + return row; +} +// true when a history change may start now (and says why not when it may not) +function historyReady() { + if (!settings.chatEdit) return false; + if (busy) { stillWriting(); return false; } + if (panel) { toast("warn", tr("hist.finishFirst", "Finish what is open first"), tr("hist.finishFirstText", "Save it or press Cancel.")); return false; } + if (pending) { toast("warn", tr("hist.pendingFirst", "A message is waiting"), tr("hist.pendingFirstText", "Send it or take it back first.")); return false; } + return true; +} +// the action rows under the messages follow the switch, without replacing any message (an answer may be streaming into one) +function syncActions() { + for (const el of $("chat").querySelectorAll(".st-msg")) { + const i = +el.dataset.i; + const old = el.querySelector(".history-actions"); + if (old) old.remove(); + const row = messages[i] ? msgActions(messages[i], i) : null; + if (row) el.appendChild(row); + } +} +function closePanel() { + if (!panel) return; + const {el} = panel; + const open = el.querySelector(".history-panel, .history-editor"); + if (open) open.remove(); + delete el.dataset.editing; + panel = null; + setBusy(!!busy); +} +function regenerateAt(i) { + if (!historyReady()) return false; + const plan = H.regenerate(messages, i); + if (!plan) return false; + if (H.lostAttachments(messages[plan.keep.length - 1])) { + toast("warn", tr("hist.lostTitle", "Attachments need to be added again"), tr("hist.lostText", "This browser kept their names, not their contents. Start a new chat and attach them again."), 7000); + return false; + } + commit(plan.keep, tr("hist.replaced", "The answer was replaced")); + return generateReply(); +} + +// edit an answer: its text, in place. The old thinking and tool calls go, and so do the messages after it. +function editAnswerAt(i) { + if (!historyReady() || !messages[i]) return false; + const m = messages[i], el = $("chat").querySelector(`[data-i="${i}"]`); + const later = messages.length - i - 1; + const box = node("div", "history-editor"); + box.innerHTML = "<label></label><textarea class=\"st-input\" rows=\"6\"></textarea><p class=\"muted small\"></p>" + + "<div class=\"history-editor__actions\"><button type=\"button\" class=\"st-btn st-btn--primary\" data-edit-save></button>" + + "<button type=\"button\" class=\"st-btn st-btn--secondary\" data-edit-cancel></button></div>"; + const label = tr("hist.editLabel", "Edit the answer"); + box.querySelector("label").textContent = label; + const input = box.querySelector("textarea"); + input.setAttribute("aria-label", label); + input.value = m.text || ""; + box.querySelector("p").textContent = (later ? tr("hist.editRemoves", {one: "Saving hides the {n} message after it. ", other: "Saving hides the {n} messages after it. "}, {n: later}) : "") + + tr("hist.editNote", "The answer's old thinking and tool calls are removed. No request is sent."); + const save = box.querySelector("[data-edit-save]"); + save.textContent = tr("hist.save", "Save"); + box.querySelector("[data-edit-cancel]").textContent = tr("cancel", "Cancel"); + save.onclick = () => saveAnswerEdit(i, input.value); + box.querySelector("[data-edit-cancel]").onclick = closePanel; + input.onkeydown = (e) => { + if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closePanel(); } + if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && !e.isComposing) { e.preventDefault(); save.click(); } + }; + el.dataset.editing = "true"; + el.appendChild(box); + panel = {kind: "edit", index: i, el}; + setBusy(!!busy); + input.focus(); + input.scrollIntoView({block: "nearest"}); + return true; +} +function saveAnswerEdit(i, text) { + if (busy || !panel || panel.kind !== "edit" || panel.index !== i) return false; + if (typeof text !== "string" || !text.trim()) { toast("warn", tr("hist.empty", "The answer is empty"), tr("hist.emptyText", "Write something before saving.")); return false; } + const plan = H.editAnswer(messages, i, text, tr("hist.edited", "Edited")); + if (!plan) return false; + closePanel(); + commit(plan.keep, plan.hidden ? tr("hist.editedHidden", {one: "Answer edited, {n} message hidden", other: "Answer edited, {n} messages hidden"}, {n: plan.hidden}) + : tr("hist.editedOnly", "Answer edited")); + return true; +} + +// "Rewind to here" asks what to do (#3823): go back HERE (this chat, with an Undo) or BRANCH (a new chat, this one stays) +function openRewind(i) { + if (!historyReady() || !messages[i]) return false; + const m = messages[i], el = $("chat").querySelector(`[data-i="${i}"]`); + const user = m.role === "user"; + const box = node("div", "history-panel"); + box.setAttribute("role", "group"); + box.setAttribute("aria-label", tr("rewind.title", "Rewind to here")); + const choice = (label, text, run, primary) => { + const row = node("div", "history-choice"); + const b = node("button", `st-btn ${primary ? "st-btn--primary" : "st-btn--secondary"}`, label); + b.type = "button"; b.onclick = run; + row.appendChild(b); + row.appendChild(node("span", "muted small", text)); + box.appendChild(row); + }; + choice(user ? tr("rewind.hereUser", "Edit and send again here") : tr("rewind.hereAnswer", "Continue from here"), + user ? tr("rewind.hereUserText", "Hides this message and the ones after it, and puts your message in the box below. Undo brings them back.") + : tr("rewind.hereAnswerText", "Hides the messages after this answer. Undo brings them back."), + () => rewindHere(i), true); + if (listOn) { + choice(tr("rewind.branch", "Branch from here"), + user ? tr("rewind.branchUserText", "Starts a new chat with the messages before this one, and puts your message in its box. This chat stays as it is.") + : tr("rewind.branchAnswerText", "Starts a new chat with the messages up to this answer. This chat stays as it is."), + () => branchHere(i), false); + } else { + box.appendChild(node("p", "muted small", tr("rewind.noList", "To start a new chat from here instead, turn on Saved chats in Chat settings."))); + } + const cancel = node("button", "st-btn st-btn--secondary", tr("cancel", "Cancel")); + cancel.type = "button"; cancel.onclick = closePanel; + box.appendChild(cancel); + box.onkeydown = (e) => { if (e.key === "Escape") { e.preventDefault(); closePanel(); } }; + el.appendChild(box); + panel = {kind: "rewind", index: i, el}; + setBusy(!!busy); + box.querySelector("button").focus(); + box.scrollIntoView({block: "nearest"}); + return true; +} +function fillBox(draft) { + $("input").value = draft.text; + attachments = [...draft.images, ...draft.files]; + renderAttachments(); + autosize(); + if (draft.lost) toast("warn", tr("hist.lostTitle", "Attachments need to be added again"), tr("hist.lostText2", "This browser kept their names, not their contents. Attach them again."), 7000); +} +function rewindHere(i) { + if (!settings.chatEdit || busy || pending || !panel || panel.kind !== "rewind") return false; // called from the open panel + const plan = H.rewind(messages, i); + if (!plan) return false; + const draftBefore = {text: $("input").value, attachments: attachments.slice()}; + closePanel(); + const u = commit(plan.keep, plan.hidden ? hiddenText(plan.hidden) : tr("hist.nothingHidden", "Back at this message")); + if (plan.draft) { u.draftBefore = draftBefore; fillBox(plan.draft); u.inserted = $("input").value; } + $("input").focus(); + return true; +} +function branchHere(i) { + if (!listOn || busy || pending || !panel || panel.kind !== "rewind") return false; + const plan = H.rewind(messages, i); + if (!plan) return false; + closePanel(); + const prev = chatId; + const c = H.branch(chat, plan.keep, plan.keep.length, tr("branch.title", "Branch of {title}", {title: H.chatTitle(chat, untitled())})); + chats.push(c); + showChat(c); + if (plan.draft) fillBox(plan.draft); + $("input").focus(); + toast("info", tr("branch.started", "Branch started"), tr("branch.startedText", "The chat you were in is unchanged, in the list on the left."), 8000, + {label: tr("branch.back", "Back to it"), run: () => openChat(prev)}); + return true; +} + +// ------------------------------------------------------------------ wiring (called once by app.js) +function initChats() { + $("sidebar-toggle").onclick = () => setSidebar(!sidebarOpen, true); + $("sidebar-new").onclick = startChat; + $("sidebar-search").addEventListener("input", () => { sidebarQuery = $("sidebar-search").value; renderSidebar(); }); + $("sidebar-list").addEventListener("click", (e) => { + // a click inside the rename field is caret placement, not a click on the row: the row's handler would open the chat, + // which re-renders the list and takes the field away mid-click + if (e.target.closest(".chat-item__input")) return; + const row = e.target.closest(".chat-item"); + if (!row) return; + const c = chats.find((x) => x.id === row.dataset.id); + if (!c) return; + if (e.target.closest("[data-delete]")) { deleteChat(c); return; } + if (e.target.closest("[data-rename]")) { renameChat(row, c); return; } + openChat(c.id); + }); + // a narrow screen starts with the list closed so the chat has room + setSidebar(store.get("sidebar", true) && !matchMedia("(max-width: 760px)").matches, false); +} diff --git a/serve/web/chatstore.js b/serve/web/chatstore.js new file mode 100644 index 00000000..fc5b682d --- /dev/null +++ b/serve/web/chatstore.js @@ -0,0 +1,66 @@ +// serve/web/chatstore.js - the saved chats, kept in this browser (IndexedDB, database "strata", store "chats", one record per +// chat). Ported from PR #1787 by Scotty-Hudson. A chat can be several megabytes and localStorage holds about 5 MB for the whole +// page, so the chats live here and only small keys (which chat is open, the settings) stay in localStorage. Nothing goes to the +// server: the server has no endpoint for chats and never sees a title. +// +// Where the browser will not keep it (a private window, a blocked or full store) the list lives in memory for the visit, and +// onProblem(kind) tells the page once: "memory" (no store), "quota" (full), "failed" (a write the browser refused). +"use strict"; +(function (root) { + function createChatStore({indexedDB: idb = root.indexedDB, onProblem = () => {}} = {}) { + let db = null, told = false; + const problem = (kind) => { if (!told) { told = true; onProblem(kind); } }; + + function open() { + return new Promise((resolve) => { + let r; + try { r = idb.open("strata", 1); } catch (e) { resolve(null); return; } // private mode: memory only + r.onupgradeneeded = () => { + const d = r.result; + if (!d.objectStoreNames.contains("chats")) d.createObjectStore("chats", {keyPath: "id"}); + }; + // a database already at version 1 does not run onupgradeneeded, so the store may not be there + r.onsuccess = () => resolve(r.result.objectStoreNames.contains("chats") ? r.result : null); + r.onerror = () => resolve(null); + r.onblocked = () => resolve(null); // another tab holds an older version of the database + }); + } + // true when the store is there; false: memory only (and the page has been told) + async function start() { + db = await open(); + if (!db) problem("memory"); + return !!db; + } + function all() { + return new Promise((resolve) => { + if (!db) { resolve([]); return; } + // the result is on the request, not on the store: reading it at oncomplete gives nothing + const req = db.transaction("chats", "readonly").objectStore("chats").getAll(); + req.onsuccess = () => resolve(req.result || []); + req.onerror = () => resolve([]); + req.transaction.onabort = () => resolve([]); // an aborted read fires abort, not error: do not hang + }); + } + // a request that fails because the storage is full aborts the transaction, so it fires abort rather than error + function watch(t) { + const warn = () => problem(t.error && t.error.name === "QuotaExceededError" ? "quota" : "failed"); + t.onerror = warn; t.onabort = warn; + } + function put(chat) { // one record per chat: not the whole list for one message + if (!db) return; + const t = db.transaction("chats", "readwrite"); + t.objectStore("chats").put(chat); + watch(t); + } + function remove(id) { + if (!db) return; + const t = db.transaction("chats", "readwrite"); + t.objectStore("chats").delete(id); + watch(t); + } + return {start, all, put, remove, get usable() { return !!db; }}; + } + const api = {createChatStore}; + root.StrataChatStore = api; + if (typeof module !== "undefined" && module.exports) module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/serve/web/history.js b/serve/web/history.js new file mode 100644 index 00000000..8e5428d5 --- /dev/null +++ b/serve/web/history.js @@ -0,0 +1,90 @@ +// serve/web/history.js - what the chat history does to a list of messages. Pure functions: no page, no storage, no clock of +// their own, so they can be tested alone (serve/test_web_history.js). app.js draws the controls and keeps the state. +// +// One design for five proposals (see docs/DETAILS.md, "The web page"): +// #2615 (uppet) edit your question, correct an answer, regenerate, go back, undo +// #1787 (Scotty-Hudson) saved chats in a list, kept in this browser (IndexedDB), renamed, deleted, searched +// #3823 (xvcezrqpbxtpzblrt) "Rewind to here" asks: edit and send again HERE, or BRANCH into a new chat +// #3550 / #4004 the header's Load / Unload; sending while an answer is being written (app.js) +// A message list is an array of {role, text, time, images, files, reasoning, tools, meta, ...}; an attachment that was read +// in this page has its contents (image url, file text), one that came back from the browser's store has its name only. +"use strict"; +(function (root) { + const TITLE_MAX = 60; + + const newChatId = (now, rnd) => `c${now.toString(36)}${Math.floor(rnd * 1e6).toString(36)}`; + function newChat(now = Date.now(), rnd = Math.random()) { + return {id: newChatId(now, rnd), title: "", time: now, messages: []}; + } + // the name in the list: what the user called it, else the first line of their first question, else the caller's word for "new" + function chatTitle(c, untitled = "New chat") { + if (c.title) return c.title; + const first = (c.messages.find((m) => m.role === "user") || {}).text || ""; + return first.split("\n")[0].trim().slice(0, TITLE_MAX) || untitled; + } + + // pictures and files are kept as their names only: a data URL would fill the browser's storage + const cleanMessages = (list) => list.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})), + files: (m.files || []).map((f) => ({name: f.name}))})); + const cleanChat = (c) => ({...c, messages: cleanMessages(c.messages)}); + + // "today" | "yesterday" | "week" | "month" | "older", by calendar days back from now + function groupKey(t, now = Date.now()) { + const days = Math.floor((now - t) / 86400000); + if (!days) return "today"; + if (days === 1) return "yesterday"; + if (days <= 7) return "week"; + if (days <= 30) return "month"; + return "older"; + } + // the list for a search box: titles and message text, newest first + function filterChats(chats, query, untitled) { + const q = String(query || "").trim().toLowerCase(); + return chats.filter((c) => !q || chatTitle(c, untitled).toLowerCase().includes(q) || + c.messages.some((m) => (m.text || "").toLowerCase().includes(q))) + .sort((a, b) => b.time - a.time); + } + + // Can a user turn be sent again as it was? A picture or file that came back from the browser's store has only its name. + const lostAttachments = (m) => ((m.images || []).filter((x) => !x.url).length + (m.files || []).filter((x) => typeof x.text !== "string").length); + // what goes back into the message box when a user turn is edited: its text and the attachments that still have contents + function draftOf(m) { + return {text: m.text || "", + images: (m.images || []).filter((x) => x.url).map((x) => ({kind: "image", name: x.name, url: x.url})), + files: (m.files || []).filter((x) => typeof x.text === "string").map((x) => ({kind: "file", name: x.name, text: x.text})), + lost: lostAttachments(m)}; + } + + // "Rewind to here" on message i. A user turn goes back into the box and leaves the list; an answer stays and the list ends + // with it. {keep, draft, hidden}: the messages that stay, the draft for the box (null for an answer), how many are hidden. + function rewind(messages, i) { + const m = messages[i]; + if (!m) return null; + if (m.role === "user") return {keep: messages.slice(0, i), draft: draftOf(m), hidden: messages.length - i}; + return {keep: messages.slice(0, i + 1), draft: null, hidden: messages.length - i - 1}; + } + // Regenerate the answer at i (or the last user turn): the list up to and including the user turn before it + function regenerate(messages, i) { + let u = i; + while (u >= 0 && messages[u] && messages[u].role !== "user") u--; + if (u < 0 || !messages[u]) return null; + return {keep: messages.slice(0, u + 1), hidden: messages.length - u - 1}; + } + // Edit the answer at i: its text replaced, its thinking, tool calls, error and stats dropped, everything after it hidden + function editAnswer(messages, i, text, meta = "Edited") { + const m = messages[i]; + if (!m || m.role !== "assistant") return null; + return {keep: [...messages.slice(0, i), {role: "assistant", text, time: m.time, meta}], hidden: messages.length - i - 1}; + } + // A branch: a new chat that starts with a copy of the first `end` messages. The original is not touched. The title says + // where it came from and stays: the first question does not rename it (the first-message case of #3823). + function branch(chat, messages, end, title, now = Date.now(), rnd = Math.random()) { + const copy = JSON.parse(JSON.stringify(messages.slice(0, end))); + return {...newChat(now, rnd), title, parent: {id: chat.id, title: chatTitle(chat)}, messages: copy}; + } + + const api = {TITLE_MAX, newChat, chatTitle, cleanMessages, cleanChat, groupKey, filterChats, lostAttachments, draftOf, rewind, + regenerate, editAnswer, branch}; + root.StrataHistory = api; + if (typeof module !== "undefined" && module.exports) module.exports = api; +})(typeof globalThis !== "undefined" ? globalThis : this); diff --git a/serve/web/index.html b/serve/web/index.html index be6f6d36..0511153d 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -41,36 +41,54 @@ <main> <!-- ============================ Chat ============================ --> <section class="view view--chat" id="view-chat" role="tabpanel" aria-labelledby="tab-btn-chat"> - <div class="chat-scroll" id="chat-scroll"> - <div class="chat" id="chat"> - <div class="chat-empty" id="chat-empty"> - <div class="chat-empty__title">Ask anything</div> - <div class="chat-empty__sub" id="chat-empty-sub">The model runs on this PC. Nothing leaves it.</div> + <!-- the chats kept in this browser (Chat settings > Chats): the open one is the chat on the right --> + <aside class="chat-sidebar" id="sidebar" data-open="true" aria-label="Chats" data-i18n-label="sidebar.title" hidden> + <div class="sidebar-head"> + <button class="st-btn st-btn--icon" id="sidebar-toggle" type="button" title="Collapse the chat list" aria-label="Collapse the chat list" aria-expanded="true"> + <svg class="st-icon"><use href="web/sprite.svg#i-chevron"/></svg></button> + <span class="card-title sidebar-title" data-i18n="sidebar.title">Chats</span> + <button class="st-btn st-btn--icon" id="sidebar-new" type="button" title="New chat" aria-label="New chat" data-i18n-title="chat.new" data-i18n-label="chat.new"> + <svg class="st-icon"><use href="web/sprite.svg#i-new-chat"/></svg></button> + </div> + <input class="st-input sidebar-search" id="sidebar-search" type="search" placeholder="Search chats" + autocomplete="off" aria-label="Search chats" data-i18n-placeholder="sidebar.search" data-i18n-label="sidebar.search"> + <div class="sidebar-list" id="sidebar-list"></div> + <p class="muted small sidebar-foot" id="sidebar-foot"></p> + </aside> + <div class="chat-main"> + <div class="chat-parent" id="chat-parent" hidden></div> + <div class="chat-scroll" id="chat-scroll"> + <div class="chat" id="chat"> + <div class="chat-empty" id="chat-empty"> + <div class="chat-empty__title" data-i18n="chat.empty">Ask anything</div> + <div class="chat-empty__sub" id="chat-empty-sub" data-i18n="chat.emptySub">The model runs on this PC. Nothing leaves it.</div> + </div> </div> </div> - </div> - <div class="composer-wrap"> - <form class="st-composer" id="composer"> - <div class="attachments" id="attachments" hidden></div> - <textarea id="input" rows="2" placeholder="Ask anything…" aria-label="Message"></textarea> - <div class="st-composer__bar"> - <button type="button" class="st-btn st-btn--icon" id="attach-btn" title="Attach a text file (or drop it here)" aria-label="Attach a file"> - <svg class="st-icon"><use href="web/sprite.svg#i-attach"/></svg></button> - <input type="file" id="file" multiple hidden> - <button type="button" class="st-btn st-btn--icon" id="new-btn" title="New chat" aria-label="New chat"> - <svg class="st-icon"><use href="web/sprite.svg#i-new-chat"/></svg></button> - <button type="button" class="st-btn st-btn--icon" id="export-btn" title="Save this chat as Markdown" aria-label="Save this chat"> - <svg class="st-icon"><use href="web/sprite.svg#i-download"/></svg></button> - <button type="button" class="st-btn st-btn--icon" id="sampling-btn" title="Sampling and thinking" aria-label="Sampling and thinking"> - <svg class="st-icon"><use href="web/sprite.svg#i-settings"/></svg></button> - <span class="spacer"></span> - <span class="composer-hint" id="composer-hint"></span> - <button type="button" class="st-btn st-btn--secondary" id="stop-btn" hidden> - <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-stop"/></svg>Stop</button> - <button type="submit" class="st-btn st-btn--primary st-btn--send" id="send-btn" aria-label="Send"> - <svg class="st-icon"><use href="web/sprite.svg#i-send"/></svg></button> - </div> - </form> + <div class="composer-wrap"> + <form class="st-composer" id="composer"> + <div class="attachments" id="attachments" hidden></div> + <textarea id="input" rows="2" placeholder="Ask anything…" aria-label="Message" data-i18n-placeholder="composer.placeholder" data-i18n-label="composer.message"></textarea> + <div class="st-composer__bar"> + <button type="button" class="st-btn st-btn--icon" id="attach-btn" title="Attach a text file (or drop it here)" aria-label="Attach a file" data-i18n-label="composer.attach"> + <svg class="st-icon"><use href="web/sprite.svg#i-attach"/></svg></button> + <input type="file" id="file" multiple hidden> + <button type="button" class="st-btn st-btn--icon" id="new-btn" title="New chat" aria-label="New chat" data-i18n-title="chat.new" data-i18n-label="chat.new"> + <svg class="st-icon"><use href="web/sprite.svg#i-new-chat"/></svg></button> + <button type="button" class="st-btn st-btn--icon" id="export-btn" title="Save this chat as Markdown" aria-label="Save this chat" data-i18n-title="composer.save" data-i18n-label="composer.saveLabel"> + <svg class="st-icon"><use href="web/sprite.svg#i-download"/></svg></button> + <button type="button" class="st-btn st-btn--secondary chat-settings-button" id="sampling-btn" title="Chat settings" aria-label="Chat settings" data-i18n-title="drawer.title" data-i18n-label="drawer.title"> + <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-settings"/></svg> + <span class="chat-settings-label" data-i18n="drawer.title">Chat settings</span><span class="chat-settings-short" aria-hidden="true" data-i18n="drawer.short">Settings</span></button> + <span class="spacer"></span> + <span class="composer-hint" id="composer-hint"></span> + <button type="button" class="st-btn st-btn--secondary" id="stop-btn" hidden> + <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-stop"/></svg><span data-i18n="composer.stop">Stop</span></button> + <button type="submit" class="st-btn st-btn--primary st-btn--send" id="send-btn" aria-label="Send" data-i18n-label="composer.send"> + <svg class="st-icon"><use href="web/sprite.svg#i-send"/></svg></button> + </div> + </form> + </div> </div> </section> @@ -216,23 +234,23 @@ </section> </main> -<!-- ============================ Sampling drawer ============================ --> -<aside class="st-drawer" id="drawer" data-open="false" aria-label="Sampling and thinking" aria-hidden="true"> - <div class="st-drawer__head"><span class="card-title">Sampling</span> - <button class="st-btn st-btn--icon" id="drawer-close" aria-label="Close"> +<!-- ============================ Chat settings drawer ============================ --> +<aside class="st-drawer" id="drawer" data-open="false" aria-label="Chat settings" data-i18n-label="drawer.title" aria-hidden="true"> + <div class="st-drawer__head"><span class="card-title" data-i18n="drawer.title">Chat settings</span> + <button class="st-btn st-btn--icon" id="drawer-close" aria-label="Close" data-i18n-label="close"> <svg class="st-icon"><use href="web/sprite.svg#i-chevron"/></svg></button></div> <div class="st-drawer__body"> <div class="st-field"> - <label class="st-label" for="s-thinking">Thinking <output id="o-thinking"></output></label> - <div class="seg" id="s-thinking" role="radiogroup" aria-label="Thinking"> - <button type="button" role="radio" data-v="none">Off</button><button type="button" role="radio" data-v="low">Low</button> - <button type="button" role="radio" data-v="medium">Medium</button><button type="button" role="radio" data-v="high">High</button> + <label class="st-label" for="s-thinking"><span data-i18n="drawer.thinking">Thinking</span> <output id="o-thinking"></output></label> + <div class="seg" id="s-thinking" role="radiogroup" aria-label="Thinking" data-i18n-label="drawer.thinking"> + <button type="button" role="radio" data-v="none" data-i18n="drawer.off">Off</button><button type="button" role="radio" data-v="low" data-i18n="drawer.low">Low</button> + <button type="button" role="radio" data-v="medium" data-i18n="drawer.medium">Medium</button><button type="button" role="radio" data-v="high" data-i18n="drawer.high">High</button> </div> </div> <div class="st-field"> - <label class="st-label" for="s-temp">Temperature <output id="o-temp"></output></label> + <label class="st-label" for="s-temp"><span data-i18n="drawer.temperature">Temperature</span> <output id="o-temp"></output></label> <input class="st-slider" type="range" id="s-temp" min="0" max="1.5" step="0.05"> - <span class="muted small">0 = always the most likely word (exact, repeatable)</span> + <span class="muted small" data-i18n="drawer.temperatureNote">0 = always the most likely word (exact, repeatable)</span> </div> <div class="st-field"> <label class="st-label" for="s-topp">Top-p <output id="o-topp"></output></label> @@ -243,30 +261,49 @@ <input class="st-slider" type="range" id="s-topk" min="1" max="64" step="1"> </div> <div class="st-field"> - <label class="st-label" for="s-max">Max tokens <output>empty = until done</output></label> - <input class="st-input" id="s-max" type="number" min="1" step="1" placeholder="Until done"> + <label class="st-label" for="s-max"><span data-i18n="drawer.maxTokens">Max tokens</span> <output data-i18n="drawer.maxTokensNote">empty = until done</output></label> + <input class="st-input" id="s-max" type="number" min="1" step="1" placeholder="Until done" data-i18n-placeholder="drawer.untilDone"> </div> <div class="st-field"> - <label class="st-label" for="s-seed">Seed <output>empty = random</output></label> - <input class="st-input" id="s-seed" type="number" min="1" step="1" placeholder="Random"> + <label class="st-label" for="s-seed"><span data-i18n="drawer.seed">Seed</span> <output data-i18n="drawer.seedNote">empty = random</output></label> + <input class="st-input" id="s-seed" type="number" min="1" step="1" placeholder="Random" data-i18n-placeholder="drawer.random"> </div> + <div class="toggle-row"><span><span data-i18n="drawer.showThinking">Show thinking</span><br><span class="muted small" data-i18n="drawer.showThinkingNote">expanded while it streams</span></span> + <button class="st-toggle" id="s-show" role="switch" aria-checked="true" aria-label="Show thinking" data-i18n-label="drawer.showThinking"></button></div> <div class="toggle-row"><span><span data-i18n="drawer.math">Render math</span><br><span class="muted small" data-i18n="drawer.mathNote">draw equations in answers as formulas (works offline)</span></span> <button class="st-toggle" id="s-math" role="switch" aria-checked="false" aria-label="Render math" data-i18n-label="drawer.math"></button></div> - <div class="toggle-row"><span>Show thinking<br><span class="muted small">expanded while it streams</span></span> - <button class="st-toggle" id="s-show" role="switch" aria-checked="true" aria-label="Show thinking"></button></div> - <div class="toggle-row" id="mcp-row" hidden><span>Use tools from MCP servers<br><span class="muted small" + <div class="toggle-row" id="mcp-row" hidden><span><span data-i18n="drawer.mcp">Use tools from MCP servers</span><br><span class="muted small" id="mcp-row-sub">the model may call them while it answers</span></span> - <button class="st-toggle" id="s-mcp" role="switch" aria-checked="true" aria-label="Use tools from MCP servers"></button></div> + <button class="st-toggle" id="s-mcp" role="switch" aria-checked="true" aria-label="Use tools from MCP servers" data-i18n-label="drawer.mcp"></button></div> <div class="toggle-row" id="esp-row" hidden><span>Experimental speed projection<br><span class="muted small">the engine's control vector; off = the stock model. Switching reads the chat again once</span></span> <button class="st-toggle" id="s-esp" role="switch" aria-checked="true" aria-label="Experimental speed projection"></button></div> - <div class="toggle-row"><span>Use for other apps too<br><span class="muted small">omp and other API clients get - these settings for anything they don't set themselves</span></span> - <button class="st-toggle" id="s-share" role="switch" aria-checked="false" aria-label="Use for other apps too"></button></div> + <div class="toggle-row"><span><span data-i18n="drawer.share">Use for other apps too</span><br><span class="muted small" data-i18n="drawer.shareNote">omp and other API clients get + these settings for anything they do not set themselves</span></span> + <button class="st-toggle" id="s-share" role="switch" aria-checked="false" aria-label="Use for other apps too" data-i18n-label="drawer.share"></button></div> + + <div class="drawer-group" role="group" aria-labelledby="g-chats"> + <h3 class="drawer-group__title" id="g-chats" data-i18n="drawer.chats">Chats</h3> + <div class="toggle-row"><span><span data-i18n="drawer.list">Saved chats list</span><br><span class="muted small" + data-i18n="drawer.listNote">keeps every chat in a list on the left, in this browser only. Off: one chat, as before</span></span> + <button class="st-toggle" id="s-list" role="switch" aria-checked="false" aria-label="Saved chats list" data-i18n-label="drawer.list"></button></div> + <div class="toggle-row"><span><span data-i18n="drawer.edit">Edit and rewind messages</span><br><span class="muted small" + data-i18n="drawer.editNote">edit an answer, ask for a new one, or go back to an earlier message (with an Undo)</span></span> + <button class="st-toggle" id="s-edit" role="switch" aria-checked="false" aria-label="Edit and rewind messages" data-i18n-label="drawer.edit"></button></div> + <div class="st-field"> + <label class="st-label" for="s-busy"><span data-i18n="drawer.busy">When you send while it is answering</span></label> + <div class="seg seg--3" id="s-busy" role="radiogroup" aria-label="When you send while it is answering" data-i18n-label="drawer.busy"> + <button type="button" role="radio" data-v="wait" data-i18n="drawer.busyWait">Wait</button><button type="button" role="radio" data-v="queue" data-i18n="drawer.busyQueue">Send after</button> + <button type="button" role="radio" data-v="interject" data-i18n="drawer.busyInterject">Interrupt</button> + </div> + <span class="muted small" id="o-busy"></span> + </div> + </div> + <div class="drawer-actions"> - <button class="st-btn st-btn--secondary" id="s-reset" type="button">Reset</button> - <button class="st-btn st-btn--primary" id="s-apply" type="button">Apply</button> + <button class="st-btn st-btn--secondary" id="s-reset" type="button" data-i18n="drawer.reset">Reset</button> + <button class="st-btn st-btn--primary" id="s-apply" type="button" data-i18n="drawer.apply">Apply</button> </div> </div> </aside> @@ -276,6 +313,9 @@ <script src="web/preview.js"></script> <script src="web/math.js"></script> <script src="web/math-adapter.js"></script> +<script src="web/history.js"></script> +<script src="web/chatstore.js"></script> +<script src="web/chats-ui.js"></script> <script src="web/app.js"></script> </body> </html> diff --git a/serve/web/sprite.svg b/serve/web/sprite.svg index 598f6234..1298c13e 100644 --- a/serve/web/sprite.svg +++ b/serve/web/sprite.svg @@ -21,6 +21,7 @@ <symbol id="i-check" viewBox="0 0 24 24" fill="none"><path d="M4.5 12.5L9.5 17.5L19.5 6.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> <symbol id="i-trash" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M5 6L6 19C6.08 20.1 7 21 8.1 21H15.9C17 21 17.92 20.1 18 19L19 6H5Z" fill="currentColor"></path><path d="M5 6L6 19C6.08 20.1 7 21 8.1 21H15.9C17 21 17.92 20.1 18 19L19 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M3 6H21" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M9 6V4.5C9 3.672 9.672 3 10.5 3H13.5C14.328 3 15 3.672 15 4.5V6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10 10.5V16.5M14 10.5V16.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> <symbol id="i-new-chat" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M21 11.5C21 16.194 16.971 20 12 20C10.8 20 9.65 19.78 8.6 19.37L4 20.5L5.2 16.8C3.83 15.34 3 13.5 3 11.5C3 6.806 7.029 3 12 3C16.971 3 21 6.806 21 11.5Z" fill="currentColor"></path><path d="M21 11.5C21 16.194 16.971 20 12 20C10.8 20 9.65 19.78 8.6 19.37L4 20.5L5.2 16.8C3.83 15.34 3 13.5 3 11.5C3 6.806 7.029 3 12 3C16.971 3 21 6.806 21 11.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M12 8.5V14.5M9 11.5H15" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> +<symbol id="i-edit" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M17.66 6.34L19.07 7.75A2 2 0 0 1 19.07 10.57L7.5 22.14L3.86 22.97L4.69 19.33L16.26 7.76A2 2 0 0 1 17.66 6.34Z" fill="currentColor"></path><path d="M17.66 6.34L19.07 7.75A2 2 0 0 1 19.07 10.57L7.5 22.14L3.86 22.97L4.69 19.33L16.26 7.76A2 2 0 0 1 17.66 6.34Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M14.83 9.17L16.24 10.58" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> <symbol id="i-chevron" viewBox="0 0 24 24" fill="none"><path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> <symbol id="i-thinking" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M12 2.5C8.41 2.5 5.5 5.41 5.5 9C5.5 11.3 6.7 13.3 8.5 14.5V16.5C8.5 17.05 8.95 17.5 9.5 17.5H14.5C15.05 17.5 15.5 17.05 15.5 16.5V14.5C17.3 13.3 18.5 11.3 18.5 9C18.5 5.41 15.59 2.5 12 2.5Z" fill="currentColor"></path><path d="M12 2.5C8.41 2.5 5.5 5.41 5.5 9C5.5 11.3 6.7 13.3 8.5 14.5V16.5C8.5 17.05 8.95 17.5 9.5 17.5H14.5C15.05 17.5 15.5 17.05 15.5 16.5V14.5C17.3 13.3 18.5 11.3 18.5 9C18.5 5.41 15.59 2.5 12 2.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M9.5 20.5H14.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> <symbol id="i-tool" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M14.7 6.3A1 1 0 0 0 14.7 7.7L16.3 9.3A1 1 0 0 0 17.7 9.3L21.47 5.53A6 6 0 0 1 13.53 13.47L6.62 20.38A2.12 2.12 0 0 1 3.62 17.38L10.53 10.47A6 6 0 0 1 18.47 2.53L14.71 6.29Z" fill="currentColor"></path><path d="M14.7 6.3A1 1 0 0 0 14.7 7.7L16.3 9.3A1 1 0 0 0 17.7 9.3L21.47 5.53A6 6 0 0 1 13.53 13.47L6.62 20.38A2.12 2.12 0 0 1 3.62 17.38L10.53 10.47A6 6 0 0 1 18.47 2.53L14.71 6.29Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol> diff --git a/tools/webtest/browser_test.mjs b/tools/webtest/browser_test.mjs index 5949db2e..9b2ec42f 100644 --- a/tools/webtest/browser_test.mjs +++ b/tools/webtest/browser_test.mjs @@ -253,6 +253,354 @@ test("load/unload: the header fits a phone", async ({ browser, mock }) => { } }); +// ------------------------------------------------------------------------------------------------ chat history (#1787, #2615, #3823, #4004) +const on = (extra = {}) => ({ sampling: { chatList: true, chatEdit: true, ...extra } }); +const texts = (page) => page.evaluate(() => messages.map((m) => m.role[0] + ":" + (m.text || ""))); +const sidebarTitles = (page) => page.$$eval(".chat-item__title", (e) => e.map((x) => x.textContent)); +const ask = async (page, text) => { await say(page, text); await idle(page); await sleep(80); }; +const requestTexts = (mock, n = -1) => mock.state.requests.at(n).messages.map((m) => m.role[0] + ":" + (typeof m.content === "string" ? m.content : m.content[0].text)); +const clickAction = async (page, i, label) => { + const handle = await page.evaluateHandle((n, text) => [...document.querySelector(`[data-i="${n}"] .history-actions`).querySelectorAll("button")].find((b) => b.textContent === text), i, label); + await handle.asElement().click(); +}; +const reset = (mock) => { mock.state.requests.length = 0; mock.state.aborted = 0; mock.state.completed = 0; mock.state.answers = 0; }; +const htest = (name, fn) => test(name, async (ctx) => { reset(ctx.mock); await fn(ctx); }); +// (a toast sits over the drawer's Apply button for a few seconds: clear it, as a person would wait for it) +const openSettings = async (page) => { await page.click("#sampling-btn"); await page.waitForSelector('#drawer[data-open="true"]'); await sleep(320); await page.evaluate(() => document.querySelectorAll(".st-toast").forEach((t) => t.remove())); }; + +htest("history: everything is off by default - the page is the page it was", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock); + assert.equal(await page.$eval("#sidebar", (e) => e.hidden), true, "no list"); + assert.equal(await page.$eval("#new-btn", (e) => e.hidden), false, "the New chat button is there"); + await ask(page, "hello"); + assert.equal(await page.$$eval(".history-actions", (e) => e.length), 0, "no edit buttons"); + assert.deepEqual(mock.state.requests[0].messages, [{ role: "user", content: "hello" }]); + assert.equal(Object.keys(mock.state.requests[0]).sort().join(), "messages,model,reasoning_effort,stream", "the request has no new field"); + assert.equal(await page.evaluate(() => settings.whileBusy), "wait"); + const dbs = await page.evaluate(async () => (indexedDB.databases ? (await indexedDB.databases()).map((d) => d.name) : [])); + assert.ok(!dbs.includes("strata"), "the browser store is never opened while the list is off"); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("strata.chat")).length), 2, "one chat in localStorage, as before"); + // Enter while an answer is being written does nothing + await say(page, "#hold one"); + await page.waitForFunction(() => busy !== null); + await page.type("#input", "second"); + await page.keyboard.press("Enter"); + await sleep(300); + assert.equal(await page.$eval("#input", (e) => e.value), "second", "the text stays in the box"); + assert.equal(await page.$("#pending"), null); + assert.equal(await page.$eval("#send-btn", (b) => b.disabled), true); + assert.equal(mock.state.requests.length, 2); + await page.click("#stop-btn"); + await idle(page); + await page.close(); +}); + +htest("list: chats are kept, found, renamed, deleted with an Undo, and survive a reload", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: on() }); + assert.equal(await page.$eval("#sidebar", (e) => e.hidden), false); + assert.equal(await page.$eval("#new-btn", (e) => e.hidden), true, "the list has its own New chat"); + await ask(page, "alpha question"); + await page.click("#sidebar-new"); + await ask(page, "beta question"); + assert.deepEqual((await sidebarTitles(page)).sort(), ["alpha question", "beta question"]); + assert.equal(await page.$$eval(".sidebar-group", (e) => e.map((x) => x.textContent).join()), "Today"); + assert.equal(await page.$eval("#sidebar-foot", (e) => e.textContent), "2 chats · kept in this browser"); + // search: titles and message text + await page.type("#sidebar-search", "alpha"); + assert.deepEqual(await sidebarTitles(page), ["alpha question"]); + await page.$eval("#sidebar-search", (e) => { e.value = "Mock answer"; e.dispatchEvent(new Event("input")); }); + assert.equal((await sidebarTitles(page)).length, 2, "the search reads the answers too"); + await page.$eval("#sidebar-search", (e) => { e.value = ""; e.dispatchEvent(new Event("input")); }); + // rename: Enter keeps, Escape gives up, a click inside the field does not end it + const row = async (title) => (await page.evaluateHandle((t) => [...document.querySelectorAll(".chat-item")].find((r) => r.querySelector(".chat-item__title") && r.querySelector(".chat-item__title").textContent === t), title)).asElement(); + await (await row("alpha question")).hover(); + await (await (await row("alpha question")).$("[data-rename]")).click(); + await page.click(".chat-item__input"); // a click in the field + assert.ok(await page.$(".chat-item__input"), "the rename is still open"); + await page.keyboard.down("Control"); await page.keyboard.press("a"); await page.keyboard.up("Control"); + await page.keyboard.type("Garden plan"); + await page.keyboard.press("Enter"); + assert.ok((await sidebarTitles(page)).includes("Garden plan")); + // delete (not the open one), then Undo + await (await row("Garden plan")).hover(); + await (await (await row("Garden plan")).$("[data-delete]")).click(); + assert.deepEqual(await sidebarTitles(page), ["beta question"]); + await page.evaluate(() => { const b = document.querySelectorAll(".st-toast .st-btn"); b[b.length - 1].click(); }); + await sleep(100); + assert.deepEqual((await sidebarTitles(page)).sort(), ["Garden plan", "beta question"], "the chat is back"); + // a reload: both chats, the open one is the same, the answers are there + await page.reload({ waitUntil: "networkidle0" }); + assert.deepEqual((await sidebarTitles(page)).sort(), ["Garden plan", "beta question"]); + assert.deepEqual(await texts(page), ["u:beta question", "a:Mock answer 2."]); + await (await row("Garden plan")).click(); + assert.deepEqual(await texts(page), ["u:alpha question", "a:Mock answer 1."]); + assert.deepEqual(page.errors, []); + await page.close(); +}); + +htest("list: switching it on keeps the chat on the screen; off keeps it as the single chat", async ({ browser, mock }) => { + const page = await openPage(browser, mock); + await ask(page, "before the list"); + await openSettings(page); + await page.click("#s-list"); + await page.click("#s-apply"); + await page.waitForFunction(() => document.querySelectorAll(".chat-item").length === 1); + assert.deepEqual(await sidebarTitles(page), ["before the list"], "the chat on the screen is the first one in the list"); + await page.click("#sidebar-new"); + await openSettings(page); + await page.click("#s-list"); + await page.click("#s-apply"); + await page.waitForFunction(() => document.getElementById("sidebar").hidden); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("strata.chat")).length), 0, "the empty chat you were in is the single chat now"); + await page.close(); +}); + +htest("rewind: edit and send again here, with an Undo that brings everything back", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on() }); + await ask(page, "q1"); await ask(page, "q2"); + await page.type("#input", "a draft"); + await clickAction(page, 2, "Rewind to here"); + assert.equal(await page.$$eval(".history-panel .st-btn", (e) => e.map((x) => x.textContent).join("|")), "Edit and send again here|Branch from here|Cancel"); + assert.equal(await page.$eval("#send-btn", (b) => b.disabled), true, "nothing can be sent while the panel is open"); + await page.$eval(".history-panel .st-btn--primary", (b) => b.click()); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1."]); + assert.equal(await page.$eval("#input", (e) => e.value), "q2", "the question is in the box"); + assert.equal(await page.$eval("#history-undo span", (e) => e.textContent), "2 messages hidden"); + await page.click("#history-undo button"); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 2."]); + assert.equal(await page.$eval("#input", (e) => e.value), "a draft", "the draft that was in the box is back"); + assert.equal(await page.$("#history-undo"), null); + // go back again, change the question, send: the request has only what is left, and the Undo is gone + await clickAction(page, 2, "Rewind to here"); + await page.$eval(".history-panel .st-btn--primary", (b) => b.click()); + await page.click("#input"); + await page.keyboard.down("Control"); await page.keyboard.press("a"); await page.keyboard.up("Control"); + await page.keyboard.type("q2 better"); + await page.keyboard.press("Enter"); + await idle(page); + assert.deepEqual(requestTexts(mock), ["u:q1", "a:Mock answer 1.", "u:q2 better"]); + assert.equal(await page.$("#history-undo"), null, "a new question ends the Undo"); + await page.close(); +}); + +htest("rewind: an answer - continue from here; the box is untouched", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: on() }); + await ask(page, "q1"); await ask(page, "q2"); + await page.type("#input", "keep me"); + await clickAction(page, 1, "Rewind to here"); + assert.equal(await page.$eval(".history-panel .st-btn--primary", (b) => b.textContent), "Continue from here"); + await page.$eval(".history-panel .st-btn--primary", (b) => b.click()); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1."]); + assert.equal(await page.$eval("#input", (e) => e.value), "keep me"); + await page.click("#history-undo button"); + assert.equal((await texts(page)).length, 4); + await page.close(); +}); + +htest("rewind: with the list off there is no branch, only a hint", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: { sampling: { chatEdit: true } } }); + await ask(page, "q1"); + await clickAction(page, 0, "Rewind to here"); + assert.equal(await page.$$eval(".history-panel .st-btn", (e) => e.map((x) => x.textContent).join("|")), "Edit and send again here|Cancel"); + assert.match(await page.$eval(".history-panel p", (e) => e.textContent), /turn on Saved chats/); + await page.keyboard.press("Escape"); + assert.equal(await page.$(".history-panel"), null, "Escape closes it"); + await page.close(); +}); + +htest("branch: a new chat from here; the original stays; the title stays; a link back", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: on() }); + await ask(page, "q1"); await ask(page, "q2"); + await clickAction(page, 2, "Rewind to here"); + await page.evaluate(() => [...document.querySelectorAll(".history-panel .st-btn")].find((b) => b.textContent === "Branch from here").click()); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1."]); + assert.equal(await page.$eval("#input", (e) => e.value), "q2"); + assert.equal(await page.$eval("#chat-parent", (e) => e.textContent), "Branched from “q1”Open the original"); + assert.deepEqual((await sidebarTitles(page)).sort(), ["Branch of q1", "q1"]); + await ask(page, "a new second question"); + assert.deepEqual((await sidebarTitles(page)).sort(), ["Branch of q1", "q1"], "sending does not rename the branch"); + await page.click("#chat-parent .st-btn"); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 2."], "the original is untouched"); + assert.equal(await page.$("#chat-parent:not([hidden])"), null); + // a branch at the very first message: an empty chat that keeps its name after the first send + await clickAction(page, 0, "Rewind to here"); + await page.evaluate(() => [...document.querySelectorAll(".history-panel .st-btn")].find((b) => b.textContent === "Branch from here").click()); + assert.deepEqual(await texts(page), []); + assert.equal(await page.$eval("#input", (e) => e.value), "q1"); + await ask(page, "something else entirely"); + assert.ok((await sidebarTitles(page)).filter((t) => t === "Branch of q1").length === 2, "both branches keep their names: " + (await sidebarTitles(page))); + await page.close(); +}); + +htest("regenerate: a new answer to the same question; Undo brings the old one back", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on() }); + await ask(page, "q1"); await ask(page, "q2"); + await clickAction(page, 3, "Regenerate"); + await idle(page); + assert.deepEqual(requestTexts(mock), ["u:q1", "a:Mock answer 1.", "u:q2"], "the old answer is not sent"); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 3."]); + await page.click("#history-undo button"); + assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 2."]); + await page.close(); +}); + +htest("edit answer: the text is saved, thinking and tools go, later messages are hidden, no request", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on() }); + await ask(page, "#think q1"); await ask(page, "q2"); + const before = mock.state.requests.length; + await clickAction(page, 1, "Edit answer"); + assert.match(await page.$eval(".history-editor p", (e) => e.textContent), /Saving hides the 2 messages after it\./); + await page.$eval(".history-editor textarea", (e) => { e.value = "The corrected answer"; }); + await page.click("[data-edit-save]"); + assert.deepEqual(await texts(page), ["u:#think q1", "a:The corrected answer"]); + assert.equal(mock.state.requests.length, before, "no request"); + assert.equal(await page.evaluate(() => messages[1].reasoning), undefined, "the old thinking is gone"); + assert.equal(await page.$eval("#history-undo span", (e) => e.textContent), "Answer edited, 2 messages hidden"); + await ask(page, "q3"); + assert.deepEqual(requestTexts(mock), ["u:#think q1", "a:The corrected answer", "u:q3"], "the corrected text is what the model reads"); + await page.close(); +}); + +htest("history: the buttons wait while an answer is written, and while something is open", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: on() }); + await ask(page, "q1"); + await say(page, "#hold q2"); + await page.waitForFunction(() => busy !== null); + assert.equal(await page.$$eval(".history-actions button:not([disabled])", (e) => e.length), 0); + assert.equal(await page.$eval("#s-list", (e) => e.disabled), true, "the list switch waits too"); + await page.click("#stop-btn"); + await idle(page); + assert.ok((await page.$$eval(".history-actions button:not([disabled])", (e) => e.length)) > 0); + await clickAction(page, 1, "Edit answer"); + assert.equal(await page.$$eval(".history-actions button:not([disabled])", (e) => e.length), 0, "while an editor is open"); + await page.keyboard.press("Escape"); + assert.equal(await page.$(".history-editor"), null); + await page.close(); +}); + +htest("history: an attachment that was only kept by name is not sent as if it were whole", async ({ browser, mock }) => { + reset(mock); + const lost = [{ role: "user", text: "see file", time: 1, files: [{ name: "notes.txt" }], images: [] }, { role: "assistant", text: "ok", time: 2 }]; + const page = await openPage(browser, mock, { seed: { ...on(), chat: lost, sampling: { chatEdit: true } } }); + await clickAction(page, 1, "Regenerate"); + await sleep(200); + assert.equal(mock.state.requests.length, 0, "no request with a missing file"); + assert.match(await page.$eval(".st-toast__title", (e) => e.textContent), /Attachments need to be added again/); + await clickAction(page, 0, "Rewind to here"); + await page.$eval(".history-panel .st-btn--primary", (b) => b.click()); + assert.equal(await page.$eval("#input", (e) => e.value), "see file"); + assert.equal(await page.$$eval("#attachments .chip", (e) => e.length), 0); + await page.close(); +}); + +// ---- sending while an answer is written (#4004) +htest("while answering - send after: the message waits and goes when the answer is done", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) }); + await say(page, "#long first"); + await page.waitForFunction(() => busy !== null); + assert.equal(await page.$eval("#send-btn", (b) => b.disabled), false); + assert.match(await page.$eval("#composer-hint", (e) => e.textContent), /sends when the answer is done/); + await say(page, "second"); + assert.match(await page.$eval("#pending .pending__text", (e) => e.textContent), /Sends when this answer is done: “second”/); + assert.equal(await page.$eval("#input", (e) => e.value), "", "the box is empty: the message is parked"); + await page.waitForFunction(() => messages.length === 4 && busy === null, { timeout: 20000 }); + assert.equal(await page.$("#pending"), null); + assert.equal(mock.state.requests.length, 2); + assert.deepEqual(requestTexts(mock).map((t) => t.slice(0, 10)), ["u:#long fi", "a:This is ", "u:second"], "the first answer is whole, then the second question"); + assert.equal(mock.state.aborted, 0, "nothing was cut"); + await page.close(); +}); + +htest("while answering - interrupt: the answer stops where it is and the message goes at once", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on({ whileBusy: "interject" }) }); + await say(page, "#long first"); + await page.waitForFunction(() => busy && busy.msg.text.length > 12); + await say(page, "actually, second"); + await page.waitForFunction(() => messages.length === 4 && busy === null, { timeout: 20000 }); + assert.equal(mock.state.aborted, 1, "the first stream was cut"); + const got = await page.evaluate(() => messages.map((m) => ({ r: m.role, t: m.text, i: !!m.interrupted, meta: m.meta }))); + assert.equal(got[1].i, true); assert.ok(got[1].t.length > 12 && got[1].t.length < 200, "what was written stays: " + got[1].t.length); + assert.match(got[1].meta, /nterrupted/); + assert.deepEqual(requestTexts(mock).map((t) => t.slice(0, 10)), ["u:#long fi", "a:This is ", "u:actually"], "the partial answer and the new message go to the model, in that order"); + assert.equal(requestTexts(mock)[1], "a:" + got[1].t.trim() || true); + assert.equal(await page.$("#pending"), null); + assert.equal(await page.$eval(".st-msg--assistant .meta-text", (e) => /nterrupted/.test(e.textContent)), true); + await page.close(); +}); + +htest("while answering - interrupt waits for a running tool, then stops", async ({ browser, mock }) => { + reset(mock); + // the mock engine here has an MCP server for the page to offer + const page = await openPage(browser, mock, { seed: on({ whileBusy: "interject" }) }); + await say(page, "#tool find it"); + await page.waitForFunction(() => busy && (busy.msg.tools || []).some((t) => t.state === "running")); + await say(page, "never mind, second"); + assert.match(await page.$eval("#pending .pending__text", (e) => e.textContent), /Waiting for the tool to finish, then sending: “never mind, second”/); + assert.equal(await page.evaluate(() => busy.cut), false, "the tool is not killed"); + await page.waitForFunction(() => messages.length === 4 && busy === null, { timeout: 20000 }); + const tool = await page.evaluate(() => messages[1].tools[0]); + assert.equal(tool.state, "done"); assert.equal(tool.result, "The file says hello.", "the tool finished and its result is kept"); + assert.equal(mock.state.aborted, 1); + assert.equal(requestTexts(mock).at(-1), "u:never mind, second"); + await page.close(); +}); + +htest("while answering - a waiting message can be taken back, or sent now", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) }); + await say(page, "#hold one"); + await page.waitForFunction(() => busy !== null); + await say(page, "later"); + await page.click("[data-pending-back]"); + assert.equal(await page.$eval("#input", (e) => e.value), "later", "back in the box"); + assert.equal(await page.$("#pending"), null); + await page.$eval("#input", (e) => { e.value = ""; }); + await say(page, "now"); + await page.click("[data-pending-now]"); // queue -> interrupt + await page.waitForFunction(() => messages.length === 4 && busy === null || (busy && busy.msg.text === "Working on it" && messages.length === 4), { timeout: 20000 }); + assert.equal(requestTexts(mock).at(-1), "u:now"); + await page.click("#stop-btn").catch(() => {}); + await page.close(); +}); + +htest("while answering - Stop keeps a waiting message for you to decide", async ({ browser, mock }) => { + reset(mock); + const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) }); + await say(page, "#hold one"); + await page.waitForFunction(() => busy !== null); + await say(page, "later"); + await page.click("#stop-btn"); + await idle(page); + await sleep(300); + assert.equal(mock.state.requests.length, 1, "a stopped answer does not send the queued message by itself"); + assert.match(await page.$eval("#pending .pending__text", (e) => e.textContent), /Not sent yet: “later”/); + await page.click("[data-pending-now]"); + await idle(page); + await page.waitForFunction(() => messages.length === 4); + assert.equal(requestTexts(mock).at(-1), "u:later"); + await page.close(); +}); + +htest("history: another chat or New chat does not lose a waiting message", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) }); + await ask(page, "first chat"); + await say(page, "#hold running"); + await page.waitForFunction(() => busy !== null); + await say(page, "parked"); + await page.click("#stop-btn"); + await idle(page); + await page.click("#sidebar-new"); + assert.equal(await page.$eval("#input", (e) => e.value), "parked", "back in the box"); + assert.equal(await page.$("#pending"), null); + await page.close(); +}); + const mock = await startMock(); const browser = await launch(); await run(async () => ({ browser, mock, close: async () => { await browser.close(); await mock.stop(); } })); diff --git a/tools/webtest/shots.mjs b/tools/webtest/shots.mjs new file mode 100644 index 00000000..5c00ca8e --- /dev/null +++ b/tools/webtest/shots.mjs @@ -0,0 +1,142 @@ +// Screenshots of the served web page (serve/web) in its new states, against the mock server (no model): +// WEBTEST_MODULES=<folder with node_modules/puppeteer-core> node tools/webtest/shots.mjs <out folder> [name-substring] +import { startMock } from "./mock.mjs"; +import { launch, openPage, say, idle, sleep, shot } from "./lib.mjs"; + +const out = process.argv[2] || "shots"; +const only = process.argv[3]; +const mock = await startMock(); +const browser = await launch(); +const turn = (role, text, extra = {}) => ({ role, text, time: Date.now(), ...extra }); +const fence = (lang, code) => "```" + lang + "\n" + code + "\n```\n"; +const on = (extra = {}) => ({ sampling: { chatList: true, chatEdit: true, ...extra } }); +const day = 86400000; + +const LONG = "Here is a short plan.\n\n1. Read the notes the user attached.\n2. Write the summary in plain words.\n3. List the open questions.\n\n" + + "The summary is **short** on purpose: three sentences, no jargon, and one next step.\n\n| Step | Who | When |\n|---|---|---|\n| Read | You | Today |\n| Summary | Me | Now |\n"; +const CHAT = [turn("user", "Can you plan how to summarise my notes?"), turn("assistant", LONG, { meta: "212 tokens · 41.3 tok/s" }), + turn("user", "Make it shorter, please."), turn("assistant", "Sure. Read the notes, write three sentences, list what is still open.", { meta: "24 tokens · 40.8 tok/s" })]; + +// the saved-chats list with chats from different days (put into the page's own store, then the page is reloaded) +async function seedChats(page) { + await page.evaluate(async (base, d) => { + const mk = (id, title, days, text) => ({ id, title, time: Date.now() - days * d, messages: [{ role: "user", text, time: 1 }, { role: "assistant", text: "Sure.", time: 2 }] }); + for (const c of [mk("s1", "", 0.1, "Plan my week"), mk("s2", "Garden plan", 0.2, "Which tomatoes grow in shade?"), mk("s3", "", 1.5, "Translate this letter"), + mk("s4", "Branch of Recipe ideas", 3, "Recipe ideas"), mk("s5", "", 12, "Explain compound interest"), mk("s6", "", 50, "Old question about the printer")]) { + chatStore.put(StrataHistory.cleanChat(c)); + } + }, null, day); + await sleep(300); + await page.reload({ waitUntil: "networkidle0" }); +} + +const shots = [ + ["01-wide-window", async () => { + const p = await openPage(browser, mock, { width: 2560, height: 1300, seed: { chat: CHAT, ...on() } }); + await seedChats(p); + return p; + }], + ["02-saved-chats-list", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } }); + await seedChats(p); + return p; + }], + ["03-rewind-choice", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } }); + await p.evaluate(() => { const i = 2; openRewind(i); }); + await sleep(200); + return p; + }], + ["04-undo-bar", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } }); + await p.evaluate(() => { openRewind(2); }); + await p.$eval(".history-panel .st-btn--primary", (b) => b.click()); + await sleep(200); + return p; + }], + ["05-edit-answer", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } }); + await p.evaluate(() => { editAnswerAt(3); }); + await sleep(200); + return p; + }], + ["06-branch-from-here", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } }); + await p.evaluate(() => { openRewind(2); }); + await p.evaluate(() => [...document.querySelectorAll(".history-panel .st-btn")].find((b) => b.textContent === "Branch from here").click()); + await sleep(300); + return p; + }], + ["07-math", async () => { + const p = await openPage(browser, mock, { width: 1100, height: 760, seed: { sampling: { math: true } } }); + await say(p, "#math show me"); await idle(p); await sleep(900); + return p; + }], + ["08-math-dark", async () => { + const p = await openPage(browser, mock, { width: 1100, height: 760, dark: true, seed: { sampling: { math: true } } }); + await say(p, "#math show me"); await idle(p); await sleep(900); + return p; + }], + ["09-svg-preview", async () => { + const p = await openPage(browser, mock, { width: 1100, height: 760 }); + await say(p, "#svg draw a circle"); await idle(p); await sleep(200); + await p.click("[data-preview-toggle]"); await sleep(400); + return p; + }], + ["10-html-preview-and-scripts", async () => { + const p = await openPage(browser, mock, { width: 1100, height: 760 }); + await say(p, "#html make a page"); await idle(p); await sleep(200); + await p.click("[data-preview-toggle]"); await sleep(300); + await p.click("[data-preview-scripts]"); await sleep(500); + return p; + }], + ["11-narrow-chat", async () => { + const p = await openPage(browser, mock, { width: 390, height: 780, seed: { chat: CHAT, ...on() } }); + await sleep(200); + return p; + }], + ["12-narrow-saved-chats-open", async () => { + const p = await openPage(browser, mock, { width: 390, height: 780, seed: { chat: CHAT, ...on() } }); + await seedChats(p); + await p.click("#sidebar-toggle"); await sleep(300); + return p; + }], + ["13-narrow-header-320", async () => openPage(browser, mock, { width: 320, height: 640, seed: { chat: CHAT } })], + ["14-chat-settings", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 900, seed: { chat: CHAT } }); + await p.click("#sampling-btn"); await sleep(500); + await p.$eval(".st-drawer__body", (e) => { e.scrollTop = e.scrollHeight; }); + await sleep(200); + return p; + }], + ["15-send-while-answering", async () => { + const p = await openPage(browser, mock, { width: 1100, height: 760, seed: on({ whileBusy: "queue" }) }); + await say(p, "#hold start a long answer"); + await p.waitForFunction(() => busy !== null); + await sleep(500); + await say(p, "And then summarise it for me"); + await sleep(300); + return p; + }], + ["16-load-unload", async () => { + mock.state.loaded = false; + const p = await openPage(browser, mock, { width: 1100, height: 520 }); + await sleep(1500); + return p; + }], + ["17-narrow-wide-mid-900", async () => openPage(browser, mock, { width: 900, height: 700, seed: { chat: CHAT, ...on() } })], +]; + +try { + for (const [name, make] of shots) { + if (only && !name.includes(only)) continue; + mock.state.loaded = true; + const page = await make(); + await sleep(300); + console.log(await shot(page, out, name), page.errors.length ? "ERRORS " + page.errors.join(" | ") : ""); + await page.close(); + } +} finally { + await browser.close(); + await mock.stop(); +} From 4661596ce37fb920a75fb005e4e79d9191d4694a Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:22:05 +0100 Subject: [PATCH 138/177] Web page: the chat view in eight languages, and the page's docs Everything the Chat view shows (header, tabs, message box, settings, toasts, tool blocks, the sidebar, the history and Load/Unload texts) now goes through the translation catalog: serve/web/locales/{de,es,ja,ko,pt,ru,zh}.json beside en.json (written from the English text in the code by tools/web_i18n.py). Plurals follow the language (Russian has few and many, Japanese and Korean only one form). serve/test_web_i18n.py fails when a catalog lacks a key, has a stale one or changes a {placeholder}. A ninth language is one file plus one line in serve/web/i18n.js. The Monitor, Images and About views are still English (the language setting says so); they are the next step. Browser tests: a language pick translates and is kept, /?lang= is for one visit, an unknown code stays English, all seven catalogs load without an error. docs/DETAILS.md: a section "The web page" (every switch, what the preview can and cannot reach, the languages, the tests), the Sampling drawer's new name, and the credits (KaTeX and the contributors of the PRs ported into the page). --- docs/DETAILS.md | 57 ++++++- serve/web/app.js | 61 ++++---- serve/web/index.html | 18 +-- serve/web/locales/de.json | 249 +++++++++++++++++++++++++++++++ serve/web/locales/en.json | 264 +++++++++++++++++++++++++++++++++ serve/web/locales/es.json | 249 +++++++++++++++++++++++++++++++ serve/web/locales/ja.json | 249 +++++++++++++++++++++++++++++++ serve/web/locales/ko.json | 249 +++++++++++++++++++++++++++++++ serve/web/locales/pt.json | 249 +++++++++++++++++++++++++++++++ serve/web/locales/ru.json | 249 +++++++++++++++++++++++++++++++ serve/web/locales/zh.json | 249 +++++++++++++++++++++++++++++++ tools/web_i18n.py | 2 +- tools/webtest/browser_test.mjs | 45 ++++++ 13 files changed, 2153 insertions(+), 37 deletions(-) create mode 100644 serve/web/locales/de.json create mode 100644 serve/web/locales/en.json create mode 100644 serve/web/locales/es.json create mode 100644 serve/web/locales/ja.json create mode 100644 serve/web/locales/ko.json create mode 100644 serve/web/locales/pt.json create mode 100644 serve/web/locales/ru.json create mode 100644 serve/web/locales/zh.json diff --git a/docs/DETAILS.md b/docs/DETAILS.md index e5c23659..92360d80 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -676,6 +676,56 @@ curl -X POST "http://127.0.0.1:8080/slots/0?action=restore" -H "Content-Type: ap only for this feature. Exact token replay across restarts is not guaranteed: expert residency and CPU/GPU rounding can change later output. +### The web page (Chat, Images, Monitor, About) + +Open the server's address in a browser. Everything in it runs from the server's own files: no CDN, no outside address. Chats, +settings and the API key stay in the browser. + +**Chat settings** (the button next to the message box) holds the sampling and thinking settings and the switches below. Every +switch below is **off by default**; with all of them off the page behaves as it did before. + +- **Render math.** Equations written as `\( ... \)`, `\[ ... \]`, `$x$` or `$$ ... $$` are drawn as formulas by KaTeX 0.19.0, which + ships in `serve/web/vendor/katex` (MIT; `PROVENANCE.json` there lists the package and a hash of every file). The text of a + message is never changed: copying, the Markdown export and the next request all carry what the model wrote. Code, prices + (`$5 and $10`) and a formula still being written stay text. A formula KaTeX cannot read stays as its source. A formula can only + draw: it cannot make a link, load a picture or run anything (`\href`, `\url`, `\includegraphics` and `\htmlClass` are shown as + their own names). +- **Saved chats list.** Keeps every chat in a list on the left, with search over titles and text, rename, delete (with Undo) and + days as headings. The chats live in this browser's IndexedDB; a picture or file is kept by name only. Nothing goes to the server. + In a private window, or when the browser's storage is full, the list stays in memory and the page says so once. Turning it on + keeps the chat on the screen as the first one in the list; turning it off keeps that chat as the single chat. +- **Edit and rewind messages.** Under each message: **Regenerate** (a new answer to the same question), **Edit answer** (correct its + text; the old thinking and tool calls go and no request is sent) and **Rewind to here**. Rewind asks what you want. On your + message, **Edit and send again here** hides it and the messages after it and puts it in the box; on an answer, **Continue from + here** hides the messages after it. **Branch from here** (needs the saved chats list) starts a new chat from the messages up to + that point and leaves this chat as it is; the branch keeps a name such as "Branch of ..." and links back to the original. An + **Undo** bar above the box brings back what was hidden, until your next question, another chat or a reload. A picture or file + that was only kept by name is not sent again: the page asks you to attach it again. +- **When you send while it is answering.** *Wait* (the default): Send is off until the answer is done. *Send after*: your message + waits and goes when the answer is done. *Interrupt*: the answer stops where it is, what was written stays and is marked + interrupted, and your message goes at once; a tool that is running finishes first. Only one message waits, and **Take back** + returns it to the box. Stop keeps a waiting message for you to send yourself. + +An answer's ` ```svg ` or ` ```html ` block gets a **Preview** button. The code is drawn in a frame that is cut off from the page: +an empty sandbox (no scripts, forms, popups or downloads, and no access to the page, its storage or the server), a policy inside +the frame that allows no address at all, and a page header (`Content-Security-Policy: frame-src 'none'`) that keeps a link or a +redirect in the model's HTML from loading a web page into it. An svg is shown as a picture. For an HTML page there is also a +warning button, **Run scripts**: after you confirm, that one block runs with scripts, still with no way to the page and no network, +until you close the preview. It can still use your CPU, and it is code the model wrote. + +**Load / Unload** in the header loads the model or frees the GPU (`POST /load`, `POST /unload`). It asks before unloading and is off +while an answer is being written or an image is made. + +**Language.** About > Settings lists the page's languages: English (the default), German, Spanish, Japanese, Korean, Portuguese, +Russian and Chinese. The Chat view, its settings and the header are translated; Monitor, Images and About are still English. A +language is a file `serve/web/locales/<lang>.json`; the English text lives in the code next to its key, and +`python tools/web_i18n.py` checks every file for the same keys and placeholders (`--write` rewrites `en.json`). `/?lang=de` shows a +language for one visit. + +Tests: `serve/test_web_*.py` and `serve/test_web_*.js` (Node), and a browser run against a stand-in server with no model: +`WEBTEST_MODULES=<folder with puppeteer-core> node tools/webtest/browser_test.mjs`. `tools/webtest/shots.mjs` takes the page's +screenshots. + ### API request monitor Off by default, because it keeps prompts and answers in memory. Turn it on with `"api_monitor": true` or @@ -765,7 +815,7 @@ after a change. needed for `npx` servers. An **address** (`url`, optional `headers`) uses MCP's Streamable HTTP transport (the older SSE-only transport is not supported). `"disabled": true` leaves an entry out. - Servers start with Strata. The server window says what each offers or why it did not start. The Monitor tab lists them, and - the Sampling drawer has **Use tools from MCP servers** (on by default). A server that stops later is started again at its next call. + Chat settings has **Use tools from MCP servers** (on by default). A server that stops later is started again at its next call. - In the chat each call shows as a small block. The model reads the result and goes on, up to `max_rounds` calls in a row. A tool that fails or takes longer than `timeout_s` gives the model an `error: ...` result. Results longer than `max_result_chars` are cut with a note. Stop stops a running tool too. @@ -1042,7 +1092,7 @@ your own prompts. The Monitor marks every request ESP or stock. ``` The engine log then says `control vector mode = project, dir = per-layer, layers 4..44 (41 steered)`. A loaded vector is on for -every request unless it says otherwise: the Sampling drawer has a switch, and the API takes `"experimental_speed_projection": false` +every request unless it says otherwise: Chat settings has a switch, and the API takes `"experimental_speed_projection": false` (config default: `"sampling": {"experimental_speed_projection": false}`). Switching drops the conversation cache once. Switched off, the output is token for token the stock model's. @@ -1154,6 +1204,9 @@ Strata itself: [MIT](../LICENSE). The model files are not part of it; their lice [HyperQwen](https://github.com/syv-ai/HyperQwen); references in the paper. - The web app's font: [Outfit](https://github.com/Outfitio/Outfit-Fonts) (SIL Open Font License 1.1, see `serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22). + Math is drawn by [KaTeX](https://katex.org) (MIT, vendored in `serve/web/vendor/katex`). The chat page's wide-window layout, svg/html preview, math, Load/Unload, saved + chats, edit and rewind came from PRs #3176 (@mnott), #1628 (@thoives), #2972 and #2974 (@CC-David-CC), #3550 (@sakuumomo), #1787 (@Scotty-Hudson) and + #2615 (@uppet), and the rewind choice and sending while answering from issues #3823 and #4004 (@xvcezrqpbxtpzblrt). - The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0, made from the model's activations (see its README). diff --git a/serve/web/app.js b/serve/web/app.js index e0ad80aa..46d79bea 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -50,7 +50,7 @@ async function copyText(text, btn) { use.setAttribute("href", `${SPRITE}#i-check`); setTimeout(() => use.setAttribute("href", `${SPRITE}#i-copy`), 1500); } - toast("success", "Copied to clipboard", "", 1800); + toast("success", tr("toast.copied", "Copied to clipboard"), "", 1800); } // ------------------------------------------------------------------ theme and tabs @@ -108,12 +108,16 @@ $("api-key").oninput = () => saveApiKey(); $("api-key").onchange = () => saveApiKey(true); let health = {model: "strata", images: false, max_context: 0}; +// the texts that depend on what this server offers: the empty chat's line and the attach button's hint +function renderEmptyChat() { + $("attach-btn").title = health.images ? tr("composer.attachPictures", "Attach a text file or a picture (or drop it here)") + : tr("composer.attach", "Attach a text file (or drop it here)"); + $("chat-empty-sub").textContent = tr("chat.emptyModel", "{model} runs on this PC. Nothing leaves it.", {model: health.model}); +} async function loadHealth() { try { health = await (await fetch("health")).json(); - $("attach-btn").title = health.images ? "Attach a text file or a picture (or drop it here)" - : "Attach a text file (or drop it here)"; - $("chat-empty-sub").textContent = `${health.model} runs on this PC. Nothing leaves it.`; + renderEmptyChat(); $("tab-btn-images").hidden = !health.image_generation; if (location.hash === "#images" && health.image_generation) showTab("images"); } catch (e) { @@ -817,8 +821,8 @@ function msgEl(m, i) { const wrap = document.createElement("div"); wrap.className = "msg-images"; for (const im of m.images) { - if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || "image"; wrap.appendChild(img); } - else { const c = document.createElement("span"); c.className = "chip"; c.innerHTML = icon("image", "st-icon st-icon--sm"); c.append(im.name || "image"); wrap.appendChild(c); } + if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || tr("chat.image", "image"); wrap.appendChild(img); } + else { const c = document.createElement("span"); c.className = "chip"; c.innerHTML = icon("image", "st-icon st-icon--sm"); c.append(im.name || tr("chat.image", "image")); wrap.appendChild(c); } } el.appendChild(wrap); } @@ -828,13 +832,13 @@ function msgEl(m, i) { el.appendChild(b); const meta = document.createElement("div"); meta.className = "st-msg__meta"; - meta.textContent = `You · ${timeStr(m.time)}`; + meta.textContent = `${tr("chat.you", "You")} · ${timeStr(m.time)}`; el.appendChild(meta); } else { el.innerHTML = `<details class="st-collapse think" hidden><summary>${icon("thinking", "st-icon st-icon--sm")}<span class="think-title"></span>` + `${icon("chevron", "st-icon st-icon--sm st-chev")}</summary><div class="st-collapse__body thinking"></div></details>` + `<div class="st-bubble"></div><div class="st-msg__meta"><span class="meta-text"></span>` + - `<button class="st-btn st-btn--icon" data-msg-copy aria-label="Copy the answer" title="Copy">${icon("copy")}</button></div>`; + `<button class="st-btn st-btn--icon" data-msg-copy aria-label="${esc(tr("chat.copyAnswer", "Copy the answer"))}" title="${esc(tr("chat.copy", "Copy"))}">${icon("copy")}</button></div>`; updateAssistant(el, m, false); } const actions = msgActions(m, i); // edit / regenerate / rewind (chats-ui.js), when switched on @@ -843,18 +847,20 @@ function msgEl(m, i) { } // One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and // the result as the model read it. Its body is built only while open: a result can be 20,000 characters. -const TOOL_STATE = {writing: ["st-badge--reading", "Writing"], running: ["st-badge--generating", "Running"], done: ["", "Done"], - error: ["st-badge--error", "Error"], skipped: ["st-badge--queued", "Not run"]}; +const TOOL_STATE = {writing: ["st-badge--reading", () => tr("tool.writing", "Writing")], running: ["st-badge--generating", () => tr("tool.running", "Running")], + done: ["", () => tr("tool.done", "Done")], error: ["st-badge--error", () => tr("tool.error", "Error")], + skipped: ["st-badge--queued", () => tr("tool.skipped", "Not run")]}; function toolHtml(t, k) { - const [cls, label] = TOOL_STATE[t.state] || ["", t.state]; + const [cls, labelOf] = TOOL_STATE[t.state] || ["", () => t.state]; + const label = labelOf(); const args = t.arguments == null ? "" : JSON.stringify(t.arguments, null, 2); const preview = t.result != null ? t.result : args.replace(/\s+/g, " "); let body = ""; if (t.open) { - body = `<div class="tool-call__label">Arguments</div><pre class="tool-call__pre">${esc(args || "(being written)")}</pre>`; + body = `<div class="tool-call__label">${esc(tr("tool.arguments", "Arguments"))}</div><pre class="tool-call__pre">${esc(args || tr("tool.beingWritten", "(being written)"))}</pre>`; if (t.result != null) { - body += `<div class="tool-call__label">${t.ok ? "Result" : "Error"}${t.chars ? ` · ${fmt(t.chars)} characters` : ""}` + - `${t.truncated ? ", cut for the model" : ""}</div><pre class="tool-call__pre">${esc(t.result)}</pre>`; + body += `<div class="tool-call__label">${esc(t.ok ? tr("tool.result", "Result") : tr("tool.error", "Error"))}${t.chars ? ` · ${esc(tr("tool.chars", "{n} characters", {n: fmt(t.chars)}))}` : ""}` + + `${t.truncated ? esc(tr("tool.cut", ", cut for the model")) : ""}</div><pre class="tool-call__pre">${esc(t.result)}</pre>`; } } return `<details class="st-collapse tool-call" data-tool="${k}" data-state="${esc(t.state)}"${t.open ? " open" : ""}>` + @@ -898,8 +904,8 @@ function updateAssistant(el, m, streaming) { if (m.reasoning) { det.hidden = false; const thinkingNow = streaming && !m.text; - el.querySelector(".think-title").textContent = thinkingNow ? "Thinking…" : - m.thinkSecs != null ? `Thought for ${fmt(m.thinkSecs, 1)} s` : "Thoughts"; + el.querySelector(".think-title").textContent = thinkingNow ? tr("think.now", "Thinking…") : + m.thinkSecs != null ? tr("think.for", "Thought for {s} s", {s: fmt(m.thinkSecs, 1)}) : tr("think.done", "Thoughts"); const body = el.querySelector(".thinking"); if (det.open || thinkingNow) body.textContent = m.reasoning; else body.dataset.pending = "1"; @@ -918,7 +924,7 @@ function updateAssistant(el, m, streaming) { if (settings.math) StrataMath.hydrate(bubble); if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor"); } - el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? "Stopped" : ""); + el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? tr("chat.stopped", "Stopped") : ""); el.querySelector("[data-msg-copy]").hidden = streaming || !m.text; } function renderChat() { @@ -1256,7 +1262,7 @@ $("new-btn").onclick = () => { }}); }; $("export-btn").onclick = () => { - if (!messages.length) { toast("info", "Nothing to save yet"); return; } + if (!messages.length) { toast("info", tr("export.nothing", "Nothing to save yet")); return; } const tools = (m) => (m.tools || []).filter((t) => t.result != null).map((t) => `<details><summary>Tool ${t.server ? `${t.server} / ` : ""}${t.tool || t.name}${t.ok ? "" : " (error)"}</summary>\n\n` + `\`\`\`json\n${JSON.stringify(t.arguments || {}, null, 2)}\n\`\`\`\n\n\`\`\`\n${t.result}\n\`\`\`\n\n</details>\n\n`).join(""); @@ -1279,19 +1285,20 @@ function isTextFile(f) { function addFiles(files) { for (const f of files) { if (f.type.startsWith("image/")) { - if (!health.images) { toast("warn", "Pictures are off", "This model was set up for text only."); continue; } - if (f.size > 20e6) { toast("warn", "Picture too large", `${f.name} is over 20 MB.`); continue; } + if (!health.images) { toast("warn", tr("file.picturesOff", "Pictures are off"), tr("file.picturesOffText", "This model was set up for text only.")); continue; } + if (f.size > 20e6) { toast("warn", tr("file.pictureBig", "Picture too large"), tr("file.pictureBigText", "{name} is over 20 MB.", {name: f.name})); continue; } const r = new FileReader(); - r.onload = () => { attachments.push({kind: "image", name: f.name || "pasted image", url: r.result}); renderAttachments(); }; + r.onload = () => { attachments.push({kind: "image", name: f.name || tr("file.pasted", "pasted image"), url: r.result}); renderAttachments(); }; r.readAsDataURL(f); continue; } - if (!isTextFile(f)) { toast("warn", "Not a text file", `${f.name}: attach text files (code, notes, logs, data)${health.images ? " or pictures" : ""}.`); continue; } - if (f.size > MAX_TEXT_FILE) { toast("warn", "File too large", `${f.name} is over 512 KB.`); continue; } + if (!isTextFile(f)) { toast("warn", tr("file.notText", "Not a text file"), health.images ? tr("file.notTextPictures", "{name}: attach text files (code, notes, logs, data) or pictures.", {name: f.name}) + : tr("file.notTextOnly", "{name}: attach text files (code, notes, logs, data).", {name: f.name})); continue; } + if (f.size > MAX_TEXT_FILE) { toast("warn", tr("file.big", "File too large"), tr("file.bigText", "{name} is over 512 KB.", {name: f.name})); continue; } const r = new FileReader(); r.onload = () => { const text = String(r.result); - if (text.includes("\u0000")) { toast("warn", "Not a text file", `${f.name} looks like a binary file.`); return; } + if (text.includes("\u0000")) { toast("warn", tr("file.notText", "Not a text file"), tr("file.binaryText", "{name} looks like a binary file.", {name: f.name})); return; } attachments.push({kind: "file", name: f.name, text}); renderAttachments(); }; @@ -1318,7 +1325,7 @@ function renderAttachments() { c.innerHTML = icon(a.kind === "file" ? "attach" : "image", "st-icon st-icon--sm"); c.append(a.name); const x = document.createElement("button"); - x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", "Remove"); + x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", tr("file.remove", "Remove")); x.innerHTML = icon("trash"); x.onclick = () => { attachments.splice(i, 1); renderAttachments(); }; c.appendChild(x); @@ -1472,6 +1479,9 @@ const urlLang = new URLSearchParams(location.search).get("lang"); $("lang").innerHTML = StrataI18n.LANGUAGES.map(([code, name]) => `<option value="${esc(code)}">${esc(name)}</option>`).join(""); function showLanguage() { $("lang").value = StrataI18n.lang; + renderEmptyChat(); + setSidebar(sidebarOpen, false); + outputs(); renderChat(); setBusy(!!busy); if (lastMetrics) render(lastMetrics); @@ -1486,6 +1496,7 @@ $("lang").onchange = async () => { async function start() { await StrataI18n.setLanguage(urlLang || store.get("lang", "en")); $("lang").value = StrataI18n.lang; + renderEmptyChat(); initChats(); if (settings.chatList) await setChatList(true, false); // the saved-chats list is read before the first draw setBusy(false); diff --git a/serve/web/index.html b/serve/web/index.html index 0511153d..4de2fc44 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -20,21 +20,21 @@ <body> <header class="st-header"> <span class="st-header__brand">Strata</span> - <nav class="st-tabs" role="tablist" aria-label="Views"> + <nav class="st-tabs" role="tablist" aria-label="Views" data-i18n-label="tab.views"> <button class="st-tab" role="tab" id="tab-btn-chat" aria-controls="view-chat" aria-selected="true" data-tab="chat"> - <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-chat"/></svg>Chat</button> + <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-chat"/></svg><span data-i18n="tab.chat">Chat</span></button> <button class="st-tab" role="tab" id="tab-btn-images" aria-controls="view-images" aria-selected="false" data-tab="images" hidden> - <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-image"/></svg>Images</button> + <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-image"/></svg><span data-i18n="tab.images">Images</span></button> <button class="st-tab" role="tab" id="tab-btn-monitor" aria-controls="view-monitor" aria-selected="false" data-tab="monitor"> - <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-activity"/></svg>Monitor</button> + <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-activity"/></svg><span data-i18n="tab.monitor">Monitor</span></button> <button class="st-tab" role="tab" id="tab-btn-about" aria-controls="view-about" aria-selected="false" data-tab="about"> - <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-info"/></svg>About</button> + <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-info"/></svg><span data-i18n="tab.about">About</span></button> </nav> <span class="st-header__spacer"></span> <span class="st-pill" id="pill" data-state="idle" role="status" aria-live="polite"> - <span class="st-pill__dot"></span><span id="pill-text">Connecting…</span></span> + <span class="st-pill__dot"></span><span id="pill-text" data-i18n="pill.connecting">Connecting…</span></span> <button class="st-btn st-btn--secondary" id="unload-btn" type="button" title="Waiting for the server" disabled>…</button> - <button class="st-btn st-btn--icon" id="theme-btn" title="Light / dark" aria-label="Switch between light and dark"> + <button class="st-btn st-btn--icon" id="theme-btn" title="Light / dark" aria-label="Switch between light and dark" data-i18n-title="theme.title" data-i18n-label="theme.label"> <svg class="st-icon"><use id="theme-icon" href="web/sprite.svg#i-moon"/></svg></button> </header> @@ -61,7 +61,7 @@ <div class="chat" id="chat"> <div class="chat-empty" id="chat-empty"> <div class="chat-empty__title" data-i18n="chat.empty">Ask anything</div> - <div class="chat-empty__sub" id="chat-empty-sub" data-i18n="chat.emptySub">The model runs on this PC. Nothing leaves it.</div> + <div class="chat-empty__sub" id="chat-empty-sub">The model runs on this PC. Nothing leaves it.</div> </div> </div> </div> @@ -70,7 +70,7 @@ <div class="attachments" id="attachments" hidden></div> <textarea id="input" rows="2" placeholder="Ask anything…" aria-label="Message" data-i18n-placeholder="composer.placeholder" data-i18n-label="composer.message"></textarea> <div class="st-composer__bar"> - <button type="button" class="st-btn st-btn--icon" id="attach-btn" title="Attach a text file (or drop it here)" aria-label="Attach a file" data-i18n-label="composer.attach"> + <button type="button" class="st-btn st-btn--icon" id="attach-btn" title="Attach a text file (or drop it here)" aria-label="Attach a file" data-i18n-label="composer.attachLabel"> <svg class="st-icon"><use href="web/sprite.svg#i-attach"/></svg></button> <input type="file" id="file" multiple hidden> <button type="button" class="st-btn st-btn--icon" id="new-btn" title="New chat" aria-label="New chat" data-i18n-title="chat.new" data-i18n-label="chat.new"> diff --git a/serve/web/locales/de.json b/serve/web/locales/de.json new file mode 100644 index 00000000..67a2c5cb --- /dev/null +++ b/serve/web/locales/de.json @@ -0,0 +1,249 @@ +{ + "branch.back": "Zurück dorthin", + "branch.from": "Abgezweigt von „{title}“", + "branch.open": "Das Original öffnen", + "branch.started": "Verzweigung gestartet", + "branch.startedText": "Der Chat, in dem Sie waren, ist unverändert und steht in der Liste links.", + "branch.title": "Verzweigung von {title}", + "busy.stillWriting": "Es schreibt noch", + "busy.stopFirst": "Stoppen Sie zuerst die Antwort.", + "cancel": "Abbrechen", + "chat.clearedToast": "Der letzte Chat wurde geleert.", + "chat.copy": "Kopieren", + "chat.copyAnswer": "Antwort kopieren", + "chat.deleted": "Chat gelöscht", + "chat.empty": "Fragen Sie, was Sie möchten", + "chat.emptyModel": "{model} läuft auf diesem PC. Nichts verlässt ihn.", + "chat.image": "Bild", + "chat.interrupted": "Unterbrochen", + "chat.interruptedLower": "unterbrochen", + "chat.new": "Neuer Chat", + "chat.newToast": "Neuer Chat", + "chat.newToastText": "Der bisherige Chat steht in der Liste links.", + "chat.projectionOff": "Projektion aus", + "chat.projectionOn": "Projektion an", + "chat.stopped": "Gestoppt", + "chat.stoppedLower": "gestoppt", + "chat.tokens": "{n} Tokens", + "chat.toolCalls": {"one": "{n} Werkzeugaufruf", "other": "{n} Werkzeugaufrufe"}, + "chat.toolLimit": "bei der Grenze von {n} Werkzeugrunden gestoppt (mcp.max_rounds)", + "chat.untitled": "Neuer Chat", + "chat.you": "Sie", + "close": "Schließen", + "code.copy": "Code kopieren", + "code.label": "Code", + "composer.attach": "Textdatei anhängen (oder hierher ziehen)", + "composer.attachLabel": "Datei anhängen", + "composer.attachPictures": "Textdatei oder Bild anhängen (oder hierher ziehen)", + "composer.finishOpen": "Speichern oder abbrechen, was oben offen ist, um fortzufahren", + "composer.hintInterject": "Eingabe stoppt die Antwort hier und sendet sofort", + "composer.hintQueue": "Eingabe sendet, sobald die Antwort fertig ist", + "composer.message": "Nachricht", + "composer.newline": "Umschalt+Eingabe: neue Zeile", + "composer.placeholder": "Fragen Sie, was Sie möchten…", + "composer.save": "Diesen Chat als Markdown speichern", + "composer.saveLabel": "Diesen Chat speichern", + "composer.send": "Senden", + "composer.stop": "Stoppen", + "drawer.apply": "Anwenden", + "drawer.busy": "Wenn Sie senden, während es antwortet", + "drawer.busyInterject": "Unterbrechen", + "drawer.busyInterjectNote": "Die Antwort hört dort auf, wo sie ist (Geschriebenes bleibt), und Ihre Nachricht geht sofort los. Ein laufendes Werkzeug wird zuerst fertig.", + "drawer.busyQueue": "Danach senden", + "drawer.busyQueueNote": "Ihre Nachricht wartet und geht los, sobald die Antwort fertig ist.", + "drawer.busyWait": "Warten", + "drawer.busyWaitNote": "Senden ist aus, bis die Antwort fertig ist, wie bisher.", + "drawer.chats": "Chats", + "drawer.edit": "Nachrichten bearbeiten und zurückspulen", + "drawer.editNote": "eine Antwort bearbeiten, eine neue verlangen oder zu einer früheren Nachricht zurückgehen (mit Rückgängig)", + "drawer.greedy": "0 · deterministisch", + "drawer.high": "Hoch", + "drawer.list": "Liste gespeicherter Chats", + "drawer.listNote": "behält jeden Chat in einer Liste links, nur in diesem Browser. Aus: ein Chat, wie bisher", + "drawer.low": "Niedrig", + "drawer.math": "Formeln darstellen", + "drawer.mathNote": "Gleichungen in Antworten als Formeln zeichnen (funktioniert offline)", + "drawer.maxTokens": "Max. Tokens", + "drawer.maxTokensNote": "leer = bis fertig", + "drawer.mcp": "Werkzeuge von MCP-Servern nutzen", + "drawer.medium": "Mittel", + "drawer.off": "Aus", + "drawer.random": "Zufällig", + "drawer.reset": "Zurücksetzen", + "drawer.saved": "Chat-Einstellungen gespeichert", + "drawer.savedGreedy": "Deterministisch: dieselbe Frage gibt dieselbe Antwort.", + "drawer.savedHere": "Hier gespeichert, aber nicht für andere Apps", + "drawer.savedOwn": "Andere Apps nutzen wieder ihre eigenen Einstellungen.", + "drawer.savedShared": "Andere Apps (omp, API-Clients) nutzen diese Einstellungen ab ihrer nächsten Anfrage.", + "drawer.seed": "Seed", + "drawer.seedNote": "leer = zufällig", + "drawer.share": "Auch für andere Apps verwenden", + "drawer.shareNote": "omp und andere API-Clients bekommen diese Einstellungen für alles, was sie nicht selbst festlegen", + "drawer.short": "Einstellungen", + "drawer.showThinking": "Denken anzeigen", + "drawer.showThinkingNote": "aufgeklappt, solange es schreibt", + "drawer.temperature": "Temperatur", + "drawer.temperatureNote": "0 = immer das wahrscheinlichste Wort (exakt, wiederholbar)", + "drawer.thinkHigh": "gründlich (Standard)", + "drawer.thinkLow": "kurz", + "drawer.thinkMedium": "mittel", + "drawer.thinkNone": "antwortet sofort", + "drawer.thinking": "Denken", + "drawer.title": "Chat-Einstellungen", + "drawer.untilDone": "Bis fertig", + "export.nothing": "Noch nichts zu speichern", + "file.big": "Datei zu groß", + "file.bigText": "{name} ist größer als 512 KB.", + "file.binaryText": "{name} sieht nach einer Binärdatei aus.", + "file.notText": "Keine Textdatei", + "file.notTextOnly": "{name}: Hängen Sie Textdateien an (Code, Notizen, Protokolle, Daten).", + "file.notTextPictures": "{name}: Hängen Sie Textdateien (Code, Notizen, Protokolle, Daten) oder Bilder an.", + "file.pasted": "eingefügtes Bild", + "file.pictureBig": "Bild zu groß", + "file.pictureBigText": "{name} ist größer als 20 MB.", + "file.picturesOff": "Bilder sind aus", + "file.picturesOffText": "Dieses Modell wurde nur für Text eingerichtet.", + "file.remove": "Entfernen", + "group.month": "Letzte 30 Tage", + "group.older": "Älter", + "group.today": "Heute", + "group.week": "Letzte 7 Tage", + "group.yesterday": "Gestern", + "hist.editAnswer": "Antwort bearbeiten", + "hist.editAnswerTitle": "Den Text der Antwort korrigieren. Es wird keine Anfrage gesendet.", + "hist.editLabel": "Antwort bearbeiten", + "hist.editNote": "Das bisherige Denken und die Werkzeugaufrufe der Antwort werden entfernt. Es wird keine Anfrage gesendet.", + "hist.editRemoves": {"one": "Speichern blendet die {n} Nachricht danach aus. ", "other": "Speichern blendet die {n} Nachrichten danach aus. "}, + "hist.edited": "Bearbeitet", + "hist.editedHidden": {"one": "Antwort bearbeitet, {n} Nachricht ausgeblendet", "other": "Antwort bearbeitet, {n} Nachrichten ausgeblendet"}, + "hist.editedOnly": "Antwort bearbeitet", + "hist.empty": "Die Antwort ist leer", + "hist.emptyText": "Schreiben Sie etwas, bevor Sie speichern.", + "hist.finishFirst": "Schließen Sie zuerst ab, was offen ist", + "hist.finishFirstText": "Speichern Sie es oder drücken Sie Abbrechen.", + "hist.hidden": {"one": "{n} Nachricht ausgeblendet", "other": "{n} Nachrichten ausgeblendet"}, + "hist.lostText": "Dieser Browser hat nur die Namen behalten, nicht den Inhalt. Starten Sie einen neuen Chat und hängen Sie sie erneut an.", + "hist.lostText2": "Dieser Browser hat nur die Namen behalten, nicht den Inhalt. Hängen Sie sie erneut an.", + "hist.lostTitle": "Anhänge müssen erneut hinzugefügt werden", + "hist.nothingHidden": "Zurück bei dieser Nachricht", + "hist.pendingFirst": "Eine Nachricht wartet", + "hist.pendingFirstText": "Senden Sie sie oder nehmen Sie sie zuerst zurück.", + "hist.regenerate": "Neu erzeugen", + "hist.regenerateTitle": "Eine neue Antwort auf diese Frage verlangen. Werkzeuge können erneut laufen.", + "hist.replaced": "Die Antwort wurde ersetzt", + "hist.rewind": "Bis hier zurückgehen", + "hist.rewindTitle": "Zu diesem Punkt im Chat zurückgehen", + "hist.save": "Speichern", + "math.source": "Formelquelltext ({reason})", + "model.alreadyUnloaded": "Bereits entladen", + "model.busy": "Das Modell ist beschäftigt", + "model.confirmUnload": "Das Modell entladen und die GPU freigeben? Laden oder die nächste Nachricht holt es zurück.", + "model.fewMinutes": "Das kann einige Minuten dauern.", + "model.gpuFree": "Die GPU ist frei. Laden oder die nächste Nachricht holt das Modell zurück.", + "model.gpuInUse": "Die GPU wird genutzt.", + "model.imageBusy": "Ein Bild wird erzeugt. Es wird von selbst fertig.", + "model.imageLoading": "Ein Bild lädt das Modell bereits", + "model.imageLoadingDot": "Ein Bild lädt das Modell bereits.", + "model.load": "Laden", + "model.loadFailed": "Laden fehlgeschlagen", + "model.loadTitle": "Das Modell jetzt laden. Eine Nachricht lädt es auch.", + "model.loaded": "Modell geladen", + "model.loading": "Lädt…", + "model.loadingTitle": "Das Modell wird geladen", + "model.loadingToast": "Das Modell wird geladen", + "model.noAnswer": "Der Server hat nicht geantwortet.", + "model.replyLoading": "Eine Antwort lädt das Modell bereits", + "model.replyLoadingDot": "Eine Antwort lädt das Modell bereits.", + "model.stopFirst": "Antwort stoppen, dann entladen", + "model.stopFirstDot": "Stoppen Sie die Antwort, dann entladen.", + "model.unload": "Entladen", + "model.unloadFailed": "Entladen fehlgeschlagen", + "model.unloadTitle": "Das Modell entladen und die GPU freigeben", + "model.unloaded": "Modell entladen", + "model.unloading": "Entlädt…", + "model.unloadingTitle": "Das Modell wird entladen", + "model.unsupported": "Entladen ist nicht verfügbar", + "model.waiting": "Warte auf den Server", + "pending.afterTool": "Wartet, bis das Werkzeug fertig ist, dann wird gesendet: „{text}“", + "pending.cutting": "Die Antwort wird gestoppt, dann wird gesendet: „{text}“", + "pending.one": "Eine Nachricht wartet bereits", + "pending.oneText": "Nehmen Sie sie zurück oder warten Sie, bis sie gesendet ist.", + "pending.queued": "Wird gesendet, wenn diese Antwort fertig ist: „{text}“", + "pending.ready": "Noch nicht gesendet: „{text}“", + "pending.send": "Senden", + "pending.sendNow": "Jetzt senden", + "pending.takeBack": "Zurücknehmen", + "pill.connecting": "Verbinde…", + "pill.generating": "Schreibt · {rate} Tok/s", + "pill.idle": "Leerlauf", + "pill.image": "Erzeugt ein Bild…", + "pill.keyNeeded": "API-Schlüssel nötig", + "pill.queued": "{n} in der Warteschlange", + "pill.reading": "Liest die Eingabe", + "pill.readingPct": "Liest die Eingabe · {pct} %", + "pill.unloaded": "Entladen", + "pill.unreachable": "Server nicht erreichbar", + "preview.confirm": "Diesen Code mit Skripten ausführen?\n\nEr läuft in Ihrem Browser, abgeschottet von diesem Chat und vom Netzwerk, kann aber den Tab trotzdem einfrieren, und es ist Code, den das Modell geschrieben hat.\n\nNur dieser Block, und nur bis Sie die Vorschau schließen.", + "preview.runScripts": "Skripte ausführen", + "preview.showCode": "Den Code zeigen", + "preview.showPage": "Die Seite in der Vorschau zeigen", + "preview.showSvg": "Das Bild in der Vorschau zeigen", + "preview.stopScripts": "Skripte beenden", + "preview.titlePage": "Seitenvorschau", + "preview.titleSvg": "Bildvorschau", + "rewind.branch": "Ab hier verzweigen", + "rewind.branchAnswerText": "Startet einen neuen Chat mit den Nachrichten bis zu dieser Antwort. Dieser Chat bleibt, wie er ist.", + "rewind.branchUserText": "Startet einen neuen Chat mit den Nachrichten vor dieser und legt Ihre Nachricht in sein Eingabefeld. Dieser Chat bleibt, wie er ist.", + "rewind.hereAnswer": "Ab hier weitermachen", + "rewind.hereAnswerText": "Blendet die Nachrichten nach dieser Antwort aus. Rückgängig holt sie zurück.", + "rewind.hereUser": "Hier bearbeiten und erneut senden", + "rewind.hereUserText": "Blendet diese Nachricht und die danach aus und legt Ihre Nachricht ins Eingabefeld unten. Rückgängig holt sie zurück.", + "rewind.noList": "Um stattdessen von hier einen neuen Chat zu starten, schalten Sie in den Chat-Einstellungen die Liste gespeicherter Chats ein.", + "rewind.title": "Bis hier zurückgehen", + "settings.language": "Sprache", + "settings.languageNote": "Chat, seine Einstellungen und die Schaltflächen oben sind übersetzt. Die Ansichten Monitor, Bilder und Info sind noch auf Englisch.", + "sidebar.collapse": "Die Chatliste einklappen", + "sidebar.delete": "Diesen Chat löschen", + "sidebar.deleteShort": "Löschen", + "sidebar.expand": "Die Chatliste öffnen", + "sidebar.foot": {"one": "{n} Chat · in diesem Browser gespeichert", "other": "{n} Chats · in diesem Browser gespeichert"}, + "sidebar.nameFor": "Name für diesen Chat", + "sidebar.noMatch": "Kein Chat passt", + "sidebar.none": "Noch keine Chats", + "sidebar.rename": "Diesen Chat umbenennen", + "sidebar.renameShort": "Umbenennen", + "sidebar.search": "Chats durchsuchen", + "sidebar.title": "Chats", + "store.failed": "Die Chatliste konnte nicht gespeichert werden. Die Chats auf dem Bildschirm sind noch da.", + "store.memory": "Dieser Browser behält die Chatliste nicht. Sie bleibt im Speicher, bis Sie die Seite schließen.", + "store.quota": "Dieser Browser kann nicht mehr behalten. Die Chats auf dem Bildschirm sind noch da.", + "store.title": "Chatliste nicht gespeichert", + "tab.about": "Info", + "tab.chat": "Chat", + "tab.images": "Bilder", + "tab.monitor": "Monitor", + "tab.views": "Ansichten", + "theme.label": "Zwischen hell und dunkel wechseln", + "theme.title": "Hell / Dunkel", + "think.done": "Gedanken", + "think.for": "Nachgedacht: {s} s", + "think.now": "Denkt nach…", + "toast.copied": "In die Zwischenablage kopiert", + "toast.engineError": "die Engine hat einen Fehler gemeldet", + "toast.httpAnswer": "Der Server antwortete mit HTTP {code}.", + "toast.keyAbout": "Dieser Server braucht einen Schlüssel: Tragen Sie ihn unter Info > Einstellungen ein.", + "toast.keyAbout2": "API-Schlüssel nötig: Tragen Sie ihn unter Info > Einstellungen ein.", + "toast.keyNeeded": "Dieser Server braucht einen API-Schlüssel: Tragen Sie ihn unter Info > Einstellungen ein.", + "toast.requestFailed": "Die Anfrage ist fehlgeschlagen", + "tool.arguments": "Argumente", + "tool.beingWritten": "(wird geschrieben)", + "tool.chars": "{n} Zeichen", + "tool.cut": ", für das Modell gekürzt", + "tool.done": "Fertig", + "tool.error": "Fehler", + "tool.result": "Ergebnis", + "tool.running": "Läuft", + "tool.skipped": "Nicht ausgeführt", + "tool.writing": "Schreibt", + "undo": "Rückgängig" +} diff --git a/serve/web/locales/en.json b/serve/web/locales/en.json new file mode 100644 index 00000000..adcd6fd2 --- /dev/null +++ b/serve/web/locales/en.json @@ -0,0 +1,264 @@ +{ + "branch.back": "Back to it", + "branch.from": "Branched from “{title}”", + "branch.open": "Open the original", + "branch.started": "Branch started", + "branch.startedText": "The chat you were in is unchanged, in the list on the left.", + "branch.title": "Branch of {title}", + "busy.stillWriting": "Still writing", + "busy.stopFirst": "Stop the answer first.", + "cancel": "Cancel", + "chat.clearedToast": "The last one was cleared.", + "chat.copy": "Copy", + "chat.copyAnswer": "Copy the answer", + "chat.deleted": "Chat deleted", + "chat.empty": "Ask anything", + "chat.emptyModel": "{model} runs on this PC. Nothing leaves it.", + "chat.image": "image", + "chat.interrupted": "Interrupted", + "chat.interruptedLower": "interrupted", + "chat.new": "New chat", + "chat.newToast": "New chat", + "chat.newToastText": "The one you were in is in the list on the left.", + "chat.projectionOff": "projection off", + "chat.projectionOn": "projection on", + "chat.stopped": "Stopped", + "chat.stoppedLower": "stopped", + "chat.tokens": "{n} tokens", + "chat.toolCalls": { + "one": "{n} tool call", + "other": "{n} tool calls" + }, + "chat.toolLimit": "stopped at the limit of {n} tool rounds (mcp.max_rounds)", + "chat.untitled": "New chat", + "chat.you": "You", + "close": "Close", + "code.copy": "Copy code", + "code.label": "code", + "composer.attach": "Attach a text file (or drop it here)", + "composer.attachLabel": "Attach a file", + "composer.attachPictures": "Attach a text file or a picture (or drop it here)", + "composer.finishOpen": "Save or cancel what is open above to continue", + "composer.hintInterject": "Enter stops the answer here and sends now", + "composer.hintQueue": "Enter sends when the answer is done", + "composer.message": "Message", + "composer.newline": "Shift+Enter: new line", + "composer.placeholder": "Ask anything…", + "composer.save": "Save this chat as Markdown", + "composer.saveLabel": "Save this chat", + "composer.send": "Send", + "composer.stop": "Stop", + "drawer.apply": "Apply", + "drawer.busy": "When you send while it is answering", + "drawer.busyInterject": "Interrupt", + "drawer.busyInterjectNote": "The answer stops where it is (what is written stays) and your message goes at once. A tool that is running finishes first.", + "drawer.busyQueue": "Send after", + "drawer.busyQueueNote": "Your message waits and goes as soon as the answer is done.", + "drawer.busyWait": "Wait", + "drawer.busyWaitNote": "Send is off until the answer is done, as before.", + "drawer.chats": "Chats", + "drawer.edit": "Edit and rewind messages", + "drawer.editNote": "edit an answer, ask for a new one, or go back to an earlier message (with an Undo)", + "drawer.greedy": "0 · greedy", + "drawer.high": "High", + "drawer.list": "Saved chats list", + "drawer.listNote": "keeps every chat in a list on the left, in this browser only. Off: one chat, as before", + "drawer.low": "Low", + "drawer.math": "Render math", + "drawer.mathNote": "draw equations in answers as formulas (works offline)", + "drawer.maxTokens": "Max tokens", + "drawer.maxTokensNote": "empty = until done", + "drawer.mcp": "Use tools from MCP servers", + "drawer.medium": "Medium", + "drawer.off": "Off", + "drawer.random": "Random", + "drawer.reset": "Reset", + "drawer.saved": "Chat settings saved", + "drawer.savedGreedy": "Greedy: the same question gives the same answer.", + "drawer.savedHere": "Saved here, but not for other apps", + "drawer.savedOwn": "Other apps use their own settings again.", + "drawer.savedShared": "Other apps (omp, API clients) use these settings from their next request.", + "drawer.seed": "Seed", + "drawer.seedNote": "empty = random", + "drawer.share": "Use for other apps too", + "drawer.shareNote": "omp and other API clients get these settings for anything they do not set themselves", + "drawer.short": "Settings", + "drawer.showThinking": "Show thinking", + "drawer.showThinkingNote": "expanded while it streams", + "drawer.temperature": "Temperature", + "drawer.temperatureNote": "0 = always the most likely word (exact, repeatable)", + "drawer.thinkHigh": "thorough (default)", + "drawer.thinkLow": "short", + "drawer.thinkMedium": "medium", + "drawer.thinkNone": "answers right away", + "drawer.thinking": "Thinking", + "drawer.title": "Chat settings", + "drawer.untilDone": "Until done", + "export.nothing": "Nothing to save yet", + "file.big": "File too large", + "file.bigText": "{name} is over 512 KB.", + "file.binaryText": "{name} looks like a binary file.", + "file.notText": "Not a text file", + "file.notTextOnly": "{name}: attach text files (code, notes, logs, data).", + "file.notTextPictures": "{name}: attach text files (code, notes, logs, data) or pictures.", + "file.pasted": "pasted image", + "file.pictureBig": "Picture too large", + "file.pictureBigText": "{name} is over 20 MB.", + "file.picturesOff": "Pictures are off", + "file.picturesOffText": "This model was set up for text only.", + "file.remove": "Remove", + "group.month": "Previous 30 days", + "group.older": "Older", + "group.today": "Today", + "group.week": "Previous 7 days", + "group.yesterday": "Yesterday", + "hist.editAnswer": "Edit answer", + "hist.editAnswerTitle": "Correct the answer's text. No request is sent.", + "hist.editLabel": "Edit the answer", + "hist.editNote": "The answer's old thinking and tool calls are removed. No request is sent.", + "hist.editRemoves": { + "one": "Saving hides the {n} message after it. ", + "other": "Saving hides the {n} messages after it. " + }, + "hist.edited": "Edited", + "hist.editedHidden": { + "one": "Answer edited, {n} message hidden", + "other": "Answer edited, {n} messages hidden" + }, + "hist.editedOnly": "Answer edited", + "hist.empty": "The answer is empty", + "hist.emptyText": "Write something before saving.", + "hist.finishFirst": "Finish what is open first", + "hist.finishFirstText": "Save it or press Cancel.", + "hist.hidden": { + "one": "{n} message hidden", + "other": "{n} messages hidden" + }, + "hist.lostText": "This browser kept their names, not their contents. Start a new chat and attach them again.", + "hist.lostText2": "This browser kept their names, not their contents. Attach them again.", + "hist.lostTitle": "Attachments need to be added again", + "hist.nothingHidden": "Back at this message", + "hist.pendingFirst": "A message is waiting", + "hist.pendingFirstText": "Send it or take it back first.", + "hist.regenerate": "Regenerate", + "hist.regenerateTitle": "Ask for a new answer to this question. Tools may run again.", + "hist.replaced": "The answer was replaced", + "hist.rewind": "Rewind to here", + "hist.rewindTitle": "Go back to this point in the chat", + "hist.save": "Save", + "math.source": "Math source ({reason})", + "model.alreadyUnloaded": "Already unloaded", + "model.busy": "Model is busy", + "model.confirmUnload": "Unload the model and free the GPU? Load, or the next message, brings it back.", + "model.fewMinutes": "This can take a few minutes.", + "model.gpuFree": "The GPU is free. Load, or the next message, brings it back.", + "model.gpuInUse": "The GPU is in use.", + "model.imageBusy": "An image is generating. It finishes on its own.", + "model.imageLoading": "An image is already loading the model", + "model.imageLoadingDot": "An image is already loading the model.", + "model.load": "Load", + "model.loadFailed": "Load failed", + "model.loadTitle": "Load the model now. A message also loads it.", + "model.loaded": "Model loaded", + "model.loading": "Loading…", + "model.loadingTitle": "The model is loading", + "model.loadingToast": "Loading the model", + "model.noAnswer": "The server did not answer.", + "model.replyLoading": "A reply is already loading the model", + "model.replyLoadingDot": "A reply is already loading the model.", + "model.stopFirst": "Stop the reply, then unload", + "model.stopFirstDot": "Stop the reply, then unload.", + "model.unload": "Unload", + "model.unloadFailed": "Unload failed", + "model.unloadTitle": "Unload the model and free the GPU", + "model.unloaded": "Model unloaded", + "model.unloading": "Unloading…", + "model.unloadingTitle": "The model is unloading", + "model.unsupported": "Unload is not available", + "model.waiting": "Waiting for the server", + "pending.afterTool": "Waiting for the tool to finish, then sending: “{text}”", + "pending.cutting": "Stopping the answer, then sending: “{text}”", + "pending.one": "A message is already waiting", + "pending.oneText": "Take it back or wait until it is sent.", + "pending.queued": "Sends when this answer is done: “{text}”", + "pending.ready": "Not sent yet: “{text}”", + "pending.send": "Send", + "pending.sendNow": "Send now", + "pending.takeBack": "Take back", + "pill.connecting": "Connecting…", + "pill.generating": "Generating · {rate} tok/s", + "pill.idle": "Idle", + "pill.image": "Generating image…", + "pill.keyNeeded": "API key needed", + "pill.queued": "{n} queued", + "pill.reading": "Reading prompt", + "pill.readingPct": "Reading prompt · {pct}%", + "pill.unloaded": "Unloaded", + "pill.unreachable": "Server not reachable", + "preview.confirm": "Run this code with scripts?\n\nIt runs in your browser, cut off from this chat and from the network, but it can still freeze the tab, and it is code the model wrote.\n\nOnly this block, and only until you close the preview.", + "preview.runScripts": "Run scripts", + "preview.showCode": "Show the code", + "preview.showPage": "Preview the page", + "preview.showSvg": "Preview the picture", + "preview.stopScripts": "Stop scripts", + "preview.titlePage": "Page preview", + "preview.titleSvg": "Picture preview", + "rewind.branch": "Branch from here", + "rewind.branchAnswerText": "Starts a new chat with the messages up to this answer. This chat stays as it is.", + "rewind.branchUserText": "Starts a new chat with the messages before this one, and puts your message in its box. This chat stays as it is.", + "rewind.hereAnswer": "Continue from here", + "rewind.hereAnswerText": "Hides the messages after this answer. Undo brings them back.", + "rewind.hereUser": "Edit and send again here", + "rewind.hereUserText": "Hides this message and the ones after it, and puts your message in the box below. Undo brings them back.", + "rewind.noList": "To start a new chat from here instead, turn on Saved chats in Chat settings.", + "rewind.title": "Rewind to here", + "settings.language": "Language", + "settings.languageNote": "Chat, its settings and the buttons above are translated. The Monitor, Images and About views are still in English.", + "sidebar.collapse": "Collapse the chat list", + "sidebar.delete": "Delete this chat", + "sidebar.deleteShort": "Delete", + "sidebar.expand": "Open the chat list", + "sidebar.foot": { + "one": "{n} chat · kept in this browser", + "other": "{n} chats · kept in this browser" + }, + "sidebar.nameFor": "Name for this chat", + "sidebar.noMatch": "No chat matches", + "sidebar.none": "No chats yet", + "sidebar.rename": "Rename this chat", + "sidebar.renameShort": "Rename", + "sidebar.search": "Search chats", + "sidebar.title": "Chats", + "store.failed": "The chat list could not be saved. The chats on the screen are still there.", + "store.memory": "This browser will not keep the chat list. It stays in memory until you close the page.", + "store.quota": "This browser cannot keep more. The chats on the screen are still there.", + "store.title": "Chat list not saved", + "tab.about": "About", + "tab.chat": "Chat", + "tab.images": "Images", + "tab.monitor": "Monitor", + "tab.views": "Views", + "theme.label": "Switch between light and dark", + "theme.title": "Light / dark", + "think.done": "Thoughts", + "think.for": "Thought for {s} s", + "think.now": "Thinking…", + "toast.copied": "Copied to clipboard", + "toast.engineError": "the engine reported an error", + "toast.httpAnswer": "The server answered HTTP {code}.", + "toast.keyAbout": "This server needs a key: add it under About > Settings.", + "toast.keyAbout2": "API key needed: add it under About > Settings.", + "toast.keyNeeded": "This server needs an API key: add it under About > Settings.", + "toast.requestFailed": "The request failed", + "tool.arguments": "Arguments", + "tool.beingWritten": "(being written)", + "tool.chars": "{n} characters", + "tool.cut": ", cut for the model", + "tool.done": "Done", + "tool.error": "Error", + "tool.result": "Result", + "tool.running": "Running", + "tool.skipped": "Not run", + "tool.writing": "Writing", + "undo": "Undo" +} diff --git a/serve/web/locales/es.json b/serve/web/locales/es.json new file mode 100644 index 00000000..9f9a2429 --- /dev/null +++ b/serve/web/locales/es.json @@ -0,0 +1,249 @@ +{ + "branch.back": "Volver a ella", + "branch.from": "Rama creada desde «{title}»", + "branch.open": "Abrir la original", + "branch.started": "Rama creada", + "branch.startedText": "El chat en el que estabas no ha cambiado; está en la lista de la izquierda.", + "branch.title": "Rama de {title}", + "busy.stillWriting": "Todavía está escribiendo", + "busy.stopFirst": "Detén primero la respuesta.", + "cancel": "Cancelar", + "chat.clearedToast": "Se vació el último chat.", + "chat.copy": "Copiar", + "chat.copyAnswer": "Copiar la respuesta", + "chat.deleted": "Chat eliminado", + "chat.empty": "Pregunta lo que quieras", + "chat.emptyModel": "{model} se ejecuta en este PC. Nada sale de él.", + "chat.image": "imagen", + "chat.interrupted": "Interrumpida", + "chat.interruptedLower": "interrumpida", + "chat.new": "Nuevo chat", + "chat.newToast": "Nuevo chat", + "chat.newToastText": "El chat anterior está en la lista de la izquierda.", + "chat.projectionOff": "proyección desactivada", + "chat.projectionOn": "proyección activada", + "chat.stopped": "Detenida", + "chat.stoppedLower": "detenida", + "chat.tokens": "{n} tokens", + "chat.toolCalls": {"one": "{n} llamada a herramienta", "other": "{n} llamadas a herramientas"}, + "chat.toolLimit": "detenida en el límite de {n} rondas de herramientas (mcp.max_rounds)", + "chat.untitled": "Nuevo chat", + "chat.you": "Tú", + "close": "Cerrar", + "code.copy": "Copiar el código", + "code.label": "código", + "composer.attach": "Adjuntar un archivo de texto (o soltarlo aquí)", + "composer.attachLabel": "Adjuntar un archivo", + "composer.attachPictures": "Adjuntar un archivo de texto o una imagen (o soltarlos aquí)", + "composer.finishOpen": "Guarda o cancela lo que está abierto arriba para continuar", + "composer.hintInterject": "Intro detiene la respuesta aquí y envía ahora", + "composer.hintQueue": "Intro envía cuando termine la respuesta", + "composer.message": "Mensaje", + "composer.newline": "Mayús+Intro: nueva línea", + "composer.placeholder": "Pregunta lo que quieras…", + "composer.save": "Guardar este chat como Markdown", + "composer.saveLabel": "Guardar este chat", + "composer.send": "Enviar", + "composer.stop": "Detener", + "drawer.apply": "Aplicar", + "drawer.busy": "Si envías mientras responde", + "drawer.busyInterject": "Interrumpir", + "drawer.busyInterjectNote": "La respuesta se detiene donde está (lo escrito se queda) y tu mensaje sale enseguida. Una herramienta en marcha termina primero.", + "drawer.busyQueue": "Enviar después", + "drawer.busyQueueNote": "Tu mensaje espera y sale en cuanto termine la respuesta.", + "drawer.busyWait": "Esperar", + "drawer.busyWaitNote": "Enviar está desactivado hasta que termine la respuesta, como antes.", + "drawer.chats": "Chats", + "drawer.edit": "Editar y rebobinar mensajes", + "drawer.editNote": "editar una respuesta, pedir otra nueva o volver a un mensaje anterior (con Deshacer)", + "drawer.greedy": "0 · determinista", + "drawer.high": "Alto", + "drawer.list": "Lista de chats guardados", + "drawer.listNote": "guarda cada chat en una lista a la izquierda, solo en este navegador. Desactivado: un solo chat, como antes", + "drawer.low": "Bajo", + "drawer.math": "Mostrar fórmulas", + "drawer.mathNote": "dibuja las ecuaciones de las respuestas como fórmulas (funciona sin conexión)", + "drawer.maxTokens": "Máx. de tokens", + "drawer.maxTokensNote": "vacío = hasta terminar", + "drawer.mcp": "Usar herramientas de servidores MCP", + "drawer.medium": "Medio", + "drawer.off": "No", + "drawer.random": "Aleatoria", + "drawer.reset": "Restablecer", + "drawer.saved": "Ajustes del chat guardados", + "drawer.savedGreedy": "Determinista: la misma pregunta da la misma respuesta.", + "drawer.savedHere": "Guardado aquí, pero no para otras apps", + "drawer.savedOwn": "Las otras apps vuelven a usar sus propios ajustes.", + "drawer.savedShared": "Las otras apps (omp, clientes de la API) usan estos ajustes desde su próxima solicitud.", + "drawer.seed": "Semilla", + "drawer.seedNote": "vacío = aleatoria", + "drawer.share": "Usar también para otras apps", + "drawer.shareNote": "omp y otros clientes de la API reciben estos ajustes para todo lo que no definan ellos mismos", + "drawer.short": "Ajustes", + "drawer.showThinking": "Mostrar el razonamiento", + "drawer.showThinkingNote": "desplegado mientras se escribe", + "drawer.temperature": "Temperatura", + "drawer.temperatureNote": "0 = siempre la palabra más probable (exacto, repetible)", + "drawer.thinkHigh": "a fondo (predeterminado)", + "drawer.thinkLow": "breve", + "drawer.thinkMedium": "medio", + "drawer.thinkNone": "responde enseguida", + "drawer.thinking": "Razonamiento", + "drawer.title": "Ajustes del chat", + "drawer.untilDone": "Hasta terminar", + "export.nothing": "Todavía no hay nada que guardar", + "file.big": "Archivo demasiado grande", + "file.bigText": "{name} supera los 512 KB.", + "file.binaryText": "{name} parece un archivo binario.", + "file.notText": "No es un archivo de texto", + "file.notTextOnly": "{name}: adjunta archivos de texto (código, notas, registros, datos).", + "file.notTextPictures": "{name}: adjunta archivos de texto (código, notas, registros, datos) o imágenes.", + "file.pasted": "imagen pegada", + "file.pictureBig": "Imagen demasiado grande", + "file.pictureBigText": "{name} supera los 20 MB.", + "file.picturesOff": "Las imágenes están desactivadas", + "file.picturesOffText": "Este modelo se configuró solo para texto.", + "file.remove": "Quitar", + "group.month": "Últimos 30 días", + "group.older": "Más antiguos", + "group.today": "Hoy", + "group.week": "Últimos 7 días", + "group.yesterday": "Ayer", + "hist.editAnswer": "Editar respuesta", + "hist.editAnswerTitle": "Corrige el texto de la respuesta. No se envía ninguna solicitud.", + "hist.editLabel": "Editar la respuesta", + "hist.editNote": "Se quitan el razonamiento y las llamadas a herramientas anteriores de la respuesta. No se envía ninguna solicitud.", + "hist.editRemoves": {"one": "Al guardar se oculta el {n} mensaje posterior. ", "other": "Al guardar se ocultan los {n} mensajes posteriores. "}, + "hist.edited": "Editada", + "hist.editedHidden": {"one": "Respuesta editada, {n} mensaje oculto", "other": "Respuesta editada, {n} mensajes ocultos"}, + "hist.editedOnly": "Respuesta editada", + "hist.empty": "La respuesta está vacía", + "hist.emptyText": "Escribe algo antes de guardar.", + "hist.finishFirst": "Termina primero lo que está abierto", + "hist.finishFirstText": "Guárdalo o pulsa Cancelar.", + "hist.hidden": {"one": "{n} mensaje oculto", "other": "{n} mensajes ocultos"}, + "hist.lostText": "Este navegador guardó los nombres, no el contenido. Empieza un chat nuevo y adjúntalos de nuevo.", + "hist.lostText2": "Este navegador guardó los nombres, no el contenido. Adjúntalos de nuevo.", + "hist.lostTitle": "Hay que volver a adjuntar los archivos", + "hist.nothingHidden": "De vuelta en este mensaje", + "hist.pendingFirst": "Hay un mensaje esperando", + "hist.pendingFirstText": "Envíalo o recupéralo primero.", + "hist.regenerate": "Regenerar", + "hist.regenerateTitle": "Pedir una respuesta nueva a esta pregunta. Las herramientas pueden volver a ejecutarse.", + "hist.replaced": "Se reemplazó la respuesta", + "hist.rewind": "Volver hasta aquí", + "hist.rewindTitle": "Volver a este punto del chat", + "hist.save": "Guardar", + "math.source": "Código de la fórmula ({reason})", + "model.alreadyUnloaded": "Ya estaba descargado", + "model.busy": "El modelo está ocupado", + "model.confirmUnload": "¿Descargar el modelo y liberar la GPU? Cargar, o el siguiente mensaje, lo devuelve.", + "model.fewMinutes": "Puede tardar unos minutos.", + "model.gpuFree": "La GPU está libre. Cargar, o el siguiente mensaje, devuelve el modelo.", + "model.gpuInUse": "La GPU está en uso.", + "model.imageBusy": "Se está generando una imagen. Terminará por sí sola.", + "model.imageLoading": "Una imagen ya está cargando el modelo", + "model.imageLoadingDot": "Una imagen ya está cargando el modelo.", + "model.load": "Cargar", + "model.loadFailed": "No se pudo cargar", + "model.loadTitle": "Cargar el modelo ahora. Un mensaje también lo carga.", + "model.loaded": "Modelo cargado", + "model.loading": "Cargando…", + "model.loadingTitle": "El modelo se está cargando", + "model.loadingToast": "Cargando el modelo", + "model.noAnswer": "El servidor no respondió.", + "model.replyLoading": "Una respuesta ya está cargando el modelo", + "model.replyLoadingDot": "Una respuesta ya está cargando el modelo.", + "model.stopFirst": "Detén la respuesta y luego descarga", + "model.stopFirstDot": "Detén la respuesta y luego descarga.", + "model.unload": "Descargar", + "model.unloadFailed": "No se pudo descargar", + "model.unloadTitle": "Descargar el modelo y liberar la GPU", + "model.unloaded": "Modelo descargado", + "model.unloading": "Descargando…", + "model.unloadingTitle": "El modelo se está descargando", + "model.unsupported": "Descargar no está disponible", + "model.waiting": "Esperando al servidor", + "pending.afterTool": "Esperando a que termine la herramienta, luego se envía: «{text}»", + "pending.cutting": "Deteniendo la respuesta, luego se envía: «{text}»", + "pending.one": "Ya hay un mensaje esperando", + "pending.oneText": "Recupéralo o espera a que se envíe.", + "pending.queued": "Se envía cuando termine esta respuesta: «{text}»", + "pending.ready": "Aún no enviado: «{text}»", + "pending.send": "Enviar", + "pending.sendNow": "Enviar ahora", + "pending.takeBack": "Recuperar", + "pill.connecting": "Conectando…", + "pill.generating": "Escribiendo · {rate} tok/s", + "pill.idle": "Inactivo", + "pill.image": "Generando imagen…", + "pill.keyNeeded": "Falta la clave de API", + "pill.queued": "{n} en cola", + "pill.reading": "Leyendo el mensaje", + "pill.readingPct": "Leyendo el mensaje · {pct} %", + "pill.unloaded": "Descargado", + "pill.unreachable": "Servidor no disponible", + "preview.confirm": "¿Ejecutar este código con scripts?\n\nSe ejecuta en tu navegador, aislado de este chat y de la red, pero aun así puede bloquear la pestaña, y es código escrito por el modelo.\n\nSolo este bloque, y solo hasta que cierres la vista previa.", + "preview.runScripts": "Ejecutar scripts", + "preview.showCode": "Mostrar el código", + "preview.showPage": "Vista previa de la página", + "preview.showSvg": "Vista previa de la imagen", + "preview.stopScripts": "Detener scripts", + "preview.titlePage": "Vista previa de la página", + "preview.titleSvg": "Vista previa de la imagen", + "rewind.branch": "Crear una rama desde aquí", + "rewind.branchAnswerText": "Empieza un chat nuevo con los mensajes hasta esta respuesta. Este chat se queda como está.", + "rewind.branchUserText": "Empieza un chat nuevo con los mensajes anteriores a este y pone tu mensaje en su cuadro. Este chat se queda como está.", + "rewind.hereAnswer": "Continuar desde aquí", + "rewind.hereAnswerText": "Oculta los mensajes posteriores a esta respuesta. Deshacer los devuelve.", + "rewind.hereUser": "Editar y volver a enviar aquí", + "rewind.hereUserText": "Oculta este mensaje y los siguientes, y pone tu mensaje en el cuadro de abajo. Deshacer los devuelve.", + "rewind.noList": "Para empezar en su lugar un chat nuevo desde aquí, activa la lista de chats guardados en los ajustes del chat.", + "rewind.title": "Volver hasta aquí", + "settings.language": "Idioma", + "settings.languageNote": "El chat, sus ajustes y los botones de arriba están traducidos. Las vistas Monitor, Imágenes y Acerca de siguen en inglés.", + "sidebar.collapse": "Contraer la lista de chats", + "sidebar.delete": "Eliminar este chat", + "sidebar.deleteShort": "Eliminar", + "sidebar.expand": "Abrir la lista de chats", + "sidebar.foot": {"one": "{n} chat · guardado en este navegador", "other": "{n} chats · guardados en este navegador"}, + "sidebar.nameFor": "Nombre de este chat", + "sidebar.noMatch": "Ningún chat coincide", + "sidebar.none": "Aún no hay chats", + "sidebar.rename": "Cambiar el nombre de este chat", + "sidebar.renameShort": "Cambiar nombre", + "sidebar.search": "Buscar chats", + "sidebar.title": "Chats", + "store.failed": "No se pudo guardar la lista de chats. Los chats de la pantalla siguen ahí.", + "store.memory": "Este navegador no guardará la lista de chats. Se queda en memoria hasta que cierres la página.", + "store.quota": "Este navegador no puede guardar más. Los chats de la pantalla siguen ahí.", + "store.title": "Lista de chats sin guardar", + "tab.about": "Acerca de", + "tab.chat": "Chat", + "tab.images": "Imágenes", + "tab.monitor": "Monitor", + "tab.views": "Vistas", + "theme.label": "Cambiar entre claro y oscuro", + "theme.title": "Claro / oscuro", + "think.done": "Razonamiento", + "think.for": "Pensó durante {s} s", + "think.now": "Pensando…", + "toast.copied": "Copiado al portapapeles", + "toast.engineError": "el motor informó de un error", + "toast.httpAnswer": "El servidor respondió con HTTP {code}.", + "toast.keyAbout": "Este servidor necesita una clave: añádela en Acerca de > Ajustes.", + "toast.keyAbout2": "Falta la clave de API: añádela en Acerca de > Ajustes.", + "toast.keyNeeded": "Este servidor necesita una clave de API: añádela en Acerca de > Ajustes.", + "toast.requestFailed": "La solicitud falló", + "tool.arguments": "Argumentos", + "tool.beingWritten": "(se está escribiendo)", + "tool.chars": "{n} caracteres", + "tool.cut": ", recortado para el modelo", + "tool.done": "Hecho", + "tool.error": "Error", + "tool.result": "Resultado", + "tool.running": "En marcha", + "tool.skipped": "No ejecutada", + "tool.writing": "Escribiendo", + "undo": "Deshacer" +} diff --git a/serve/web/locales/ja.json b/serve/web/locales/ja.json new file mode 100644 index 00000000..024050c1 --- /dev/null +++ b/serve/web/locales/ja.json @@ -0,0 +1,249 @@ +{ + "branch.back": "元に戻る", + "branch.from": "「{title}」から分岐", + "branch.open": "元のチャットを開く", + "branch.started": "分岐を作成しました", + "branch.startedText": "元のチャットは変わらず、左の一覧にあります。", + "branch.title": "{title} の分岐", + "busy.stillWriting": "まだ書き込み中です", + "busy.stopFirst": "先に回答を停止してください。", + "cancel": "キャンセル", + "chat.clearedToast": "前のチャットを消去しました。", + "chat.copy": "コピー", + "chat.copyAnswer": "回答をコピー", + "chat.deleted": "チャットを削除しました", + "chat.empty": "なんでも聞いてください", + "chat.emptyModel": "{model} はこの PC で動いています。外部には何も送られません。", + "chat.image": "画像", + "chat.interrupted": "中断しました", + "chat.interruptedLower": "中断", + "chat.new": "新しいチャット", + "chat.newToast": "新しいチャット", + "chat.newToastText": "前のチャットは左の一覧にあります。", + "chat.projectionOff": "プロジェクションオフ", + "chat.projectionOn": "プロジェクションオン", + "chat.stopped": "停止しました", + "chat.stoppedLower": "停止", + "chat.tokens": "{n} トークン", + "chat.toolCalls": {"other": "ツール呼び出し {n} 回"}, + "chat.toolLimit": "ツールのラウンド上限 {n} 回で停止 (mcp.max_rounds)", + "chat.untitled": "新しいチャット", + "chat.you": "あなた", + "close": "閉じる", + "code.copy": "コードをコピー", + "code.label": "コード", + "composer.attach": "テキストファイルを添付 (ここにドロップも可)", + "composer.attachLabel": "ファイルを添付", + "composer.attachPictures": "テキストファイルまたは画像を添付 (ここにドロップも可)", + "composer.finishOpen": "続けるには、上で開いているものを保存するかキャンセルしてください", + "composer.hintInterject": "Enter で回答をここで止めてすぐに送信します", + "composer.hintQueue": "Enter で回答が終わってから送信します", + "composer.message": "メッセージ", + "composer.newline": "Shift+Enter: 改行", + "composer.placeholder": "なんでも聞いてください…", + "composer.save": "このチャットを Markdown で保存", + "composer.saveLabel": "このチャットを保存", + "composer.send": "送信", + "composer.stop": "停止", + "drawer.apply": "適用", + "drawer.busy": "回答中に送信したとき", + "drawer.busyInterject": "割り込む", + "drawer.busyInterjectNote": "回答はその場で止まり (書かれた分は残ります)、メッセージがすぐ送られます。実行中のツールは先に終わります。", + "drawer.busyQueue": "終了後に送信", + "drawer.busyQueueNote": "メッセージは待機し、回答が終わりしだい送られます。", + "drawer.busyWait": "待つ", + "drawer.busyWaitNote": "回答が終わるまで送信はできません (これまでどおり)。", + "drawer.chats": "チャット", + "drawer.edit": "メッセージの編集と巻き戻し", + "drawer.editNote": "回答の編集、新しい回答の再生成、以前のメッセージへの巻き戻し (元に戻せます)", + "drawer.greedy": "0 · 固定", + "drawer.high": "高", + "drawer.list": "保存したチャットの一覧", + "drawer.listNote": "すべてのチャットを左の一覧に、このブラウザー内だけに保存します。オフ: これまでどおり 1 つのチャット", + "drawer.low": "低", + "drawer.math": "数式を表示", + "drawer.mathNote": "回答の数式を整形して描画します (オフラインで動作)", + "drawer.maxTokens": "最大トークン数", + "drawer.maxTokensNote": "空欄 = 最後まで", + "drawer.mcp": "MCP サーバーのツールを使う", + "drawer.medium": "中", + "drawer.off": "オフ", + "drawer.random": "ランダム", + "drawer.reset": "リセット", + "drawer.saved": "チャット設定を保存しました", + "drawer.savedGreedy": "固定: 同じ質問には同じ回答が返ります。", + "drawer.savedHere": "ここには保存しましたが、他のアプリには反映されません", + "drawer.savedOwn": "他のアプリは再び独自の設定を使います。", + "drawer.savedShared": "他のアプリ (omp、API クライアント) は次のリクエストからこの設定を使います。", + "drawer.seed": "シード", + "drawer.seedNote": "空欄 = ランダム", + "drawer.share": "他のアプリにも使う", + "drawer.shareNote": "omp などの API クライアントが自分で指定しない項目に、この設定が使われます", + "drawer.short": "設定", + "drawer.showThinking": "思考を表示", + "drawer.showThinkingNote": "生成中は開いた状態にします", + "drawer.temperature": "温度", + "drawer.temperatureNote": "0 = 常に最も確率の高い単語 (正確で再現可能)", + "drawer.thinkHigh": "じっくり (既定)", + "drawer.thinkLow": "短め", + "drawer.thinkMedium": "中程度", + "drawer.thinkNone": "すぐに回答", + "drawer.thinking": "思考", + "drawer.title": "チャット設定", + "drawer.untilDone": "最後まで", + "export.nothing": "保存するものがまだありません", + "file.big": "ファイルが大きすぎます", + "file.bigText": "{name} は 512 KB を超えています。", + "file.binaryText": "{name} はバイナリファイルのようです。", + "file.notText": "テキストファイルではありません", + "file.notTextOnly": "{name}: テキストファイル (コード、メモ、ログ、データ) を添付してください。", + "file.notTextPictures": "{name}: テキストファイル (コード、メモ、ログ、データ) または画像を添付してください。", + "file.pasted": "貼り付けた画像", + "file.pictureBig": "画像が大きすぎます", + "file.pictureBigText": "{name} は 20 MB を超えています。", + "file.picturesOff": "画像はオフです", + "file.picturesOffText": "このモデルはテキスト専用に設定されています。", + "file.remove": "削除", + "group.month": "過去 30 日", + "group.older": "それ以前", + "group.today": "今日", + "group.week": "過去 7 日", + "group.yesterday": "昨日", + "hist.editAnswer": "回答を編集", + "hist.editAnswerTitle": "回答の文章を直します。リクエストは送られません。", + "hist.editLabel": "回答を編集", + "hist.editNote": "回答のこれまでの思考とツール呼び出しは削除されます。リクエストは送られません。", + "hist.editRemoves": {"other": "保存すると、これ以降の {n} 件のメッセージが非表示になります。"}, + "hist.edited": "編集済み", + "hist.editedHidden": {"other": "回答を編集しました。{n} 件のメッセージを非表示"}, + "hist.editedOnly": "回答を編集しました", + "hist.empty": "回答が空です", + "hist.emptyText": "保存する前に何か入力してください。", + "hist.finishFirst": "先に開いているものを終えてください", + "hist.finishFirstText": "保存するか、キャンセルを押してください。", + "hist.hidden": {"other": "{n} 件のメッセージを非表示"}, + "hist.lostText": "このブラウザーには名前だけが残り、内容は残っていません。新しいチャットを始めて、もう一度添付してください。", + "hist.lostText2": "このブラウザーには名前だけが残り、内容は残っていません。もう一度添付してください。", + "hist.lostTitle": "添付をもう一度追加してください", + "hist.nothingHidden": "このメッセージまで戻りました", + "hist.pendingFirst": "待機中のメッセージがあります", + "hist.pendingFirstText": "先に送信するか、取り下げてください。", + "hist.regenerate": "再生成", + "hist.regenerateTitle": "この質問に新しい回答を求めます。ツールがもう一度動くことがあります。", + "hist.replaced": "回答を置き換えました", + "hist.rewind": "ここまで戻す", + "hist.rewindTitle": "チャットのこの時点まで戻ります", + "hist.save": "保存", + "math.source": "数式のソース ({reason})", + "model.alreadyUnloaded": "すでに解放済みです", + "model.busy": "モデルは使用中です", + "model.confirmUnload": "モデルを解放して GPU を空けますか?「読み込む」または次のメッセージで元に戻ります。", + "model.fewMinutes": "数分かかることがあります。", + "model.gpuFree": "GPU は空きました。「読み込む」または次のメッセージでモデルが戻ります。", + "model.gpuInUse": "GPU を使用中です。", + "model.imageBusy": "画像を生成中です。自動で終わります。", + "model.imageLoading": "画像がすでにモデルを読み込んでいます", + "model.imageLoadingDot": "画像がすでにモデルを読み込んでいます。", + "model.load": "読み込む", + "model.loadFailed": "読み込みに失敗しました", + "model.loadTitle": "今すぐモデルを読み込みます。メッセージを送っても読み込まれます。", + "model.loaded": "モデルを読み込みました", + "model.loading": "読み込み中…", + "model.loadingTitle": "モデルを読み込んでいます", + "model.loadingToast": "モデルを読み込み中", + "model.noAnswer": "サーバーが応答しませんでした。", + "model.replyLoading": "回答がすでにモデルを読み込んでいます", + "model.replyLoadingDot": "回答がすでにモデルを読み込んでいます。", + "model.stopFirst": "回答を停止してから解放してください", + "model.stopFirstDot": "回答を停止してから解放してください。", + "model.unload": "解放", + "model.unloadFailed": "解放に失敗しました", + "model.unloadTitle": "モデルを解放して GPU を空けます", + "model.unloaded": "モデルを解放しました", + "model.unloading": "解放中…", + "model.unloadingTitle": "モデルを解放しています", + "model.unsupported": "解放は利用できません", + "model.waiting": "サーバーを待っています", + "pending.afterTool": "ツールの終了を待ってから送信します:「{text}」", + "pending.cutting": "回答を止めてから送信します:「{text}」", + "pending.one": "すでに待機中のメッセージがあります", + "pending.oneText": "取り下げるか、送信されるまでお待ちください。", + "pending.queued": "この回答が終わったら送信します:「{text}」", + "pending.ready": "未送信:「{text}」", + "pending.send": "送信", + "pending.sendNow": "今すぐ送信", + "pending.takeBack": "取り下げる", + "pill.connecting": "接続中…", + "pill.generating": "生成中 · {rate} tok/s", + "pill.idle": "待機中", + "pill.image": "画像を生成中…", + "pill.keyNeeded": "API キーが必要です", + "pill.queued": "待機 {n} 件", + "pill.reading": "プロンプトを読み込み中", + "pill.readingPct": "プロンプトを読み込み中 · {pct}%", + "pill.unloaded": "解放済み", + "pill.unreachable": "サーバーに接続できません", + "preview.confirm": "このコードをスクリプト付きで実行しますか?\n\nコードはお使いのブラウザー内で、このチャットとネットワークから隔離されて動きますが、タブがフリーズすることはあります。また、モデルが書いたコードです。\n\nこのブロックだけ、プレビューを閉じるまでの間だけ実行されます。", + "preview.runScripts": "スクリプトを実行", + "preview.showCode": "コードを表示", + "preview.showPage": "ページをプレビュー", + "preview.showSvg": "画像をプレビュー", + "preview.stopScripts": "スクリプトを停止", + "preview.titlePage": "ページのプレビュー", + "preview.titleSvg": "画像のプレビュー", + "rewind.branch": "ここから分岐", + "rewind.branchAnswerText": "この回答までのメッセージで新しいチャットを始めます。このチャットはそのまま残ります。", + "rewind.branchUserText": "このメッセージより前のメッセージで新しいチャットを始め、あなたのメッセージをその入力欄に入れます。このチャットはそのまま残ります。", + "rewind.hereAnswer": "ここから続ける", + "rewind.hereAnswerText": "この回答より後のメッセージを非表示にします。「元に戻す」で戻せます。", + "rewind.hereUser": "ここで編集して再送信", + "rewind.hereUserText": "このメッセージとそれ以降を非表示にし、あなたのメッセージを下の入力欄に入れます。「元に戻す」で戻せます。", + "rewind.noList": "代わりにここから新しいチャットを始めるには、チャット設定で「保存したチャットの一覧」をオンにしてください。", + "rewind.title": "ここまで戻す", + "settings.language": "言語", + "settings.languageNote": "チャットとその設定、上のボタンは翻訳されています。モニター、画像、情報の画面はまだ英語です。", + "sidebar.collapse": "チャット一覧を閉じる", + "sidebar.delete": "このチャットを削除", + "sidebar.deleteShort": "削除", + "sidebar.expand": "チャット一覧を開く", + "sidebar.foot": {"other": "{n} 件のチャット · このブラウザーに保存"}, + "sidebar.nameFor": "このチャットの名前", + "sidebar.noMatch": "一致するチャットはありません", + "sidebar.none": "チャットはまだありません", + "sidebar.rename": "このチャットの名前を変更", + "sidebar.renameShort": "名前を変更", + "sidebar.search": "チャットを検索", + "sidebar.title": "チャット", + "store.failed": "チャット一覧を保存できませんでした。画面上のチャットはそのまま残っています。", + "store.memory": "このブラウザーはチャット一覧を保存しません。ページを閉じるまでメモリ上に残ります。", + "store.quota": "このブラウザーはこれ以上保存できません。画面上のチャットはそのまま残っています。", + "store.title": "チャット一覧は保存されていません", + "tab.about": "情報", + "tab.chat": "チャット", + "tab.images": "画像", + "tab.monitor": "モニター", + "tab.views": "表示", + "theme.label": "ライトとダークを切り替え", + "theme.title": "ライト / ダーク", + "think.done": "思考", + "think.for": "{s} 秒考えました", + "think.now": "考え中…", + "toast.copied": "クリップボードにコピーしました", + "toast.engineError": "エンジンがエラーを報告しました", + "toast.httpAnswer": "サーバーが HTTP {code} で応答しました。", + "toast.keyAbout": "このサーバーにはキーが必要です。「情報」>「設定」で入力してください。", + "toast.keyAbout2": "API キーが必要です。「情報」>「設定」で入力してください。", + "toast.keyNeeded": "このサーバーには API キーが必要です。「情報」>「設定」で入力してください。", + "toast.requestFailed": "リクエストに失敗しました", + "tool.arguments": "引数", + "tool.beingWritten": "(書き込み中)", + "tool.chars": "{n} 文字", + "tool.cut": "、モデル向けに省略", + "tool.done": "完了", + "tool.error": "エラー", + "tool.result": "結果", + "tool.running": "実行中", + "tool.skipped": "未実行", + "tool.writing": "書き込み中", + "undo": "元に戻す" +} diff --git a/serve/web/locales/ko.json b/serve/web/locales/ko.json new file mode 100644 index 00000000..c14f4437 --- /dev/null +++ b/serve/web/locales/ko.json @@ -0,0 +1,249 @@ +{ + "branch.back": "원래 채팅으로", + "branch.from": "“{title}”에서 분기됨", + "branch.open": "원본 열기", + "branch.started": "분기를 만들었습니다", + "branch.startedText": "이전 채팅은 그대로이며 왼쪽 목록에 있습니다.", + "branch.title": "{title}의 분기", + "busy.stillWriting": "아직 작성 중입니다", + "busy.stopFirst": "먼저 답변을 중지하세요.", + "cancel": "취소", + "chat.clearedToast": "지난 채팅을 비웠습니다.", + "chat.copy": "복사", + "chat.copyAnswer": "답변 복사", + "chat.deleted": "채팅을 삭제했습니다", + "chat.empty": "무엇이든 물어보세요", + "chat.emptyModel": "{model}은(는) 이 PC에서 실행됩니다. 밖으로 나가는 것은 없습니다.", + "chat.image": "이미지", + "chat.interrupted": "중단됨", + "chat.interruptedLower": "중단됨", + "chat.new": "새 채팅", + "chat.newToast": "새 채팅", + "chat.newToastText": "이전 채팅은 왼쪽 목록에 있습니다.", + "chat.projectionOff": "프로젝션 꺼짐", + "chat.projectionOn": "프로젝션 켜짐", + "chat.stopped": "중지됨", + "chat.stoppedLower": "중지됨", + "chat.tokens": "토큰 {n}개", + "chat.toolCalls": {"other": "도구 호출 {n}회"}, + "chat.toolLimit": "도구 라운드 한도 {n}회에서 중지됨 (mcp.max_rounds)", + "chat.untitled": "새 채팅", + "chat.you": "나", + "close": "닫기", + "code.copy": "코드 복사", + "code.label": "코드", + "composer.attach": "텍스트 파일 첨부 (여기로 끌어다 놓아도 됩니다)", + "composer.attachLabel": "파일 첨부", + "composer.attachPictures": "텍스트 파일 또는 이미지 첨부 (여기로 끌어다 놓아도 됩니다)", + "composer.finishOpen": "계속하려면 위에 열려 있는 것을 저장하거나 취소하세요", + "composer.hintInterject": "Enter를 누르면 답변을 여기서 멈추고 바로 보냅니다", + "composer.hintQueue": "Enter를 누르면 답변이 끝난 뒤에 보냅니다", + "composer.message": "메시지", + "composer.newline": "Shift+Enter: 줄바꿈", + "composer.placeholder": "무엇이든 물어보세요…", + "composer.save": "이 채팅을 Markdown으로 저장", + "composer.saveLabel": "이 채팅 저장", + "composer.send": "보내기", + "composer.stop": "중지", + "drawer.apply": "적용", + "drawer.busy": "답변 중에 보내면", + "drawer.busyInterject": "중단", + "drawer.busyInterjectNote": "답변이 그 자리에서 멈추고 (쓰인 내용은 남습니다) 메시지가 바로 전송됩니다. 실행 중인 도구는 먼저 끝납니다.", + "drawer.busyQueue": "끝난 뒤 보내기", + "drawer.busyQueueNote": "메시지가 기다렸다가 답변이 끝나는 즉시 전송됩니다.", + "drawer.busyWait": "대기", + "drawer.busyWaitNote": "답변이 끝날 때까지 보내기가 꺼져 있습니다. 이전과 같습니다.", + "drawer.chats": "채팅", + "drawer.edit": "메시지 편집 및 되감기", + "drawer.editNote": "답변을 편집하거나, 새 답변을 요청하거나, 이전 메시지로 되돌아갑니다 (실행 취소 가능)", + "drawer.greedy": "0 · 고정", + "drawer.high": "높음", + "drawer.list": "저장된 채팅 목록", + "drawer.listNote": "모든 채팅을 이 브라우저 안에서만 왼쪽 목록에 보관합니다. 끔: 이전처럼 채팅 하나", + "drawer.low": "낮음", + "drawer.math": "수식 표시", + "drawer.mathNote": "답변의 수식을 공식 형태로 그립니다 (오프라인에서 동작)", + "drawer.maxTokens": "최대 토큰", + "drawer.maxTokensNote": "비우면 끝까지", + "drawer.mcp": "MCP 서버의 도구 사용", + "drawer.medium": "보통", + "drawer.off": "끔", + "drawer.random": "무작위", + "drawer.reset": "초기화", + "drawer.saved": "채팅 설정을 저장했습니다", + "drawer.savedGreedy": "고정: 같은 질문에는 같은 답변이 나옵니다.", + "drawer.savedHere": "여기에는 저장했지만 다른 앱에는 적용되지 않았습니다", + "drawer.savedOwn": "다른 앱이 다시 자체 설정을 사용합니다.", + "drawer.savedShared": "다른 앱 (omp, API 클라이언트)은 다음 요청부터 이 설정을 사용합니다.", + "drawer.seed": "시드", + "drawer.seedNote": "비우면 무작위", + "drawer.share": "다른 앱에도 사용", + "drawer.shareNote": "omp 등 API 클라이언트가 직접 지정하지 않은 항목에 이 설정이 적용됩니다", + "drawer.short": "설정", + "drawer.showThinking": "추론 표시", + "drawer.showThinkingNote": "작성되는 동안 펼쳐 둡니다", + "drawer.temperature": "온도", + "drawer.temperatureNote": "0 = 항상 가장 가능성 높은 단어 (정확하고 반복 가능)", + "drawer.thinkHigh": "꼼꼼히 (기본값)", + "drawer.thinkLow": "짧게", + "drawer.thinkMedium": "보통", + "drawer.thinkNone": "바로 답변", + "drawer.thinking": "추론", + "drawer.title": "채팅 설정", + "drawer.untilDone": "끝까지", + "export.nothing": "아직 저장할 내용이 없습니다", + "file.big": "파일이 너무 큽니다", + "file.bigText": "{name}은(는) 512 KB를 넘습니다.", + "file.binaryText": "{name}은(는) 바이너리 파일 같습니다.", + "file.notText": "텍스트 파일이 아닙니다", + "file.notTextOnly": "{name}: 텍스트 파일(코드, 메모, 로그, 데이터)을 첨부하세요.", + "file.notTextPictures": "{name}: 텍스트 파일(코드, 메모, 로그, 데이터) 또는 이미지를 첨부하세요.", + "file.pasted": "붙여넣은 이미지", + "file.pictureBig": "이미지가 너무 큽니다", + "file.pictureBigText": "{name}은(는) 20 MB를 넘습니다.", + "file.picturesOff": "이미지가 꺼져 있습니다", + "file.picturesOffText": "이 모델은 텍스트 전용으로 설정되었습니다.", + "file.remove": "제거", + "group.month": "지난 30일", + "group.older": "이전", + "group.today": "오늘", + "group.week": "지난 7일", + "group.yesterday": "어제", + "hist.editAnswer": "답변 편집", + "hist.editAnswerTitle": "답변의 텍스트를 고칩니다. 요청은 전송되지 않습니다.", + "hist.editLabel": "답변 편집", + "hist.editNote": "답변의 이전 추론과 도구 호출이 제거됩니다. 요청은 전송되지 않습니다.", + "hist.editRemoves": {"other": "저장하면 이후 메시지 {n}개가 숨겨집니다. "}, + "hist.edited": "편집됨", + "hist.editedHidden": {"other": "답변을 편집했습니다. 메시지 {n}개 숨김"}, + "hist.editedOnly": "답변을 편집했습니다", + "hist.empty": "답변이 비어 있습니다", + "hist.emptyText": "저장하기 전에 내용을 입력하세요.", + "hist.finishFirst": "먼저 열려 있는 것을 마무리하세요", + "hist.finishFirstText": "저장하거나 취소를 누르세요.", + "hist.hidden": {"other": "메시지 {n}개 숨김"}, + "hist.lostText": "이 브라우저에는 이름만 남아 있고 내용은 없습니다. 새 채팅을 시작해 다시 첨부하세요.", + "hist.lostText2": "이 브라우저에는 이름만 남아 있고 내용은 없습니다. 다시 첨부하세요.", + "hist.lostTitle": "첨부 파일을 다시 추가해야 합니다", + "hist.nothingHidden": "이 메시지로 돌아왔습니다", + "hist.pendingFirst": "대기 중인 메시지가 있습니다", + "hist.pendingFirstText": "먼저 보내거나 되돌려 놓으세요.", + "hist.regenerate": "다시 생성", + "hist.regenerateTitle": "이 질문에 새 답변을 요청합니다. 도구가 다시 실행될 수 있습니다.", + "hist.replaced": "답변을 교체했습니다", + "hist.rewind": "여기로 되감기", + "hist.rewindTitle": "채팅의 이 지점으로 돌아갑니다", + "hist.save": "저장", + "math.source": "수식 원문 ({reason})", + "model.alreadyUnloaded": "이미 해제되어 있습니다", + "model.busy": "모델이 사용 중입니다", + "model.confirmUnload": "모델을 해제하고 GPU를 비울까요? 불러오기 또는 다음 메시지로 다시 돌아옵니다.", + "model.fewMinutes": "몇 분 걸릴 수 있습니다.", + "model.gpuFree": "GPU가 비었습니다. 불러오기 또는 다음 메시지로 모델이 돌아옵니다.", + "model.gpuInUse": "GPU를 사용 중입니다.", + "model.imageBusy": "이미지를 생성 중입니다. 저절로 끝납니다.", + "model.imageLoading": "이미지가 이미 모델을 불러오고 있습니다", + "model.imageLoadingDot": "이미지가 이미 모델을 불러오고 있습니다.", + "model.load": "불러오기", + "model.loadFailed": "불러오지 못했습니다", + "model.loadTitle": "지금 모델을 불러옵니다. 메시지를 보내도 불러옵니다.", + "model.loaded": "모델을 불러왔습니다", + "model.loading": "불러오는 중…", + "model.loadingTitle": "모델을 불러오는 중입니다", + "model.loadingToast": "모델을 불러오는 중", + "model.noAnswer": "서버가 응답하지 않았습니다.", + "model.replyLoading": "답변이 이미 모델을 불러오고 있습니다", + "model.replyLoadingDot": "답변이 이미 모델을 불러오고 있습니다.", + "model.stopFirst": "답변을 중지한 뒤 해제하세요", + "model.stopFirstDot": "답변을 중지한 뒤 해제하세요.", + "model.unload": "해제", + "model.unloadFailed": "해제하지 못했습니다", + "model.unloadTitle": "모델을 해제하고 GPU를 비웁니다", + "model.unloaded": "모델을 해제했습니다", + "model.unloading": "해제하는 중…", + "model.unloadingTitle": "모델을 해제하는 중입니다", + "model.unsupported": "해제를 사용할 수 없습니다", + "model.waiting": "서버를 기다리는 중", + "pending.afterTool": "도구가 끝나기를 기다린 뒤 보냅니다: “{text}”", + "pending.cutting": "답변을 멈춘 뒤 보냅니다: “{text}”", + "pending.one": "이미 대기 중인 메시지가 있습니다", + "pending.oneText": "되돌려 놓거나 전송될 때까지 기다리세요.", + "pending.queued": "이 답변이 끝나면 보냅니다: “{text}”", + "pending.ready": "아직 보내지 않음: “{text}”", + "pending.send": "보내기", + "pending.sendNow": "지금 보내기", + "pending.takeBack": "되돌리기", + "pill.connecting": "연결 중…", + "pill.generating": "작성 중 · {rate} tok/s", + "pill.idle": "유휴 상태", + "pill.image": "이미지 생성 중…", + "pill.keyNeeded": "API 키 필요", + "pill.queued": "대기 {n}건", + "pill.reading": "프롬프트 읽는 중", + "pill.readingPct": "프롬프트 읽는 중 · {pct}%", + "pill.unloaded": "해제됨", + "pill.unreachable": "서버에 연결할 수 없음", + "preview.confirm": "이 코드를 스크립트와 함께 실행할까요?\n\n코드는 이 채팅과 네트워크에서 격리된 채 브라우저 안에서 실행되지만, 탭이 멈출 수는 있으며 모델이 작성한 코드입니다.\n\n이 블록만, 미리보기를 닫을 때까지만 실행됩니다.", + "preview.runScripts": "스크립트 실행", + "preview.showCode": "코드 보기", + "preview.showPage": "페이지 미리보기", + "preview.showSvg": "이미지 미리보기", + "preview.stopScripts": "스크립트 중지", + "preview.titlePage": "페이지 미리보기", + "preview.titleSvg": "이미지 미리보기", + "rewind.branch": "여기서 분기", + "rewind.branchAnswerText": "이 답변까지의 메시지로 새 채팅을 시작합니다. 이 채팅은 그대로 남습니다.", + "rewind.branchUserText": "이 메시지 이전의 메시지로 새 채팅을 시작하고 내 메시지를 그 입력란에 넣습니다. 이 채팅은 그대로 남습니다.", + "rewind.hereAnswer": "여기서 계속", + "rewind.hereAnswerText": "이 답변 이후의 메시지를 숨깁니다. 실행 취소로 되돌릴 수 있습니다.", + "rewind.hereUser": "여기서 편집하고 다시 보내기", + "rewind.hereUserText": "이 메시지와 이후 메시지를 숨기고 내 메시지를 아래 입력란에 넣습니다. 실행 취소로 되돌릴 수 있습니다.", + "rewind.noList": "대신 여기서 새 채팅을 시작하려면 채팅 설정에서 저장된 채팅 목록을 켜세요.", + "rewind.title": "여기로 되감기", + "settings.language": "언어", + "settings.languageNote": "채팅과 채팅 설정, 위의 버튼은 번역되어 있습니다. 모니터, 이미지, 정보 화면은 아직 영어입니다.", + "sidebar.collapse": "채팅 목록 접기", + "sidebar.delete": "이 채팅 삭제", + "sidebar.deleteShort": "삭제", + "sidebar.expand": "채팅 목록 열기", + "sidebar.foot": {"other": "채팅 {n}개 · 이 브라우저에 저장됨"}, + "sidebar.nameFor": "이 채팅의 이름", + "sidebar.noMatch": "일치하는 채팅이 없습니다", + "sidebar.none": "아직 채팅이 없습니다", + "sidebar.rename": "이 채팅 이름 변경", + "sidebar.renameShort": "이름 변경", + "sidebar.search": "채팅 검색", + "sidebar.title": "채팅", + "store.failed": "채팅 목록을 저장하지 못했습니다. 화면의 채팅은 그대로 있습니다.", + "store.memory": "이 브라우저는 채팅 목록을 보관하지 않습니다. 페이지를 닫을 때까지 메모리에만 남습니다.", + "store.quota": "이 브라우저는 더 이상 보관할 수 없습니다. 화면의 채팅은 그대로 있습니다.", + "store.title": "채팅 목록이 저장되지 않음", + "tab.about": "정보", + "tab.chat": "채팅", + "tab.images": "이미지", + "tab.monitor": "모니터", + "tab.views": "보기", + "theme.label": "라이트와 다크 전환", + "theme.title": "라이트 / 다크", + "think.done": "추론", + "think.for": "{s}초 동안 생각함", + "think.now": "생각하는 중…", + "toast.copied": "클립보드에 복사했습니다", + "toast.engineError": "엔진이 오류를 보고했습니다", + "toast.httpAnswer": "서버가 HTTP {code}로 응답했습니다.", + "toast.keyAbout": "이 서버에는 키가 필요합니다. 정보 > 설정에 입력하세요.", + "toast.keyAbout2": "API 키가 필요합니다. 정보 > 설정에 입력하세요.", + "toast.keyNeeded": "이 서버에는 API 키가 필요합니다. 정보 > 설정에 입력하세요.", + "toast.requestFailed": "요청이 실패했습니다", + "tool.arguments": "인수", + "tool.beingWritten": "(작성 중)", + "tool.chars": "{n}자", + "tool.cut": ", 모델용으로 줄임", + "tool.done": "완료", + "tool.error": "오류", + "tool.result": "결과", + "tool.running": "실행 중", + "tool.skipped": "실행 안 됨", + "tool.writing": "작성 중", + "undo": "실행 취소" +} diff --git a/serve/web/locales/pt.json b/serve/web/locales/pt.json new file mode 100644 index 00000000..bc343a61 --- /dev/null +++ b/serve/web/locales/pt.json @@ -0,0 +1,249 @@ +{ + "branch.back": "Voltar a ele", + "branch.from": "Ramificado de “{title}”", + "branch.open": "Abrir o original", + "branch.started": "Ramificação criada", + "branch.startedText": "O chat em que você estava não mudou; ele está na lista à esquerda.", + "branch.title": "Ramificação de {title}", + "busy.stillWriting": "Ainda está escrevendo", + "busy.stopFirst": "Pare a resposta primeiro.", + "cancel": "Cancelar", + "chat.clearedToast": "O último chat foi limpo.", + "chat.copy": "Copiar", + "chat.copyAnswer": "Copiar a resposta", + "chat.deleted": "Chat excluído", + "chat.empty": "Pergunte o que quiser", + "chat.emptyModel": "{model} roda neste PC. Nada sai dele.", + "chat.image": "imagem", + "chat.interrupted": "Interrompida", + "chat.interruptedLower": "interrompida", + "chat.new": "Novo chat", + "chat.newToast": "Novo chat", + "chat.newToastText": "O chat anterior está na lista à esquerda.", + "chat.projectionOff": "projeção desativada", + "chat.projectionOn": "projeção ativada", + "chat.stopped": "Parada", + "chat.stoppedLower": "parada", + "chat.tokens": "{n} tokens", + "chat.toolCalls": {"one": "{n} chamada de ferramenta", "other": "{n} chamadas de ferramenta"}, + "chat.toolLimit": "parada no limite de {n} rodadas de ferramentas (mcp.max_rounds)", + "chat.untitled": "Novo chat", + "chat.you": "Você", + "close": "Fechar", + "code.copy": "Copiar o código", + "code.label": "código", + "composer.attach": "Anexar um arquivo de texto (ou soltá-lo aqui)", + "composer.attachLabel": "Anexar um arquivo", + "composer.attachPictures": "Anexar um arquivo de texto ou uma imagem (ou soltá-los aqui)", + "composer.finishOpen": "Salve ou cancele o que está aberto acima para continuar", + "composer.hintInterject": "Enter interrompe a resposta aqui e envia agora", + "composer.hintQueue": "Enter envia quando a resposta terminar", + "composer.message": "Mensagem", + "composer.newline": "Shift+Enter: nova linha", + "composer.placeholder": "Pergunte o que quiser…", + "composer.save": "Salvar este chat como Markdown", + "composer.saveLabel": "Salvar este chat", + "composer.send": "Enviar", + "composer.stop": "Parar", + "drawer.apply": "Aplicar", + "drawer.busy": "Quando você envia enquanto ele responde", + "drawer.busyInterject": "Interromper", + "drawer.busyInterjectNote": "A resposta para onde está (o que foi escrito fica) e sua mensagem vai na hora. Uma ferramenta em execução termina primeiro.", + "drawer.busyQueue": "Enviar depois", + "drawer.busyQueueNote": "Sua mensagem espera e vai assim que a resposta terminar.", + "drawer.busyWait": "Esperar", + "drawer.busyWaitNote": "Enviar fica desativado até a resposta terminar, como antes.", + "drawer.chats": "Chats", + "drawer.edit": "Editar e voltar nas mensagens", + "drawer.editNote": "editar uma resposta, pedir uma nova ou voltar a uma mensagem anterior (com Desfazer)", + "drawer.greedy": "0 · determinístico", + "drawer.high": "Alto", + "drawer.list": "Lista de chats salvos", + "drawer.listNote": "guarda cada chat em uma lista à esquerda, só neste navegador. Desativado: um único chat, como antes", + "drawer.low": "Baixo", + "drawer.math": "Exibir fórmulas", + "drawer.mathNote": "desenha as equações das respostas como fórmulas (funciona offline)", + "drawer.maxTokens": "Máx. de tokens", + "drawer.maxTokensNote": "vazio = até terminar", + "drawer.mcp": "Usar ferramentas de servidores MCP", + "drawer.medium": "Médio", + "drawer.off": "Não", + "drawer.random": "Aleatória", + "drawer.reset": "Redefinir", + "drawer.saved": "Configurações do chat salvas", + "drawer.savedGreedy": "Determinístico: a mesma pergunta dá a mesma resposta.", + "drawer.savedHere": "Salvo aqui, mas não para outros apps", + "drawer.savedOwn": "Os outros apps voltam a usar as próprias configurações.", + "drawer.savedShared": "Os outros apps (omp, clientes da API) usam estas configurações a partir da próxima solicitação.", + "drawer.seed": "Semente", + "drawer.seedNote": "vazio = aleatória", + "drawer.share": "Usar também para outros apps", + "drawer.shareNote": "omp e outros clientes da API recebem estas configurações para tudo que eles mesmos não definirem", + "drawer.short": "Configurações", + "drawer.showThinking": "Mostrar o raciocínio", + "drawer.showThinkingNote": "aberto enquanto escreve", + "drawer.temperature": "Temperatura", + "drawer.temperatureNote": "0 = sempre a palavra mais provável (exato, repetível)", + "drawer.thinkHigh": "a fundo (padrão)", + "drawer.thinkLow": "curto", + "drawer.thinkMedium": "médio", + "drawer.thinkNone": "responde na hora", + "drawer.thinking": "Raciocínio", + "drawer.title": "Configurações do chat", + "drawer.untilDone": "Até terminar", + "export.nothing": "Ainda não há nada para salvar", + "file.big": "Arquivo grande demais", + "file.bigText": "{name} passa de 512 KB.", + "file.binaryText": "{name} parece ser um arquivo binário.", + "file.notText": "Não é um arquivo de texto", + "file.notTextOnly": "{name}: anexe arquivos de texto (código, notas, logs, dados).", + "file.notTextPictures": "{name}: anexe arquivos de texto (código, notas, logs, dados) ou imagens.", + "file.pasted": "imagem colada", + "file.pictureBig": "Imagem grande demais", + "file.pictureBigText": "{name} passa de 20 MB.", + "file.picturesOff": "As imagens estão desativadas", + "file.picturesOffText": "Este modelo foi configurado só para texto.", + "file.remove": "Remover", + "group.month": "Últimos 30 dias", + "group.older": "Mais antigos", + "group.today": "Hoje", + "group.week": "Últimos 7 dias", + "group.yesterday": "Ontem", + "hist.editAnswer": "Editar resposta", + "hist.editAnswerTitle": "Corrija o texto da resposta. Nenhuma solicitação é enviada.", + "hist.editLabel": "Editar a resposta", + "hist.editNote": "O raciocínio e as chamadas de ferramenta anteriores da resposta são removidos. Nenhuma solicitação é enviada.", + "hist.editRemoves": {"one": "Ao salvar, a {n} mensagem seguinte fica oculta. ", "other": "Ao salvar, as {n} mensagens seguintes ficam ocultas. "}, + "hist.edited": "Editada", + "hist.editedHidden": {"one": "Resposta editada, {n} mensagem oculta", "other": "Resposta editada, {n} mensagens ocultas"}, + "hist.editedOnly": "Resposta editada", + "hist.empty": "A resposta está vazia", + "hist.emptyText": "Escreva algo antes de salvar.", + "hist.finishFirst": "Termine primeiro o que está aberto", + "hist.finishFirstText": "Salve ou pressione Cancelar.", + "hist.hidden": {"one": "{n} mensagem oculta", "other": "{n} mensagens ocultas"}, + "hist.lostText": "Este navegador guardou os nomes, não o conteúdo. Comece um novo chat e anexe-os de novo.", + "hist.lostText2": "Este navegador guardou os nomes, não o conteúdo. Anexe-os de novo.", + "hist.lostTitle": "É preciso anexar os arquivos de novo", + "hist.nothingHidden": "De volta a esta mensagem", + "hist.pendingFirst": "Há uma mensagem esperando", + "hist.pendingFirstText": "Envie-a ou retire-a primeiro.", + "hist.regenerate": "Gerar de novo", + "hist.regenerateTitle": "Pedir uma nova resposta a esta pergunta. As ferramentas podem rodar de novo.", + "hist.replaced": "A resposta foi substituída", + "hist.rewind": "Voltar até aqui", + "hist.rewindTitle": "Voltar a este ponto do chat", + "hist.save": "Salvar", + "math.source": "Código da fórmula ({reason})", + "model.alreadyUnloaded": "Já estava descarregado", + "model.busy": "O modelo está ocupado", + "model.confirmUnload": "Descarregar o modelo e liberar a GPU? Carregar, ou a próxima mensagem, o traz de volta.", + "model.fewMinutes": "Isso pode levar alguns minutos.", + "model.gpuFree": "A GPU está livre. Carregar, ou a próxima mensagem, traz o modelo de volta.", + "model.gpuInUse": "A GPU está em uso.", + "model.imageBusy": "Uma imagem está sendo gerada. Ela termina sozinha.", + "model.imageLoading": "Uma imagem já está carregando o modelo", + "model.imageLoadingDot": "Uma imagem já está carregando o modelo.", + "model.load": "Carregar", + "model.loadFailed": "Falha ao carregar", + "model.loadTitle": "Carregar o modelo agora. Uma mensagem também o carrega.", + "model.loaded": "Modelo carregado", + "model.loading": "Carregando…", + "model.loadingTitle": "O modelo está sendo carregado", + "model.loadingToast": "Carregando o modelo", + "model.noAnswer": "O servidor não respondeu.", + "model.replyLoading": "Uma resposta já está carregando o modelo", + "model.replyLoadingDot": "Uma resposta já está carregando o modelo.", + "model.stopFirst": "Pare a resposta e depois descarregue", + "model.stopFirstDot": "Pare a resposta e depois descarregue.", + "model.unload": "Descarregar", + "model.unloadFailed": "Falha ao descarregar", + "model.unloadTitle": "Descarregar o modelo e liberar a GPU", + "model.unloaded": "Modelo descarregado", + "model.unloading": "Descarregando…", + "model.unloadingTitle": "O modelo está sendo descarregado", + "model.unsupported": "Descarregar não está disponível", + "model.waiting": "Esperando o servidor", + "pending.afterTool": "Esperando a ferramenta terminar, depois envia: “{text}”", + "pending.cutting": "Parando a resposta, depois envia: “{text}”", + "pending.one": "Já há uma mensagem esperando", + "pending.oneText": "Retire-a ou espere até ela ser enviada.", + "pending.queued": "Envia quando esta resposta terminar: “{text}”", + "pending.ready": "Ainda não enviada: “{text}”", + "pending.send": "Enviar", + "pending.sendNow": "Enviar agora", + "pending.takeBack": "Retirar", + "pill.connecting": "Conectando…", + "pill.generating": "Escrevendo · {rate} tok/s", + "pill.idle": "Ocioso", + "pill.image": "Gerando imagem…", + "pill.keyNeeded": "Falta a chave de API", + "pill.queued": "{n} na fila", + "pill.reading": "Lendo a mensagem", + "pill.readingPct": "Lendo a mensagem · {pct}%", + "pill.unloaded": "Descarregado", + "pill.unreachable": "Servidor inacessível", + "preview.confirm": "Executar este código com scripts?\n\nEle roda no seu navegador, isolado deste chat e da rede, mas ainda pode travar a aba, e é código escrito pelo modelo.\n\nSó este bloco, e só até você fechar a prévia.", + "preview.runScripts": "Executar scripts", + "preview.showCode": "Mostrar o código", + "preview.showPage": "Prévia da página", + "preview.showSvg": "Prévia da imagem", + "preview.stopScripts": "Parar scripts", + "preview.titlePage": "Prévia da página", + "preview.titleSvg": "Prévia da imagem", + "rewind.branch": "Criar ramificação a partir daqui", + "rewind.branchAnswerText": "Começa um novo chat com as mensagens até esta resposta. Este chat fica como está.", + "rewind.branchUserText": "Começa um novo chat com as mensagens anteriores a esta e põe sua mensagem no campo dele. Este chat fica como está.", + "rewind.hereAnswer": "Continuar daqui", + "rewind.hereAnswerText": "Oculta as mensagens depois desta resposta. Desfazer as traz de volta.", + "rewind.hereUser": "Editar e enviar de novo aqui", + "rewind.hereUserText": "Oculta esta mensagem e as seguintes e põe sua mensagem no campo abaixo. Desfazer as traz de volta.", + "rewind.noList": "Para começar um novo chat a partir daqui, ative a lista de chats salvos nas configurações do chat.", + "rewind.title": "Voltar até aqui", + "settings.language": "Idioma", + "settings.languageNote": "O chat, as configurações dele e os botões acima estão traduzidos. As telas Monitor, Imagens e Sobre ainda estão em inglês.", + "sidebar.collapse": "Recolher a lista de chats", + "sidebar.delete": "Excluir este chat", + "sidebar.deleteShort": "Excluir", + "sidebar.expand": "Abrir a lista de chats", + "sidebar.foot": {"one": "{n} chat · guardado neste navegador", "other": "{n} chats · guardados neste navegador"}, + "sidebar.nameFor": "Nome deste chat", + "sidebar.noMatch": "Nenhum chat corresponde", + "sidebar.none": "Ainda não há chats", + "sidebar.rename": "Renomear este chat", + "sidebar.renameShort": "Renomear", + "sidebar.search": "Buscar chats", + "sidebar.title": "Chats", + "store.failed": "Não foi possível salvar a lista de chats. Os chats na tela continuam lá.", + "store.memory": "Este navegador não vai guardar a lista de chats. Ela fica na memória até você fechar a página.", + "store.quota": "Este navegador não consegue guardar mais. Os chats na tela continuam lá.", + "store.title": "Lista de chats não salva", + "tab.about": "Sobre", + "tab.chat": "Chat", + "tab.images": "Imagens", + "tab.monitor": "Monitor", + "tab.views": "Telas", + "theme.label": "Alternar entre claro e escuro", + "theme.title": "Claro / escuro", + "think.done": "Raciocínio", + "think.for": "Pensou por {s} s", + "think.now": "Pensando…", + "toast.copied": "Copiado para a área de transferência", + "toast.engineError": "o motor informou um erro", + "toast.httpAnswer": "O servidor respondeu com HTTP {code}.", + "toast.keyAbout": "Este servidor precisa de uma chave: adicione-a em Sobre > Configurações.", + "toast.keyAbout2": "Falta a chave de API: adicione-a em Sobre > Configurações.", + "toast.keyNeeded": "Este servidor precisa de uma chave de API: adicione-a em Sobre > Configurações.", + "toast.requestFailed": "A solicitação falhou", + "tool.arguments": "Argumentos", + "tool.beingWritten": "(sendo escrito)", + "tool.chars": "{n} caracteres", + "tool.cut": ", cortado para o modelo", + "tool.done": "Concluído", + "tool.error": "Erro", + "tool.result": "Resultado", + "tool.running": "Em execução", + "tool.skipped": "Não executada", + "tool.writing": "Escrevendo", + "undo": "Desfazer" +} diff --git a/serve/web/locales/ru.json b/serve/web/locales/ru.json new file mode 100644 index 00000000..7b83de91 --- /dev/null +++ b/serve/web/locales/ru.json @@ -0,0 +1,249 @@ +{ + "branch.back": "Вернуться к нему", + "branch.from": "Ответвление от «{title}»", + "branch.open": "Открыть оригинал", + "branch.started": "Ответвление создано", + "branch.startedText": "Чат, в котором вы были, не изменился: он в списке слева.", + "branch.title": "Ответвление от «{title}»", + "busy.stillWriting": "Ответ ещё пишется", + "busy.stopFirst": "Сначала остановите ответ.", + "cancel": "Отмена", + "chat.clearedToast": "Последний чат очищен.", + "chat.copy": "Копировать", + "chat.copyAnswer": "Копировать ответ", + "chat.deleted": "Чат удалён", + "chat.empty": "Спрашивайте что угодно", + "chat.emptyModel": "{model} работает на этом ПК. Ничто не уходит наружу.", + "chat.image": "изображение", + "chat.interrupted": "Прервано", + "chat.interruptedLower": "прервано", + "chat.new": "Новый чат", + "chat.newToast": "Новый чат", + "chat.newToastText": "Прежний чат остался в списке слева.", + "chat.projectionOff": "проекция выключена", + "chat.projectionOn": "проекция включена", + "chat.stopped": "Остановлено", + "chat.stoppedLower": "остановлено", + "chat.tokens": "{n} токенов", + "chat.toolCalls": {"one": "{n} вызов инструмента", "few": "{n} вызова инструмента", "many": "{n} вызовов инструмента", "other": "{n} вызова инструмента"}, + "chat.toolLimit": "остановлено на пределе в {n} раундов инструментов (mcp.max_rounds)", + "chat.untitled": "Новый чат", + "chat.you": "Вы", + "close": "Закрыть", + "code.copy": "Копировать код", + "code.label": "код", + "composer.attach": "Прикрепить текстовый файл (или перетащить сюда)", + "composer.attachLabel": "Прикрепить файл", + "composer.attachPictures": "Прикрепить текстовый файл или изображение (или перетащить сюда)", + "composer.finishOpen": "Сохраните или отмените то, что открыто выше, чтобы продолжить", + "composer.hintInterject": "Enter остановит ответ здесь и сразу отправит", + "composer.hintQueue": "Enter отправит, когда ответ закончится", + "composer.message": "Сообщение", + "composer.newline": "Shift+Enter: новая строка", + "composer.placeholder": "Спрашивайте что угодно…", + "composer.save": "Сохранить этот чат как Markdown", + "composer.saveLabel": "Сохранить этот чат", + "composer.send": "Отправить", + "composer.stop": "Остановить", + "drawer.apply": "Применить", + "drawer.busy": "Если отправить, пока идёт ответ", + "drawer.busyInterject": "Прервать", + "drawer.busyInterjectNote": "Ответ остановится там, где он есть (написанное останется), и ваше сообщение уйдёт сразу. Работающий инструмент сначала закончит.", + "drawer.busyQueue": "Отправить после", + "drawer.busyQueueNote": "Сообщение подождёт и уйдёт, как только ответ закончится.", + "drawer.busyWait": "Ждать", + "drawer.busyWaitNote": "Отправка выключена, пока ответ не закончится, как раньше.", + "drawer.chats": "Чаты", + "drawer.edit": "Правка и возврат по сообщениям", + "drawer.editNote": "править ответ, просить новый или вернуться к более раннему сообщению (с отменой)", + "drawer.greedy": "0 · детерминированно", + "drawer.high": "Высокий", + "drawer.list": "Список сохранённых чатов", + "drawer.listNote": "хранит каждый чат в списке слева, только в этом браузере. Выключено: один чат, как раньше", + "drawer.low": "Низкий", + "drawer.math": "Показывать формулы", + "drawer.mathNote": "рисовать уравнения в ответах как формулы (работает без сети)", + "drawer.maxTokens": "Макс. токенов", + "drawer.maxTokensNote": "пусто = до конца", + "drawer.mcp": "Использовать инструменты серверов MCP", + "drawer.medium": "Средний", + "drawer.off": "Выкл.", + "drawer.random": "Случайно", + "drawer.reset": "Сбросить", + "drawer.saved": "Настройки чата сохранены", + "drawer.savedGreedy": "Детерминированно: один и тот же вопрос даёт один и тот же ответ.", + "drawer.savedHere": "Сохранено здесь, но не для других приложений", + "drawer.savedOwn": "Другие приложения снова используют свои настройки.", + "drawer.savedShared": "Другие приложения (omp, клиенты API) используют эти настройки со следующего запроса.", + "drawer.seed": "Seed", + "drawer.seedNote": "пусто = случайно", + "drawer.share": "Использовать и для других приложений", + "drawer.shareNote": "omp и другие клиенты API получают эти настройки для всего, что не задают сами", + "drawer.short": "Настройки", + "drawer.showThinking": "Показывать рассуждение", + "drawer.showThinkingNote": "раскрыто, пока идёт ответ", + "drawer.temperature": "Температура", + "drawer.temperatureNote": "0 = всегда самое вероятное слово (точно, повторяемо)", + "drawer.thinkHigh": "тщательно (по умолчанию)", + "drawer.thinkLow": "коротко", + "drawer.thinkMedium": "средне", + "drawer.thinkNone": "отвечает сразу", + "drawer.thinking": "Рассуждение", + "drawer.title": "Настройки чата", + "drawer.untilDone": "До конца", + "export.nothing": "Пока нечего сохранять", + "file.big": "Файл слишком большой", + "file.bigText": "{name} больше 512 КБ.", + "file.binaryText": "{name} похож на двоичный файл.", + "file.notText": "Это не текстовый файл", + "file.notTextOnly": "{name}: прикрепляйте текстовые файлы (код, заметки, журналы, данные).", + "file.notTextPictures": "{name}: прикрепляйте текстовые файлы (код, заметки, журналы, данные) или изображения.", + "file.pasted": "вставленное изображение", + "file.pictureBig": "Изображение слишком большое", + "file.pictureBigText": "{name} больше 20 МБ.", + "file.picturesOff": "Изображения выключены", + "file.picturesOffText": "Эта модель настроена только на текст.", + "file.remove": "Удалить", + "group.month": "Последние 30 дней", + "group.older": "Раньше", + "group.today": "Сегодня", + "group.week": "Последние 7 дней", + "group.yesterday": "Вчера", + "hist.editAnswer": "Править ответ", + "hist.editAnswerTitle": "Исправить текст ответа. Запрос не отправляется.", + "hist.editLabel": "Правка ответа", + "hist.editNote": "Прежнее рассуждение и вызовы инструментов в ответе удаляются. Запрос не отправляется.", + "hist.editRemoves": {"one": "При сохранении скроется {n} следующее сообщение. ", "few": "При сохранении скроются {n} следующих сообщения. ", "many": "При сохранении скроются {n} следующих сообщений. ", "other": "При сохранении скроются {n} следующих сообщения. "}, + "hist.edited": "Изменено", + "hist.editedHidden": {"one": "Ответ изменён, скрыто {n} сообщение", "few": "Ответ изменён, скрыто {n} сообщения", "many": "Ответ изменён, скрыто {n} сообщений", "other": "Ответ изменён, скрыто {n} сообщения"}, + "hist.editedOnly": "Ответ изменён", + "hist.empty": "Ответ пуст", + "hist.emptyText": "Напишите что-нибудь перед сохранением.", + "hist.finishFirst": "Сначала закончите то, что открыто", + "hist.finishFirstText": "Сохраните это или нажмите «Отмена».", + "hist.hidden": {"one": "Скрыто {n} сообщение", "few": "Скрыто {n} сообщения", "many": "Скрыто {n} сообщений", "other": "Скрыто {n} сообщения"}, + "hist.lostText": "Браузер сохранил только имена, без содержимого. Начните новый чат и прикрепите их снова.", + "hist.lostText2": "Браузер сохранил только имена, без содержимого. Прикрепите их снова.", + "hist.lostTitle": "Вложения нужно добавить заново", + "hist.nothingHidden": "Возврат к этому сообщению", + "hist.pendingFirst": "Одно сообщение ждёт отправки", + "hist.pendingFirstText": "Сначала отправьте его или заберите обратно.", + "hist.regenerate": "Сгенерировать заново", + "hist.regenerateTitle": "Запросить новый ответ на этот вопрос. Инструменты могут запуститься снова.", + "hist.replaced": "Ответ заменён", + "hist.rewind": "Вернуться сюда", + "hist.rewindTitle": "Вернуться к этому месту в чате", + "hist.save": "Сохранить", + "math.source": "Исходный текст формулы ({reason})", + "model.alreadyUnloaded": "Уже выгружена", + "model.busy": "Модель занята", + "model.confirmUnload": "Выгрузить модель и освободить GPU? Кнопка «Загрузить» или следующее сообщение вернёт её.", + "model.fewMinutes": "Это может занять несколько минут.", + "model.gpuFree": "GPU свободен. Кнопка «Загрузить» или следующее сообщение вернёт модель.", + "model.gpuInUse": "GPU используется.", + "model.imageBusy": "Создаётся изображение. Оно закончится само.", + "model.imageLoading": "Изображение уже загружает модель", + "model.imageLoadingDot": "Изображение уже загружает модель.", + "model.load": "Загрузить", + "model.loadFailed": "Не удалось загрузить", + "model.loadTitle": "Загрузить модель сейчас. Сообщение тоже загрузит её.", + "model.loaded": "Модель загружена", + "model.loading": "Загрузка…", + "model.loadingTitle": "Модель загружается", + "model.loadingToast": "Загрузка модели", + "model.noAnswer": "Сервер не ответил.", + "model.replyLoading": "Ответ уже загружает модель", + "model.replyLoadingDot": "Ответ уже загружает модель.", + "model.stopFirst": "Остановите ответ, затем выгрузите", + "model.stopFirstDot": "Остановите ответ, затем выгрузите.", + "model.unload": "Выгрузить", + "model.unloadFailed": "Не удалось выгрузить", + "model.unloadTitle": "Выгрузить модель и освободить GPU", + "model.unloaded": "Модель выгружена", + "model.unloading": "Выгрузка…", + "model.unloadingTitle": "Модель выгружается", + "model.unsupported": "Выгрузка недоступна", + "model.waiting": "Ожидание сервера", + "pending.afterTool": "Ждёт, пока закончит инструмент, затем отправит: «{text}»", + "pending.cutting": "Останавливает ответ, затем отправит: «{text}»", + "pending.one": "Одно сообщение уже ждёт", + "pending.oneText": "Заберите его обратно или дождитесь отправки.", + "pending.queued": "Отправится, когда закончится этот ответ: «{text}»", + "pending.ready": "Ещё не отправлено: «{text}»", + "pending.send": "Отправить", + "pending.sendNow": "Отправить сейчас", + "pending.takeBack": "Забрать", + "pill.connecting": "Подключение…", + "pill.generating": "Пишет · {rate} ток/с", + "pill.idle": "Ожидание", + "pill.image": "Создаёт изображение…", + "pill.keyNeeded": "Нужен ключ API", + "pill.queued": "В очереди: {n}", + "pill.reading": "Читает запрос", + "pill.readingPct": "Читает запрос · {pct}%", + "pill.unloaded": "Выгружена", + "pill.unreachable": "Сервер недоступен", + "preview.confirm": "Запустить этот код со скриптами?\n\nОн работает в вашем браузере, отрезанный от этого чата и от сети, но всё равно может заморозить вкладку, и это код, написанный моделью.\n\nТолько этот блок и только пока вы не закроете предпросмотр.", + "preview.runScripts": "Запустить скрипты", + "preview.showCode": "Показать код", + "preview.showPage": "Предпросмотр страницы", + "preview.showSvg": "Предпросмотр изображения", + "preview.stopScripts": "Остановить скрипты", + "preview.titlePage": "Предпросмотр страницы", + "preview.titleSvg": "Предпросмотр изображения", + "rewind.branch": "Создать ветку отсюда", + "rewind.branchAnswerText": "Начинает новый чат с сообщениями до этого ответа. Этот чат остаётся как есть.", + "rewind.branchUserText": "Начинает новый чат с сообщениями до этого и кладёт ваше сообщение в его поле. Этот чат остаётся как есть.", + "rewind.hereAnswer": "Продолжить отсюда", + "rewind.hereAnswerText": "Скрывает сообщения после этого ответа. «Отменить» вернёт их.", + "rewind.hereUser": "Изменить и отправить заново здесь", + "rewind.hereUserText": "Скрывает это сообщение и следующие и кладёт ваше сообщение в поле ввода ниже. «Отменить» вернёт их.", + "rewind.noList": "Чтобы вместо этого начать новый чат отсюда, включите список сохранённых чатов в настройках чата.", + "rewind.title": "Вернуться сюда", + "settings.language": "Язык", + "settings.languageNote": "Чат, его настройки и кнопки выше переведены. Разделы «Монитор», «Изображения» и «О программе» пока на английском.", + "sidebar.collapse": "Свернуть список чатов", + "sidebar.delete": "Удалить этот чат", + "sidebar.deleteShort": "Удалить", + "sidebar.expand": "Открыть список чатов", + "sidebar.foot": {"one": "{n} чат · хранится в этом браузере", "few": "{n} чата · хранятся в этом браузере", "many": "{n} чатов · хранятся в этом браузере", "other": "{n} чата · хранятся в этом браузере"}, + "sidebar.nameFor": "Название этого чата", + "sidebar.noMatch": "Подходящих чатов нет", + "sidebar.none": "Чатов пока нет", + "sidebar.rename": "Переименовать этот чат", + "sidebar.renameShort": "Переименовать", + "sidebar.search": "Поиск по чатам", + "sidebar.title": "Чаты", + "store.failed": "Не удалось сохранить список чатов. Чаты на экране остаются на месте.", + "store.memory": "Этот браузер не сохранит список чатов. Он останется в памяти, пока вы не закроете страницу.", + "store.quota": "Этот браузер не может хранить больше. Чаты на экране остаются на месте.", + "store.title": "Список чатов не сохранён", + "tab.about": "О программе", + "tab.chat": "Чат", + "tab.images": "Изображения", + "tab.monitor": "Монитор", + "tab.views": "Разделы", + "theme.label": "Переключить светлую и тёмную тему", + "theme.title": "Светлая / тёмная", + "think.done": "Рассуждение", + "think.for": "Думал {s} с", + "think.now": "Думает…", + "toast.copied": "Скопировано в буфер обмена", + "toast.engineError": "движок сообщил об ошибке", + "toast.httpAnswer": "Сервер ответил HTTP {code}.", + "toast.keyAbout": "Этому серверу нужен ключ: укажите его в разделе «О программе» > «Настройки».", + "toast.keyAbout2": "Нужен ключ API: укажите его в разделе «О программе» > «Настройки».", + "toast.keyNeeded": "Этому серверу нужен ключ API: укажите его в разделе «О программе» > «Настройки».", + "toast.requestFailed": "Запрос не удался", + "tool.arguments": "Аргументы", + "tool.beingWritten": "(пишется)", + "tool.chars": "{n} симв.", + "tool.cut": ", сокращено для модели", + "tool.done": "Готово", + "tool.error": "Ошибка", + "tool.result": "Результат", + "tool.running": "Выполняется", + "tool.skipped": "Не выполнен", + "tool.writing": "Пишется", + "undo": "Отменить" +} diff --git a/serve/web/locales/zh.json b/serve/web/locales/zh.json new file mode 100644 index 00000000..773d5f60 --- /dev/null +++ b/serve/web/locales/zh.json @@ -0,0 +1,249 @@ +{ + "branch.back": "回到原聊天", + "branch.from": "分支自“{title}”", + "branch.open": "打开原聊天", + "branch.started": "已创建分支", + "branch.startedText": "你之前所在的聊天没有改变,仍在左侧列表中。", + "branch.title": "{title} 的分支", + "busy.stillWriting": "仍在生成", + "busy.stopFirst": "请先停止回答。", + "cancel": "取消", + "chat.clearedToast": "上一个聊天已清空。", + "chat.copy": "复制", + "chat.copyAnswer": "复制回答", + "chat.deleted": "聊天已删除", + "chat.empty": "想问什么都可以", + "chat.emptyModel": "{model} 运行在这台电脑上,不会向外发送任何内容。", + "chat.image": "图片", + "chat.interrupted": "已打断", + "chat.interruptedLower": "已打断", + "chat.new": "新聊天", + "chat.newToast": "新聊天", + "chat.newToastText": "之前的聊天在左侧列表中。", + "chat.projectionOff": "投影关闭", + "chat.projectionOn": "投影开启", + "chat.stopped": "已停止", + "chat.stoppedLower": "已停止", + "chat.tokens": "{n} 个 token", + "chat.toolCalls": {"other": "{n} 次工具调用"}, + "chat.toolLimit": "已在 {n} 轮工具调用的上限处停止 (mcp.max_rounds)", + "chat.untitled": "新聊天", + "chat.you": "你", + "close": "关闭", + "code.copy": "复制代码", + "code.label": "代码", + "composer.attach": "附加文本文件 (也可拖到这里)", + "composer.attachLabel": "附加文件", + "composer.attachPictures": "附加文本文件或图片 (也可拖到这里)", + "composer.finishOpen": "请先保存或取消上方打开的内容,再继续", + "composer.hintInterject": "按 Enter 会在此处停止回答并立即发送", + "composer.hintQueue": "按 Enter 会在回答结束后发送", + "composer.message": "消息", + "composer.newline": "Shift+Enter: 换行", + "composer.placeholder": "想问什么都可以…", + "composer.save": "将此聊天保存为 Markdown", + "composer.saveLabel": "保存此聊天", + "composer.send": "发送", + "composer.stop": "停止", + "drawer.apply": "应用", + "drawer.busy": "回答过程中发送消息时", + "drawer.busyInterject": "打断", + "drawer.busyInterjectNote": "回答会在当前位置停止 (已写的内容保留),你的消息立即发出。正在运行的工具会先完成。", + "drawer.busyQueue": "结束后发送", + "drawer.busyQueueNote": "你的消息会等待,回答一结束就发出。", + "drawer.busyWait": "等待", + "drawer.busyWaitNote": "回答结束前无法发送,和以前一样。", + "drawer.chats": "聊天", + "drawer.edit": "编辑和回退消息", + "drawer.editNote": "编辑回答、要求重新生成,或回到更早的消息 (可撤销)", + "drawer.greedy": "0 · 确定性", + "drawer.high": "高", + "drawer.list": "已保存聊天列表", + "drawer.listNote": "把每个聊天保存在左侧列表中,仅保存在此浏览器内。关闭: 和以前一样只有一个聊天", + "drawer.low": "低", + "drawer.math": "渲染公式", + "drawer.mathNote": "把回答中的公式绘制成数学公式 (可离线使用)", + "drawer.maxTokens": "最大 token 数", + "drawer.maxTokensNote": "留空 = 直到完成", + "drawer.mcp": "使用 MCP 服务器的工具", + "drawer.medium": "中", + "drawer.off": "关", + "drawer.random": "随机", + "drawer.reset": "重置", + "drawer.saved": "聊天设置已保存", + "drawer.savedGreedy": "确定性: 同一个问题得到同一个回答。", + "drawer.savedHere": "已保存在这里,但未用于其他应用", + "drawer.savedOwn": "其他应用重新使用它们自己的设置。", + "drawer.savedShared": "其他应用 (omp、API 客户端) 从下一次请求起使用这些设置。", + "drawer.seed": "种子", + "drawer.seedNote": "留空 = 随机", + "drawer.share": "也用于其他应用", + "drawer.shareNote": "omp 等 API 客户端未自行设置的项目会使用这些设置", + "drawer.short": "设置", + "drawer.showThinking": "显示思考过程", + "drawer.showThinkingNote": "生成时保持展开", + "drawer.temperature": "温度", + "drawer.temperatureNote": "0 = 总是选概率最高的词 (精确、可重复)", + "drawer.thinkHigh": "深入 (默认)", + "drawer.thinkLow": "简短", + "drawer.thinkMedium": "适中", + "drawer.thinkNone": "立即回答", + "drawer.thinking": "思考", + "drawer.title": "聊天设置", + "drawer.untilDone": "直到完成", + "export.nothing": "还没有可保存的内容", + "file.big": "文件太大", + "file.bigText": "{name} 超过 512 KB。", + "file.binaryText": "{name} 看起来是二进制文件。", + "file.notText": "不是文本文件", + "file.notTextOnly": "{name}: 请附加文本文件 (代码、笔记、日志、数据)。", + "file.notTextPictures": "{name}: 请附加文本文件 (代码、笔记、日志、数据) 或图片。", + "file.pasted": "粘贴的图片", + "file.pictureBig": "图片太大", + "file.pictureBigText": "{name} 超过 20 MB。", + "file.picturesOff": "图片功能已关闭", + "file.picturesOffText": "此模型只按文本方式设置。", + "file.remove": "移除", + "group.month": "过去 30 天", + "group.older": "更早", + "group.today": "今天", + "group.week": "过去 7 天", + "group.yesterday": "昨天", + "hist.editAnswer": "编辑回答", + "hist.editAnswerTitle": "修改回答的文字。不会发送请求。", + "hist.editLabel": "编辑回答", + "hist.editNote": "该回答之前的思考过程和工具调用会被移除。不会发送请求。", + "hist.editRemoves": {"other": "保存会隐藏其后的 {n} 条消息。"}, + "hist.edited": "已编辑", + "hist.editedHidden": {"other": "回答已编辑,隐藏了 {n} 条消息"}, + "hist.editedOnly": "回答已编辑", + "hist.empty": "回答是空的", + "hist.emptyText": "保存前请先写点内容。", + "hist.finishFirst": "请先完成打开着的内容", + "hist.finishFirstText": "保存它,或点击取消。", + "hist.hidden": {"other": "已隐藏 {n} 条消息"}, + "hist.lostText": "此浏览器只保留了名称,没有保留内容。请开始新聊天并重新附加。", + "hist.lostText2": "此浏览器只保留了名称,没有保留内容。请重新附加。", + "hist.lostTitle": "需要重新添加附件", + "hist.nothingHidden": "已回到这条消息", + "hist.pendingFirst": "有一条消息正在等待", + "hist.pendingFirstText": "请先发送它,或把它取回。", + "hist.regenerate": "重新生成", + "hist.regenerateTitle": "要求对这个问题给出新的回答。工具可能会再次运行。", + "hist.replaced": "回答已替换", + "hist.rewind": "回退到此处", + "hist.rewindTitle": "回到聊天中的这个位置", + "hist.save": "保存", + "math.source": "公式源码 ({reason})", + "model.alreadyUnloaded": "已经卸载", + "model.busy": "模型正忙", + "model.confirmUnload": "要卸载模型并释放 GPU 吗?点击“加载”或发送下一条消息即可恢复。", + "model.fewMinutes": "这可能需要几分钟。", + "model.gpuFree": "GPU 已空闲。点击“加载”或发送下一条消息即可恢复模型。", + "model.gpuInUse": "GPU 正在使用。", + "model.imageBusy": "正在生成图片,会自行结束。", + "model.imageLoading": "图片任务已在加载模型", + "model.imageLoadingDot": "图片任务已在加载模型。", + "model.load": "加载", + "model.loadFailed": "加载失败", + "model.loadTitle": "立即加载模型。发送消息也会加载。", + "model.loaded": "模型已加载", + "model.loading": "正在加载…", + "model.loadingTitle": "模型正在加载", + "model.loadingToast": "正在加载模型", + "model.noAnswer": "服务器没有响应。", + "model.replyLoading": "回答已在加载模型", + "model.replyLoadingDot": "回答已在加载模型。", + "model.stopFirst": "先停止回答,再卸载", + "model.stopFirstDot": "请先停止回答,再卸载。", + "model.unload": "卸载", + "model.unloadFailed": "卸载失败", + "model.unloadTitle": "卸载模型并释放 GPU", + "model.unloaded": "模型已卸载", + "model.unloading": "正在卸载…", + "model.unloadingTitle": "模型正在卸载", + "model.unsupported": "无法卸载", + "model.waiting": "正在等待服务器", + "pending.afterTool": "等工具完成后发送:“{text}”", + "pending.cutting": "停止回答后发送:“{text}”", + "pending.one": "已经有一条消息在等待", + "pending.oneText": "请取回它,或等它发送出去。", + "pending.queued": "本次回答结束后发送:“{text}”", + "pending.ready": "尚未发送:“{text}”", + "pending.send": "发送", + "pending.sendNow": "立即发送", + "pending.takeBack": "取回", + "pill.connecting": "正在连接…", + "pill.generating": "生成中 · {rate} tok/s", + "pill.idle": "空闲", + "pill.image": "正在生成图片…", + "pill.keyNeeded": "需要 API 密钥", + "pill.queued": "排队 {n} 个", + "pill.reading": "正在读取提示词", + "pill.readingPct": "正在读取提示词 · {pct}%", + "pill.unloaded": "已卸载", + "pill.unreachable": "无法连接服务器", + "preview.confirm": "要带脚本运行这段代码吗?\n\n它在你的浏览器中运行,与此聊天和网络隔离,但仍可能让标签页卡死,而且这是模型写的代码。\n\n仅限这一块,且只到你关闭预览为止。", + "preview.runScripts": "运行脚本", + "preview.showCode": "显示代码", + "preview.showPage": "预览页面", + "preview.showSvg": "预览图片", + "preview.stopScripts": "停止脚本", + "preview.titlePage": "页面预览", + "preview.titleSvg": "图片预览", + "rewind.branch": "从此处分支", + "rewind.branchAnswerText": "用到这条回答为止的消息开始一个新聊天。当前聊天保持原样。", + "rewind.branchUserText": "用这条消息之前的消息开始一个新聊天,并把你的消息放进它的输入框。当前聊天保持原样。", + "rewind.hereAnswer": "从此处继续", + "rewind.hereAnswerText": "隐藏这条回答之后的消息。点“撤销”可以恢复。", + "rewind.hereUser": "在此编辑并重新发送", + "rewind.hereUserText": "隐藏这条消息及其后的消息,并把你的消息放进下方输入框。点“撤销”可以恢复。", + "rewind.noList": "想改为从这里开始新聊天,请在聊天设置中打开“已保存聊天列表”。", + "rewind.title": "回退到此处", + "settings.language": "语言", + "settings.languageNote": "聊天、聊天设置和上方的按钮已翻译。监控、图片和关于页面仍是英文。", + "sidebar.collapse": "收起聊天列表", + "sidebar.delete": "删除此聊天", + "sidebar.deleteShort": "删除", + "sidebar.expand": "展开聊天列表", + "sidebar.foot": {"other": "{n} 个聊天 · 保存在此浏览器中"}, + "sidebar.nameFor": "此聊天的名称", + "sidebar.noMatch": "没有匹配的聊天", + "sidebar.none": "还没有聊天", + "sidebar.rename": "重命名此聊天", + "sidebar.renameShort": "重命名", + "sidebar.search": "搜索聊天", + "sidebar.title": "聊天", + "store.failed": "无法保存聊天列表。屏幕上的聊天仍在。", + "store.memory": "此浏览器不会保存聊天列表。它只留在内存中,关闭页面后就没有了。", + "store.quota": "此浏览器无法再保存更多内容。屏幕上的聊天仍在。", + "store.title": "聊天列表未保存", + "tab.about": "关于", + "tab.chat": "聊天", + "tab.images": "图片", + "tab.monitor": "监控", + "tab.views": "视图", + "theme.label": "在浅色和深色之间切换", + "theme.title": "浅色 / 深色", + "think.done": "思考", + "think.for": "思考了 {s} 秒", + "think.now": "正在思考…", + "toast.copied": "已复制到剪贴板", + "toast.engineError": "引擎报告了错误", + "toast.httpAnswer": "服务器返回了 HTTP {code}。", + "toast.keyAbout": "此服务器需要密钥: 请在“关于”>“设置”中填写。", + "toast.keyAbout2": "需要 API 密钥: 请在“关于”>“设置”中填写。", + "toast.keyNeeded": "此服务器需要 API 密钥: 请在“关于”>“设置”中填写。", + "toast.requestFailed": "请求失败", + "tool.arguments": "参数", + "tool.beingWritten": "(正在写入)", + "tool.chars": "{n} 个字符", + "tool.cut": ",已为模型截短", + "tool.done": "完成", + "tool.error": "错误", + "tool.result": "结果", + "tool.running": "运行中", + "tool.skipped": "未运行", + "tool.writing": "正在写入", + "undo": "撤销" +} diff --git a/tools/web_i18n.py b/tools/web_i18n.py index 747f1101..f40f8c27 100644 --- a/tools/web_i18n.py +++ b/tools/web_i18n.py @@ -120,7 +120,7 @@ def html_strings(src: str) -> dict: def english() -> dict: """Every key in serve/web with its English text; the same key twice must have the same text.""" out: dict = {} - sources = {p.name: js_strings(p.read_text(encoding="utf-8"), p.name) for p in sorted(WEB.glob("*.js"))} + sources = {p.name: js_strings(p.read_text(encoding="utf-8"), p.name) for p in sorted(WEB.glob("*.js")) if p.name != "i18n.js"} sources["index.html"] = html_strings((WEB / "index.html").read_text(encoding="utf-8")) for name, found in sources.items(): for key, value in found.items(): diff --git a/tools/webtest/browser_test.mjs b/tools/webtest/browser_test.mjs index 9b2ec42f..b0f7846b 100644 --- a/tools/webtest/browser_test.mjs +++ b/tools/webtest/browser_test.mjs @@ -601,6 +601,51 @@ htest("history: another chat or New chat does not lose a waiting message", async await page.close(); }); +// ------------------------------------------------------------------------------------------------ language +htest("language: English until the user picks one; a pick translates the chat and is kept", async ({ browser, mock }) => { + const page = await openPage(browser, mock, { seed: on() }); + assert.equal(await page.evaluate(() => StrataI18n.lang), "en"); + assert.equal(await page.$eval("html", (e) => e.lang), "en"); + assert.equal(await page.$eval("#tab-btn-chat", (e) => e.textContent.trim()), "Chat"); + await page.evaluate(() => { document.getElementById("tab-btn-about").click(); }); + await page.select("#lang", "de"); + await page.waitForFunction(() => StrataI18n.lang === "de"); + assert.equal(await page.$eval("html", (e) => e.lang), "de"); + assert.equal(await page.$eval("#tab-btn-chat", (e) => e.textContent.trim()), "Chat"); + assert.equal(await page.$eval("#tab-btn-about", (e) => e.textContent.trim()), "Info"); + await page.evaluate(() => { document.getElementById("tab-btn-chat").click(); }); + assert.equal(await page.$eval("#input", (e) => e.placeholder), "Fragen Sie, was Sie möchten…"); + await ask(page, "hallo"); + assert.equal(await page.$eval(".st-msg--user .st-msg__meta", (e) => e.textContent.startsWith("Sie · ")), true); + assert.equal(await page.$eval(".history-actions button:last-child", (e) => e.textContent), "Bis hier zurückgehen"); + assert.equal(await page.$eval("#sidebar-foot", (e) => e.textContent), "1 Chat · in diesem Browser gespeichert"); + await page.reload({ waitUntil: "networkidle0" }); + assert.equal(await page.evaluate(() => StrataI18n.lang), "de", "kept in this browser"); + await page.select("#lang", "en"); + await page.waitForFunction(() => StrataI18n.lang === "en"); + assert.equal(await page.$eval("#input", (e) => e.placeholder), "Ask anything…"); + assert.deepEqual(page.errors.filter((e) => !e.includes("404")), [], "(About asks for /config, which the mock does not have)"); + await page.close(); +}); + +htest("language: /?lang= is for one visit, an unknown code stays English, every language loads", async ({ browser, mock }) => { + let page = await openPage(browser, mock, { query: "?lang=ru" }); + assert.equal(await page.$eval("#send-btn", (e) => e.getAttribute("aria-label")), "Отправить"); + assert.equal(await page.evaluate(() => localStorage.getItem("strata.lang")), null, "not remembered"); + await page.close(); + page = await openPage(browser, mock, { query: "?lang=xx" }); + assert.equal(await page.evaluate(() => StrataI18n.lang), "en"); + await page.close(); + for (const lang of ["de", "es", "ja", "ko", "pt", "ru", "zh"]) { + page = await openPage(browser, mock, { query: "?lang=" + lang, seed: on() }); + assert.equal(await page.evaluate(() => StrataI18n.lang), lang); + assert.notEqual(await page.$eval("#send-btn", (e) => e.getAttribute("aria-label")), "Send", lang); + await ask(page, "hello " + lang); + assert.deepEqual(page.errors, [], lang); + await page.close(); + } +}); + const mock = await startMock(); const browser = await launch(); await run(async () => ({ browser, mock, close: async () => { await browser.close(); await mock.stop(); } })); From 40e78366bc6ae20986a8e706c1d822c53c0a8c4c Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:23:06 +0100 Subject: [PATCH 139/177] Web page: German and dark screenshots in tools/webtest/shots.mjs --- tools/webtest/shots.mjs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tools/webtest/shots.mjs b/tools/webtest/shots.mjs index 5c00ca8e..0462108a 100644 --- a/tools/webtest/shots.mjs +++ b/tools/webtest/shots.mjs @@ -124,6 +124,24 @@ const shots = [ await sleep(1500); return p; }], + ["18-german-chat", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, query: "?lang=de", seed: { chat: CHAT, ...on() } }); + await p.evaluate(() => { openRewind(2); }); + await sleep(200); + return p; + }], + ["19-german-chat-settings", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 900, query: "?lang=de", seed: { chat: CHAT } }); + await p.click("#sampling-btn"); await sleep(500); + await p.$eval(".st-drawer__body", (e) => { e.scrollTop = e.scrollHeight; }); + await sleep(200); + return p; + }], + ["20-dark-saved-chats", async () => { + const p = await openPage(browser, mock, { width: 1280, height: 800, dark: true, seed: { chat: CHAT, ...on() } }); + await seedChats(p); + return p; + }], ["17-narrow-wide-mid-900", async () => openPage(browser, mock, { width: 900, height: 700, seed: { chat: CHAT, ...on() } })], ]; From b434a8aa6e2f1db2011e9ab1fb972e9c6e52aa7b Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:25:56 +0100 Subject: [PATCH 140/177] qsa_select: multi-CTA decode top-k and a shuffle-free decode scorer, opt-in STRATA_SELECT_LONG=1 (#3820) Problem: a decode window's QSA select runs one CTA per query for the top-k (block_topk_wide_kernel past ~135K cells) and the warp-shuffle block scorer (block_scores_multi_kernel), in each QSA layer. Both grow linearly with the context: on one GP100 die at 300K cells a top-k call takes 0.39 ms with 1-5 SMs busy and a scores call 0.22 ms (two queries). At short contexts the same work is small and an extra kernel is pure overhead. Change: qsa_select.cu (inside !__HIPCC__ && STRATA_EXPERIMENTAL_SM60) gets block_topk_multi_* (six kernels over several CTAs per query, one per 2,048 blocks of capacity, at most 32, exchanging through caller scratch: no clusters, no spin waits, capturable) and block_scores_dx_kernel (the multi scorer's per-head sums built in registers as the same 32-leaf xor-butterfly tree, no __shfl_xor_sync, the tail block stays block_scores_tail_kernel's). New public qsa_topk_multi_scratch_ints, qsa_block_topk_long and qsa_block_scores_long forward to qsa_block_topk / qsa_block_scores outside the build gate or their conditions. verify.cpp keeps a second set of window graphs (exec_[sel_long_][T]) for windows that reach STRATA_SELECT_LONG_AT cells (default 65536); the choice is made before a capture and handed to the next stage of an overlapped layer split, capture_all captures both, pl_launch picks by the window's position. The ids and the score bits are the replaced kernels'. STRATA_TOPK_MULTI=0 and STRATA_SCORES_DX=0 turn either half off inside the long graphs. Review changes against the PR: in a build without the multi-CTA kernels STRATA_SELECT_LONG=1 now says so and is ignored (the PR would have kept two sets of graphs for nothing there); Metal gets stubs for the three new calls (the SYCL tree has its own verify.cpp and qsa_select copy). Default path: unset, select_long_on() is a cached false, topk_scratch_ is not allocated, sel_long_ stays 0, and every window uses exec_[0][T], the graph it used before; the index change is the only difference in verify.cpp. Merge note for f-027-gh-eng (#3702 evict_window_graph, not in this branch's base): its exec_ / exec_nr_ / launched_ accesses need the same [sel_long_] first index. Tests: src/kernels/qsa_select_long_parity.cpp (new; registered with STRATA_SCORES_DX=1 STRATA_TOPK_MULTI=1 in the SM60 test block, and a second case with STRATA_TOPK_MULTI_N=3; skips with 77 without the kernels) compares qsa_block_scores_long with qsa_block_scores (nq 1-8, n_bid 8 .. 131072, tail blocks of 0-3 cells, every block 0..n_bid memcmp) and qsa_block_topk_long with qsa_block_topk (nq 1-16, contexts 1,000 .. 524,288, random scores, all-equal scores and 7 distinct values for ties across CTAs, selected ids of every query; the multi scratch is junk-filled and must have been written). z440 (RTX A4000, sm_86, CUDA 13.0, gpu lock, build with -DSTRATA_EXPERIMENTAL_SM60=ON): "172 cases, 0 differ -> PASS" with one CTA per 2,048 blocks and with N=3. sm_60 compile of the whole tree (CUDA 12.9, P1004): exit 0. Not covered: no GP100 run here (the kernels' last word is the P100, and the speed claim). The contributor's numbers (four GP100 dies, every expert resident, --pipeline-windows 3: 400 tokens at 115K context 51.0 -> 52.5 tok/s, +2.9%; prompts below 64K unchanged; replies and state hashes equal on 15 requests) were not re-measured. The model gate is phaseA-tests/gh027/gates/3820-select-long.sh. --- CMakeLists.txt | 13 + docs/OLDER_GPUS.md | 10 +- include/strata/core/verify.hpp | 10 +- include/strata/kernels/qsa_select.hpp | 16 + metal/src/engine/stubs_0145.cpp | 4 + src/core/verify.cpp | 75 +++- src/kernels/cuda/qsa_select.cu | 528 +++++++++++++++++++++++++ src/kernels/qsa_select_long_parity.cpp | 214 ++++++++++ 8 files changed, 853 insertions(+), 17 deletions(-) create mode 100644 src/kernels/qsa_select_long_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ff5494d2..3628d144 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -470,6 +470,19 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME qsa_pattn_parity COMMAND qsa_pattn_parity) set_tests_properties(qsa_pattn_parity PROPERTIES SKIP_RETURN_CODE 77) endif() + # PR #3820: STRATA_SELECT_LONG's multi-CTA top-k and shuffle-free decode scorer against qsa_block_topk and + # qsa_block_scores, bitwise, on random scores (GPU, synthetic, no model). The switches force the new kernels on any + # card; the "n3" case fixes three CTAs a query. Only in the experimental sm_60 build (skips with 77 otherwise). + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_select_long_parity src/kernels/qsa_select_long_parity.cpp) + target_include_directories(qsa_select_long_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_select_long_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_select_long_parity COMMAND qsa_select_long_parity) + add_test(NAME qsa_select_long_parity_n3 COMMAND qsa_select_long_parity) + set_tests_properties(qsa_select_long_parity qsa_select_long_parity_n3 PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(qsa_select_long_parity PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1") + set_tests_properties(qsa_select_long_parity_n3 PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1;STRATA_TOPK_MULTI_N=3") + 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) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 93a0aa7c..149cb09f 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -129,7 +129,7 @@ in [DETAILS.md](DETAILS.md#rtx-30-series-sm_86-and-tesla-p100-sm_60-bitwise-deco ## Pascal GP100: a Q8_0 decode kernel (opt-in) GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projections read their weights at 40-80 GB/s of about -730, decoding K- and i-quant blocks one int at a time. Four opt-in changes, all measured on a PH402 only: +730, decoding K- and i-quant blocks one int at a time. Five opt-in changes, all measured on a PH402 only: - **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp per row, 16-byte weight loads, activations copied once per workgroup into shared memory, @@ -155,6 +155,14 @@ GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projectio chunk's attention at 43.3 -> 30.8 ms per QSA layer at 26K context on one GP100 die, and 2-3% less time on 8K-150K token prompts on four dies; we have not measured it here, and nobody has measured compute capability 6.1. `qsa_pattn_parity` (built with the tests in this build) checks the bytes on random data. +- **`STRATA_SELECT_LONG=1`** (decode, CUDA build with `STRATA_EXPERIMENTAL_SM60`, compute capability 6.x by default): past + `STRATA_SELECT_LONG_AT` cells (default 65,536) a decode window's QSA select runs a top-k over several CTAs a query (six kernels) + and a decode block scorer without warp shuffles, in place of one CTA a query. They return the same ids and the same score bits + (`qsa_select_long_parity` checks this on random data). Each costs a few more kernels a call, which only a long context pays + back, so the verifier keeps a second set of window graphs for it: expect some more VRAM for graphs, and nothing changes below + the threshold. `STRATA_TOPK_MULTI=0` and `STRATA_SCORES_DX=0` turn one half off. The author measured, on four GP100 dies with + every expert resident and `--pipeline-windows 3`, 51.0 -> 52.5 tok/s (+2.9%) decoding 400 tokens at 115K context, and no change + below 64K; we have not measured it. A build without the sm_6x kernels ignores the switch with a warning. None of these changes is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default application clock is 759 MHz and a layer split leaves each die idle most of a window, so lock the clocks diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index dc6613da..4ed58808 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -544,9 +544,12 @@ private: cudaStream_t df_side_[2] = {}; cudaEvent_t df_fork_ = nullptr; cudaEvent_t df_join_[2] = {}; - cudaGraphExec_t exec_[9] = {}; - cudaGraphExec_t exec_nr_[9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise - bool launched_[9] = {}, launched_nr_[9] = {}; ///< this graph has been launched once (early_ple_flag: a cold first launch raises the PLE flag first) + // [sel_long_][T]: 1 is the long-context QSA select (STRATA_SELECT_LONG=1: multi-CTA top-k, shuffle-free decode + // scores; see run()); without it only [0] is ever captured + cudaGraphExec_t exec_[2][9] = {}; + cudaGraphExec_t exec_nr_[2][9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise + bool launched_[2][9] = {}, launched_nr_[2][9] = {}; ///< this graph has been launched once (early_ple_flag: a cold first launch raises the PLE flag first) + int sel_long_ = 0; // fork 34a35db (STRATA_SIDE_MIXER=1): the GDN gates and the QSA indexer on a branch of the window's graph beside the // mixer's projections, joined before the recurrence / the attention cudaStream_t side_ = nullptr; @@ -630,6 +633,7 @@ private: float *qidx_ = nullptr, *scores_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr, *attn_scratch_ = nullptr; float* tail_snap_ = nullptr; // per QSA layer int32_t* sel_ = nullptr; + int32_t* topk_scratch_ = nullptr; // qsa_block_topk_long's multi-CTA exchange (STRATA_SELECT_LONG=1 only) float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *hit_out_ = nullptr; int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr; int32_t* plan_ = nullptr; // device copy of the plan block diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index e8beacce..35ee7a58 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -78,4 +78,20 @@ bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t n void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, const QsaShapes& s, int32_t* ids, void* stream); +/// The long-context decode select (the verifier's STRATA_SELECT_LONG=1 windows; CUDA builds with +/// STRATA_EXPERIMENTAL_SM60, elsewhere the plain calls). qsa_block_topk_long: qsa_block_topk's ids; a call with +/// `multi_scratch` (qsa_topk_multi_scratch_ints(nq) device ints, one call at a time per scratch, no initial value), no +/// active count and <= 16 queries runs several CTAs per query (block_topk_multi_*: STRATA_TOPK_MULTI=0 off, =1 on any +/// card, default compute capability 6.x past the register kernel's reach); otherwise it is qsa_block_topk. +/// qsa_block_scores_long: qsa_block_scores's bits; a call of <= 8 queries with no active count runs +/// block_scores_dx_kernel (STRATA_SCORES_DX=0 off, =1 on any card, default compute capability 6.x); otherwise it is +/// qsa_block_scores. +void qsa_block_topk_long(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks, int32_t* multi_scratch); +void qsa_block_scores_long(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks); +/// Device ints a qsa_block_topk_long call of `nq` queries may use as multi_scratch (0 on a build without the multi-CTA +/// path: pass null). +int64_t qsa_topk_multi_scratch_ints(int64_t nq); + } // namespace strata::kernels diff --git a/metal/src/engine/stubs_0145.cpp b/metal/src/engine/stubs_0145.cpp index 351665ec..8aa89f3d 100644 --- a/metal/src/engine/stubs_0145.cpp +++ b/metal/src/engine/stubs_0145.cpp @@ -150,5 +150,9 @@ namespace strata::kernels { void native_q8_0_sm60_release(void const* p0) { } } // the MTP drafter's STRATA_MTP_Q8_SM60 packing (mtp.cpp): nothing packed on Metal namespace strata::kernels { bool native_q8_0_sm60_pack_quiet(void const* p0, int p1, int p2, char const* p3) { return false; } } namespace strata::kernels { bool native_q8_0_sm60_pack_in_place(void* p0, int p1, int p2, char const* p3) { return false; } } +// STRATA_SELECT_LONG (verify.cpp's long-context decode select): CUDA only; never reached on Metal (no scratch asked for) +namespace strata::kernels { long long qsa_topk_multi_scratch_ints(long long p0) { return 0; } } +namespace strata::kernels { void qsa_block_topk_long(float const* p0, int const* p1, long long p2, long long p3, long long p4, strata::kernels::QsaShapes const& p5, int* p6, void* p7, long long p8, int* p9) { strata::metal_engine::missing("strata::kernels::qsa_block_topk_long"); } } +namespace strata::kernels { void qsa_block_scores_long(float const* p0, float const* p1, float const* p2, int const* p3, long long p4, long long p5, strata::kernels::QsaShapes const& p6, float* p7, void* p8, long long p9) { strata::metal_engine::missing("strata::kernels::qsa_block_scores_long"); } } // only reached with pf_wmma (off on Metal) namespace strata::prefill { void swiglu_split_f16(float const* p0, unsigned short* p1, long long p2, int p3, bool p4, void* p5) { } } diff --git a/src/core/verify.cpp b/src/core/verify.cpp index b82181c2..06306a23 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -166,6 +166,32 @@ inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv // fork F4 (Eddoursul): 2-4 token dense projections read an interleaved copy of the q8_1 activations (bitwise the same // outputs); STRATA_MMVQ_IL=0 keeps native_mmvq's multi-column kernels inline bool g_mmvq_il() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL"); return v == nullptr || v[0] != '0'; }(); return on; } +// STRATA_SELECT_LONG=1 (opt-in): a window graph past select_long_at() cells takes the long-context QSA select +// (qsa_block_topk_long's multi-CTA top-k through topk_scratch_, qsa_block_scores_long's shuffle-free decode scorer; +// both compute capability 6.x by default, the same ids and score bits). Each costs ~6 more kernels a call, which only +// a longer context pays back (4x GP100: 0.5 ms a window more at 1K, even at 30K, 4.0-4.7 ms less at 300K), so the +// verifier keeps a second set of window graphs for it. Off: no scratch, no second graphs. +inline bool select_long_on() { + static const bool on = [] { + const char* v = std::getenv("STRATA_SELECT_LONG"); + if (v == nullptr || v[0] != '1') return false; + if (strata::kernels::qsa_topk_multi_scratch_ints(1) <= 0) { // a build without the multi-CTA kernels: no second graphs + std::fprintf(stderr, "strata verify: STRATA_SELECT_LONG=1 needs the CUDA build with STRATA_EXPERIMENTAL_SM60; " + "ignored\n"); + return false; + } + return true; + }(); + return on; +} +// STRATA_SELECT_LONG_AT: the threshold in cells (default 65536; 0: always) +inline int64_t select_long_at() { + static const int64_t at = [] { + const char* v = std::getenv("STRATA_SELECT_LONG_AT"); + return v != nullptr && v[0] != 0 ? (int64_t) std::atoll(v) : (int64_t) 65536; + }(); + return at; +} // 143-amdk: STRATA_QFUSE_HC - only the hyper-connection read writes its consumer's q8_1 image (not the GDN recurrence): gfx12 default (=0 / 1 forces off / on) inline bool g_qfuse_hc() { #if defined(STRATA_USE_HIP) @@ -617,10 +643,12 @@ Verifier::~Verifier() { } if (cs_) cudaStreamSynchronize(cs_); if (sh_cs_) cudaStreamSynchronize(sh_cs_); - for (auto& e : exec_) - if (e) cudaGraphExecDestroy(e); - for (auto& e : exec_nr_) - if (e) cudaGraphExecDestroy(e); + for (auto& row : exec_) + for (auto& e : row) + if (e) cudaGraphExecDestroy(e); + for (auto& row : exec_nr_) + for (auto& e : row) + if (e) cudaGraphExecDestroy(e); if (commit_exec_) cudaGraphExecDestroy(commit_exec_); for (auto& kv : exec_bm_) if (kv.second) cudaGraphExecDestroy(kv.second); @@ -878,6 +906,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD); idx_raw_L_ = b.take<float>(nQ * T * ID); qidx_ = b.take<float>(T * IQ * ID); scores_ = b.take<float>(T * (uint64_t) max_blocks_); sel_ = b.take<int32_t>(T * (uint64_t) cap_); + if (select_long_on() && strata::kernels::qsa_topk_multi_scratch_ints(T) > 0) // STRATA_SELECT_LONG only + topk_scratch_ = b.take<int32_t>((uint64_t) strata::kernels::qsa_topk_multi_scratch_ints(T)); attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD); attn_scratch_ = b.take<float>(T * (uint64_t) attn_scratch_floats_); tail_snap_ = b.take<float>(nQ * TS); @@ -1662,6 +1692,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } }; auto idx_select = [&](cudaStream_t ns) { + if (sel_long_) { // STRATA_SELECT_LONG: the long-context window graphs (the same ids) + qsa_block_scores_long(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, + max_blocks_, s, scores_ + (size_t) tb * max_blocks_, ns, -1); + qsa_block_topk_long(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, + cap_, s, sel_ + (size_t) tb * cap_, ns, -1, topk_scratch_); + return; + } qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_, s, scores_ + (size_t) tb * max_blocks_, ns); qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s, @@ -2452,7 +2489,7 @@ void Verifier::refresh_ar() { } bool Verifier::capture(int T, std::string& err) { - cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; + cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T]; if (exec_t != nullptr) return true; { // said before the capture: a process that exits inside it (#1275: Windows, 313 MiB free) leaves this line as the trace size_t free_b = 0, total_b = 0; @@ -2839,7 +2876,8 @@ bool Verifier::chain_overlap() const { bool Verifier::prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string& err) { const OnDevice on_device(device_); prelaunched_ = 0; - cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; // #871: the variant the previous stage refreshed + sel_long_ = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0; // the variant the previous stage captured + cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T]; // #871: the variant the previous stage refreshed if (T < 1 || T > max_t_ || exec_t == nullptr) { err = "verify: prelaunch before the window was captured"; return false; } if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } if (pos0 + T > ss_->qsa_states[ss_->qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } @@ -2883,11 +2921,14 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, prelaunched_ = 0; if (!pre && pre_launch_ && !pre_launch_(cs_, err)) return false; // (a prelaunched window's was served with the first stage's) if (!pre) refresh_ar(); + // STRATA_SELECT_LONG: the select kernels this window's context pays off with (the same on every stage) + sel_long_ = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0; if (!capture(T, err) || !capture_commit(err)) return false; const bool chain = chain_overlap(); if (chain) { // capture the next stage's window here, on this thread, so the helper only stages and launches const OnDevice on_next(next_->device_); next_->refresh_ar(); // #871: the variant its prelaunch and its run() will both use + next_->sel_long_ = sel_long_; if (!next_->capture(T, err) || !next_->capture_commit(err)) return false; } VDBG("captured; staging\n"); @@ -2910,7 +2951,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, #endif const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) bool flag_raised = false; // the PLE flag went up before the launch (early_ple_flag_mode) - bool& graph_launched = ar_off_ ? launched_nr_[T] : launched_[T]; + bool& graph_launched = ar_off_ ? launched_nr_[sel_long_][T] : launched_[sel_long_][T]; if (!pre && ar_on() && !test_stall && (early_ple_flag_mode() == 1 || (early_ple_flag_mode() == 2 && !graph_launched))) { if (do_ple) { const Clock::time_point tp = Clock::now(); @@ -2939,11 +2980,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH"); return value != nullptr && value[0] == '1'; }(); - launch_o.emplace(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch, + launch_o.emplace(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_, device_, threaded_launch, [this] { (void) release_gpu_waits(5000); }); const cudaError_t le = launch_o->status(); #else - const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); + const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_); #endif trace_ev("LAUNCHED", -1, -1, (int64_t) le); graph_launched = true; @@ -3531,6 +3572,7 @@ bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err row_base_ = hbase; for (int t = 0; t < S; ++t) brow_[t] = rows[t]; std::string rerr; + sel_long_ = 0; // batch rows: the one-CTA select const bool ok = record_window(S, cs_, rerr); batch_rec_ = false; row_base_ = 0; @@ -4204,8 +4246,14 @@ bool Verifier::capture_all(std::string& err) { if (g_ == nullptr) { err = "verify: capture_all before init"; return false; } if (remote_opt_ != nullptr) { err = "verify: pipelined windows do not serve --remote-expert-opt"; return false; } if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } - for (int T = 1; T <= max_t_; ++T) - if (!capture(T, err)) return false; + // STRATA_SELECT_LONG: both select variants (see select_long_at): pl_launch takes the one its window's context + // needs, and nothing can be captured once pipelined windows are in flight. Without it only [0] + for (int sl = 0; sl < (select_long_on() ? 2 : 1); ++sl) { + sel_long_ = sl; + for (int T = 1; T <= max_t_; ++T) + if (!capture(T, err)) return false; + } + sel_long_ = 0; if (!capture_commit(err)) return false; if ((ev_done_ == nullptr && cudaEventCreateWithFlags(&ev_done_, cudaEventDisableTiming) != cudaSuccess) || (ev_commit_ == nullptr && cudaEventCreateWithFlags(&ev_commit_, cudaEventDisableTiming) != cudaSuccess)) { @@ -4260,7 +4308,8 @@ bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } SessionState& ss = *ss_; if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } - if (exec_[T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) { + const int sl = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0; // the variant this window's context pays off with + if (exec_[sl][T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; } @@ -4282,7 +4331,7 @@ bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string std::atomic_thread_fence(std::memory_order_seq_cst); trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); - const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + const cudaError_t le = cudaGraphLaunch(exec_[sl][T], cs_); trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } if (fl_prof_) cudaMemcpyAsync(prof_pin_, prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost, cs_); diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index e956dc8b..283aba9e 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -1553,6 +1553,385 @@ bool scores_early_exit() { static const bool on = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }(); return on; } + +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// STRATA_SELECT_LONG (verify.cpp): the long-context decode select, qsa_block_scores_long / qsa_block_topk_long. +// ---- decode block scores bit for bit block_scores_multi_kernel's, without its shuffles (STRATA_SCORES_DX, default on +// 6.x, under STRATA_SELECT_LONG). The multi kernel gives a block to a warp and pays 5 shuffles per head per (block, query) for 4 products per +// lane: on GP100 a decode window's call costs ~88 us more per query at 300K cells. Here lane i of warp h builds, for +// block i of a 32-block tile and indexer head h, the same 32-leaf tree as block_scores_multi_kernel's xor butterfly (lanes visited in +// 5-bit-reversed order, depth-first: the xor butterfly's association) for every query of the call at once, the key +// staged once per tile in shared memory and read by all of the queries; the relu sum over the heads then runs in the +// warp kernel's order (0 + r0 + r1 + r2 + r3) from shared memory. Blocks < n_bid; the tail block n_bid is +// block_scores_tail_kernel's (the multi kernel's arithmetic for it). A fixed grid strides over the tiles below the +// call's largest n_bid (capturable). +__device__ __forceinline__ int dx_lane(int j) { return (int) (__brev((unsigned) j) >> 27); } // 5-bit reversal +constexpr int DX_NB = 32; // blocks per tile: one per lane +constexpr int DX_T = 32 * IDX_HEADS; // warp h: indexer head h +constexpr int DX_KS = IDX_DIM + 4; // a key row in shared memory (a quarter warp's 16-byte reads: 32 banks) + +template <int NQ> +__global__ void __launch_bounds__(DX_T) block_scores_dx_kernel(const float* __restrict__ pooled, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int64_t max_blocks, + float* __restrict__ out) { + extern __shared__ __align__(16) float dx_smem[]; + float* Ks = dx_smem; // [DX_NB][DX_KS] + float* Qs = Ks + DX_NB * DX_KS; // [NQ][IDX_HEADS][IDX_DIM] + float* Ds = Qs + NQ * IDX_HEADS * IDX_DIM; // [NQ][IDX_HEADS][DX_NB]: each head's sum, for the relu pass + __shared__ int64_t s_nbid[NQ]; + const int t = threadIdx.x, lane = t & 31, h = t >> 5; + if (t < NQ) s_nbid[t] = steps[t * kStepCount + kStepNBid]; + __syncthreads(); + int64_t top = 0; +#pragma unroll + for (int q = 0; q < NQ; ++q) top = s_nbid[q] > top ? s_nbid[q] : top; + if (top > max_blocks) top = max_blocks; + if ((int64_t) blockIdx.x * DX_NB >= top) return; // CTA-uniform + for (int i = t; i < NQ * IDX_HEADS * IDX_DIM / 4; i += DX_T) + reinterpret_cast<float4*>(Qs)[i] = reinterpret_cast<const float4*>(q_idx)[i]; + const float* krow = Ks + lane * DX_KS; + // the next tile's keys in registers while this one is scored (coalesced: thread t row (t + 128 i) / 32, float4 t % 32) + constexpr int PF = DX_NB * (IDX_DIM / 4) / DX_T; + float4 pre[PF]; + const int64_t stride = (int64_t) gridDim.x * DX_NB; + auto fetch = [&](int64_t tb) { +#pragma unroll + for (int i = 0; i < PF; ++i) { + const int idx = t + i * DX_T, row = idx / (IDX_DIM / 4), c4 = idx % (IDX_DIM / 4); + pre[i] = tb + row < top ? __ldg(reinterpret_cast<const float4*>(pooled + (tb + row) * IDX_DIM) + c4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + }; + fetch((int64_t) blockIdx.x * DX_NB); + for (int64_t b0 = (int64_t) blockIdx.x * DX_NB; b0 < top; b0 += stride) { +#pragma unroll + for (int i = 0; i < PF; ++i) { + const int idx = t + i * DX_T, row = idx / (IDX_DIM / 4), c4 = idx % (IDX_DIM / 4); + *reinterpret_cast<float4*>(Ks + row * DX_KS + c4 * 4) = pre[i]; + } + __syncthreads(); + if (b0 + stride < top) fetch(b0 + stride); + float half0[NQ], half1[NQ]; +#pragma unroll 1 + for (int c = 0; c < 4; ++c) { + float l0[NQ], l1[NQ], l2[NQ]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int L = dx_lane(8 * c + jj); + const float4 k4 = *reinterpret_cast<const float4*>(krow + L * 4); +#pragma unroll + for (int q = 0; q < NQ; ++q) { + const float4 q4 = *reinterpret_cast<const float4*>(Qs + (q * IDX_HEADS + h) * IDX_DIM + L * 4); + const float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; + // the depth-first tree over the slice's 8 leaves (pairs, quads, the octet), then the octets + if (jj == 0 || jj == 2 || jj == 4 || jj == 6) l0[q] = d; + else if (jj == 1 || jj == 5) l1[q] = l0[q] + d; + else if (jj == 3) l2[q] = l1[q] + (l0[q] + d); + else { + const float oct = l2[q] + (l1[q] + (l0[q] + d)); + if (c == 0) half0[q] = oct; + else if (c == 1) half0[q] = half0[q] + oct; + else if (c == 2) half1[q] = oct; + else half1[q] = half1[q] + oct; + } + } + } + } +#pragma unroll + for (int q = 0; q < NQ; ++q) Ds[(q * IDX_HEADS + h) * DX_NB + lane] = half0[q] + half1[q]; + __syncthreads(); // also: every warp is done reading Ks before the next tile + for (int q = h; q < NQ; q += IDX_HEADS) { + const int64_t b = b0 + lane; + if (b >= s_nbid[q]) continue; + float score = 0.0f; +#pragma unroll + for (int hh = 0; hh < IDX_HEADS; ++hh) { + const float d = Ds[(q * IDX_HEADS + hh) * DX_NB + lane]; + score += d > 0.0f ? d : 0.0f; + } + out[q * max_blocks + b] = score; + } + } +} + +// ---- the decode top-k over several CTAs per query without clusters (any CUDA card; on sm_6x by default under +// STRATA_SELECT_LONG). A decode +// window's 1-5 queries otherwise run one 1,024-thread CTA each (block_topk_wide_kernel past ~135K cells) on one SM +// apiece: on GP100 0.39 ms per call at 300K cells and 1.15 ms at 1M, x12 QSA layers per window. Here each query gets +// n CTAs (a grid of n x nq), CTA r taking blocks [r * per, (r + 1) * per), and the four radix passes, the count and the +// emit are six kernels in a row on the caller's stream - capturable, no co-residency or spin waits: the kernel boundary +// is the barrier. Exchange goes through the caller's scratch (qsa_topk_multi_scratch_ints): pass 0's histograms one +// row per CTA (plain stores), passes 1-3 summed with atomics into rows the pass-0 kernel zeroes, (prefix, above) after +// each digit, and each warp's cells above / at the threshold. Nothing is carried from one call to the next. +// Warp w of a CTA takes the rows [w * rpw, (w + 1) * rpw) of 32 consecutive blocks (lane l block l of a row: coalesced), +// MT_U rows' loads in flight at a time; the loops stay rolled (GP100's instruction cache: a fully unrolled 33-row body +// doubled every kernel's time). +// +// IDENTICAL IDS, as block_topk_cluster_kernel's: thr (the width-th largest key, cells counted with their weights) and +// `above` are pure functions of the integer histograms whatever order they are summed in, and the digit rule is +// block_topk_kernel's (the largest digit d >= 1 whose cells at or above it reach `need`, else 0), here as a 256-thread +// scan. The emit writes every cell of a block above thr and the first eq_budget = width - above cells at thr, ascending +// (block_topk_wide_kernel's row emit, offset by the cells of the warps and CTAs before). +constexpr int MT_T = 256; // threads per CTA +constexpr int MT_W = MT_T / 32; // warps per CTA +constexpr int MT_U = 4; // rows of loads in flight per warp +constexpr int MT_NMAX = 32; // CTAs per query, at most +constexpr int MT_MAXQ = 16; // more queries per call fill the GPU with one CTA each already +// scratch per query (int32): pass 0's rows [MT_NMAX][256], passes 1-3 [3][256], state [5][2], counts [MT_NMAX][MT_W][2] +constexpr int MT_ACC = MT_NMAX * 256, MT_STATE = MT_ACC + 3 * 256, MT_CNT = MT_STATE + 16; +constexpr int MT_Q_INTS = MT_CNT + 2 * MT_NMAX * MT_W + 64; +static_assert(MT_NMAX * MT_W <= MT_T, "the emit sums the earlier CTAs' warp counts one per thread"); + +struct MtQuery { + int64_t n_kv, n_bid, width, lo, hi, row0; // row0: the first block of this warp's first row + int rpw, wtail; + bool all; // n_kv <= width: every cell, nothing to select +}; + +__device__ __forceinline__ MtQuery mt_query(const int32_t* __restrict__ steps) { + const int32_t* st = steps + (int64_t) blockIdx.y * kStepCount; + MtQuery m; + m.n_kv = st[kStepNKv]; + m.n_bid = st[kStepNBid]; + m.width = st[kStepWidth]; + m.all = m.n_kv <= m.width; + // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0) + m.wtail = (int) (m.n_kv - m.n_bid * R); + const int64_t nbe = m.n_bid + (m.wtail > 0 ? 1 : 0); + const int64_t per = (nbe + gridDim.x - 1) / gridDim.x; + m.lo = (int64_t) blockIdx.x * per < nbe ? (int64_t) blockIdx.x * per : nbe; + m.hi = m.lo + per < nbe ? m.lo + per : nbe; + m.rpw = (int) (((m.hi - m.lo + 31) / 32 + MT_W - 1) / MT_W); + m.row0 = m.lo + (int64_t) (threadIdx.x >> 5) * m.rpw * 32; + return m; +} + +// rows j0 .. j0 + MT_U - 1 of this warp: key[u] for block row0 + 32 (j0 + u) + lane (0 past hi or the warp's rows) +__device__ __forceinline__ void mt_load(const MtQuery& m, const float* __restrict__ sc, int j0, uint32_t (&key)[MT_U]) { + const int lane = threadIdx.x & 31; +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + key[u] = (j0 + u < m.rpw && b < m.hi) ? order_key(__ldg(sc + b)) : 0u; + } +} + +// inclusive scan of one value per thread over the MT_T threads +template <typename V> __device__ __forceinline__ V mt_incl_scan(V v, V* s_w) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + V x = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const V y = __shfl_up_sync(0xffffffffu, x, o); + if (lane >= o) x += y; + } + if (lane == 31) s_w[warp] = x; + __syncthreads(); + V off = 0; + for (int w = 0; w < warp; ++w) off += s_w[w]; + __syncthreads(); + return x + off; +} + +// The digit at `shift` from the 256 counts (thread t holds digit 255 - t's): block_topk_kernel's rule. +__device__ __forceinline__ void mt_choose(int v, int64_t width, int shift, uint32_t& prefix, int& above, int* s_w, + int* s_ex, int* s_i) { + const int t = threadIdx.x; + if (t == 0) *s_i = 255; // no digit >= 1 reaches it: 0, all of 1..255 above + const int incl = mt_incl_scan(v, s_w); + s_ex[t] = incl - v; + const int64_t need = width - above; + if (t < 255 && incl >= need && incl - v < need) *s_i = t; // the one t where the running count crosses `need` + __syncthreads(); + const int i = *s_i; + prefix |= (uint32_t) (255 - i) << shift; + above += s_ex[i]; + __syncthreads(); +} + +// pass PASS's histogram of the CTA's keys under the prefix so far (PASS >= 1 first takes digit PASS - 1) +template <int PASS> +__global__ void __launch_bounds__(MT_T) block_topk_multi_hist_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, + int64_t max_blocks, int32_t* __restrict__ scratch) { + __shared__ int h[MT_W][256]; + __shared__ int s_w[MT_W], s_ex[256], s_i; + const MtQuery m = mt_query(steps); + if (m.all) return; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float* sc = scores + (int64_t) blockIdx.y * max_blocks; + uint32_t key[MT_U]; + mt_load(m, sc, 0, key); // in flight while the digit is taken + for (int i = t; i < MT_W * 256; i += MT_T) (&h[0][0])[i] = 0; + int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS; + uint32_t prefix = 0; + int above = 0; + if (PASS == 0) { + if (blockIdx.x == 0) // passes 1-3 sum into these: zero them for this call + for (int i = t; i < 3 * 256; i += MT_T) qs[MT_ACC + i] = 0; + } else { + int v = 0; + if (PASS == 1) { // pass 0: one row per CTA +#pragma unroll 8 + for (unsigned r = 0; r < gridDim.x; ++r) v += qs[r * 256 + 255 - t]; + } else { + prefix = (uint32_t) qs[MT_STATE + 2 * (PASS - 1)]; + above = qs[MT_STATE + 2 * (PASS - 1) + 1]; + v = qs[MT_ACC + (PASS - 2) * 256 + 255 - t]; + } + mt_choose(v, m.width, 32 - 8 * PASS, prefix, above, s_w, s_ex, &s_i); + if (blockIdx.x == 0 && t == 0) { + qs[MT_STATE + 2 * PASS] = (int) prefix; + qs[MT_STATE + 2 * PASS + 1] = above; + } + } + __syncthreads(); + const int shift = 24 - 8 * PASS; + const uint32_t hmask = PASS == 0 ? 0u : (0xffffffffu << (shift + 8)); +#pragma unroll 1 + for (int j0 = 0; j0 < m.rpw; j0 += MT_U) { // uniform over the warp: the ballots see all its lanes + if (j0 > 0) mt_load(m, sc, j0, key); +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + if (j0 + u >= m.rpw) break; + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + const int bin = (b < m.hi && (key[u] & hmask) == prefix) ? (int) ((key[u] >> shift) & 255) : -1; + // the scores share their top bits: the lanes on the first lane's bin in one atomic (no __match_any_sync on 6.x) + const unsigned pend = __ballot_sync(0xffffffffu, bin >= 0); + if (pend) { + const int leader = __ffs(pend) - 1; + const int lb = __shfl_sync(0xffffffffu, bin, leader); + const unsigned same = __ballot_sync(0xffffffffu, bin == lb); + if (lane == leader) atomicAdd(&h[warp][lb], __popc(same) * R); + else if (bin >= 0 && bin != lb) atomicAdd(&h[warp][bin], R); + } + if (bin >= 0 && b == m.n_bid) atomicAdd(&h[warp][bin], m.wtail - R); + } + } + __syncthreads(); + int sum = 0; +#pragma unroll + for (int w = 0; w < MT_W; ++w) sum += h[w][t]; + if (PASS == 0) qs[blockIdx.x * 256 + t] = sum; + else if (sum != 0) atomicAdd(&qs[MT_ACC + (PASS - 1) * 256 + t], sum); +} + +// digit 3 (the threshold), then each warp's cells above it and at it +__global__ void __launch_bounds__(MT_T) block_topk_multi_count_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, + int64_t max_blocks, int32_t* __restrict__ scratch) { + __shared__ int s_w[MT_W], s_ex[256], s_i; + const MtQuery m = mt_query(steps); + if (m.all) return; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float* sc = scores + (int64_t) blockIdx.y * max_blocks; + uint32_t key[MT_U]; + mt_load(m, sc, 0, key); + int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS; + uint32_t prefix = (uint32_t) qs[MT_STATE + 6]; + int above = qs[MT_STATE + 7]; + mt_choose(qs[MT_ACC + 2 * 256 + 255 - t], m.width, 0, prefix, above, s_w, s_ex, &s_i); + if (blockIdx.x == 0 && t == 0) { + qs[MT_STATE + 8] = (int) prefix; + qs[MT_STATE + 9] = above; + } + const uint32_t thr = prefix; + int gt = 0, eq = 0; +#pragma unroll 1 + for (int j0 = 0; j0 < m.rpw; j0 += MT_U) { + if (j0 > 0) mt_load(m, sc, j0, key); +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + if (j0 + u >= m.rpw || b >= m.hi) continue; + const int w = b == m.n_bid ? m.wtail : R; + if (key[u] > thr) gt += w; + else if (key[u] == thr) eq += w; + } + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + gt += __shfl_xor_sync(0xffffffffu, gt, o); + eq += __shfl_xor_sync(0xffffffffu, eq, o); + } + if (lane == 0) { + qs[MT_CNT + 2 * (blockIdx.x * MT_W + warp)] = gt; + qs[MT_CNT + 2 * (blockIdx.x * MT_W + warp) + 1] = eq; + } +} + +// the cells, ascending: a warp's first cell goes after the cells the CTAs and warps before it selected +__global__ void __launch_bounds__(MT_T) block_topk_multi_emit_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, + int64_t max_blocks, int64_t cap, + int32_t* __restrict__ ids, + const int32_t* __restrict__ scratch) { + __shared__ unsigned long long s_w[MT_W]; + const MtQuery m = mt_query(steps); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + int32_t* out = ids + (int64_t) blockIdx.y * cap; + if (m.all) { // the identity, split over the CTAs + for (int64_t j = (int64_t) blockIdx.x * MT_T + t; j < m.n_kv; j += (int64_t) gridDim.x * MT_T) out[j] = (int32_t) j; + return; + } + const float* sc = scores + (int64_t) blockIdx.y * max_blocks; + uint32_t key[MT_U]; + mt_load(m, sc, 0, key); + const int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS; + const uint32_t thr = (uint32_t) qs[MT_STATE + 8]; + const int eq_budget = (int) (m.width - qs[MT_STATE + 9]); // cells at thr that fit, lowest index first + // the cells of the warps before this one: the earlier CTAs' (one warp count per thread), then this CTA's + unsigned long long c = 0; + if (t < (int) blockIdx.x * MT_W) + c = (unsigned long long) (unsigned) qs[MT_CNT + 2 * t] | ((unsigned long long) (unsigned) qs[MT_CNT + 2 * t + 1] << 32); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) c += __shfl_xor_sync(0xffffffffu, c, o); + if (lane == 0) s_w[warp] = c; + __syncthreads(); + unsigned long long before = 0; + for (int w = 0; w < MT_W; ++w) before += s_w[w]; + for (int w = 0; w < warp; ++w) { + const int i = (int) blockIdx.x * MT_W + w; + before += (unsigned long long) (unsigned) qs[MT_CNT + 2 * i] | + ((unsigned long long) (unsigned) qs[MT_CNT + 2 * i + 1] << 32); + } + const int gt_before = (int) (before & 0xffffffffu), eq_before = (int) (before >> 32); + int run_sel = gt_before + (eq_before < eq_budget ? eq_before : eq_budget), run_eq = eq_before; +#pragma unroll 1 + for (int j0 = 0; j0 < m.rpw; j0 += MT_U) { + if (j0 > 0) mt_load(m, sc, j0, key); +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + if (j0 + u >= m.rpw) break; + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + const int w = b < m.hi ? (b == m.n_bid ? m.wtail : R) : 0; + const uint32_t k = key[u]; + const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0; + if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue; // a row without a selected block + int pe = my_eq; // tied cells up to and with this lane +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, pe, o); + if (lane >= o) pe += y; + } + const int left = eq_budget - (run_eq + pe - my_eq); + const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left); + const int my_sel = my_gt + take; + int ps = my_sel; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, ps, o); + if (lane >= o) ps += y; + } + int32_t* dst = out + run_sel + ps - my_sel; + for (int cc = 0; cc < my_sel; ++cc) dst[cc] = (int32_t) (b * R + cc); + run_eq += __shfl_sync(0xffffffffu, pe, 31); + run_sel += __shfl_sync(0xffffffffu, ps, 31); + } + } +} +#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60 } // namespace bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead, const float* q_idx, @@ -2584,4 +2963,153 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64 if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); } } +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// STRATA_SCORES_DX: 0 off, 1 on for any CUDA card; unset: on for compute capability 6.x (block_scores_dx_kernel). +// `sms`: the device's multiprocessors (the grid: as many CTAs as fit on each). +static bool scores_dx_device(int& sms) { + static const int env = [] { + const char* v = std::getenv("STRATA_SCORES_DX"); + return v == nullptr || *v == '\0' ? -1 : std::atoi(v); + }(); + if (env == 0) return false; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return false; } + static thread_local int cached_device = -1, cached_sms = 0; + static thread_local bool pascal = false; + if (dev != cached_device) { + int major = 0; + pascal = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + strata::cc_major_of(major) == 6; + if (cudaDeviceGetAttribute(&cached_sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) cached_sms = 0; + cudaGetLastError(); + cached_device = dev; + } + sms = cached_sms; + return sms > 0 && (env > 0 || pascal); +} + +template <int NQ> +static void scores_dx_launch(const float* pooled, const float* q_idx, const int32_t* steps, int64_t max_blocks, + float* scores, int sms, cudaStream_t st) { + const size_t smem = (size_t) (DX_NB * DX_KS + NQ * IDX_HEADS * IDX_DIM + NQ * IDX_HEADS * DX_NB) * sizeof(float); + static thread_local int per_sm[64][9] = {}; // CTAs per multiprocessor, by device and NQ + int dev = 0; + cudaGetDevice(&dev); + int& occ = per_sm[dev & 63][NQ]; + if (occ == 0 && (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, block_scores_dx_kernel<NQ>, DX_T, smem) != + cudaSuccess || occ < 1)) { + cudaGetLastError(); + occ = 2; + } + const int64_t tiles = (max_blocks + DX_NB - 1) / DX_NB, want = (int64_t) occ * sms; + const unsigned grid = (unsigned) (want < tiles ? want : tiles); + block_scores_dx_kernel<NQ><<<grid, DX_T, smem, st>>>(pooled, q_idx, steps, max_blocks, scores); +} + +static bool qsa_block_scores_dx(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, + int64_t nq, int64_t max_blocks, float* scores, void* stream) { + int sms = 0; + if (nq < 1 || nq > MQ || !scores_dx_device(sms)) return false; + const cudaStream_t st = (cudaStream_t) stream; + switch (nq) { + case 1: scores_dx_launch<1>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 2: scores_dx_launch<2>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 3: scores_dx_launch<3>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 4: scores_dx_launch<4>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 5: scores_dx_launch<5>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 6: scores_dx_launch<6>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 7: scores_dx_launch<7>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + default: scores_dx_launch<8>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + } + block_scores_tail_kernel<<<(unsigned) nq, 32, 0, st>>>(dead, q_idx, steps, max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (dx): %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} +#endif + +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// STRATA_TOPK_MULTI: 0 off, 1 on for any CUDA card and capacity; unset: on for compute capability 6.x past the register +// kernel's reach (GP100: 0.39 -> 0.04 ms per call at 300K cells; see block_topk_multi_hist_kernel) +static int topk_multi_mode() { + static const int env = [] { + const char* v = std::getenv("STRATA_TOPK_MULTI"); + return v == nullptr || *v == '\0' ? -1 : std::atoi(v); + }(); + if (env >= 0) return env != 0 ? 1 : 0; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return 0; } + static thread_local int cached_device = -1; + static thread_local int mode = 0; + if (dev != cached_device) { + int major = 0; + mode = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + strata::cc_major_of(major) == 6 ? 2 : 0; + cudaGetLastError(); + cached_device = dev; + } + return mode; +} + +static bool qsa_block_topk_multi(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + int32_t* ids, void* stream, int32_t* scratch) { + // CTAs per query from the capacity (the grid is fixed in a captured graph; each CTA's share follows n_bid): one per + // 2,048 blocks, at most MT_NMAX. STRATA_TOPK_MULTI_N: a fixed count (tests) + static const int n_env = [] { const char* v = std::getenv("STRATA_TOPK_MULTI_N"); return v ? std::atoi(v) : 0; }(); + int64_t n = n_env > 0 ? n_env : (max_blocks + 2047) / 2048; + n = n < 1 ? 1 : n > MT_NMAX ? MT_NMAX : n; + const dim3 grid((unsigned) n, (unsigned) nq); + const cudaStream_t st = (cudaStream_t) stream; + block_topk_multi_hist_kernel<0><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch); + block_topk_multi_hist_kernel<1><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch); + block_topk_multi_hist_kernel<2><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch); + block_topk_multi_hist_kernel<3><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch); + block_topk_multi_count_kernel<<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch); + block_topk_multi_emit_kernel<<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, cap, ids, scratch); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk multi: %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} +#endif + +// ---- STRATA_SELECT_LONG (verify.cpp, opt-in): the decode select past ~64K cells. Outside the SM60 build (and on HIP) +// these are the plain calls; the scratch is never asked for. +int64_t qsa_topk_multi_scratch_ints(int64_t nq) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + return (nq < MT_MAXQ ? nq : MT_MAXQ) * (int64_t) MT_Q_INTS; +#else + (void) nq; + return 0; +#endif +} + +void qsa_block_topk_long(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks, int32_t* multi_scratch) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + // several CTAs per query through the caller's scratch (decode calls: no active count, a few queries) + static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr; + if (nq > 0 && multi_scratch != nullptr && !old && active_blocks <= 0 && nq <= MT_MAXQ && s.idx_block == R && + cap >= qsa_selection_width(kTopkMaxCells, s)) { + const int mode = topk_multi_mode(); + if ((mode == 1 || (mode == 2 && max_blocks > (int64_t) TK_T * TK_PER)) && + qsa_block_topk_multi(scores, steps, nq, max_blocks, cap, ids, stream, multi_scratch)) + return; + } +#else + (void) multi_scratch; +#endif + qsa_block_topk(scores, steps, nq, max_blocks, cap, s, ids, stream, active_blocks); +} + +void qsa_block_scores_long(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + if (nq > 0 && s.idx_dim == IDX_DIM && s.idx_n_head == IDX_HEADS && s.idx_block == R && scores_multi_on() && + nq <= MQ && active_blocks <= 0 && + qsa_block_scores_dx(pooled, dead, q_idx, steps, nq, max_blocks, scores, stream)) + return; +#endif + qsa_block_scores(pooled, dead, q_idx, steps, nq, max_blocks, s, scores, stream, active_blocks); +} + } // namespace strata::kernels diff --git a/src/kernels/qsa_select_long_parity.cpp b/src/kernels/qsa_select_long_parity.cpp new file mode 100644 index 00000000..affb41ac --- /dev/null +++ b/src/kernels/qsa_select_long_parity.cpp @@ -0,0 +1,214 @@ +// src/kernels/qsa_select_long_parity.cpp - STRATA_SELECT_LONG's decode select (PR #3820): qsa_block_scores_long +// (block_scores_dx_kernel) and qsa_block_topk_long (the multi-CTA top-k) against qsa_block_scores and qsa_block_topk, +// bit for bit (GPU, synthetic data, no model). +// +// Needs the CUDA build with STRATA_EXPERIMENTAL_SM60 (elsewhere the _long calls forward to the plain ones and there is +// nothing to compare; the test skips with 77) and STRATA_SCORES_DX=1 STRATA_TOPK_MULTI=1 in the environment, which make +// the new kernels run on any card (on compute capability 6.x they are the default). STRATA_TOPK_MULTI_N=<n> fixes the +// CTAs per query (the ctest "n3" case), otherwise one per 2,048 blocks of capacity. +// +// scores: random pooled keys, queries and a dead key; nq 1..8 queries with their own n_bid (a decode window's +// consecutive positions, so tail blocks of 0..3 cells), n_bid 0 / 1 / 31 / 32 / 33 / 1000 / 70001 ...; the +// scores of every block 0..n_bid of every query are compared by memcmp (the tail block n_bid included). +// top-k: scores that are random, all equal, 7 distinct values (many ties across CTAs, so the "first eq_budget cells +// at the threshold" rule is exercised) and random with a boosted tail block; contexts 1,000 (width equals +// n_kv: the identity) up to 524,288 cells; nq 1, 2, 5, 8, 16; capacity max_blocks = the largest context / 4 + 2. +// The selected ids of every query are compared on the first `width` entries. The multi-CTA scratch is filled +// with junk before every call (the contract says no initial value) and must have been written (the new +// kernels ran; a forwarded call would leave it untouched). +// +// qsa_select_long_parity [--device N] exit 0: all cases identical; 77: no GPU or a build without the kernels +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_select.hpp" + +#include <cuda_runtime.h> + +#include <algorithm> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <random> +#include <vector> + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_select_long_parity: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(2); + } +} +template <typename T> T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc((void**) &p, n * sizeof(T) + 64), "cudaMalloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 64), "cudaMemset"); + return p; +} +template <typename T> T* upload(const std::vector<T>& h) { + T* d = dalloc<T>(h.size()); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} + +// steps of a decode window: query i at position pos0 + i +std::vector<int32_t> make_steps(int nq, int64_t pos0, const k::QsaShapes& s) { + std::vector<int32_t> st((size_t) nq * k::kStepCount, 0); + for (int i = 0; i < nq; ++i) { + int32_t* p = st.data() + (size_t) i * k::kStepCount; + const int64_t pos = pos0 + i; + p[k::kStepPos] = (int32_t) pos; + p[k::kStepNKv] = (int32_t) (pos + 1); + p[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); + p[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); + } + return st; +} + +long long g_cases = 0, g_failed = 0; + +void check_scores(const k::QsaShapes& s, int nq, int64_t n_bid0, std::mt19937& rng) { + const int64_t D = s.idx_dim, H = s.idx_n_head; + const int64_t max_blocks = n_bid0 + nq + 8; + std::normal_distribution<float> nd(0.0f, 1.0f); + std::vector<float> pooled((size_t) (max_blocks * D)), dead((size_t) D), q((size_t) (nq * H * D)); + for (auto& x : pooled) x = nd(rng); + for (auto& x : dead) x = nd(rng); + for (auto& x : q) x = nd(rng); + // the window's last query has n_bid0 blocks; the others one position earlier each (their tails differ) + const std::vector<int32_t> steps = make_steps(nq, n_bid0 * s.idx_block - 1 + (int64_t) (rng() % 4u) - (nq - 1), s); + float *dp = upload(pooled), *dd = upload(dead), *dq = upload(q); + int32_t* dst = upload(steps); + float* a = dalloc<float>((size_t) (nq * max_blocks)); + float* b = dalloc<float>((size_t) (nq * max_blocks)); + ck(cudaMemset(a, 0xFF, (size_t) (nq * max_blocks) * 4), "fill a"); + ck(cudaMemset(b, 0xFF, (size_t) (nq * max_blocks) * 4), "fill b"); + k::qsa_block_scores(dp, dd, dq, dst, nq, max_blocks, s, a, nullptr); + k::qsa_block_scores_long(dp, dd, dq, dst, nq, max_blocks, s, b, nullptr, -1); + ck(cudaDeviceSynchronize(), "scores"); + std::vector<float> ha((size_t) (nq * max_blocks)), hb(ha.size()); + ck(cudaMemcpy(ha.data(), a, ha.size() * 4, cudaMemcpyDeviceToHost), "read a"); + ck(cudaMemcpy(hb.data(), b, hb.size() * 4, cudaMemcpyDeviceToHost), "read b"); + bool ok = true; + for (int i = 0; i < nq && ok; ++i) { + const int64_t nb = steps[(size_t) i * k::kStepCount + k::kStepNBid]; + for (int64_t j = 0; j <= nb; ++j) { // block n_bid is the tail + if (std::memcmp(&ha[(size_t) (i * max_blocks + j)], &hb[(size_t) (i * max_blocks + j)], 4) != 0) { + std::printf("FAIL scores nq %d n_bid0 %lld: query %d block %lld: %.9g vs %.9g\n", nq, (long long) n_bid0, i, + (long long) j, ha[(size_t) (i * max_blocks + j)], hb[(size_t) (i * max_blocks + j)]); + ok = false; + break; + } + } + } + ++g_cases; + if (!ok) ++g_failed; + for (void* p : {(void*) dp, (void*) dd, (void*) dq, (void*) dst, (void*) a, (void*) b}) cudaFree(p); +} + +void check_topk(const k::QsaShapes& s, int nq, int64_t ctx, int mode, int64_t max_blocks, std::mt19937& rng, bool& multi_ran) { + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); + const std::vector<int32_t> steps = make_steps(nq, ctx - nq, s); + std::vector<float> sc((size_t) (nq * max_blocks), -999.0f); + std::uniform_real_distribution<float> ur(0.0f, 200.0f); + for (int i = 0; i < nq; ++i) { + const int32_t nb = steps[(size_t) i * k::kStepCount + k::kStepNBid]; + const bool tail = steps[(size_t) i * k::kStepCount + k::kStepNKv] % s.idx_block != 0; + for (int64_t j = 0; j <= nb; ++j) { + float v = mode == 1 ? 3.0f : mode == 2 ? (float) (rng() % 7u) : ur(rng); + sc[(size_t) (i * max_blocks + j)] = v; + } + if (tail && mode != 1) sc[(size_t) (i * max_blocks + nb)] += 1e9f; + } + float* ds = upload(sc); + int32_t* dst = upload(steps); + int32_t* ia = dalloc<int32_t>((size_t) (nq * cap)); + int32_t* ib = dalloc<int32_t>((size_t) (nq * cap)); + const int64_t scratch_ints = k::qsa_topk_multi_scratch_ints(nq); + int32_t* scratch = dalloc<int32_t>((size_t) scratch_ints); + ck(cudaMemset(scratch, 0xFF, (size_t) scratch_ints * 4), "scratch junk"); + ck(cudaMemset(ia, 0xFF, (size_t) (nq * cap) * 4), "fill ia"); + ck(cudaMemset(ib, 0xFF, (size_t) (nq * cap) * 4), "fill ib"); + k::qsa_block_topk(ds, dst, nq, max_blocks, cap, s, ia, nullptr); + k::qsa_block_topk_long(ds, dst, nq, max_blocks, cap, s, ib, nullptr, -1, scratch); + ck(cudaDeviceSynchronize(), "topk"); + std::vector<int32_t> ha((size_t) (nq * cap)), hb(ha.size()), hs((size_t) scratch_ints); + ck(cudaMemcpy(ha.data(), ia, ha.size() * 4, cudaMemcpyDeviceToHost), "read ia"); + ck(cudaMemcpy(hb.data(), ib, hb.size() * 4, cudaMemcpyDeviceToHost), "read ib"); + ck(cudaMemcpy(hs.data(), scratch, hs.size() * 4, cudaMemcpyDeviceToHost), "read scratch"); + // the multi kernels write the scratch (pass 0's histogram rows) when the contexts are above the identity width + const bool touched = std::any_of(hs.begin(), hs.end(), [](int32_t v) { return v != -1; }); + if (touched) multi_ran = true; + bool ok = true; + for (int i = 0; i < nq && ok; ++i) { + const int64_t w = steps[(size_t) i * k::kStepCount + k::kStepWidth]; + if (!std::equal(ha.begin() + i * cap, ha.begin() + i * cap + w, hb.begin() + i * cap)) { + size_t first = 0; + while (ha[(size_t) (i * cap) + first] == hb[(size_t) (i * cap) + first]) ++first; + std::printf("FAIL topk nq %d ctx %lld mode %d max_blocks %lld: query %d entry %zu: %d vs %d\n", nq, + (long long) ctx, mode, (long long) max_blocks, i, first, ha[(size_t) (i * cap) + first], + hb[(size_t) (i * cap) + first]); + ok = false; + } + } + ++g_cases; + if (!ok) ++g_failed; + for (void* p : {(void*) ds, (void*) dst, (void*) ia, (void*) ib, (void*) scratch}) cudaFree(p); +} +} // namespace + +int main(int argc, char** argv) { + int device = 0; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else { + std::fprintf(stderr, "usage: qsa_select_long_parity [--device N]\n"); + return 2; + } + } + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::puts("SKIP: no GPU"); + return 77; + } + ck(cudaSetDevice(device), "cudaSetDevice"); + if (k::qsa_topk_multi_scratch_ints(1) <= 0) { + std::puts("SKIP: this build has no multi-CTA select (CUDA with STRATA_EXPERIMENTAL_SM60)"); + return 77; + } + const char* dx = std::getenv("STRATA_SCORES_DX"); + const char* mt = std::getenv("STRATA_TOPK_MULTI"); + if (dx == nullptr || dx[0] != '1' || mt == nullptr || mt[0] != '1') { + std::fprintf(stderr, "qsa_select_long_parity: set STRATA_SCORES_DX=1 and STRATA_TOPK_MULTI=1 (the kernels are " + "otherwise default only on compute capability 6.x)\n"); + return 2; + } + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + std::printf("qsa_select_long_parity on device %d (%s, %d.%d), STRATA_TOPK_MULTI_N=%s\n", device, prop.name, prop.major, + prop.minor, std::getenv("STRATA_TOPK_MULTI_N") ? std::getenv("STRATA_TOPK_MULTI_N") : "(per capacity)"); + + const k::QsaShapes s = k::qsa_real_shapes(); + std::mt19937 rng(20261026u); + for (int nq : {1, 2, 3, 5, 8}) + for (int64_t nb : {(int64_t) 8, (int64_t) 31, (int64_t) 32, (int64_t) 33, (int64_t) 1000, (int64_t) 70001, (int64_t) 131072}) + check_scores(s, nq, nb, rng); + + bool multi_ran = false; + const int64_t max_ctx = 524288, max_blocks = max_ctx / s.idx_block + 2; + for (int nq : {1, 2, 5, 8, 16}) + for (int64_t ctx : {(int64_t) 1000, (int64_t) 2051, (int64_t) 2055, (int64_t) 8192, (int64_t) 70000, (int64_t) 135164, + (int64_t) 135168, (int64_t) 300003, max_ctx}) + for (int mode = 0; mode < 3; ++mode) + check_topk(s, nq, ctx, mode, max_blocks, rng, multi_ran); + // a smaller capacity than the context asks for (max_blocks only bounds the row stride) + for (int nq : {1, 4}) check_topk(s, nq, 40000, 0, 40000 / s.idx_block + 2, rng, multi_ran); + if (!multi_ran) { + std::printf("FAIL: the multi-CTA top-k never wrote its scratch: the new kernels did not run\n"); + ++g_failed; + } + std::printf("qsa_select_long_parity: %lld cases, %lld differ -> %s\n", g_cases, g_failed, g_failed == 0 ? "PASS" : "FAIL"); + return g_failed == 0 ? 0 : 1; +} From 805ebe17be37dd1e58a150c70aa797370347618b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:30:31 +0100 Subject: [PATCH 141/177] serve: a call returned as text for an undeclared name is named in the reply; the collapsed mcp__a__b spelling is the declared tool (#3796) Problem: a request declares tools; the model writes a complete call for a name that is not among them (bash for shell, a dropped prefix, an MCP name with every "__" written as "_"). Since #3075 such a call stays text, which is the rule we keep, but the client saw an ordinary answer with finish_reason stop and nothing else, so the agent turn ended with raw XML and the model never learned of its mistake. Reporters on OpenCode, Pithagoras, OpenClaw, LibreChat, Open WebUI and Pi hit it. What changed (declared-only stays: nothing undeclared is ever returned as a call, finish_reason is unchanged): - serve/frontend.py OutputParser: a declared name that contains "__" is also read when written with every "__" as "_" (mcp_playwright_browser_navigate for mcp__playwright__browser_navigate); the call goes to the client under the declared name. Same rules as the other aliases: only when unambiguous, and a tool declared under that spelling wins. A reordered or renamed tool (server1_label_values for label_values_mcp_server1, bash for shell) is not guessed. - serve/server.py: when a block went back as text for an undeclared name, the reply carries "strata_rejected_tool_calls": [{"name": ..., "reason": "undeclared"}] (the names the parser already collected, up to five): at the top level of a Chat Completions reply and in its last streamed chunk, and in the message_delta event and the message of /v1/messages. It is absent when nothing was rejected, so every other reply is unchanged. The text itself is untouched. - The server window line says the response carries the names; the count goes to totals["tool_calls_unread"] and to /metrics/prometheus as strata:tool_calls_unread_total. - docs/DETAILS.md: the alias, the marker, the counter. Tests: serve/test_tool_name_alias.py (collapsed spelling at several chunk widths, a declared spelling and a plain tool unchanged, a tool declared in the collapsed spelling wins, two tools with one collapsed spelling are not guessed, reordered/renamed names stay text and are named), serve/test_server.py ForcedToolChoice (the field in Chat Completions whole and streamed and in /v1/messages, absent for an ordinary answer and a declared call, the collapsed name is a call; the counter). The whole serve/ suite: 1055 tests, two failures that also fail on the base tree (test_fatal_recovery on this PC, RestartWindow.test_not_alive_until_ready under load). Not covered: returning an undeclared call as a real tool call (the owner keeps declared-only); a block for a DECLARED name that came back as text because it was malformed (counted, no name to list); the /v1/messages field with a real client; a stderr or log-file copy of the warning. --- docs/DETAILS.md | 15 ++++++-- serve/frontend.py | 6 ++++ serve/server.py | 29 +++++++++++---- serve/test_server.py | 68 +++++++++++++++++++++++++++++++++++ serve/test_tool_name_alias.py | 64 +++++++++++++++++++++++++++++++++ 5 files changed, 174 insertions(+), 8 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index f60429bf..29dcefd8 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -483,9 +483,20 @@ applies at the next start. Network, key, MCP and program keys are not editable t every 15 s and `GET /status` says what it is doing. Closing the connection or pressing stop in your app stops the model. - A tool call counts only when it names a tool the request declared. A namespaced tool (`mcp__filesystem.write_file`) is that call when the model writes `mcp__filesystem__write_file`, `mcp__filesystem=write_file`, `mcp__filesystem_write_file`, - or the bare member (`write_file`) and exactly one declared tool has that member. Any other call, or any call in a request - that declared no tools, comes back as the text it was written as. A call whose envelope drifted by a token (`<=NAME>`, + or the bare member (`write_file`) and exactly one declared tool has that member. A name with `__` in it (`mcp__playwright__browser_navigate`) + is also that call when the model writes every `__` as `_` (`mcp_playwright_browser_navigate`), unless two declared tools collapse to the same + spelling. Any other call, or any call in a request that declared no tools, comes back as the text it was written as. Names are never + guessed: `bash` is not `shell`, and a reordered name (`server1_label_values` for `label_values_mcp_server1`) is not the declared one. + A call whose envelope drifted by a token (`<=NAME>`, `<function:NAME>` or `<NAME>` instead of `<function=NAME>`) is read as the call when NAME is a declared tool. +- **A call that came back as text because its name was not declared (#3796).** The text stays exactly as the model wrote it and + `finish_reason` stays `stop` (or `end_turn` on `/v1/messages`). Next to it the reply carries a list, only when there is something in it: + `"strata_rejected_tool_calls": [{"name": "bash", "reason": "undeclared"}]` (at the top level of a Chat Completions reply, in + its last streamed chunk, and in the `message_delta` event and the message of `/v1/messages`; up to five names). A client that + wants to recover can answer the model with the tool names it does have and ask again; Strata never runs or forwards a call for a + tool the request did not declare. The server window prints the same names (`N <tool_call> block(s) ... went back as text`), and + `/metrics/prometheus` counts the blocks in `strata:tool_calls_unread_total`. A block that is malformed (not an undeclared name) is counted + there and in the window, but has no name to list. - JSON output: `response_format: {"type":"json_object"}` or `{"type":"json_schema", ...}` on `/v1/chat/completions`. The schema must accept only JSON objects at its root (`"type":"object"`, or `anyOf`/`oneOf` of object schemas). Local `#` references work and remote ones are refused. This is schema prompting followed by server validation, not grammar-constrained diff --git a/serve/frontend.py b/serve/frontend.py index 0d00ded4..d4bac5d7 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -935,6 +935,12 @@ class OutputParser: for alias in (f"{namespace}__{member}", f"{namespace}={member}", f"{namespace}_{member}", member): aliases.setdefault(alias, set()).add(name) + # #3796: the same tool written with every `__` collapsed to `_` (`mcp__playwright__browser_navigate` as + # `mcp_playwright_browser_navigate`, the way Qwen often flattens a name) is that tool. Only a spelling of a declared + # name: a reordered or renamed tool (`server1_label_values` for `label_values_mcp_server1`) is not guessed. + for name in self.schemas: + if isinstance(name, str) and "__" in name: + aliases.setdefault(name.replace("__", "_"), set()).add(name) self.aliases = {alias: next(iter(names)) for alias, names in aliases.items() if len(names) == 1 and alias not in self.schemas} self.unread = 0 # #3441: `<tool_call>` blocks that opened like a call and were returned as text diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..0ce1942c 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4680,6 +4680,8 @@ class Service: ("strata:requests_total", "counter", "Requests finished", t["requests"]), ("strata:drafts_offered_total", "counter", "Speculative draft tokens offered", t["drafts_offered"]), ("strata:drafts_accepted_total", "counter", "Speculative draft tokens accepted", t["drafts_accepted"]), + ("strata:tool_calls_unread_total", "counter", "<tool_call> blocks returned as text (an undeclared name or a form the template does not use)", + t.get("tool_calls_unread", 0)), ("strata:model_loaded", "gauge", "1 while the model is loaded", int(self.loaded())), ] return "".join(f"# HELP {name} {help_}\n# TYPE {name} {kind}\n{name} {value}\n" @@ -5596,11 +5598,17 @@ class Service: self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as " f"reasoning (quoted, or the turn did not end on a stop)", flush=True) + rejected = [] if parser.unread: named = getattr(parser, "unread_names", None) print(f"[strata] {parser.unread} <tool_call> block(s) in the answer did not read as a call of a declared " "tool and went back as text (a name the request did not declare, or a form the template does " - "not use)" + (f"; the names the model wrote: {', '.join(named)}" if named else ""), flush=True) + "not use)" + (f"; the names the model wrote: {', '.join(named)}" if named else "") + + "; the response carries them as strata_rejected_tool_calls, /metrics counts them", flush=True) + with self.status_lock: + self.totals["tool_calls_unread"] = self.totals.get("tool_calls_unread", 0) + parser.unread + # #3796: the same names for the client (a machine-readable marker next to the text, which stays as the model wrote it) + rejected = [{"name": nm, "reason": "undeclared"} for nm in named or []] if stops is not None and stops.hit is None and stops.held: yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), @@ -5608,6 +5616,8 @@ class Service: "reasoning_recoveries": recovery_count} if stops is not None and stops.hit is not None: done["stop_sequence"] = stops.hit + if rejected: + done["rejected_tool_calls"] = rejected yield "done", done @@ -5892,6 +5902,8 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel "prompt_tokens_details": {"cached_tokens": x.get("reused") or 0}} if x.get("timings"): last["timings"] = x["timings"] # llama.cpp's field: the speed its clients show + if x.get("rejected_tool_calls"): + last["strata_rejected_tool_calls"] = x["rejected_tool_calls"] # #3796: only when a call was refused as undeclared yield last @@ -5938,6 +5950,8 @@ def openai_collect(chunks) -> dict: "usage": last["usage"]} if last.get("timings"): out["timings"] = last["timings"] + if last.get("strata_rejected_tool_calls"): + out["strata_rejected_tool_calls"] = last["strata_rejected_tool_calls"] return out @@ -6029,11 +6043,12 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can # request, a cache write; input_tokens keeps the last token, as 0 makes Claude Code count the prompt twice (#1013) reused = max(0, min(x.get("reused") or 0, len(ids) - 1)) read_now = len(ids) - reused - yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, - "stop_sequence": x.get("stop_sequence")}, - "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1, - "cache_read_input_tokens": reused, - "output_tokens": x["completion_tokens"]}} + delta_event = {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": x.get("stop_sequence")}, + "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1, + "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} + if x.get("rejected_tool_calls"): + delta_event["strata_rejected_tool_calls"] = x["rejected_tool_calls"] # #3796 + yield "message_delta", delta_event yield "message_stop", {"type": "message_stop"} @@ -6065,6 +6080,8 @@ def anthropic_collect(events) -> dict: msg["stop_reason"] = e["delta"]["stop_reason"] msg["stop_sequence"] = e["delta"].get("stop_sequence") msg["usage"].update(e["usage"]) + if e.get("strata_rejected_tool_calls"): + msg["strata_rejected_tool_calls"] = e["strata_rejected_tool_calls"] for i in range(len(blocks) - 1): # a turn with no </think> (serve/dsml.py): the text is the answer; it is not also a thinking block a, b = blocks[i], blocks[i + 1] if a.get("type") == "thinking" and b.get("type") == "text" and a.get("thinking", "").strip() == b.get("text", "").strip(): diff --git a/serve/test_server.py b/serve/test_server.py index 3e60dee4..7babcde1 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -4521,6 +4521,74 @@ class ForcedToolChoice(unittest.TestCase): self.assertIn("Here is the report.", content) self.assertIn("<function=lookup>", content) + def _undeclared_call_answer(self, name="lookup"): + from serve.frontend import CALL_END, CALL_START + return ("I will check that.\n" + CALL_START + f"\n<function={name}>\n<parameter=q>\n2+2\n</parameter>\n" + "</function>\n" + CALL_END) + + def _rejected_of(self, b, stream): + """The strata_rejected_tool_calls of a whole reply or of a streamed one (None when the reply has none).""" + if not stream: + return b.get("strata_rejected_tool_calls") + found = [json.loads(line[6:]).get("strata_rejected_tool_calls") for line in b.splitlines() if line.startswith("data: {")] + found = [f for f in found if f] + self.assertLessEqual(len(found), 1, "sent once, with the last chunk") + return found[0] if found else None + + def test_an_undeclared_call_is_named_in_the_response(self): + """#3796: the call stays text and finish_reason stays "stop"; the response also lists the names the model wrote + (strata_rejected_tool_calls), so a client can tell this from an ordinary answer and answer the model.""" + self.says(self._undeclared_call_answer("execute_gdscript")) + for stream in (False, True): + with self.subTest(stream=stream): + before = self.svc.totals.get("tool_calls_unread", 0) + code, b = self.openai(stream=stream) + finish, calls, _ = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("stop", []), b) + self.assertEqual(self._rejected_of(b, stream), [{"name": "execute_gdscript", "reason": "undeclared"}]) + self.assertEqual(self.svc.totals["tool_calls_unread"], before + 1) # /metrics counts it + if not stream: + self.assertIn("<function=execute_gdscript>", b["choices"][0]["message"]["content"]) # the text is untouched + + def test_no_marker_when_nothing_was_rejected(self): + """An ordinary answer and a declared call carry no extra field: the API is what it was.""" + from serve.frontend import CALL_END, CALL_START + for label, answer in (("text", "The answer is 4."), + ("declared call", CALL_START + "\n<function=search>\n<parameter=q>\n2+2\n</parameter>\n</function>\n" + CALL_END)): + self.says(answer) + for stream in (False, True): + with self.subTest(case=label, stream=stream): + code, b = self.openai(stream=stream) + self.call_of(code, b, stream) + self.assertIsNone(self._rejected_of(b, stream)) + if stream: + self.assertNotIn("strata_rejected_tool_calls", b) + + def test_a_collapsed_mcp_name_is_a_call_not_a_rejection(self): + """#3796: `mcp_playwright_browser_navigate` for the declared `mcp__playwright__browser_navigate`.""" + from serve.frontend import CALL_END, CALL_START + tools = [{"type": "function", "function": {"name": "mcp__playwright__browser_navigate", "description": "open a page", + "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}}}] + self.says(CALL_START + "\n<function=mcp_playwright_browser_navigate>\n<parameter=q>\nx\n</parameter>\n</function>\n" + CALL_END) + for stream in (False, True): + with self.subTest(stream=stream): + code, b = self.openai(stream=stream, tools=tools) + finish, calls, _ = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("tool_calls", [("mcp__playwright__browser_navigate", {"q": "x"})])) + self.assertIsNone(self._rejected_of(b, stream)) + + def test_the_anthropic_reply_names_the_rejected_call_too(self): + self.says(self._undeclared_call_answer("bash")) + body = {"model": "m", "max_tokens": 400, "messages": [{"role": "user", "content": "2+2?"}], + "tools": [{"name": "search", "description": "search", "input_schema": {"type": "object", "properties": {}}}]} + req = urllib.request.Request(self.base + "/v1/messages", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + msg = json.loads(r.read().decode()) + self.assertEqual(msg["stop_reason"], "end_turn") + self.assertEqual(msg["strata_rejected_tool_calls"], [{"name": "bash", "reason": "undeclared"}]) + self.assertFalse([c for c in msg["content"] if c["type"] == "tool_use"]) + def test_a_call_with_a_dropped_function_keyword_is_still_the_call(self): """#3441: `<=search>` for `<function=search>`, as a model under a large tool surface writes it.""" from serve.frontend import CALL_END, CALL_START diff --git a/serve/test_tool_name_alias.py b/serve/test_tool_name_alias.py index 1ceda8b8..5efc8365 100644 --- a/serve/test_tool_name_alias.py +++ b/serve/test_tool_name_alias.py @@ -193,5 +193,69 @@ class DriftedMcpNames(unittest.TestCase): self.assertNotIn("namespace", calls[0]) +def plain_tool(name): + return {"name": name, "parameters": {"type": "object", "properties": {"url": {"type": "string"}}}} + + +def call_text(name, param="url", value="https://example.com"): + return f"<tool_call>\n<function={name}>\n<parameter={param}>\n{value}\n</parameter>\n</function>\n</tool_call>" + + +def run_parser(text, tools, width=0): + parser = OutputParser(thinking=False, tools=tools, stream_tools=True, declared_only=True) + evs = [] + step = width or len(text) or 1 + for k in range(0, len(text), step): + evs += parser.feed(text[k:k + step]) + evs += parser.finish("stop") + return evs, parser + + +class CollapsedUnderscoreNames(unittest.TestCase): + """#3796: `mcp__server__tool` written as `mcp_server_tool` is a spelling of the declared tool (the same class of + difference as namespace__member). A name that is only similar stays text, and is named for the client.""" + MCP = [plain_tool("mcp__playwright__browser_navigate"), plain_tool("mcp__playwright__browser_snapshot"), + plain_tool("mcp__playwright__browser_tabs"), plain_tool("todo_write")] + + def test_the_collapsed_spelling_is_the_declared_tool(self): + for name in ("browser_navigate", "browser_snapshot", "browser_tabs"): + for width in (0, 1, 5): + with self.subTest(name=name, width=width): + evs, parser = run_parser("Opening it.\n" + call_text("mcp_playwright_" + name), self.MCP, width) + found = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual([c.name for c in found], ["mcp__playwright__" + name]) # the client gets the name it declared + self.assertEqual(found[0].arguments, {"url": "https://example.com"}) + self.assertEqual(text_of(evs).strip(), "Opening it.") + self.assertEqual((parser.unread, parser.unread_names), (0, [])) + + def test_the_declared_spelling_and_a_plain_tool_are_unchanged(self): + evs, _ = run_parser(call_text("mcp__playwright__browser_tabs") + "\n" + call_text("todo_write"), self.MCP) + self.assertEqual([e.call.name for e in evs if e.kind == "tool_call"], ["mcp__playwright__browser_tabs", "todo_write"]) + + def test_a_tool_declared_in_the_collapsed_spelling_wins(self): + tools = self.MCP + [plain_tool("mcp_playwright_browser_tabs")] + evs, _ = run_parser(call_text("mcp_playwright_browser_tabs"), tools) + self.assertEqual([e.call.name for e in evs if e.kind == "tool_call"], ["mcp_playwright_browser_tabs"]) + + def test_two_tools_with_the_same_collapsed_spelling_are_not_guessed(self): + tools = [plain_tool("a__b_c"), plain_tool("a_b__c")] + evs, parser = run_parser(call_text("a_b_c"), tools) + self.assertEqual([e for e in evs if e.kind == "tool_call"], []) + self.assertIn("a_b_c", text_of(evs)) + self.assertEqual(parser.unread_names, ["a_b_c"]) + + def test_a_reordered_or_renamed_tool_stays_text_and_is_named(self): + """The LibreChat case (`server1_label_values` for `label_values_mcp_server1`) and the bash/shell case: no guessing.""" + for declared, written in (("label_values_mcp_server1", "server1_label_values"), ("shell", "bash"), + ("godot_execute_gdscript", "execute_gdscript")): + for width in (0, 3): + with self.subTest(written=written, width=width): + raw = "Done.\n" + call_text(written) + evs, parser = run_parser(raw, [plain_tool(declared)], width) + self.assertEqual([e for e in evs if e.kind == "tool_call"], []) + self.assertEqual(text_of(evs), raw) # the text is exactly what the model wrote + self.assertEqual((parser.unread, parser.unread_names), (1, [written])) + + if __name__ == "__main__": unittest.main() From 269c6d3e4ad9531a874f4a74fab725c8ee867312 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:34:14 +0100 Subject: [PATCH 142/177] Dense dequant: the wide kernels by default on sm_80 too, bitwise (#3779, #3712) Problem: sm_80 (GA100: A100, A30, CMP 170HX) ran the per-group dequant kernels that sm_61 and sm_86 had already left for the wide ones, because dequant_wide_on() had no sm_80 entry. Change: dequant_wide_on() answers yes for compute capability 8.0 as well. The test is the raw (major, minor) of the device, so it is false on every other card (sm_60, 70, 75, 86 keep their answer, sm_89, sm_90 and sm_120 stay off as before). STRATA_DEQUANT_WIDE=0 still turns the wide kernels off. Reporter's numbers (linxuhao, one CMP 170HX, GA100 sm_80 with 70 SMs): the GPU time of a 3,259-token prompt went from 857 to 792 ms, prompts +6.3..+7.2 % at 3.3K tokens and +3.9 % at 52K. We have no sm_80 card; these are theirs. Bit identity: the wide kernels are the ones sm_61 and sm_86 already run by default. dequant_wide_parity compares them with the per-group kernels byte for byte for FP16, BF16, FP32, the padded stride and a row slice. The kernels have no sm_80-only code, so the result does not depend on the card; what only an sm_80 card can show is that ptxas for sm_80 keeps the same arithmetic (see the checklist in phaseA-tests/gh027/gates/3779-sm80-checklist.md). Original change by linxuhao (PR #3779, commit 48dc535e); the commit message here is rewritten. --- src/kernels/cuda/dequant_bf16.cu | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index f0aaa925..00e1dd51 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -285,14 +285,16 @@ bool dequant_wide_on() { static const int env = [] { const char* v = std::getenv("STRATA_DEQUANT_WIDE"); return v != nullptr && v[0] != '\0' ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); if (g_dequant_wide >= 0) return g_dequant_wide != 0; if (env >= 0) return env != 0; - static int per_dev[64]; // 0 unknown, 1 no, 2 yes: sm_61 (measured on a Tesla P40) and sm_86 (RTX 3060 / A4000, 0.1.45: short-prompt TTFT -12..-17%, bitwise) + // 0 unknown, 1 no, 2 yes: sm_61 (measured on a Tesla P40), sm_86 (RTX 3060 / A4000, 0.1.45: short-prompt TTFT -12..-17%, + // bitwise) and sm_80 (CMP 170HX: a 3,259-token prompt 857 -> 792 ms of GPU time, prompts +4-7%, bitwise) + static int per_dev[64]; int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { (void) cudaGetLastError(); return false; } if (!per_dev[dev]) { int major = 0, minor = 0; if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { (void) cudaGetLastError(); return false; } - per_dev[dev] = (major == 6 && minor == 1) || (major == 8 && minor == 6) ? 2 : 1; + per_dev[dev] = (major == 6 && minor == 1) || (major == 8 && (minor == 6 || minor == 0)) ? 2 : 1; } return per_dev[dev] == 2; } From 91aebae6363df17193208bd0f2879191370edd3f Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:34:14 +0100 Subject: [PATCH 143/177] MMVQ-IL: sm_80 row tables, bitwise (#3779, #3712) Problem: an sm_80 card took the shared interleaved-MMVQ row tables, which were measured on other cards (#3252 reports A100 slowdowns). Change: kIlRows_80 (2-4 columns), kIlRows58_80 (5-8 columns) and kIl1Rows_80 (one column), looked up under the key 80 only. They were read off mmvq_il_parity --bench --emit-table with the same 3 % rule as the other tables. STRATA_MMVQ_IL_SM80=0 maps an sm_80 card to the key 81, which has no table, so it gets the shared table again (and no one-column table, as before). A table only picks the rows a warp (0, 1, 2 or 4); 0 means native_mmvq's kernels. mmvq_il_parity already checks every rows choice against native_mmvq bitwise for every type and shape, T = 1..8, so any entry of the new tables is covered. Reporter's numbers (linxuhao, one CMP 170HX): decode +2.7..+3.2 % over the shared table, Qwen3.8-Flash-Next IQ3_S. The measured card is not an A100; the rows may want re-measuring there. Original change by linxuhao (PR #3779, commit eaedca84); the commit message here is rewritten. The sm_89 table of #3453 is a separate change in the same list. --- src/kernels/cuda/native_mmvq.cu | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 05f9b42d..2cc1c75a 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -3045,6 +3045,15 @@ constexpr IlRows kIlRows_120[] = { {14, {{0, 0, 2, 1, 1}, {0, 0, 4, 2, 4}, {0, 2, 2, 2, 2}}}, // Q6_K {11, {{0, 1, 2, 2, 2}, {0, 2, 4, 2, 2}, {0, 2, 2, 2, 2}}}, // Q3_K }; +// sm_80: read off mmvq_il_parity --bench --emit-table on a CMP 170HX (GA100, 70 SMs, HBM2e 1.5 TB/s), the same 3% rule; +// bitwise equal to native_mmvq (the tool checks every case). +constexpr IlRows kIlRows_80[] = { + {23, {{0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 2, 1, 1, 1}}}, // IQ4_XS + {12, {{0, 0, 4, 4, 4}, {0, 0, 2, 2, 2}, {0, 0, 2, 2, 2}}}, // Q4_K + {13, {{0, 0, 2, 2, 4}, {0, 0, 2, 2, 2}, {0, 0, 2, 2, 2}}}, // Q5_K + {14, {{0, 0, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 2, 4, 2, 2}}}, // Q6_K + {11, {{1, 2, 2, 2, 2}, {1, 1, 2, 2, 2}, {1, 2, 2, 2, 2}}}, // Q3_K +}; // Turing (sm_75): read off mmvq_il_parity --bench --emit-table on an RTX 2080 Ti 22 GB (SM 1650 MHz), the same 3% rule. // The plain multi-column kernels are bound by dp4a throughput on Turing from 2 columns on (IQ4_XS 2560x10240 at 4 // columns 81.1 -> 37.4 us, the Q5_K head 1671 -> 1045 us); bitwise equal to native_mmvq. No one-column table here: @@ -3068,8 +3077,16 @@ constexpr IlRows58 kIlRows58_120[] = { // 4 = 2 rows a warp here (launch_il_ro {14, {{0, 2, 4, 4, 4}, {0, 4, 2, 4, 2}, {0, 2, 4, 2, 2}, {0, 4, 4, 4, 2}}}, // Q6_K {11, {{0, 2, 4, 2, 4}, {0, 2, 2, 4, 4}, {0, 2, 2, 2, 4}, {0, 4, 2, 2, 2}}}, // Q3_K }; +constexpr IlRows58 kIlRows58_80[] = { // CMP 170HX, as kIlRows_80 + {23, {{0, 4, 4, 2, 2}, {0, 2, 4, 4, 4}, {0, 2, 4, 1, 1}, {1, 4, 1, 1, 1}}}, // IQ4_XS + {12, {{0, 0, 4, 2, 2}, {0, 2, 4, 2, 2}, {0, 2, 4, 4, 4}, {0, 2, 2, 4, 4}}}, // Q4_K + {13, {{0, 0, 4, 2, 2}, {0, 4, 2, 2, 2}, {0, 4, 4, 2, 4}, {0, 2, 4, 4, 2}}}, // Q5_K + {14, {{0, 0, 4, 2, 4}, {0, 0, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 0, 4, 2, 4}}}, // Q6_K + {11, {{0, 0, 4, 2, 4}, {0, 0, 4, 1, 4}, {0, 0, 1, 1, 1}, {1, 1, 1, 1, 1}}}, // Q3_K +}; struct Il58Arch { int cc; const IlRows58* t; size_t n; }; constexpr Il58Arch kIl58Arch[] = { + {80, kIlRows58_80, sizeof(kIlRows58_80) / sizeof(IlRows58)}, {120, kIlRows58_120, sizeof(kIlRows58_120) / sizeof(IlRows58)}, {1201, kIlRows58_120, sizeof(kIlRows58_120) / sizeof(IlRows58)}, // a 12.0 card with 80+ SMs (il_cc) }; @@ -3084,8 +3101,15 @@ constexpr Il1Rows kIl1Rows_61[] = { {13, {0, 0, 0, 2, 2}}, // Q5_K {11, {0, 0, 2, 2, 2}}, // Q3_K }; +constexpr Il1Rows kIl1Rows_80[] = { // CMP 170HX, as kIlRows_80 + {23, {0, 0, 1, 4, 1}}, // IQ4_XS + {12, {0, 0, 2, 2, 2}}, // Q4_K + {13, {0, 0, 0, 4, 1}}, // Q5_K + {11, {0, 0, 2, 2, 2}}, // Q3_K +}; struct Il1Arch { int cc; const Il1Rows* t; size_t n; }; constexpr Il1Arch kIl1Arch[] = { + {80, kIl1Rows_80, sizeof(kIl1Rows_80) / sizeof(Il1Rows)}, {61, kIl1Rows_61, sizeof(kIl1Rows_61) / sizeof(Il1Rows)}, {86, kIl1Rows_86, sizeof(kIl1Rows_86) / sizeof(Il1Rows)}, }; @@ -3101,6 +3125,7 @@ constexpr IlArch kIlArch[] = { {61, kIlRows_61, sizeof(kIlRows_61) / sizeof(IlRows)}, // Pascal with dp4a: measured on a Tesla P40 {75, kIlRows_75, sizeof(kIlRows_75) / sizeof(IlRows)}, // Turing: measured on an RTX 2080 Ti {70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)}, // Volta: PR 1401, measured on a V100-SXM2 + {80, kIlRows_80, sizeof(kIlRows_80) / sizeof(IlRows)}, // sm_80: measured on a CMP 170HX {86, kIlRows_86, sizeof(kIlRows_86) / sizeof(IlRows)}, // 143-dense: RTX A4000 with the real shapes (Q3_K added) // 147-verify: RTX PRO 5000 Blackwell (110 SMs). Only 12.0 cards with 80+ SMs (il_cc's 1201) take it: the shared table // was measured on an RTX 5070 (48 SMs) and stays that card's @@ -3188,6 +3213,8 @@ int il_cc() { int sms = 0; if (cc[dev] == 120 && cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && sms >= 80) cc[dev] = 1201; + // STRATA_MMVQ_IL_SM80=0: an sm_80 card takes the shared table as before kIlRows_80 (A/B) + if (cc[dev] == 80) { const char* v = std::getenv("STRATA_MMVQ_IL_SM80"); if (v != nullptr && v[0] == '0') cc[dev] = 81; } cudaGetLastError(); } return cc[dev]; From bdcc34dfa80f6f84ed928c8e12a769d04042e9fd Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:35:30 +0100 Subject: [PATCH 144/177] Prefill fused IQ experts: opt-in 256-thread kernels STRATA_PF_FUSED_NT=256 and whole-layer launches STRATA_PF_BATCH=N (#3779, #3712) Problem: on a GA100 card (70 SMs) the 512-thread fused prompt-expert kernels leave the card idle at every barrier and at every grid tail. Change, all opt-in: - STRATA_PF_FUSED_NT=256 sets up a second set of native_kernel instances with 256 threads and two blocks a multiprocessor (WW 2 only), with two-pass weight loads (the loads of the next k step are issued before the current step's decode; load_unit_l gives the same words as load_unit). Every output is the same thread's sum in the same order. - STRATA_PF_BATCH=N launches up to N experts at once (WideBatch holds 512 blob pointers, 4 KB of kernel parameters: CUDA 12.1+, Volta and newer; HIP, gfx906 and the Pascal build keep kMaxBatch). Above 128 it needs the NT = 256 kernels. Below 128 it only changes the launch grouping. - With neither variable set the 512-thread kernels, their launches and their load sequence are unchanged: tile_rows(ww, 512) equals the old 256 / ww, the two-pass code is behind a constant-false TWO_PASS, and the one added test in experts_native is occ_nt > 0, which only STRATA_PF_FUSED_NT=256 sets. - If the 256-thread instances cannot be set up (shared memory, occupancy) the engine prints one line and keeps the 512-thread kernels. Cost: the NT = 256 instances are new device code in every CUDA build (the reporter measured 365,632 bytes for sm_80). Tests: new ctest entry prefill_fused_iq_test_nt256 runs prefill_fused_iq_test (the fused kernels against the double-precision reference and the MMQ path) with STRATA_PF_FUSED_NT=256; it exits 77 below sm_80. Reporter's numbers (linxuhao, CMP 170HX): one MoE layer of 3,256 tokens 8.27 ms with NT = 256; prompts +7.6 % (4K), +4.9 % (16K), +4.3 % (52K) for NT=256 with BATCH=512 on the PR's own build. Greedy answers identical on their 11 prompts. These are theirs. Original change by linxuhao (PR #3779, commit 056d36a9). Merged onto the Q2_0 fused path of #3809 (STRATA_PF_FUSED_Q2N=1) without textual conflicts; the PR predates it, so one line is mine: the NT = 256 setup also sets up the Q2_0 gate/up instance when Q2N is on (without it that instance would have launched without its shared-memory attribute). --- CMakeLists.txt | 4 + include/strata/prefill/moe_fused.hpp | 14 ++ include/strata/prefill/moe_fused_iq.hpp | 6 + src/prefill/moe_fused_iq.cu | 168 +++++++++++++++++++++--- src/prefill/prefill.cpp | 40 ++++-- 5 files changed, 207 insertions(+), 25 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9bbd8716..31d3664b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2076,6 +2076,10 @@ if(STRATA_NATIVE_EXPERTS) # layers on sm_80+ (77 below sm_80 and without a card) add_test(NAME prefill_fused_iq_test_q2n COMMAND prefill_fused_iq_test "--only=Q2_0 / Q2_0" --unset-pf-fused) set_tests_properties(prefill_fused_iq_test_q2n PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_Q2N=1" SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_NT=256 kernels (256 threads, two blocks a multiprocessor, two-pass weight loads) against the + # same references; the batches of the test reach them through the Batch overload of experts_native (77 below sm_80) + add_test(NAME prefill_fused_iq_test_nt256 COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_nt256 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_NT=256" 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) diff --git a/include/strata/prefill/moe_fused.hpp b/include/strata/prefill/moe_fused.hpp index eef9e2dc..47df7144 100644 --- a/include/strata/prefill/moe_fused.hpp +++ b/include/strata/prefill/moe_fused.hpp @@ -24,6 +24,14 @@ namespace strata::prefill::fused { constexpr int kTileRows = 64; /// Experts per launch: their blob pointers travel in the launch's parameters (1 KB). constexpr int kMaxBatch = 128; +/// The room of WideBatch::blob (below): a whole layer of 512 experts, which STRATA_PF_BATCH=512 (opt-in) launches at +/// once on the native kernels' NT = 256 instances when all of them are resident (4 KB of kernel parameters: CUDA 12.1+, +/// Volta and newer). HIP, gfx906 and the Pascal / Volta build (STRATA_EXPERIMENTAL_SM60): kMaxBatch. +#if defined(__HIPCC__) || defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_EXPERIMENTAL_SM60) +constexpr int kBatchRoom = kMaxBatch; +#else +constexpr int kBatchRoom = 512; +#endif /// This build has the kernels (a CUDA build; HIP and builds without MMQ do not). bool built(); @@ -57,6 +65,12 @@ struct Batch { int e0 = 0, e1 = 0; const uint8_t* blob[kMaxBatch] = {}; }; +/// Batch with room for kBatchRoom experts (e1 - e0 <= kBatchRoom): only the opt-in launches of STRATA_PF_BATCH above +/// kMaxBatch on the native NT = 256 kernels (moe_fused_iq.hpp, native_wide()) take it; every other launch takes Batch. +struct WideBatch { + int e0 = 0, e1 = 0; + const uint8_t* blob[kBatchRoom] = {}; +}; /// The batch's products: gate/up from `xa` (quantize_act of the layer's input, [tokens][2560]) through the rows /// `src` of `group`, SwiGLU, H as int8 into `ha` (act_bytes(n, 640)), down into `dm` [n][2560] FP32 at the rows of /// `group`. `n`: the layer's routed rows (tokens * k), which bounds the launch grid. diff --git a/include/strata/prefill/moe_fused_iq.hpp b/include/strata/prefill/moe_fused_iq.hpp index 7e63df9b..a5ebd54f 100644 --- a/include/strata/prefill/moe_fused_iq.hpp +++ b/include/strata/prefill/moe_fused_iq.hpp @@ -38,5 +38,11 @@ void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, v /// through Alloc's 256-byte takes from a 256-aligned cache slot or cudaMalloc). void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha, float* dm, void* stream); +/// The NT = 256 kernels (STRATA_PF_FUSED_NT=256) are set up on the current device: experts_native takes a WideBatch +/// (STRATA_PF_BATCH up to kBatchRoom experts a launch). +bool native_wide(); +/// experts_native() of a WideBatch, on the NT = 256 kernels; only when native_wide(). +void experts_native(const WideBatch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, + const int32_t* src, void* ha, float* dm, void* stream); } // namespace strata::prefill::fused diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index d239972f..de40847c 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -44,6 +44,7 @@ #include <cstdlib> #include <cstring> #include <mutex> +#include <type_traits> namespace strata::prefill::fused { namespace { @@ -63,7 +64,7 @@ constexpr float MAGICF = 12582912.0f; // per launch by the rows per expert (pick_ww) constexpr int THREADS = 512; constexpr int WLD = 80; // bytes per decoded weight row of a stage: 64 int8 + 16 (no bank conflicts) -__host__ __device__ constexpr int tile_rows(int ww) { return 256 / ww; } +__host__ __device__ constexpr int tile_rows(int ww, int nt = THREADS) { return nt / 32 / ww * 16; } __host__ __device__ constexpr int weight_rows(int ww) { return 64 * ww; } constexpr int ASTAGES = 4; // cp.async depth of the activations (64 values of K a stage) // Turing: 2 (its copies are plain loads, so depth buys nothing, and 4 does not fit its 64 KB of shared memory) @@ -107,9 +108,9 @@ __host__ __device__ constexpr int grid_bytes(int t) { return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4 : t == T_IQ3_S ? 512 * 4 : 0; } -__host__ __device__ constexpr size_t smem_bytes(int t, int ww, int astages = ASTAGES) { - return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) astages * tile_rows(ww) * AB + - (size_t) tile_rows(ww) * 4 + grid_bytes(t); +__host__ __device__ constexpr size_t smem_bytes(int t, int ww, int astages = ASTAGES, int nt = THREADS) { + return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) astages * tile_rows(ww, nt) * AB + + (size_t) tile_rows(ww, nt) * 4 + grid_bytes(t); } // moe_fused.cu's grouping tables (the same layout: fused::group writes them) @@ -340,6 +341,58 @@ template <int T, int NW> __device__ __forceinline__ void load_unit(const uint8_t } } +// load_unit's bytes in two passes (native_kernel's opt-in NT = 256 instances only, CUDA): `issue` loads the 16-bit and +// 8-bit pieces into registers and `take` assembles the words from them a stage later, so no instruction waits on the +// loads in the stage that issues them (in one pass the shifts and ORs right after the loads stalled every stage on a +// memory round trip). The same bytes in the same words as load_unit. +constexpr int NP = 12; // pieces: at most IQ4_XS's 10 halves and a byte +struct LdIssue { + uint32_t* pc; int k; + __device__ __forceinline__ uint32_t h(const uint8_t* p) { pc[k++] = *(const uint16_t*) p; return 0; } + __device__ __forceinline__ uint32_t b(const uint8_t* p) { pc[k++] = *p; return 0; } +}; +struct LdTake { + const uint32_t* pc; int k; + __device__ __forceinline__ uint32_t h(const uint8_t*) { return pc[k++]; } + __device__ __forceinline__ uint32_t b(const uint8_t*) { return pc[k++]; } +}; +template <class L> __device__ __forceinline__ uint32_t lw(L& l, const uint8_t* p) { + const uint32_t lo = l.h(p); + const uint32_t hi = l.h(p + 2); + return lo | (hi << 16); +} +template <int T, class L, int NW> __device__ __forceinline__ void load_unit_l(L& l, const uint8_t* bp, int ib, uint32_t (&w)[NW]) { + static_assert(NW >= raw_words(T), "raw words"); + if constexpr (T == T_IQ2_XXS || T == T_Q2_0) { + w[0] = lw(l, bp + 2 + 8 * ib); w[1] = lw(l, bp + 6 + 8 * ib); w[2] = l.h(bp); + } else if constexpr (T == T_IQ2_XS) { + w[0] = lw(l, bp + 2 + 8 * ib); w[1] = lw(l, bp + 6 + 8 * ib); + const uint32_t d = l.h(bp); const uint32_t s = l.b(bp + 66 + ib); + w[2] = d | (s << 16); + } else if constexpr (T == T_IQ2_S) { + w[0] = lw(l, bp + 2 + 4 * ib); w[1] = lw(l, bp + 34 + 4 * ib); + const uint32_t d = l.h(bp); const uint32_t qh = l.b(bp + 66 + ib); const uint32_t sc = l.b(bp + 74 + ib); + w[2] = d | (qh << 16) | (sc << 24); + } else if constexpr (T == T_IQ3_XXS) { + w[0] = lw(l, bp + 2 + 8 * ib); w[1] = lw(l, bp + 6 + 8 * ib); w[2] = lw(l, bp + 66 + 4 * ib); w[3] = l.h(bp); + } else if constexpr (T == T_IQ3_S) { + w[0] = lw(l, bp + 2 + 8 * ib); w[1] = lw(l, bp + 6 + 8 * ib); w[2] = lw(l, bp + 74 + 4 * ib); + const uint32_t d = l.h(bp); const uint32_t qh = l.b(bp + 66 + ib); const uint32_t sc = l.b(bp + 106 + ib / 2); + w[3] = d | (qh << 16) | (((sc >> (4 * (ib & 1))) & 15) << 24); + } else if constexpr (T == T_IQ4_XS) { +#pragma unroll + for (int k = 0; k < 4; ++k) w[k] = lw(l, bp + 8 + 16 * ib + 4 * k); + const uint32_t lo = l.b(bp + 4 + ib / 2); const uint32_t hi = l.h(bp + 2); const uint32_t d = l.h(bp); + const uint32_t ls = ((lo >> (4 * (ib & 1))) & 15) | (((hi >> (2 * ib)) & 3) << 4); + w[4] = d | (ls << 16); + } else { // IQ4_NL + static_assert(T == T_IQ4_NL, "the CUDA native formats"); +#pragma unroll + for (int k = 0; k < 4; ++k) w[k] = lw(l, bp + 2 + 4 * k); + w[4] = l.h(bp); + } +} + // The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31). template <int T, int NW> __device__ __forceinline__ void convert(const uint32_t (&w)[NW], const uint8_t* grid, const uint32_t (&kv)[4], @@ -475,13 +528,20 @@ template <int T> __device__ __forceinline__ const void* grid_src() { // tokens' activations, SwiGLU, H to int8 per 32 features into `out`. !GU: down rows (format WT) against H, FP32 into // `dm`. Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, gate rows as mma rows 0-7 and // up rows as 8-15, so a lane holds gate and up of one feature), routed rows 16 wt.. as two n8. -template <int WT, bool GU, int WW> -__global__ void __launch_bounds__(THREADS, 1) -native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, +// NT (STRATA_PF_FUSED_NT=256, sm_80+ opt-in): 256 threads, two blocks a multiprocessor - one block's products run while +// the other waits at a barrier. WW 2 only (its 2 WR = 256 decode units are the block's threads); a work item is 128 +// weight rows x one 64-row tile. Every output is the same thread's sum in the same order: the same bits. The NT = 256 +// instances take a WideBatch (STRATA_PF_BATCH up to kBatchRoom experts a launch), the default ones Batch. +template <int NT> using BatchOf = std::conditional_t<NT == THREADS, Batch, WideBatch>; +template <int WT, bool GU, int WW, int NT = THREADS> +__global__ void __launch_bounds__(NT, NT == THREADS ? 1 : 2) +native_kernel(const BatchOf<NT> b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 - constexpr int TR = tile_rows(WW), WR = weight_rows(WW); + constexpr int TR = tile_rows(WW, NT), WR = weight_rows(WW); + static_assert(2 * WR <= NT, "every decode unit is a thread of the block"); constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB; + constexpr bool TWO_PASS = NT != THREADS; // the two-pass loads (load_unit_l) only in the opt-in NT = 256 kernels constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K constexpr int NFB = (GU ? 1280 : 2560) / WR; // weight-row blocks per tile constexpr int ACT_LD = NS * AB; // bytes per activation row: 3200 (a token), 800 (a row's H) @@ -498,7 +558,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_ const int wf = warp % WW, nb0 = 16 * (warp / WW); if constexpr (grid_bytes(WT) > 0) { const uint32_t* gs = (const uint32_t*) grid_src<WT>(); - for (int i = tid; i < grid_bytes(WT) / 4; i += THREADS) ((uint32_t*) sgrid)[i] = gs[i]; + for (int i = tid; i < grid_bytes(WT) / 4; i += NT) ((uint32_t*) sgrid)[i] = gs[i]; } uint32_t kv[4] = {0, 0, 0, 0}; if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { @@ -555,7 +615,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_ // of a partial one are never written (no reduction mixes columns) auto load_act = [&](int s) { uint8_t* st = stages + (s % ASTAGES_DEV) * ACT_STAGE; - for (int c = tid; c < TR * 5; c += THREADS) { + for (int c = tid; c < TR * 5; c += NT) { const int r = c / 5, q = c % 5; if (r < nrows) cp16(st + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + s * AB + q * 16); } @@ -576,7 +636,11 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_ cp_commit(); } uint32_t raw[5] = {0, 0, 0, 0, 0}; + uint32_t pc[NP]; // stage s + 2's pieces in flight (load_unit_l) + auto issue = [&](int s) { LdIssue l{pc, 0}; uint32_t w[5]; load_unit_l<WT>(l, unit(s), sub(s), w); }; + auto take = [&](int s) { LdTake l{pc, 0}; load_unit_l<WT>(l, unit(s), sub(s), raw); }; if (dec) load_unit<WT>(unit(0), sub(0), raw); + if (dec && TWO_PASS && 2 < NS) issue(2); put(raw, 0); if (dec) load_unit<WT>(unit(1), sub(1), raw); // a warp whose rows are all past the tile's end only takes part in the loads @@ -672,7 +736,14 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_ // 5.2 / 9.5 / 17.5 ms -> 6.0 / 10.2 / 18.3.) if (s + 1 < NS) { put(raw, (s + 1) & 1); - if (dec && s + 2 < NS) load_unit<WT>(unit(s + 2), sub(s + 2), raw); + if (dec && s + 2 < NS) { + if constexpr (TWO_PASS) { + take(s + 2); + if (s + 3 < NS) issue(s + 3); + } else { + load_unit<WT>(unit(s + 2), sub(s + 2), raw); + } + } } } if (!on0) continue; @@ -1191,6 +1262,7 @@ struct DevInfo { bool q2n = false; // sm_80+ with STRATA_PF_FUSED_Q2N=1: the native Q2_0 pack's Q2_0 gate/up is set up as well (opt-in) bool s120 = false; // compute capability 12.0 (sm120_series.hpp): the default for the formats measured there int sms = 0, occ = 1; + int occ_nt = 0; // blocks per multiprocessor of the NT = 256 kernels (0: not set up) }; std::mutex g_mu; DevInfo g_dev[32]; @@ -1208,20 +1280,27 @@ int host_astages() { } return per[dev]; } -template <int T, bool GU, int WW> bool setup_ww(int& occ) { +template <int T, bool GU, int WW, int NT = THREADS> bool setup_ww(int& occ) { cudaFuncAttributes fa{}; - if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW>) != cudaSuccess || fa.ptxVersion < 75) return false; - if (cudaFuncSetAttribute(native_kernel<T, GU, WW>, cudaFuncAttributeMaxDynamicSharedMemorySize, - (int) smem_bytes(T, WW, host_astages())) != cudaSuccess) + if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW, NT>) != cudaSuccess || fa.ptxVersion < 75) return false; + const size_t sm = smem_bytes(T, WW, host_astages(), NT); + if (cudaFuncSetAttribute(native_kernel<T, GU, WW, NT>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm) != cudaSuccess) return false; int o = 0; - if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel<T, GU, WW>, THREADS, smem_bytes(T, WW, host_astages())) != - cudaSuccess || o < 1) + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel<T, GU, WW, NT>, NT, sm) != cudaSuccess || o < 1) return false; occ = std::min(occ, o); return true; } template <int T, bool GU> bool setup_one(int& occ) { return setup_ww<T, GU, 4>(occ) && setup_ww<T, GU, 2>(occ); } +// STRATA_PF_FUSED_NT=256 (sm_80+, opt-in): the 256-thread kernels (native_kernel's NT) +bool nt256_requested() { + static const bool on = [] { const char* v = std::getenv("STRATA_PF_FUSED_NT"); return v != nullptr && std::atoi(v) == 256; }(); + return on; +} +template <int T, bool GU> bool setup_nt(int& occ) { + return setup_ww<T, GU, 2, 256>(occ); +} #endif #if defined(__HIPCC__) @@ -1316,6 +1395,15 @@ const DevInfo& dev_info() { static const bool q2n = [] { const char* v = std::getenv("STRATA_PF_FUSED_Q2N"); return v != nullptr && v[0] == '1'; }(); if (int o2 = occ; q2n && d.ok && setup_one<T_Q2_0, true>(o2)) { d.q2n = true; occ = o2; } d.occ = d.ok ? occ : 1; + if (d.ok && nt256_requested()) { + int o2 = 1 << 20; + const bool ok2 = setup_nt<T_IQ2_XXS, true>(o2) && setup_nt<T_IQ2_XS, true>(o2) && setup_nt<T_IQ2_S, true>(o2) && + setup_nt<T_IQ3_XXS, true>(o2) && setup_nt<T_IQ3_S, true>(o2) && setup_nt<T_IQ4_XS, true>(o2) && + setup_nt<T_Q2_0, false>(o2) && setup_nt<T_IQ4_NL, false>(o2) && + (!d.q2n || setup_nt<T_Q2_0, true>(o2)); // (the Q2_0 gate/up of STRATA_PF_FUSED_Q2N=1 too) + d.occ_nt = ok2 ? o2 : 0; + if (!ok2) std::fprintf(stderr, "prefill fused experts (native): STRATA_PF_FUSED_NT=256 is not available here\n"); + } cudaGetLastError(); #endif return d; @@ -1375,6 +1463,13 @@ void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Ta if (ww == 4) native_kernel<T, GU, 4><<<grid, THREADS, smem_bytes(T, 4, host_astages()), s>>>(b, g, tb, a, src, o, dm); else native_kernel<T, GU, 2><<<grid, THREADS, smem_bytes(T, 2, host_astages()), s>>>(b, g, tb, a, src, o, dm); } +// the NT = 256 kernels (WW 2) +template <int T, bool GU> +void launch(unsigned grid, const WideBatch& b, const NativeGeom& g, const Tables& tb, const void* act, const int32_t* src, + void* out, float* dm, cudaStream_t s) { + native_kernel<T, GU, 2, 256><<<grid, 256, smem_bytes(T, 2, host_astages(), 256), s>>>(b, g, tb, (const uint8_t*) act, + src, (uint8_t*) out, dm); +} // The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has // about one such tile (56 to 112 rows on average), else 64. Measured on the RTX 5070 (tests/cuda/prefill_fused_iq_test, @@ -1530,6 +1625,14 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n return; } #endif + if (d.occ_nt > 0) { // STRATA_PF_FUSED_NT=256: the NT = 256 kernels, which take a WideBatch + WideBatch w; + w.e0 = b.e0; + w.e1 = b.e1; + std::copy(b.blob, b.blob + (b.e1 - b.e0), w.blob); + experts_native(w, g, n_expert, n, scratch, xa, src, ha, dm, stream); + return; + } const int ww = pick_ww(n, n_expert); // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the // ones inside a larger item end at once @@ -1550,4 +1653,35 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n ck(cudaGetLastError(), "experts_native"); } +bool native_wide() { return dev_info().occ_nt > 0; } + +void experts_native(const WideBatch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, + const int32_t* src, void* ha, float* dm, void* stream) { + if (b.e1 <= b.e0 || n <= 0) return; + const DevInfo& d = dev_info(); + if (d.occ_nt <= 0 || !gu_covered(g.gu_type) || !d_covered_on(g.d_type, d)) { + std::fprintf(stderr, "prefill fused experts (native, NT = 256): types %d / %d are not covered here\n", g.gu_type, + g.d_type); + std::exit(1); + } + const cudaStream_t s = (cudaStream_t) stream; + const Tables tb = tables(const_cast<void*>(scratch), n_expert); + // WW 2 (128 x 64 items), as many blocks as are resident; the tiles as in experts_native(const Batch&) + const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); + const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / weight_rows(2)), (int64_t) d.sms * d.occ_nt); + const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / weight_rows(2)), (int64_t) d.sms * d.occ_nt); + switch (g.gu_type) { + case T_IQ2_XXS: launch<T_IQ2_XXS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_XS: launch<T_IQ2_XS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_S: launch<T_IQ2_S, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ3_XXS: launch<T_IQ3_XXS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ3_S: launch<T_IQ3_S, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_Q2_0: launch<T_Q2_0, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + default: launch<T_IQ4_XS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + } + if (g.d_type == T_Q2_0) launch<T_Q2_0, false>(g_d, b, g, tb, ha, src, nullptr, dm, s); + else launch<T_IQ4_NL, false>(g_d, b, g, tb, ha, src, nullptr, dm, s); + ck(cudaGetLastError(), "experts_native (NT = 256)"); +} + } // namespace strata::prefill::fused diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 8b08b511..a96c2a03 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -63,6 +63,7 @@ #include <cstring> #include <future> #include <memory> +#include <optional> #include <mutex> #include <thread> #include <utility> @@ -115,6 +116,9 @@ bool native_supported(int, int) { return false; } void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {} +bool native_wide() { return false; } +void experts_native(const WideBatch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, + float*, void*) {} } // namespace strata::prefill::fused #endif @@ -3962,23 +3966,36 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (fused_nat) fused::quantize_act_native(m.mixed, T, N, m.Xq, m.cs); else fused::quantize_act(m.mixed, T, N, m.Xq, m.cs); fused::group(m.ids, T * K, (int) K, (int) m.g->n_expert, m.GU, m.slot_dev, m.src_dev, m.cs); - // launches over the experts in id order, each at most kMaxBatch experts of which at most a - // third of the ring streamed: the next batch's blobs arrive while one computes. An expert - // the routing did not pick has no tiles; its ring slot is given back with its batch. + // launches over the experts in id order, each at most kMaxBatch experts (STRATA_PF_BATCH: below) + // of which at most a third of the ring streamed: the next batch's blobs arrive while one computes. + // An expert the routing did not pick has no tiles; its ring slot is given back with its batch. const size_t per = (size_t) std::max(1, m.ring / 3); size_t k = seq_start[(size_t) l]; const size_t kend = seq_start[(size_t) l + 1]; + // STRATA_PF_BATCH=N (opt-in): experts per launch (the same rows, so the same bits; a launch is one + // persistent grid, so fewer launches leave fewer grid tails) - at most kMaxBatch, or up to + // kBatchRoom in a WideBatch on the native NT = 256 kernels (STRATA_PF_FUSED_NT=256) + static const int pf_batch = [] { + const char* v = std::getenv("STRATA_PF_BATCH"); + const int n = v ? std::atoi(v) : 0; + return n > 0 ? std::min(n, fused::kBatchRoom) : fused::kMaxBatch; + }(); + const bool wide = fused_nat && pf_batch > fused::kMaxBatch && fused::native_wide(); + const int per_launch = wide ? pf_batch : std::min(pf_batch, fused::kMaxBatch); for (int32_t e = 0; e < m.g->n_expert;) { fused::Batch b; + std::optional<fused::WideBatch> wb; // wide: the launch's pointers (b keeps e0 / e1) + if (wide) wb.emplace(); + const uint8_t** blob = wb ? wb->blob : b.blob; b.e0 = e; const size_t k0 = k; - for (; e < m.g->n_expert && e - b.e0 < fused::kMaxBatch; ++e) { + for (; e < m.g->n_expert && e - b.e0 < per_launch; ++e) { if (k < kend && seq[k].e == e) { if (k - k0 == per) break; - b.blob[e - b.e0] = m.stage_dev[k % (size_t) m.ring]; + blob[e - b.e0] = m.stage_dev[k % (size_t) m.ring]; ++k; } else { // not streamed: resident (the walk streams all others) - b.blob[e - b.e0] = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]); + blob[e - b.e0] = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]); // counted whether routed or not (the routing stays on the GPU): at a streamed // chunk's size (>= 1024 tokens x 10 of 512) nearly every expert is routed ++stats_.experts_resident; @@ -3995,8 +4012,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (fused_nat) { const auto& f = lay.fmt[(size_t) l]; const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off}; - fused::experts_native(b, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, - m.Dm, m.cs); + if (wb) { + wb->e0 = b.e0; + wb->e1 = b.e1; + fused::experts_native(*wb, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, + m.H, m.Dm, m.cs); + } else { + fused::experts_native(b, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, + m.Dm, m.cs); + } } else { fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs); } From dd97421d3fbb97a1905598a82ce3188663d865ca Mon Sep 17 00:00:00 2001 From: sergiywith <sergiywith@gmail.com> Date: Mon, 26 Oct 2026 20:38:06 +0100 Subject: [PATCH 145/177] prefill: mmq::swiglu_quant, swiglu and the down product's q8_1 rows in one kernel (#3752) Problem: the prompt path stores H (swiglu of the gate/up rows) as floats and then quantizes it to the q8_1 rows the down product reads: two kernels and an H round trip per MMQ group. Change: swiglu_quant_kernel, a block per row (128 threads, 4 values each, blockIdx.y the row's 512-value half), computes swiglu_kernel's expression for each value and quantize_mmq_q8_1<D4>'s result for each 32-value block, so hq holds the same bytes and H is never stored. swiglu_quant_ok(type) says where it applies (a q8_1 D4 down type, no FP4 activations). Built only in the CUDA build with STRATA_EXPERIMENTAL_SM60; HIP and the other builds get swiglu_quant_ok() == false and a no-op. Nothing calls it in this commit; the weight-stationary path of the next commit does. prefill.cpp gets the matching stubs for builds without the MMQ sources. Tests: prefill_swiglu_quant_test (new, registered under STRATA_BUILD_TESTS in the SM60 build, skips with 77 without a device) compares the fused kernel with swiglu + quantize byte for byte for Q2_0, IQ4_NL and Q8_0 down types, split and interleaved gate/up rows, a zero row and a row with one huge value. Run on z440 (RTX A4000, sm_86, CUDA 13.0, SM60 build, gpu lock): all 18 cases print "0 of N bytes differ" (1, 37 and 4113 rows) and the test ends "prefill_swiglu_quant_test: ok". sm_60 compile of the tree (CUDA 12.9, P1004): exit 0. This is a partial port of another contributor's prompt-path fusion change; only the kernel is taken, as in PR 3752. --- CMakeLists.txt | 7 ++ include/strata/prefill/moe_mmq.hpp | 5 ++ src/prefill/moe_mmq.cu | 70 ++++++++++++++++++ src/prefill/prefill.cpp | 2 + tests/cuda/prefill_swiglu_quant_test.cpp | 94 ++++++++++++++++++++++++ 5 files changed, 178 insertions(+) create mode 100644 tests/cuda/prefill_swiglu_quant_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 3628d144..0ac52a9a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2088,6 +2088,13 @@ if(STRATA_NATIVE_EXPERTS) 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) + if(STRATA_EXPERIMENTAL_SM60) + # mmq::swiglu_quant: swiglu + the down product's q8_1 rows in one kernel against the two, byte for byte + add_executable(prefill_swiglu_quant_test tests/cuda/prefill_swiglu_quant_test.cpp) + target_link_libraries(prefill_swiglu_quant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_swiglu_quant_test COMMAND prefill_swiglu_quant_test) + set_tests_properties(prefill_swiglu_quant_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endif() 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) diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index fee662fc..6fba093e 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -122,6 +122,11 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre /// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split /// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats). void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream); +/// swiglu (n_ff 640), then quantize() of its rows for a down product of `ggml_type`, in one pass: H never stored, +/// the same bytes in hq. Only where swiglu_quant_ok (a q8_1 D4 down type; gu 16-byte aligned): CUDA, the +/// STRATA_EXPERIMENTAL_SM60 build. +bool swiglu_quant_ok(int ggml_type); +void swiglu_quant(const float* gu, void* hq, int64_t rows, bool interleaved, void* stream); /// swiglu of an NVFP4 group's gate/up rows (split halves) with scale_gu_rows' scales applied as they are read. void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n, const float* tails, int64_t row0, void* stream); diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index e7ff5d45..e832cffe 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -144,6 +144,54 @@ __global__ void swiglu_kernel(const float* __restrict__ gu, float* __restrict__ h[i] = g / (1.0f + __expf(-g)) * u; } +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// swiglu_kernel (n_ff 640), then quantize_mmq_q8_1<D4>'s rows of its output, in one pass: a block per row (128 +// threads, 4 values each, blockIdx.y the row's 512-value half), H never stored. Each value is swiglu_kernel's +// expression and each 32-value block quantize_mmq_q8_1's (the same unit and flags: the same bits). +template <bool IL> +__global__ void __launch_bounds__(128) swiglu_quant_kernel(const float* __restrict__ gu, block_q8_1_mmq* __restrict__ y, + int64_t rows) { + constexpr int64_t n_ff = 640, ne0 = 1024; // the padded row: pad512(640) + const int64_t i0 = ((int64_t) blockDim.x * blockIdx.y + threadIdx.x) * 4; + if (i0 >= ne0) return; + const int64_t r = blockIdx.x; + float4 xi = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + if (i0 < n_ff) { + const float* row = gu + r * 2 * n_ff; + float4 g4, u4; + if constexpr (IL) { // gate 2k, up 2k + 1 + const float4 a = *reinterpret_cast<const float4*>(row + 2 * i0), b = *reinterpret_cast<const float4*>(row + 2 * i0 + 4); + g4 = make_float4(a.x, a.z, b.x, b.z); + u4 = make_float4(a.y, a.w, b.y, b.w); + } else { + g4 = *reinterpret_cast<const float4*>(row + i0); + u4 = *reinterpret_cast<const float4*>(row + n_ff + i0); + } + xi.x = g4.x / (1.0f + __expf(-g4.x)) * u4.x; + xi.y = g4.y / (1.0f + __expf(-g4.y)) * u4.y; + xi.z = g4.z / (1.0f + __expf(-g4.z)) * u4.z; + xi.w = g4.w / (1.0f + __expf(-g4.w)) * u4.w; + } + float amax = fabsf(xi.x); + amax = fmaxf(amax, fabsf(xi.y)); + amax = fmaxf(amax, fabsf(xi.z)); + amax = fmaxf(amax, fabsf(xi.w)); +#pragma unroll + for (int offset = 32 / 8; offset > 0; offset >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE)); + const float d_inv = 127.0f / amax; + char4 c; + c.x = roundf(xi.x * d_inv); + c.y = roundf(xi.y * d_inv); + c.z = roundf(xi.z * d_inv); + c.w = roundf(xi.w * d_inv); + const float d = 1.0f / d_inv; + const int64_t k_block = i0 / QK8_1_MMQ, iqs = i0 % QK8_1_MMQ; + block_q8_1_mmq* yb = y + k_block * rows + r; + reinterpret_cast<char4*>(yb->qs)[iqs / 4] = c; + if (iqs % 32 == 0) yb->d4[iqs / 32] = d; +} +#endif + // swiglu_kernel on the MMQ gate/up output with each expert's gate and up scales applied as it is read: the products // scale_gu_rows stored, without the pass that stored them __global__ void swiglu_scaled_kernel(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff, @@ -665,6 +713,28 @@ void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interlea ck(cudaGetLastError(), "swiglu"); } +bool swiglu_quant_ok(int t) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + // the q8_1 D4 rows quantize() writes for a down product's H (K 640) + return supported(t) && !fp4_activations(t) && mmq_get_q8_1_ds_layout((ggml_type) t) == MMQ_Q8_1_DS_LAYOUT_D4; +#else + (void) t; + return false; // HIP: not checked against the HIP build's quantizer; outside the SM60 build: not built +#endif +} + +void swiglu_quant(const float* gu, void* hq, int64_t rows, bool interleaved, void* stream) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + if (rows <= 0) return; + const dim3 grid((unsigned) rows, 2); + if (interleaved) swiglu_quant_kernel<true><<<grid, 128, 0, (cudaStream_t) stream>>>(gu, (block_q8_1_mmq*) hq, rows); + else swiglu_quant_kernel<false><<<grid, 128, 0, (cudaStream_t) stream>>>(gu, (block_q8_1_mmq*) hq, rows); + ck(cudaGetLastError(), "swiglu_quant"); +#else + (void) gu; (void) hq; (void) rows; (void) interleaved; (void) stream; +#endif +} + void iota(int32_t* dst, int64_t n, void* stream) { if (n <= 0) return; iota_kernel<<<blocks(n), 256, 0, (cudaStream_t) stream>>>(dst, n); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index a9d121f9..0f3ee3a0 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -87,6 +87,8 @@ bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, voi void*, size_t) { return false; } void gather_strata_q2(const uint8_t*, void*, void*, void*) {} void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} +bool swiglu_quant_ok(int) { return false; } +void swiglu_quant(const float*, void*, int64_t, bool, void*) {} void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {} void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {} void iota(int32_t*, int64_t, void*) {} diff --git a/tests/cuda/prefill_swiglu_quant_test.cpp b/tests/cuda/prefill_swiglu_quant_test.cpp new file mode 100644 index 00000000..0d7b9d68 --- /dev/null +++ b/tests/cuda/prefill_swiglu_quant_test.cpp @@ -0,0 +1,94 @@ +// prefill_swiglu_quant_test - the prompt path's fused MMQ expert step against the kernels it replaces, byte for byte: +// mmq::swiglu_quant against swiglu + quantize (the down product's q8_1 rows of H), for down types the packs have +// (Q2_0, IQ4_NL, Q8_0), with the gate/up rows split (GGUF) and interleaved (the Strata pack), a zero row and a row +// with one huge value. Exit 77 without a CUDA device. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include <cuda_runtime.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <random> +#include <stdexcept> +#include <string> +#include <vector> + +namespace { +namespace mmq = strata::prefill::mmq; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template <class T> T* as() const { return (T*) p; } +}; + +int swiglu_quant_case(ggml_type t, int64_t rows, bool interleaved, uint32_t seed) { + constexpr int64_t NFF = 640; + std::mt19937 rng(seed); + std::normal_distribution<float> nd(0.f, 1.f); + std::uniform_real_distribution<float> mag(0.05f, 40.f); + std::vector<float> gu((size_t) rows * 2 * NFF); + for (int64_t r = 0; r < rows; ++r) { + const float m = mag(rng); + for (int64_t k = 0; k < 2 * NFF; ++k) gu[(size_t) (r * 2 * NFF + k)] = nd(rng) * m; + } + if (rows > 3) { // a zero row, a row with one huge value + std::memset(gu.data() + 2 * NFF, 0, 2 * NFF * sizeof(float)); + gu[(size_t) (3 * 2 * NFF + 5)] = 3e4f; + } + const size_t qb = mmq::q8_bytes(rows, NFF); + Dev dgu(gu.size() * 4), dh((size_t) rows * NFF * 4 + 16), dq0(qb), dq1(qb); + ck(cudaMemcpy(dgu.p, gu.data(), gu.size() * 4, cudaMemcpyHostToDevice), "upload"); + ck(cudaMemset(dq0.p, 0x5a, qb), "memset"); + ck(cudaMemset(dq1.p, 0x5a, qb), "memset"); + // the two kernels it replaces, as prefill.cpp launches them + mmq::swiglu(dgu.as<float>(), dh.as<float>(), rows, NFF, interleaved, nullptr); + mmq::quantize(dh.as<float>(), nullptr, dq0.p, (int) t, NFF, NFF, rows, nullptr); + mmq::swiglu_quant(dgu.as<float>(), dq1.p, rows, interleaved, nullptr); + ck(cudaDeviceSynchronize(), "run"); + const size_t used = (size_t) rows * (1024 / 128) * 144; // the rows' 8 blocks of 128 values (144 bytes each) + std::vector<uint8_t> a(used), b(used); + ck(cudaMemcpy(a.data(), dq0.p, used, cudaMemcpyDeviceToHost), "download"); + ck(cudaMemcpy(b.data(), dq1.p, used, cudaMemcpyDeviceToHost), "download"); + size_t bad = 0; + for (size_t i = 0; i < used; ++i) bad += a[i] != b[i]; + std::printf(" swiglu_quant %-6s %5lld rows%s: %zu of %zu bytes differ\n", ggml_type_name(t), (long long) rows, + interleaved ? " interleaved" : "", bad, used); + return bad == 0 ? 0 : 1; +} + +} // namespace + +int main() { + int ndev = 0; + if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { + std::printf("prefill_swiglu_quant_test: no CUDA device (skipped)\n"); + return 77; + } + int fails = 0; + try { + for (ggml_type t : {GGML_TYPE_Q2_0, GGML_TYPE_IQ4_NL, GGML_TYPE_Q8_0}) { + if (!mmq::swiglu_quant_ok((int) t)) { std::printf(" %s: not on the fused path here\n", ggml_type_name(t)); continue; } + for (bool il : {false, true}) { + fails += swiglu_quant_case(t, 1, il, 1); + fails += swiglu_quant_case(t, 37, il, 2); + fails += swiglu_quant_case(t, 4113, il, 3); + } + } + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill_swiglu_quant_test: %s\n", e.what()); + return 1; + } + std::printf("prefill_swiglu_quant_test: %s\n", fails ? "FAILED" : "ok"); + return fails ? 1 : 0; +} From 17b08c96339f1d9eaf499846296e2ab9eb7c3c28 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:40:20 +0100 Subject: [PATCH 146/177] Prefill PLE: opt-in STRATA_PLE_COMPACT=1 uploads the raw IQ4_NL rows and dequantizes them on the device (#3779, #3712) Problem: the prompt path reads 16 PLE rows a token, dequantizes them on the host and uploads 10,240 floats a token. On a slow host link (PCIe Gen2 x4) that upload is on the critical path of the first layer. Change, opt-in with STRATA_PLE_COMPACT=1: for an IQ4_NL table held in memory (--ple-io ram / mmap) the prompt path copies the raw 90-byte rows (1,440 bytes a token) into the same pinned buffer, uploads them and runs ple_iq4nl_dequant on the device (d times the code's value, one multiply, the split-half nibble order of iq4nl_dequant_row). Any other table (Direct I/O, pageable fallback, another format) and a failed allocation take the host path as before. With the variable unset nothing changes: the new code is behind one cached flag, and the extra members of the Prefill state stay null. Two things differ from the PR as submitted: - PleTable::gather_raw_iq4nl writes a row past the table as scale 0 and code 8 in every nibble. The PR wrote zero bytes, which the device decodes to -0.0f (0 times code 0's value -127), while the host path writes +0.0f for such a row. - New test ple_iq4nl_dequant_test (ctest, synthetic, no model, 77 without a device): the device decode against iq4nl_dequant_row, bit for bit, over every fp16 scale pattern with random codes, random rows, an odd row count and the out-of-table row. Reporter's numbers (linxuhao, CMP 170HX, PCIe Gen2 x4): prompts +1.0..+1.7 % (4K, 16K) with the switch on. Theirs, not measured here. On a Gen4 x16 card the gain will be smaller. Metal gets a stub (the Metal prompt runs through its window and never calls it). Original change by linxuhao (PR #3779, commit da818261). --- CMakeLists.txt | 6 ++ include/strata/kernels/ngram.hpp | 4 + include/strata/kernels/ple.hpp | 4 + metal/src/engine/stubs_0145.cpp | 2 + src/kernels/cuda/ple.cu | 23 ++++++ src/kernels/ngram.cpp | 20 +++++ src/kernels/ple_iq4nl_dequant_test.cpp | 101 +++++++++++++++++++++++++ src/prefill/prefill.cpp | 31 +++++++- 8 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 src/kernels/ple_iq4nl_dequant_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 31d3664b..69a3fa7c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1428,6 +1428,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME ple_parity COMMAND ple_parity --selftest --in "${STRATA_PLE_FIXTURE_DIR}/ple_in.bin" --out "${STRATA_PLE_FIXTURE_DIR}/ple_out.bin" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + # STRATA_PLE_COMPACT: the raw IQ4_NL rows dequantized on the device against the host decode, bit for bit (synthetic, no model) + add_executable(ple_iq4nl_dequant_test src/kernels/ple_iq4nl_dequant_test.cpp) + target_include_directories(ple_iq4nl_dequant_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(ple_iq4nl_dequant_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME ple_iq4nl_dequant_test COMMAND ple_iq4nl_dequant_test) + set_tests_properties(ple_iq4nl_dequant_test PROPERTIES SKIP_RETURN_CODE 77) # Plan v0.3 P7: INT8 KV storage vs a host reference and vs the FP16 path (GPU, synthetic, no model). add_executable(kv_q8_parity src/kernels/kv_q8_parity.cpp) diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index d25a1eee..9954a0f3 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -187,6 +187,10 @@ public: /// as ONE reader request - page dedupe and sort across the whole batch, the reader's full queue depth. Not /// while a single-token `issue` is pending. The mapped mode gathers row by row. bool gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err); + /// STRATA_PLE_COMPACT: the same rows as their raw IQ4_NL bytes (n_tokens x 16 rows of PLE_ROW_BYTES; a row past the + /// table: scale 0 and code 8 everywhere, which decode to the +0.0f gather_batch writes) for ple_iq4nl_dequant on the device. False (nothing + /// written) unless the table is in memory (--ple-io ram / mmap) and IQ4_NL. + bool gather_raw_iq4nl(const uint32_t* rows, size_t n_tokens, uint8_t* out) const; /// Fault injection (Direct mode): every row read completes no earlier than `us` after issue. void set_injected_delay_us(double us); diff --git a/include/strata/kernels/ple.hpp b/include/strata/kernels/ple.hpp index 98bfc388..a558e1e2 100644 --- a/include/strata/kernels/ple.hpp +++ b/include/strata/kernels/ple.hpp @@ -125,4 +125,8 @@ void ple_history_advance(float* hist, const float* normalized, void* stream); /// Whether the CUDA path is available. The host hash and the table read work without it; the block does not. bool ple_block_available(); +/// STRATA_PLE_COMPACT: `rows` raw IQ4_NL PLE rows (PleTable::gather_raw_iq4nl, PLE_ROW_BYTES each) to 160 floats each, +/// the floats iq4nl_dequant_row writes (d times the code's value, one multiply), on `stream`. +void ple_iq4nl_dequant(const uint8_t* raw, int64_t rows, float* out, void* stream); + } // namespace strata::kernels diff --git a/metal/src/engine/stubs_0145.cpp b/metal/src/engine/stubs_0145.cpp index 0c1976f6..791d1df4 100644 --- a/metal/src/engine/stubs_0145.cpp +++ b/metal/src/engine/stubs_0145.cpp @@ -149,3 +149,5 @@ namespace strata::kernels { bool native_q8_0_sm60_pack(void const* p0, int p1, i namespace strata::kernels { void native_q8_0_sm60_release(void const* p0) { } } // only reached with pf_wmma (off on Metal) namespace strata::prefill { void swiglu_split_f16(float const* p0, unsigned short* p1, long long p2, int p3, bool p4, void* p5) { } } +// STRATA_PLE_COMPACT (opt-in, CUDA / HIP prompt path): prefill.cpp references it; the Metal prompt runs through its window and never reaches it. +namespace strata::kernels { void ple_iq4nl_dequant(const uint8_t* p0, int64_t p1, float* p2, void* p3) { strata::metal_engine::missing("strata::kernels::ple_iq4nl_dequant"); } } diff --git a/src/kernels/cuda/ple.cu b/src/kernels/cuda/ple.cu index f945ef3b..89c54502 100644 --- a/src/kernels/cuda/ple.cu +++ b/src/kernels/cuda/ple.cu @@ -23,6 +23,7 @@ #include "strata/kernels/native_ple_postops.hpp" #include <cuda_runtime.h> +#include <cuda_fp16.h> #include <cmath> #include <cstdio> @@ -387,4 +388,26 @@ void ple_block_projected(const float* projected_key, const float* projected_valu native_ple_postops(projected_key, hidden, projected_value, hist_rows, w, buffers, stream); } +namespace { +__constant__ int8_t kPleIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; +// one thread a value: row r, block b (18 bytes: fp16 d, 16 bytes of codes), element j of 32 (j < 16: low nibble of +// qs[j], else the high nibble of qs[j - 16] - the split halves of iq4nl_dequant_row) +__global__ void ple_iq4nl_dequant_kernel(const uint8_t* __restrict__ raw, int64_t n, float* __restrict__ out) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const int64_t r = i / PLE_HEAD_DIM; + const int e = (int) (i - r * PLE_HEAD_DIM), b = e >> 5, j = e & 31; + const uint8_t* blk = raw + r * PLE_ROW_BYTES + b * 18; + const float d = __half2float(__ushort_as_half((unsigned short) (blk[0] | (blk[1] << 8)))); + const uint8_t q = blk[2 + (j & 15)]; + out[i] = d * (float) kPleIq4Nl[j < 16 ? (q & 15) : (q >> 4)]; +} +} // namespace + +void ple_iq4nl_dequant(const uint8_t* raw, int64_t rows, float* out, void* stream) { + const int64_t n = rows * PLE_HEAD_DIM; + if (n <= 0) return; + ple_iq4nl_dequant_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>(raw, n, out); +} + } // namespace strata::kernels diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index c32dc786..7b8d844e 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -618,6 +618,26 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s return true; } +bool PleTable::gather_raw_iq4nl(const uint32_t* rows, size_t n_tokens, uint8_t* out) const { + std::lock_guard<std::recursive_mutex> lk(impl_->mu); + if (impl_->data == nullptr || impl_->fmt->id != PleFormat::IQ4_NL || impl_->rb != PLE_ROW_BYTES) return false; + const size_t n = n_tokens * (size_t) PLE_N_HEADS; + for (size_t i = 0; i < n; ++i) { + uint8_t* o = out + i * PLE_ROW_BYTES; + if (rows[i] >= impl_->n_rows) { + // a row past the table reads as +0.0f (read_row): scale 0 and code 8 (value +1) in every nibble decode to +0.0f + // on the device, where all-zero bytes would decode to -0.0f (scale 0 times code 0's value -127) + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) { + uint8_t* blk = o + (size_t) b * 18; + std::memset(blk, 0, 2); + std::memset(blk + 2, 0x88, 16); + } + } else std::memcpy(o, impl_->data + (size_t) rows[i] * PLE_ROW_BYTES, PLE_ROW_BYTES); + } + impl_->bytes_read += (uint64_t) n * PLE_ROW_BYTES; + return true; +} + void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } std::string PleTable::io_report() const { diff --git a/src/kernels/ple_iq4nl_dequant_test.cpp b/src/kernels/ple_iq4nl_dequant_test.cpp new file mode 100644 index 00000000..e5312cf9 --- /dev/null +++ b/src/kernels/ple_iq4nl_dequant_test.cpp @@ -0,0 +1,101 @@ +// src/kernels/ple_iq4nl_dequant_test.cpp - STRATA_PLE_COMPACT: ple_iq4nl_dequant (raw IQ4_NL PLE rows to floats on the +// device) against iq4nl_dequant_row (the host decode the prompt path used before), bit for bit. Synthetic bytes, no model. +// +// - every one of the 65,536 fp16 scale patterns (infinities and NaNs included: those are compared as "both NaN") in +// every block position, with random codes; +// - rows of random bytes; +// - the row the table gives for an index past its end (scale 0, code 8 in every nibble: +0.0f, what PleTable::read_row +// writes for such a row); +// - an odd row count (not a multiple of the 256-thread block). +// Exit 77 without a CUDA device. +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/ple.hpp" + +#include <cuda_runtime.h> + +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <random> +#include <vector> + +namespace { +using namespace strata::kernels; + +int check(const std::vector<uint8_t>& raw, int64_t rows, const char* what) { + float* dout = nullptr; + uint8_t* draw = nullptr; + if (cudaMalloc((void**) &dout, (size_t) rows * PLE_HEAD_DIM * 4) != cudaSuccess || + cudaMalloc((void**) &draw, raw.size()) != cudaSuccess || + cudaMemcpy(draw, raw.data(), raw.size(), cudaMemcpyHostToDevice) != cudaSuccess) { + std::printf("CUDA setup failed for %s\n", what); + return 1; + } + cudaMemset(dout, 0xff, (size_t) rows * PLE_HEAD_DIM * 4); + ple_iq4nl_dequant(draw, rows, dout, nullptr); + if (cudaDeviceSynchronize() != cudaSuccess) { std::printf("CUDA error for %s: %s\n", what, cudaGetErrorString(cudaGetLastError())); return 1; } + std::vector<float> got((size_t) rows * PLE_HEAD_DIM), want(got.size()); + cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost); + cudaFree(dout); + cudaFree(draw); + for (int64_t r = 0; r < rows; ++r) iq4nl_dequant_row(raw.data() + (size_t) r * PLE_ROW_BYTES, want.data() + (size_t) r * PLE_HEAD_DIM); + long long diff = 0, first = -1; + for (size_t i = 0; i < got.size(); ++i) { + uint32_t a, b; + std::memcpy(&a, &got[i], 4); + std::memcpy(&b, &want[i], 4); + if (std::isnan(got[i]) && std::isnan(want[i])) continue; // a NaN scale: any payload is a NaN + if (a != b) { if (first < 0) first = (long long) i; ++diff; } + } + std::printf(" %-52s %lld rows: %s\n", what, (long long) rows, diff ? "*** DIFFERS ***" : "bitwise equal"); + if (diff) std::printf(" %lld values differ, first at %lld\n", diff, first); + return diff ? 1 : 0; +} +} // namespace + +int main() { + int n_dev = 0; + if (cudaGetDeviceCount(&n_dev) != cudaSuccess || n_dev < 1) { std::printf("no CUDA device (skipped)\n"); return 77; } + int bad = 0; + std::mt19937 rng(20261026u); + { // all fp16 patterns: 65,536 scales over 5 blocks a row = 13,108 rows (the last row pads with 0) + const int64_t rows = (65536 + 4) / 5; + std::vector<uint8_t> raw((size_t) rows * PLE_ROW_BYTES); + for (auto& b : raw) b = (uint8_t) (rng() & 0xff); + uint32_t d = 0; + for (int64_t r = 0; r < rows; ++r) + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b, ++d) { + const uint16_t h = (uint16_t) (d & 0xffff); + std::memcpy(&raw[(size_t) r * PLE_ROW_BYTES + (size_t) b * 18], &h, 2); + } + bad += check(raw, rows, "every fp16 scale pattern, random codes"); + } + { // random rows + const int64_t rows = 4096 + 37; + std::vector<uint8_t> raw((size_t) rows * PLE_ROW_BYTES); + for (auto& b : raw) b = (uint8_t) (rng() & 0xff); + bad += check(raw, rows, "random bytes (odd row count)"); + } + { // the out-of-table row of PleTable::gather_raw_iq4nl + const int64_t rows = 16; + std::vector<uint8_t> raw((size_t) rows * PLE_ROW_BYTES); + for (int64_t r = 0; r < rows; ++r) + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) { + uint8_t* blk = &raw[(size_t) r * PLE_ROW_BYTES + (size_t) b * 18]; + std::memset(blk, 0, 2); + std::memset(blk + 2, 0x88, 16); + } + bad += check(raw, rows, "out-of-table row (scale 0, code 8)"); + // and it is +0.0f, not -0.0f, on both sides + std::vector<float> want(PLE_HEAD_DIM); + iq4nl_dequant_row(raw.data(), want.data()); + for (float v : want) { + uint32_t a; + std::memcpy(&a, &v, 4); + if (a != 0) { std::printf(" *** the out-of-table row does not decode to +0.0f\n"); ++bad; break; } + } + } + std::printf("ple_iq4nl_dequant_test: %s\n", bad ? "FAILED" : "OK"); + return bad ? 1 : 0; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index a96c2a03..a101503f 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -132,6 +132,14 @@ bool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0, const float* con } // namespace strata::metal_engine #endif +namespace { +// STRATA_PLE_COMPACT=1 (opt-in): the prompt chunk's PLE rows go up raw and are dequantized on the device (IQ4_NL tables +// held in memory); the same floats as the host dequant, 7x fewer bytes over PCIe +bool ple_compact_on() { + static const bool on = [] { const char* v = std::getenv("STRATA_PLE_COMPACT"); return v != nullptr && v[0] == '1'; }(); + return on; +} +} // namespace namespace strata::prefill { namespace { @@ -987,6 +995,8 @@ struct Prefill::Impl { float* ple_emb_host[2] = {}; // pinned, double-buffered: the next chunk's rows are read while this cudaEvent_t ple_copied[2] = {}; // one runs; the event marks that buffer's upload done std::vector<uint32_t> ple_rows[2]; + bool ple_compact[2] = {false, false}; // STRATA_PLE_COMPACT: the pinned buffer holds raw IQ4_NL rows + uint8_t* ple_raw_dev = nullptr; // their device copy (cudaMalloc'd, the chunk's 16 rows a token) float* ple_norm = nullptr; uint8_t* region = nullptr; // the attention/MoE scratch region (idle while the PLE block runs) uint64_t region_bytes = 0; @@ -1097,6 +1107,7 @@ void Prefill::release() { if (e) cudaEventDestroy(e); if (impl_->ple_copied[b]) cudaEventDestroy(impl_->ple_copied[b]); if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]); + if (b == 0 && impl_->ple_raw_dev) { (void) cudaFree(impl_->ple_raw_dev); impl_->ple_raw_dev = nullptr; } } if (impl_->copy) cudaStreamDestroy(impl_->copy); if (impl_->kv_copy) cudaStreamDestroy(impl_->kv_copy); @@ -1525,6 +1536,11 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co if (!m.ple_copied[b] && cudaEventCreateWithFlags(&m.ple_copied[b], cudaEventDisableTiming) != cudaSuccess) ok = false; m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS); + if (ple_compact_on() && m.ple_raw_dev == nullptr && + cudaMalloc((void**) &m.ple_raw_dev, (size_t) T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES) != cudaSuccess) { + m.ple_raw_dev = nullptr; + (void) cudaGetLastError(); + } } if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages; @@ -2839,6 +2855,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri pv[0] = pv[1]; pv[1] = tok; } + // STRATA_PLE_COMPACT=1: the raw rows (1,440 bytes a token instead of 10,240 floats' bytes) into the same pinned + // buffer; ple_land uploads them and dequantizes on the device + if (ple_compact_on() && m.ple_pageable[buf].empty() && m.ple_raw_dev != nullptr && + ss.ple.table->gather_raw_iq4nl(m.ple_rows[buf].data(), (size_t) T, (uint8_t*) m.ple_emb_host[buf])) { + m.ple_compact[buf] = true; + return true; + } + m.ple_compact[buf] = false; return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); }; std::string ple_next_err; @@ -3002,7 +3026,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri 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() + const size_t raw_bytes = (size_t) T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES; + if ((m.ple_compact[ple_buf] + ? cudaMemcpyAsync(m.ple_raw_dev, m.ple_emb_host[ple_buf], raw_bytes, cudaMemcpyHostToDevice, m.cs) + : 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 || @@ -3010,6 +3037,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); return false; } + if (m.ple_compact[ple_buf]) + strata::kernels::ple_iq4nl_dequant(m.ple_raw_dev, T * strata::kernels::PLE_N_HEADS, m.ple_emb, m.cs); 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) { From d6428bf2919fd011c42bd0390113d3990dfcf205 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:40:42 +0100 Subject: [PATCH 147/177] Prefill: opt-in STRATA_PLE_COPY_STREAM=1 uploads the compact PLE rows on their own stream (#3779, #3712) Problem: with STRATA_PLE_COMPACT the raw-row upload sat on the compute stream before layer 1, which idles for the DMA (4.7 MB per 3K-token chunk, 2.9 ms on a Gen2 x4 link). Change, opt-in, only with STRATA_PLE_COMPACT=1: the raw rows go up on a non-blocking stream of their own once the previous chunk's dequant has read the device buffer (ple_raw_free event); the compute stream waits for the upload (ple_copied) only at the dequant. Same bytes, same kernel. The stream is drained when a run ends so no upload is left in flight from a buffer the next run refills. Differs from the PR as submitted: if the stream or the event cannot be created, the PR failed Prefill::init. Here it prints one line and the rows go up on the compute stream as with STRATA_PLE_COMPACT alone. With the variable unset nothing changes (the stream and the events stay null). Reporter's numbers (linxuhao, CMP 170HX): PLE time of a 51.8K-token prompt 95-103 to 47 ms, measured together with STRATA_EMBED_VRAM and STRATA_DEQUANT_SIDE (+2.2..+2.6 % prompts for the four PLE/embedding/dequant switches together). Theirs, not measured here. Original change by linxuhao (PR #3779, commit 0ba47e61). --- src/prefill/prefill.cpp | 43 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index a101503f..21f65e6a 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -139,6 +139,12 @@ bool ple_compact_on() { static const bool on = [] { const char* v = std::getenv("STRATA_PLE_COMPACT"); return v != nullptr && v[0] == '1'; }(); return on; } +// STRATA_PLE_COPY_STREAM=1 (opt-in, with PLE_COMPACT): the raw rows go up on a stream of their own instead of the compute +// stream, which otherwise idles for the DMA (4.7 MB a 3K chunk = 2.9 ms on a Gen2 x4 link); the same bytes and kernels +bool ple_copy_stream_on() { + static const bool on = [] { const char* v = std::getenv("STRATA_PLE_COPY_STREAM"); return v != nullptr && v[0] == '1'; }(); + return on; +} } // namespace namespace strata::prefill { namespace { @@ -997,6 +1003,8 @@ struct Prefill::Impl { std::vector<uint32_t> ple_rows[2]; bool ple_compact[2] = {false, false}; // STRATA_PLE_COMPACT: the pinned buffer holds raw IQ4_NL rows uint8_t* ple_raw_dev = nullptr; // their device copy (cudaMalloc'd, the chunk's 16 rows a token) + cudaStream_t ple_copy = nullptr; // STRATA_PLE_COPY_STREAM: the raw rows' upload stream (null: on cs) + cudaEvent_t ple_raw_free = nullptr; // cs has dequantized ple_raw_dev: the next chunk's upload may overwrite it float* ple_norm = nullptr; uint8_t* region = nullptr; // the attention/MoE scratch region (idle while the PLE block runs) uint64_t region_bytes = 0; @@ -1096,6 +1104,7 @@ void Prefill::release() { if (impl_->cs) cudaStreamSynchronize(impl_->cs); if (impl_->copy) cudaStreamSynchronize(impl_->copy); if (impl_->kv_copy) cudaStreamSynchronize(impl_->kv_copy); + if (impl_->ple_copy) (void) cudaStreamSynchronize(impl_->ple_copy); for (int i = 0; i < RING_MAX; ++i) { if (impl_->copied[i]) cudaEventDestroy(impl_->copied[i]); if (impl_->used[i]) cudaEventDestroy(impl_->used[i]); @@ -1111,6 +1120,8 @@ void Prefill::release() { } if (impl_->copy) cudaStreamDestroy(impl_->copy); if (impl_->kv_copy) cudaStreamDestroy(impl_->kv_copy); + if (impl_->ple_copy) (void) cudaStreamDestroy(impl_->ple_copy); + if (impl_->ple_raw_free) (void) cudaEventDestroy(impl_->ple_raw_free); if (impl_->kv_released) cudaEventDestroy(impl_->kv_released); if (impl_->kv_ready) cudaEventDestroy(impl_->kv_ready); if (impl_->grp_host) cudaFreeHost(impl_->grp_host); @@ -1542,6 +1553,16 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co (void) cudaGetLastError(); } } + // STRATA_PLE_COPY_STREAM: a stream of its own, not the expert copy stream - that one may hold a ring of blobs and + // waits on their slots' release, so a wait on it could idle the compute stream for longer than the DMA itself + if (ple_copy_stream_on() && m.ple_raw_dev != nullptr && + ((!m.ple_copy && cudaStreamCreateWithFlags(&m.ple_copy, cudaStreamNonBlocking) != cudaSuccess) || + (!m.ple_raw_free && cudaEventCreateWithFlags(&m.ple_raw_free, cudaEventDisableTiming) != cudaSuccess))) { + // an optional optimization: the raw rows go up on the compute stream as with STRATA_PLE_COMPACT alone + if (m.ple_copy) { (void) cudaStreamDestroy(m.ple_copy); m.ple_copy = nullptr; } + (void) cudaGetLastError(); + std::fprintf(stderr, "prefill: STRATA_PLE_COPY_STREAM=1: the upload stream could not be created, the PLE rows go up on the compute stream\n"); + } if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages; std::vector<int32_t> ident((size_t) pages); @@ -2785,6 +2806,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri cudaStream_t stream; ~KvDrain() { if (stream) cudaStreamSynchronize(stream); } } kv_drain{kv_prefetch ? m.kv_copy : nullptr}; + KvDrain ple_drain{m.ple_copy}; // STRATA_PLE_COPY_STREAM: no upload left in flight from a buffer the next run refills int64_t kv_prefetches = 0; const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); @@ -3027,18 +3049,31 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before const size_t raw_bytes = (size_t) T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES; - if ((m.ple_compact[ple_buf] - ? cudaMemcpyAsync(m.ple_raw_dev, m.ple_emb_host[ple_buf], raw_bytes, cudaMemcpyHostToDevice, m.cs) + // STRATA_PLE_COPY_STREAM: the raw rows go up on their own stream once the previous chunk's dequant has read + // the buffer (ple_raw_free), and the compute stream waits for them (ple_copied) only at the dequant - the + // DMA overlaps layer 0 instead of idling the compute queue. ple_copied still marks that buffer's upload + // done, on whichever stream ran it, for the host-side reuse guard below. + const bool ple_side = m.ple_compact[ple_buf] && m.ple_copy != nullptr; + const cudaStream_t ple_up = ple_side ? m.ple_copy : m.cs; + if ((ple_side && cudaStreamWaitEvent(m.ple_copy, m.ple_raw_free, 0) != cudaSuccess) || + (m.ple_compact[ple_buf] + ? cudaMemcpyAsync(m.ple_raw_dev, m.ple_emb_host[ple_buf], raw_bytes, cudaMemcpyHostToDevice, ple_up) : 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) { + cudaEventRecord(m.ple_copied[ple_buf], ple_up) != cudaSuccess || + (ple_side && cudaStreamWaitEvent(m.cs, m.ple_copied[ple_buf], 0) != cudaSuccess)) { err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); return false; } - if (m.ple_compact[ple_buf]) + if (m.ple_compact[ple_buf]) { strata::kernels::ple_iq4nl_dequant(m.ple_raw_dev, T * strata::kernels::PLE_N_HEADS, m.ple_emb, m.cs); + if (ple_side && cudaEventRecord(m.ple_raw_free, 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) { From 884e37dfdfd9511e939a935c02180c14e0c26505 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:41:23 +0100 Subject: [PATCH 148/177] Native head: opt-in STRATA_EMBED_VRAM=1 keeps the token-embedding table in VRAM (#3779, #3712) Problem: the token-embedding table of a native pack lives in mapped pinned host memory, so every prompt's scattered row gather crosses the PCIe link. On a Gen2 x4 link that costs more than the table's size in VRAM is worth. Change, opt-in: with STRATA_EMBED_VRAM=1 the table is copied into the current device's VRAM when the table plus 512 MiB stay free (322 MiB for an IQ4_XS table). The gather kernels read the same bytes through dev_ as before. If the VRAM is not there or the copy fails, the table stays in mapped host memory as before and one line says so. The start-up line now says where the table is ("in VRAM" also for the two existing VRAM fallbacks, which it called mapped host memory). With the variable unset nothing changes (one getenv at load). Not covered: a layer split across several devices places the table on the device that is current when it loads, as the existing VRAM fallback does. No unit test (it moves the same bytes to a different memory; the gather kernel is unchanged). Reporter's numbers (linxuhao, CMP 170HX): measured together with STRATA_PLE_COPY_STREAM and STRATA_DEQUANT_SIDE on a 51.8K-token prompt, the embedding step went from 191-201 to 70 ms. Theirs, not measured here. Original change by linxuhao (PR #3779, commit 952dd784). --- include/strata/core/native_head.hpp | 5 ++++- src/core/native_head.cpp | 29 +++++++++++++++++++++++++++++ src/program/generate.cpp | 6 ++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/include/strata/core/native_head.hpp b/include/strata/core/native_head.hpp index 501f6ec2..29fe9d37 100644 --- a/include/strata/core/native_head.hpp +++ b/include/strata/core/native_head.hpp @@ -43,7 +43,8 @@ private: /// Plan v0.3 P6: `token_embd.weight` in its GGUF form (the IQ model files), in mapped pinned host memory: a row /// is read over PCIe per token, so the table costs no VRAM. `embed_row`, the verify window and the MTP drafter -/// use it instead of the canonical table when it is set (`set_native_embed`). +/// use it instead of the canonical table when it is set (`set_native_embed`). `STRATA_EMBED_VRAM=1` places the +/// same bytes in VRAM instead (slow PCIe links); the gathers read `dev_` either way. class NativeEmbed { public: NativeEmbed() = default; @@ -57,6 +58,8 @@ public: void gather_one(int64_t token, float* out, void* stream) const; uint64_t bytes() const { return bytes_; } int type() const { return type_; } + /// The table was placed in VRAM (STRATA_EMBED_VRAM=1, or the pinned / alias fallbacks) rather than mapped. + bool in_vram() const { return dev_ != nullptr && host_ == nullptr; } private: void* host_ = nullptr; diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index a1fb1944..f9e75728 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -7,6 +7,7 @@ #include <cuda_runtime.h> #include <climits> #include <cstdio> +#include <cstdlib> #include <cstring> #include <exception> @@ -146,6 +147,34 @@ bool NativeEmbed::load(const std::vector<std::string>& shards, int64_t n_embd, i return false; } strata::platform::advise_willneed(gguf.tensor_data(*t), bytes_); // copied out of the mapping below + // STRATA_EMBED_VRAM=1: the table in the current device's VRAM instead of mapped host memory. The same + // bytes, read by the same gather kernels through dev_ (bitwise the same rows); what changes is where a + // prompt's scattered row reads go: over a PCIe Gen2 x4 link they cost more than the table's size in VRAM + // is worth. Taken only with the table plus 512 MiB free; otherwise, or when the upload fails, the mapped + // placement below is used as before (and the fallback is said). + if (const char* ev = std::getenv("STRATA_EMBED_VRAM"); ev != nullptr && ev[0] == '1') { + size_t free_b = 0, total_b = 0; + const bool have_free = cudaMemGetInfo(&free_b, &total_b) == cudaSuccess; + void* d = nullptr; + if (have_free && (uint64_t) free_b > bytes_ + ((uint64_t) 512 << 20) && + cudaMalloc(&d, bytes_) == cudaSuccess) { + if (cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) == cudaSuccess) { + std::fprintf(stderr, "strata: native embedding: STRATA_EMBED_VRAM=1: %llu MiB placed in VRAM " + "(%llu MiB were free)\n", + (unsigned long long) (bytes_ >> 20), (unsigned long long) (free_b >> 20)); + dev_ = d; // host_ stays null: the destructor frees dev_ + type_ = (int) t->type; + n_embd_ = n_embd; + n_vocab_ = n_vocab; + return true; + } + (void) cudaFree(d); + } + (void) cudaGetLastError(); + std::fprintf(stderr, "strata: native embedding: STRATA_EMBED_VRAM=1 not taken (%llu MiB free, the table " + "needs %llu MiB plus 512 MiB): kept in mapped host memory\n", + (unsigned long long) (have_free ? free_b >> 20 : 0), (unsigned long long) (bytes_ >> 20)); + } cudaError_t host_err = cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable); if (host_err != cudaSuccess) { // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 54d221cd..187df09a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3848,9 +3848,11 @@ int main(int argc, char** argv) { } strata::core::set_native_embed(&native_embed); std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " - "%s in mapped host memory (%.0f MiB, %.1f s)\n", + "%s %s (%.0f MiB, %.1f s)\n", o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, - strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0, + strata::ggml_type_name((uint32_t) native_embed.type()), + native_embed.in_vram() ? "in VRAM" : "in mapped host memory", + (double) native_embed.bytes() / 1048576.0, std::chrono::duration<double>(std::chrono::steady_clock::now() - embed_t0).count()); } // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back From 5dbd8774d82faea48db681e14dd6f6970cdad83a Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:52:32 +0100 Subject: [PATCH 149/177] prefill: a resident layer's experts weight-stationary on GP100, opt-in STRATA_MMQ_WS=1 (#3752) Problem: on a GP100 die (compute capability 6.0: no dp4a, no tensor cores) the prompt pass's routed experts run as MMQ launches per 16-expert group: a gate/up, a swiglu, a quantize and a down launch per group, each group's experts gathered and padded to the group's largest row count, every MMQ tile decoding its weight blocks again. With every expert resident the per-group overhead, not the weight bytes, is a large share of a prompt read on this card. Change: with STRATA_MMQ_WS=1, a layer whose routed experts are all resident on this GPU runs quantize_scatter, then gate/up as ONE weight-stationary launch over all its experts (read where they lie in the expert cache), ONE swiglu_quant over all its rows, then the down as ONE launch. New src/prefill/moe_ws*.cu(h): a CTA holds 128 (or 256) weight rows of one expert and runs them against up to 64 of that expert's activation rows, a thread per weight row, so each weight block is decoded once per pass; gate/up for IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS and IQ3_S, down for Q2_0 and IQ4_NL. Every product keeps MMQ's int8 values, scales and per-32-value epilogue in its K order, so GU, H and the down rows are MMQ's bits. ws::faster carries the author's measured ws / MMQ time ratios per format and picks a layer only where both products win at its rows per routed expert. prefill.cpp decides per layer after quantize_scatter (all experts resident, this GPU alone, no peer or CPU share, not the fused layout, not STRATA_MMQ_DIRECT, no Hadamard, no NVFP4 tail, no FP4 activations, aligned, not STRATA_DBG_NAN); every other layer keeps its path. STRATA_WS_FAST=1 (second opt-in, same bits) selects a down kernel for the IQ4_NL 32-token tier with fewer instructions per pass. Gating: the kernels and STRATA_PREFILL_WS exist only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (not HIP, not Metal; prefill.cpp links stubs that answer mode 0 elsewhere). At run time ws::mode() is 1 only with STRATA_MMQ_WS=1 and every visible GPU at compute capability 6.0. Unset, nothing is allocated (the offset and chunk buffers, under 1 MiB per die, exist only when the mode is not 0), the arena layout and the mapped table are the ones before, and the per-layer test short-circuits on the cached mode. Not ported: moe_ws_down_bench (needs a model shard) and its CMake target. Added: ws::set_mode (tests only) and tests/cuda/prefill_ws_parity_test.cpp, a synthetic layer-level check: random experts of all 5 gate/up x 2 down formats, random routing, the per-group MMQ (mmq::Context per expert) against ws::gate_up + swiglu_quant + ws::down, GU, Hq and Dm compared byte for byte, the down also alone on the reference H and with STRATA_WS_FAST on. It gives its verdict on a compute capability 6.0 card only (the kernels follow MMQ's sm_60 SASS); other cards run it for information with --any. Tests: prefill_ws_parity_test on boston (2x RTX A6000, sm_86, CUDA 13.1, gpu lock, SM60 build, --any because it is not a GP100): 40 cases (all 5 gate/up x 2 down formats, four routings each), 0 declined; the largest GU and down-alone error against that card's MMQ is 5.2e-07 of the largest value (float rounding: MMQ's sm_86 epilogue is not the sm_60 one the kernels follow), the full chain's Dm differs up to 1e-3 where int8 rounding of H flips on those rounding differences, and STRATA_WS_FAST output equals the default kernel's in all cases, 0 differing bytes. The byte-for-byte verdict against MMQ is the P100's. sm_60 compile of the whole tree (CUDA 12.9, P1004): exit 0; sm_86 build without the SM60 option (z440): exit 0. SASS of the 10 kernels moe_mmq.cu had before this change is identical in the sm_60 build. Not covered: no GP100 run here. The contributor's numbers (prompt reads 31-37% shorter on four GP100 dies with every expert resident: 240 tokens 2,156 -> 1,364 ms, a fresh 26K read 41,231 -> 28,555 ms; one run per arm) were not re-measured. The model gate is phaseA-tests/gh027/gates/3752-mmq-ws.sh. --- CMakeLists.txt | 16 + docs/OLDER_GPUS.md | 13 +- include/strata/prefill/moe_ws.hpp | 72 +++ src/prefill/moe_ws.cu | 165 ++++++ src/prefill/moe_ws.cuh | 49 ++ src/prefill/moe_ws_down.cu | 645 ++++++++++++++++++++++ src/prefill/moe_ws_gu_iq2.cu | 736 ++++++++++++++++++++++++++ src/prefill/moe_ws_gu_iq3.cu | 370 +++++++++++++ src/prefill/prefill.cpp | 111 +++- tests/cuda/prefill_ws_parity_test.cpp | 279 ++++++++++ 10 files changed, 2453 insertions(+), 3 deletions(-) create mode 100644 include/strata/prefill/moe_ws.hpp create mode 100644 src/prefill/moe_ws.cu create mode 100644 src/prefill/moe_ws.cuh create mode 100644 src/prefill/moe_ws_down.cu create mode 100644 src/prefill/moe_ws_gu_iq2.cu create mode 100644 src/prefill/moe_ws_gu_iq3.cu create mode 100644 tests/cuda/prefill_ws_parity_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0ac52a9a..efb23121 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1933,6 +1933,12 @@ if(STRATA_NATIVE_EXPERTS) 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}) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # GP100 (sm_60): a resident layer's experts weight-stationary, one launch per product (moe_ws.hpp; opt-in at + # run time, STRATA_MMQ_WS=1, and only where every visible GPU is cc 6.0) + target_sources(strata_mmq PRIVATE src/prefill/moe_ws.cu src/prefill/moe_ws_gu_iq2.cu src/prefill/moe_ws_gu_iq3.cu + src/prefill/moe_ws_down.cu) + endif() # 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 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 @@ -2071,6 +2077,10 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # the weight-stationary experts (moe_ws.hpp) are in strata_mmq: the prompt path may take them (STRATA_MMQ_WS=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_WS=1) + endif() 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) @@ -2094,6 +2104,12 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(prefill_swiglu_quant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_swiglu_quant_test COMMAND prefill_swiglu_quant_test) set_tests_properties(prefill_swiglu_quant_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the weight-stationary experts (STRATA_MMQ_WS) against the per-group MMQ, byte for byte, on random experts; the + # verdict is given on a compute capability 6.0 card only (77 elsewhere) + add_executable(prefill_ws_parity_test tests/cuda/prefill_ws_parity_test.cpp) + target_link_libraries(prefill_ws_parity_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_ws_parity_test COMMAND prefill_ws_parity_test) + set_tests_properties(prefill_ws_parity_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) endif() endif() if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 149cb09f..58118faf 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -129,7 +129,7 @@ in [DETAILS.md](DETAILS.md#rtx-30-series-sm_86-and-tesla-p100-sm_60-bitwise-deco ## Pascal GP100: a Q8_0 decode kernel (opt-in) GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projections read their weights at 40-80 GB/s of about -730, decoding K- and i-quant blocks one int at a time. Five opt-in changes, all measured on a PH402 only: +730, decoding K- and i-quant blocks one int at a time. Six opt-in changes, all measured on a PH402 only: - **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp per row, 16-byte weight loads, activations copied once per workgroup into shared memory, @@ -163,6 +163,17 @@ GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projectio the threshold. `STRATA_TOPK_MULTI=0` and `STRATA_SCORES_DX=0` turn one half off. The author measured, on four GP100 dies with every expert resident and `--pipeline-windows 3`, 51.0 -> 52.5 tok/s (+2.9%) decoding 400 tokens at 115K context, and no change below 64K; we have not measured it. A build without the sm_6x kernels ignores the switch with a warning. +- **`STRATA_MMQ_WS=1`** (prompt reading, CUDA build with `STRATA_EXPERIMENTAL_SM60`, every visible card compute capability 6.0): a + layer whose routed experts are all resident in VRAM, on this GPU alone (no peer, CPU or streamed share), runs its gate/up as one + weight-stationary launch over all its experts, one `swiglu_quant` over all its rows and its down as one launch, in place of a + gate/up, swiglu and down MMQ launch per 16-expert group. A CTA holds 128 or 256 weight rows of one expert and runs them against + up to 64 of that expert's rows, so each weight block is decoded once per pass. Gate/up for IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS and + IQ3_S, down for Q2_0 and IQ4_NL; the products keep MMQ's int8 values, scales and per-32-value epilogue order, so the results are + MMQ's bits. Every other layer keeps its path. `STRATA_WS_FAST=1` adds a down kernel for the IQ4_NL 32-token tier with fewer + instructions per pass (the same bits). The author measured, on four GP100 dies with every expert resident, prompt reads 31-37% + shorter (240 tokens 2,156 -> 1,364 ms; a fresh 26K read 41,231 -> 28,555 ms; one run per arm) and decode unchanged; we have not + measured it. A single 16 GB card that keeps experts in RAM takes the per-group path. `prefill_ws_parity_test` compares the + products with MMQ on random experts; its verdict needs a GP100. None of these changes is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default application clock is 759 MHz and a layer split leaves each die idle most of a window, so lock the clocks diff --git a/include/strata/prefill/moe_ws.hpp b/include/strata/prefill/moe_ws.hpp new file mode 100644 index 00000000..d5a42eff --- /dev/null +++ b/include/strata/prefill/moe_ws.hpp @@ -0,0 +1,72 @@ +// include/strata/prefill/moe_ws.hpp - GP100 (sm_60, the STRATA_EXPERIMENTAL_SM60 build): the prompt path's expert +// products of a layer whose experts are all resident in VRAM, read in place there and weight-stationary: ONE launch +// for the layer's gate/up and ONE for its down instead of a gate/up, swiglu and down MMQ launch per 16-expert group. +// A CTA holds 128 (or 256) weight rows of one expert and runs them against up to 64 of the expert's activation rows, a +// thread per weight row: each weight block is decoded once per pass instead of once per MMQ tile, and an expert's +// rows are its own count, not the group's largest. Every product keeps MMQ's int8 values, scales and per-32-value +// epilogue in its K order (the down K loop stops at 640), so GU, H and Dm are the per-group MMQ's bits. Swift +// Flash's shapes and formats only: gate/up [1280 x 2560] IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS or IQ3_S, down [2560 x 640] +// Q2_0 or IQ4_NL. +#pragma once + +#include <cstddef> +#include <cstdint> + +namespace strata::prefill::ws { + +/// The products of a layer: 1 with STRATA_MMQ_WS=1 (opt-in) gate/up and down, else 0 (the per-group MMQ). 0 also where +/// the build has no kernels (HIP, no ggml sources, not the STRATA_EXPERIMENTAL_SM60 build) or a visible GPU is not +/// cc 6.0 (the kernels were tuned and checked on GP100 only). +int mode(); +/// mode() != 0 and both formats have kernels. +bool supported(int gu_type, int d_type); +/// STRATA_WS_FAST=1 (opt-in, read once): the IQ4_NL down's 32-token tier (u >= 20 rows per routed expert) runs a +/// kernel that issues fewer instructions per pass - a switch into the unrolled token pairs, dy transposed - with every +/// token's operations and their order unchanged, so Dm is the same bits. 0 (unset): the kernels as before. +int fast(); +/// Benches and tests: 0 / 1 overrides fast(), -1 goes back to the environment. +void set_fast(int v); +/// Tests: 0 / 1 overrides mode() (1 runs the kernels on a card that is not cc 6.0), -1 goes back to the environment. +void set_mode(int v); +/// The weight-stationary product of `ggml_type` beats the per-group MMQ at u rows per routed expert (the measured +/// ratios, moe_ws.cu; u is clamped to the measured 2.5 .. 160). +bool faster(int ggml_type, double u); +/// Every gate/up and down matrix starts this aligned (the IQ4_NL down reads 8-byte pieces; the expert cache's slots are +/// 256-byte aligned and the Swift gate/up sizes multiples of 8). +constexpr uint64_t kAlign = 8; + +/// The CTAs' work: rows [row0, row0 + rows) of Xq / GU / Hq / Dm, all of the expert at position j of the layer's order +/// (MMQ's: its xoff entry), at most kChunkRows. A CTA takes one chunk and one 128- or 256-row piece of the weights. +struct alignas(16) Chunk { + int32_t j, row0, rows, pad; +}; +constexpr int kChunkRows = 64; +/// The most chunks a layer of `rows` routed rows over at most `n_expert` experts makes. +inline size_t max_chunks(int64_t rows, int64_t n_expert) { return (size_t) (rows / kChunkRows + n_expert); } +/// The chunks of the n experts of `order` (expert e has cnt[e] rows from bounds[j], j its position), the largest +/// expert first (the long CTAs start first); returns their number (<= max_chunks). +size_t chunks(const int32_t* order, size_t n, const int32_t* cnt, const int32_t* bounds, Chunk* out); + +/// One layer: its n routed experts' matrices at w + xoff[j] (gate/up, rows 0-639 gate then up) and w + xoff[j] + +/// down_off (down), xoff on the device in the layer's order (Product::xoff's table, all n entries); `rows` = T*K. +struct Layer { + int gu_type = -1, d_type = -1; + const void* w = nullptr; + const int64_t* xoff = nullptr; + int64_t down_off = 0; + const Chunk* chunks = nullptr; ///< on the device + int64_t nchunks = 0; + int64_t rows = 0; + int n = 0; + const void* xq = nullptr; ///< the gate/up's q8_1 rows (mmq::quantize_scatter's, rows of them) + float* gu = nullptr; ///< [rows][1280], the rows MMQ writes through identity ids + const void* hq = nullptr; ///< H's q8_1 rows: ONE mmq::swiglu_quant over all `rows` rows of gu + float* dm = nullptr; ///< [rows][2560] +}; +/// The layer's gate/up into gu, one launch; false (nothing launched) where the per-group MMQ is to run instead (mode 0, +/// or not faster at this u) - the same GU rows either way. +bool gate_up(const Layer& L, void* stream); +/// The layer's down from hq into dm, one launch. +void down(const Layer& L, void* stream); + +} // namespace strata::prefill::ws diff --git a/src/prefill/moe_ws.cu b/src/prefill/moe_ws.cu new file mode 100644 index 00000000..4a50719c --- /dev/null +++ b/src/prefill/moe_ws.cu @@ -0,0 +1,165 @@ +// src/prefill/moe_ws.cu - see include/strata/prefill/moe_ws.hpp: which layers and products take the weight-stationary +// kernels (moe_ws_gu_iq2.cu, moe_ws_gu_iq3.cu, moe_ws_down.cu), their work tables and launches. +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include <algorithm> +#include <atomic> +#include <cmath> +#include <cstdio> +#include <cstdlib> +#include <vector> + +namespace strata::prefill::ws { +namespace { + +// ws / per-group MMQ (one 512-expert top-10 layer, lognormal counts sigma 0.5 and 1.0, the worse of the two; isolated +// sustained medians measured on a GP100 die, the variant moe_ws_*.cu picks) at 2.5, 10, 35 and 160 rows per routed +// expert +struct Measured { int type; float r[4]; }; +constexpr double kU[4] = {2.5, 10.0, 35.0, 160.0}; +constexpr Measured kMeasured[] = { + {GGML_TYPE_IQ2_XXS, {0.276f, 0.494f, 0.728f, 0.754f}}, + {GGML_TYPE_IQ2_XS, {0.299f, 0.513f, 0.750f, 0.824f}}, + {GGML_TYPE_IQ2_S, {0.317f, 0.520f, 0.754f, 0.816f}}, + {GGML_TYPE_IQ3_XXS, {0.329f, 0.514f, 0.755f, 0.786f}}, + {GGML_TYPE_IQ3_S, {0.347f, 0.521f, 0.715f, 0.793f}}, + {GGML_TYPE_Q2_0, {0.246f, 0.389f, 0.555f, 0.614f}}, + {GGML_TYPE_IQ4_NL, {0.292f, 0.492f, 0.682f, 0.742f}}, +}; + +const Measured* measured(int t) { + for (const Measured& m : kMeasured) + if (m.type == t) return &m; + return nullptr; +} +bool gu_type(int t) { + return t == GGML_TYPE_IQ2_XXS || t == GGML_TYPE_IQ2_XS || t == GGML_TYPE_IQ2_S || t == GGML_TYPE_IQ3_XXS || + t == GGML_TYPE_IQ3_S; +} + +} // namespace + +namespace { +std::atomic<int> g_mode_override{-1}; // set_mode (tests); -1: the environment +} // namespace + +void set_mode(int v) { g_mode_override.store(v < 0 ? -1 : (v != 0 ? 1 : 0), std::memory_order_relaxed); } + +int mode() { +#if defined(__HIPCC__) + return 0; +#else + const int o = g_mode_override.load(std::memory_order_relaxed); + if (o >= 0) return o; + static const int m = [] { + const char* e = std::getenv("STRATA_MMQ_WS"); // opt-in + if (e == nullptr || std::atoi(e) != 1) return 0; + // GP100 (cc 6.0) only: tuned and checked there (any visible GPU that is not: off for all) + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n <= 0) { cudaGetLastError(); return 0; } + for (int d = 0; d < n; ++d) { + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, d) != cudaSuccess || p.major != 6 || p.minor != 0) { cudaGetLastError(); return 0; } + } + return 1; + }(); + return m; +#endif +} + +bool supported(int gt, int dt) { return mode() != 0 && gu_type(gt) && (dt == GGML_TYPE_Q2_0 || dt == GGML_TYPE_IQ4_NL); } + +namespace { +std::atomic<int> g_fast_override{-1}; // set_fast (benches, tests); -1: the environment +} // namespace + +int fast() { + const int o = g_fast_override.load(std::memory_order_relaxed); + if (o >= 0) return o; + static const int f = [] { + const char* e = std::getenv("STRATA_WS_FAST"); // opt-in + return e != nullptr && std::atoi(e) == 1 ? 1 : 0; + }(); + return f; +} + +void set_fast(int v) { g_fast_override.store(v < 0 ? -1 : (v != 0 ? 1 : 0), std::memory_order_relaxed); } + +bool faster(int t, double u) { + const Measured* m = measured(t); + if (m == nullptr) return false; + // linear in log u between the measured points, the ends held + if (u <= kU[0]) return m->r[0] < 1.0f; + for (int i = 1; i < 4; ++i) + if (u <= kU[i]) { + const double f = std::log(u / kU[i - 1]) / std::log(kU[i] / kU[i - 1]); + return m->r[i - 1] + f * (m->r[i] - m->r[i - 1]) < 1.0; + } + return m->r[3] < 1.0f; +} + +size_t chunks(const int32_t* order, size_t n, const int32_t* cnt, const int32_t* bounds, Chunk* out) { + // largest expert first: MMQ's order is ascending by count where the resident sort ran (walked backwards), else + // by id (sorted here) + bool asc = true; + for (size_t j = 1; j < n && asc; ++j) asc = cnt[order[j - 1]] <= cnt[order[j]]; + static thread_local std::vector<int32_t> by; + by.resize(n); + for (size_t j = 0; j < n; ++j) by[j] = (int32_t) (n - 1 - j); + if (!asc) + std::stable_sort(by.begin(), by.end(), [&](int32_t a, int32_t b) { return cnt[order[a]] > cnt[order[b]]; }); + size_t k = 0; + for (const int32_t j : by) { + const int32_t c = cnt[order[j]], b = bounds[j]; + for (int32_t tk = 0; tk < c; tk += kChunkRows) out[k++] = Chunk{j, b + tk, std::min(kChunkRows, c - tk), 0}; + } + return k; +} + +bool gate_up(const Layer& L, void* stream) { + if (L.n <= 0 || L.nchunks <= 0) return true; + const double u = (double) L.rows / L.n; + if (mode() != 1 || !faster(L.gu_type, u)) return false; + const cudaStream_t s = (cudaStream_t) stream; + switch (L.gu_type) { + case GGML_TYPE_IQ2_XXS: detail::gu_iq2_xxs(L, u, s); break; + case GGML_TYPE_IQ2_XS: detail::gu_iq2_xs(L, u, s); break; + case GGML_TYPE_IQ2_S: detail::gu_iq2_s(L, u, s); break; + case GGML_TYPE_IQ3_XXS: detail::gu_iq3_xxs(L, u, s); break; + case GGML_TYPE_IQ3_S: detail::gu_iq3_s(L, u, s); break; + default: + std::fprintf(stderr, "prefill ws: gate/up type %d has no kernel\n", L.gu_type); + std::exit(1); + } + return true; +} + +void down(const Layer& L, void* stream) { + if (L.n <= 0 || L.nchunks <= 0) return; + const double u = (double) L.rows / L.n; + const cudaStream_t s = (cudaStream_t) stream; + switch (L.d_type) { + case GGML_TYPE_Q2_0: detail::dn_q2_0(L, u, s); break; + case GGML_TYPE_IQ4_NL: { + const bool f = fast() == 1; + if (f) { // once per process: the switch is on and the WS path runs + static const bool said = [] { + std::fprintf(stderr, "strata prefill: STRATA_WS_FAST=1: the weight-stationary IQ4_NL down's 32-token " + "tier with switched token pairs and transposed dy (the same Dm bits)\n"); + return true; + }(); + (void) said; + } + detail::dn_iq4_nl(L, u, s, f); + break; + } + default: + std::fprintf(stderr, "prefill ws: down type %d has no kernel\n", L.d_type); + std::exit(1); + } +} + +} // namespace strata::prefill::ws diff --git a/src/prefill/moe_ws.cuh b/src/prefill/moe_ws.cuh new file mode 100644 index 00000000..ef37d434 --- /dev/null +++ b/src/prefill/moe_ws.cuh @@ -0,0 +1,49 @@ +// src/prefill/moe_ws.cuh - the weight-stationary expert kernels' shared pieces (see moe_ws.hpp): included after +// ggml-cuda's common.cuh and mmq.cuh by moe_ws.cu and the moe_ws_*.cu that hold the kernels (a few formats per file, +// so the instances compile in parallel). +#pragma once + +#include "strata/prefill/moe_ws.hpp" + +#include <cuda_runtime.h> + +namespace strata::prefill::ws::detail { + +// The two ways every kernel multiplies: int8 values sign-extended to int16 pairs (one PRMT per pair: bytes 0,2 and 1,3) +// and a pair of products added to a 32-bit sum by two XMAD (mad.wide.s16) - MMQ's dp4a on sm_60, one product at a time. +// A 32-value block's integer sum is exact (|sum| < 2^22 for every format here), so the order of its MACs is free. +__device__ __forceinline__ void split2(const int v, int& lo02, int& hi13) { + asm("prmt.b32 %0, %1, 0, 0xA280;" : "=r"(lo02) : "r"(v)); + asm("prmt.b32 %0, %1, 0, 0xB391;" : "=r"(hi13) : "r"(v)); +} +__device__ __forceinline__ int mad2(const int w, const int a, int c) { + asm("{\n\t.reg .s16 al, ah, bl, bh;\n\t" + "mov.b32 {al, ah}, %1;\n\tmov.b32 {bl, bh}, %2;\n\t" + "mad.wide.s16 %0, al, bl, %0;\n\tmad.wide.s16 %0, ah, bh, %0;\n\t}" + : "+r"(c) : "r"(w), "r"(a)); + return c; +} +// float(sum) for |sum| < 2^22 without the quarter-rate I2F: a chain seeded with 1.5 * 2^23 holds the float's bits +constexpr int kMagicI = 0x4B400000; +constexpr float kMagicF = 12582912.0f; + +// CTA b's chunk and first weight row: chunk b / pieces, piece b % pieces (`pieces` = weight rows / rows per CTA) - the +// chunks' order, each chunk's pieces next to each other +template <int PIECES, int ROWS> +__device__ __forceinline__ Chunk cta_work(const Chunk* __restrict__ chunks, int& r0) { + r0 = (int) (blockIdx.x % PIECES) * ROWS; + const int4 c = __ldg((const int4*) chunks + blockIdx.x / PIECES); + return Chunk{c.x, c.y, c.z, c.w}; +} + +// one launch of a layer's product, the variant picked by u (rows per routed expert); grid = nchunks x pieces +void gu_iq2_xxs(const Layer& L, double u, cudaStream_t s); +void gu_iq2_xs(const Layer& L, double u, cudaStream_t s); +void gu_iq2_s(const Layer& L, double u, cudaStream_t s); +void gu_iq3_xxs(const Layer& L, double u, cudaStream_t s); +void gu_iq3_s(const Layer& L, double u, cudaStream_t s); +void dn_q2_0(const Layer& L, double u, cudaStream_t s); +// `fast`: ws::fast() (STRATA_WS_FAST=1) - the 32-token tier's fast kernel, the same Dm rows +void dn_iq4_nl(const Layer& L, double u, cudaStream_t s, bool fast); + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/moe_ws_down.cu b/src/prefill/moe_ws_down.cu new file mode 100644 index 00000000..346f3a82 --- /dev/null +++ b/src/prefill/moe_ws_down.cu @@ -0,0 +1,645 @@ +// src/prefill/moe_ws_down.cu - weight-stationary down products (see moe_ws.hpp): Q2_0 and IQ4_NL, [2560 x 640] read in +// place at the blob's down offset, K stopping at 640 (nothing past a matrix is read). A CTA = 128 or 256 threads = +// as many weight rows of one expert (a row per thread, all of the chunk's H rows TPP at a time, the sums in registers); +// per K step the next step's weight bytes and q8_1 words are loaded into registers before this step's compute and +// stored to shared memory after it (one barrier pair per step). The H rows are ONE mmq::swiglu_quant over all of the +// layer's rows: [k/128][rows] block_q8_1_mmq, of which blocks 0-4 are read. (Measured on a GP100 die: ws / per-group +// MMQ 0.24-0.29 at 2.5 rows per expert, 0.38-0.49 at 10, 0.52-0.68 at 35, 0.61-0.74 at 160; bit-identical, +// compute-sanitizer clean with exact-size matrices.) +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include <cstdio> +#include <cstdlib> +#include <type_traits> + +namespace strata::prefill::ws::detail { +namespace { + +constexpr int DN_ROWS = 2560, DN_K = 640; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// ---- Q2_0: 18-B blocks {f16 d; 16 B of 2-bit codes}, 180-B rows; a step is 128 values = 2 blocks = 36 B of a row. +// MMQ's values {-1, 0, 1, 2}[code] (ggml_cuda_mmq_load_tiles_q2_0's PRMT, the selector masked to 3 bits) and the +// activations' int8 are both made exact fp16 pairs; a 32-value block is 16 HFMA2 into 2 half2 sums, each fp16 lane +// summing 8 products of magnitude <= 256 - integers <= 2048, exact - added in fp32: the float MMQ's I2F(sumi) gives. +// Epilogue as MMQ's sm_60 SASS: per 32-value block FMUL.FTZ (dx * dy), FFMA.FTZ (prod, sum, acc), blocks in K order. +namespace q20 { +constexpr int NT = 128, ROWB = 180, NSTEP = DN_K / 128, QB = 144, PIECES = DN_ROWS / NT; + +__device__ __forceinline__ uint32_t prmt(const uint32_t a, const uint32_t b, const uint32_t s) { + uint32_t d; + asm("prmt.b32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(s)); + return d; +} +__device__ __forceinline__ uint32_t hfma2(const uint32_t a, const uint32_t b, const uint32_t c) { + uint32_t d; + asm("fma.rn.f16x2 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); + return d; +} +__device__ __forceinline__ uint32_t hadd2(const uint32_t a, const uint32_t b) { + uint32_t d; + asm("add.rn.f16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); + return d; +} +// the two fp16 lanes of h converted exactly to f32 and added +__device__ __forceinline__ float h2sum(const uint32_t h) { + float f; + asm("{\n\t.reg .f16 lo, hi;\n\t.reg .f32 a, b;\n\tmov.b32 {lo, hi}, %1;\n\t" + "cvt.f32.f16 a, lo;\n\tcvt.f32.f16 b, hi;\n\tadd.f32 %0, a, b;\n\t}" + : "=f"(f) : "r"(h)); + return f; +} +__device__ __forceinline__ float f16_to_f32(const uint32_t bits16) { + float f; + asm("{\n\t.reg .b16 h;\n\tcvt.u16.u32 h, %1;\n\tcvt.f32.f16 %0, h;\n\t}" : "=f"(f) : "r"(bits16)); + return f; +} + +// the 16 values of the int16 qa = x2 & 0xFFFF, qb = x2 >> 16 of a block's codes (value i at bits 2i) as fp16 pairs +// (v0,v4) (v1,v5) (v2,v6) (v3,v7), qa's to wa and qb's to wb: prmt(H, 0, sel) with nibbles 1 / 3 of sel the code with +// its low bit flipped and nibbles 0 / 2 zero (byte 0 of H, the zero high byte) +__device__ __forceinline__ void dec2_h16(const uint32_t x2, uint32_t (&wa)[4], uint32_t (&wb)[4]) { + constexpr uint32_t H = 0x3C40BC00u; // bytes 00 BC 40 3C = fp16 high bytes of {0, -1, +2, +1}[c ^ 1] = {-1,0,1,2}[c] + const uint32_t x = x2 ^ 0x55555555u; + const uint32_t m0 = (x << 4) & 0x30303030u, m1 = (x << 2) & 0x30303030u, m2 = x & 0x30303030u, m3 = (x >> 2) & 0x30303030u; + wa[0] = prmt(H, 0u, m0); + wa[1] = prmt(H, 0u, m1); + wa[2] = prmt(H, 0u, m2); + wa[3] = prmt(H, 0u, m3); + wb[0] = prmt(H, 0u, m0 >> 16); + wb[1] = prmt(H, 0u, m1 >> 16); + wb[2] = prmt(H, 0u, m2 >> 16); + wb[3] = prmt(H, 0u, m3 >> 16); +} + +// the 8 int8 of activation words A (values 0-3) and B (4-7) as fp16 pairs (a0,a4) (a1,a5) (a2,a6) (a3,a7): +// u = a + 128; fp16 bits 0x64uu = 1024 + u exactly; minus 1152 = a exactly +__device__ __forceinline__ void act_h16(const uint32_t A, const uint32_t B, uint32_t (&a)[4]) { + const uint32_t P1 = prmt(A, B, 0x5140u) ^ 0x80808080u; // u0 u4 u1 u5 + const uint32_t P2 = prmt(A, B, 0x7362u) ^ 0x80808080u; // u2 u6 u3 u7 + constexpr uint32_t M = 0x64646464u, NEG1152 = 0xE480E480u; + a[0] = hadd2(prmt(P1, M, 0x4140u), NEG1152); + a[1] = hadd2(prmt(P1, M, 0x4342u), NEG1152); + a[2] = hadd2(prmt(P2, M, 0x4140u), NEG1152); + a[3] = hadd2(prmt(P2, M, 0x4342u), NEG1152); +} + +// the exact integer dot of one 32-value block (weights w[16], activations a0..a3 = 16 fp16 pairs) as a float +__device__ __forceinline__ float block_sum(const uint32_t (&w)[16], const uint4 a0, const uint4 a1, const uint4 a2, + const uint4 a3) { + uint32_t p = hfma2(w[0], a0.x, 0u), q = hfma2(w[1], a0.y, 0u); + p = hfma2(w[2], a0.z, p); q = hfma2(w[3], a0.w, q); + p = hfma2(w[4], a1.x, p); q = hfma2(w[5], a1.y, q); + p = hfma2(w[6], a1.z, p); q = hfma2(w[7], a1.w, q); + p = hfma2(w[8], a2.x, p); q = hfma2(w[9], a2.y, q); + p = hfma2(w[10], a2.z, p); q = hfma2(w[11], a2.w, q); + p = hfma2(w[12], a3.x, p); q = hfma2(w[13], a3.y, q); + p = hfma2(w[14], a3.z, p); q = hfma2(w[15], a3.w, q); + return h2sum(p) + h2sum(q); +} + +// TPP tokens per pass; tokens guarded in pairs (a pair's token past the count runs on a clamped row, not written). +// Per step every thread stages exactly 9 words of the CTA's 128 x 36 B (row stride 9 words: conflict-free decode reads) +// and threads < 8 TPP one 16-value q8_1 piece each. +template <int TPP> +__global__ void __launch_bounds__(NT, 4) dn_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const int64_t xadd, + const char* __restrict__ xq, const int total_rows, + float* __restrict__ dst) { + constexpr int G = 2, WPR = 9, AQ = TPP * 8, AI = (AQ + NT - 1) / NT; + static_assert(TPP % G == 0, ""); + __shared__ int wsm[NT * WPR]; + __shared__ __align__(16) uint32_t act_s[TPP][4][16]; + __shared__ __align__(8) float dy_s[4][TPP]; + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const char* __restrict__ W = w + xoff[c.j] + xadd + (size_t) r0 * ROWB; + const int tid = threadIdx.x; + int woff[WPR]; // word tid + NT i of the step's NT x 9 words: row (tid + NT i) / 9, word (tid + NT i) % 9 +#pragma unroll + for (int i = 0; i < WPR; ++i) { + const int idx = tid + i * NT, r = idx / WPR; + woff[i] = r * ROWB + 4 * (idx - r * WPR); + } + int wpre[WPR]; + uint4 apre[AI]; + float dpre[AI]; + auto load_w = [&](const int st) { + const char* __restrict__ Ws = W + st * 36; +#pragma unroll + for (int i = 0; i < WPR; ++i) wpre[i] = __ldg((const int*) (Ws + woff[i])); + }; + auto store_w = [&]() { +#pragma unroll + for (int i = 0; i < WPR; ++i) wsm[tid + i * NT] = wpre[i]; + }; + auto load_a = [&](const int st, const int trow0, const int nt) { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = tid + i * NT; + if (AQ % NT == 0 || idx < AQ) { + const int t = idx >> 3, m = idx & 7; + const char* blk = xq + ((size_t) st * total_rows + trow0 + min(t, nt - 1)) * QB; + apre[i] = __ldg((const uint4*) (blk + 16) + m); // values 16m .. 16m + 15 of the 128 + dpre[i] = __ldg((const float*) blk + (m >> 1)); // d of their 32-value block + } + } + }; + auto store_a = [&]() { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = tid + i * NT; + if (AQ % NT == 0 || idx < AQ) { + const int t = idx >> 3, m = idx & 7, b = m >> 1, hf = m & 1; + uint32_t p0[4], p1[4]; + act_h16(apre[i].x, apre[i].y, p0); + act_h16(apre[i].z, apre[i].w, p1); + uint4* d = (uint4*) &act_s[t][b][8 * hf]; + d[0] = make_uint4(p0[0], p0[1], p0[2], p0[3]); + d[1] = make_uint4(p1[0], p1[1], p1[2], p1[3]); + dy_s[b][t] = dpre[i]; // both pieces of a block write the same value + } + } + }; + + load_w(0); + load_a(0, c.row0, min(TPP, c.rows)); + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int st = 0; st < NSTEP; ++st) { + __syncthreads(); + store_w(); + store_a(); + __syncthreads(); + if (st + 1 < NSTEP) { + load_w(st + 1); + load_a(st + 1, trow0, nt); + } else if (p0 + TPP < c.rows) { + load_w(0); + load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP)); + } + // the row's 9 step words: block 0 = d0 | qs0 at bytes 0..17 (the codes 2 bytes into a word: funnel shift), + // block 1 = d1 in the top half of word 4, qs1 = words 5..8 + const uint32_t* cw = (const uint32_t*) (wsm + tid * WPR); +#pragma unroll 1 + for (int b = 0; b < 4; ++b) { // 32-value block: Q2_0 block b / 2, half b % 2 (int16 4h .. 4h + 3), K order + const int pq = b >> 1, h = b & 1; + const int base = pq ? 5 + 2 * h : 2 * h, sh = pq ? 0 : 16; + const uint32_t c0 = cw[base], c1 = cw[base + 1], c2 = cw[min(base + 2, WPR - 1)]; + const float dx = f16_to_f32(pq ? cw[4] >> 16 : cw[0] & 0xFFFFu); + uint32_t wv[16], wa[4], wb[4]; + dec2_h16(__funnelshift_r(c0, c1, sh), wa, wb); // int16 0 and 1 of the half +#pragma unroll + for (int k = 0; k < 4; ++k) { wv[k] = wa[k]; wv[4 + k] = wb[k]; } + dec2_h16(__funnelshift_r(c1, c2, sh), wa, wb); // int16 2 and 3 +#pragma unroll + for (int k = 0; k < 4; ++k) { wv[8 + k] = wa[k]; wv[12 + k] = wb[k]; } +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += G) { + if (t0 < nt) { + const float2 d2 = *(const float2*) &dy_s[b][t0]; +#pragma unroll + for (int t = t0; t < t0 + G; ++t) { + const uint4* a4 = (const uint4*) act_s[t][b]; + const float s = block_sum(wv, a4[0], a4[1], a4[2], a4[3]); + acc[t] = __fmaf_rn(__fmul_rn(dx, t == t0 ? d2.x : d2.y), s, acc[t]); + } + } + } + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + tid] = acc[t]; + } +} +} // namespace q20 + +// ---- IQ4_NL: 18-B blocks {f16 d; 16 B of 4-bit indices into kvalues_iq4nl}, 360-B rows; a step is SB blocks (SB 4: +// 72 B of a row, 8-byte aligned; SB 2: 36 B). The int8 values are get_int_from_table_16's table lookups (the 16-byte +// table in registers) without its final byte reorder - the same values paired (v4k, v4k+1), (v4k+16, v4k+17), ... and +// the activations paired the same way (PRMT 0x9180 / 0xB3A2); one XMAD chain per (row, token, block), then MMQ's sm_60 +// FMUL.FTZ (dx * dy), I2F (sumi), FFMA.FTZ, blocks in K order. Staging: 3 rows per warp and k (lanes 0-26, a row's 9 +// 4- or 8-byte pieces), the last k guarded so no row past the CTA's is read. +namespace nl4 { +constexpr int NB = DN_K / QK4_NL, BB = (int) sizeof(block_iq4_nl), ROWB = NB * BB; // 20, 18, 360 +static_assert(NB == 20 && BB == 18 && ROWB == 360, ""); + +// bytes (0,1) and (2,3) of v, each sign-extended to 16 bits +__device__ __forceinline__ void split01(const int v, int& p01, int& p23) { + asm("prmt.b32 %0, %1, 0, 0x9180;" : "=r"(p01) : "r"(v)); + asm("prmt.b32 %0, %1, 0, 0xB3A2;" : "=r"(p23) : "r"(v)); +} +// the 16-byte kvalues_iq4nl table as 4 words, read byte by byte +__device__ __forceinline__ void load_tab(uint32_t (&tab)[4]) { +#pragma unroll + for (int i = 0; i < 4; ++i) { + uint32_t v = 0; +#pragma unroll + for (int b = 0; b < 4; ++b) v |= (uint32_t) (uint8_t) kvalues_iq4nl[4 * i + b] << (8 * b); + tab[i] = v; + } +} +// a 32-value block from its 4 qs words (q[k]: values 4k..4k+3 in the low nibbles, 16+4k.. in the high ones): 16 int16 +// pair words against the activation pairs split01 makes of activation words m = 0..7 (at act[2m], act[2m + 1]). +// get_int_from_table_16's body (CUDA branch) up to its two lookup words tmp[0] = (v4k, v4k+16, v4k+1, v4k+17), +// tmp[1] = (v4k+2, v4k+18, v4k+3, v4k+19) +__device__ __forceinline__ void dec(const int (&q)[4], const uint32_t (&tab)[4], int (&wv)[16]) { +#pragma unroll + for (int k = 0; k < 4; ++k) { + const uint32_t q4 = (uint32_t) q[k]; + uint32_t tmp[2]; + const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1)); +#pragma unroll + for (uint32_t i = 0; i < 2; ++i) { + const uint32_t shift = 16 * i; + const uint32_t low = __byte_perm(tab[0], tab[1], q4 >> shift); + const uint32_t high = __byte_perm(tab[2], tab[3], q4 >> shift); + tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); + } + split2((int) tmp[0], wv[2 * k], wv[2 * (k + 4)]); // (v4k, v4k+1) | (v16+4k, v17+4k) + split2((int) tmp[1], wv[2 * k + 1], wv[2 * (k + 4) + 1]); // (v4k+2, v4k+3) | (v18+4k, v19+4k) + } +} +// block PAR of block pair p of the staged step (9 words per pair: even block d = lo16(w0), qs = bytes 2..17 by funnel +// shifts; odd block d = hi16(w4), qs = w5..w8) +template <int PAR> +__device__ __forceinline__ float load_blk(const int* __restrict__ cw, const int p, int (&q)[4]) { + const int* c = cw + 9 * p; + if constexpr (PAR == 0) { +#pragma unroll + for (int k = 0; k < 4; ++k) q[k] = (int) __funnelshift_r((uint32_t) c[k], (uint32_t) c[k + 1], 16); + return __half2float(__ushort_as_half((unsigned short) ((uint32_t) c[0] & 0xFFFFu))); + } else { +#pragma unroll + for (int k = 0; k < 4; ++k) q[k] = c[5 + k]; + return __half2float(__ushort_as_half((unsigned short) ((uint32_t) c[4] >> 16))); + } +} + +template <int NT, int TPP, int SB, int G, int PAR> +__device__ __forceinline__ void blk_compute(const int* __restrict__ cw, const int p, const uint32_t (&tab)[4], + const int (*act_s)[SB][16], const float (*dy_s)[SB], const int nt, + float (&acc)[TPP]) { + const int b = 2 * p + PAR; // block within the step + int wv[16]; + float dx; + { + int q[4]; + dx = load_blk<PAR>(cw, p, q); + dec(q, tab, wv); + } + // tokens in groups of G behind one guard (a group's tokens past nt run on stale shared memory, not written) +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += G) { + if (t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + G; ++t) { + const int4* a4 = (const int4*) act_s[t][b]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const float dy = dy_s[t][b]; + int s0 = 0; + s0 = mad2(wv[0], a0.x, s0); s0 = mad2(wv[1], a0.y, s0); s0 = mad2(wv[2], a0.z, s0); s0 = mad2(wv[3], a0.w, s0); + s0 = mad2(wv[4], a1.x, s0); s0 = mad2(wv[5], a1.y, s0); s0 = mad2(wv[6], a1.z, s0); s0 = mad2(wv[7], a1.w, s0); + s0 = mad2(wv[8], a2.x, s0); s0 = mad2(wv[9], a2.y, s0); s0 = mad2(wv[10], a2.z, s0); s0 = mad2(wv[11], a2.w, s0); + s0 = mad2(wv[12], a3.x, s0); s0 = mad2(wv[13], a3.y, s0); s0 = mad2(wv[14], a3.z, s0); s0 = mad2(wv[15], a3.w, s0); + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __int2float_rn(s0), acc[t]); + } + } + } +} + +template <int NT, int TPP, int SB, int G> +__global__ void __launch_bounds__(NT, 1) dn_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const int64_t xadd, + const block_q8_1_mmq* __restrict__ xq, const int total_rows, + float* __restrict__ dst) { + static_assert((SB == 2 || SB == 4) && NT % 32 == 0 && TPP % G == 0, ""); + constexpr int NW = NT / 32, WPS = 9 * SB / 2, S = WPS | 1, NSTEP = NB / SB, PIECES = DN_ROWS / NT; + constexpr int KI = (NT + 3 * NW - 1) / (3 * NW); + constexpr int AW = 9 * SB; // activation words per token and step (SB d + 8 SB qs words) + constexpr int AI = (TPP * AW + NT - 1) / NT; + using PT = typename std::conditional<SB == 4, int2, int>::type; + __shared__ int wsm[NT * S]; + __shared__ __align__(16) int act_s[TPP][SB][16]; + __shared__ float dy_s[TPP][SB]; + uint32_t tab[4]; + load_tab(tab); + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int sub = lane / 9, pc = lane - 9 * sub; // sub 3: lanes 27-31, idle + const int srow0 = 3 * warp + sub; + const bool sact = sub < 3; + const char* __restrict__ Wg = w + xoff[c.j] + xadd + (size_t) (r0 + srow0) * ROWB + pc * (int) sizeof(PT); + int* __restrict__ ws_st = wsm + srow0 * S + pc * (int) (sizeof(PT) / 4); + PT pre[KI]; + int apre[AI]; + auto load_w = [&](const int st) { + if (sact) { + const char* g = Wg + st * (SB * BB); +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) pre[k] = __ldg((const PT*) (g + (size_t) k * 3 * NW * ROWB)); + } + }; + auto store_w = [&]() { + if (sact) { +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) { + if constexpr (SB == 4) { + ws_st[k * 3 * NW * S] = pre[k].x; + ws_st[k * 3 * NW * S + 1] = pre[k].y; + } else { + ws_st[k * 3 * NW * S] = pre[k]; + } + } + } + }; + // word wd of token t's step: d4[b0 + wd] for wd < SB, else qs word 8 b0 + (wd - SB) + auto load_a = [&](const int st, const int trow0, const int nt) { + const int kb = (st * SB) >> 2, b0 = (st * SB) & 3; // the 128-value q8_1 block and the first 32-block in it +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + const int* blk = (const int*) (xq + (size_t) kb * total_rows + trow0 + t); + apre[i] = __ldg(blk + (wd < SB ? b0 + wd : 4 + 8 * b0 + (wd - SB))); + } + } + }; + auto store_a = [&](const int nt) { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + if (wd < SB) { + dy_s[t][wd] = __int_as_float(apre[i]); + } else { + const int m = wd - SB, bb = m >> 3, mm = m & 7; + int lo, hi; + split01(apre[i], lo, hi); + *(int2*) &act_s[t][bb][2 * mm] = make_int2(lo, hi); + } + } + } + }; + load_w(0); + load_a(0, c.row0, min(TPP, c.rows)); + const int* cw = wsm + threadIdx.x * S; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int st = 0; st < NSTEP; ++st) { + __syncthreads(); + store_w(); + store_a(nt); + __syncthreads(); + if (st + 1 < NSTEP) { + load_w(st + 1); + load_a(st + 1, trow0, nt); + } else if (p0 + TPP < c.rows) { + load_w(0); + load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP)); + } +#pragma unroll 1 + for (int p = 0; p < SB / 2; ++p) { + blk_compute<NT, TPP, SB, G, 0>(cw, p, tab, act_s, dy_s, nt, acc); + blk_compute<NT, TPP, SB, G, 1>(cw, p, tab, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + threadIdx.x] = acc[t]; + } +} + +// ---- STRATA_WS_FAST=1 (ws::fast(), moe_ws.hpp): the 256 x 32 tier (2-block steps, pairs of tokens) with fewer +// instructions per pass, the same Dm rows bit for bit: every token's operations and their order are dn_kernel's. +// (Prototyped as a bench variant on one GP100 die: memcmp-equal to dn_kernel on real IQ4_NL layers at T 1024 and +// 1536, lognormal sigma 0.5 / 1.0 and a flat-32 control; 4.7-9.2% faster, 122 -> 102 registers, still two CTAs per +// SM. moe_ws_down_bench checks and times it against dn_kernel.) +// DUFF a switch on the number of token pairs falls through the 16 unrolled pairs (a jump table) instead of a guard +// per pair and block +// DYT dy as [block][token]: a pair's two dy in one LDS.64 +template <int NT, int TPP, int SB, int G, int PAR> +__device__ __forceinline__ void blk_compute_fast(const int* __restrict__ cw, const int p, const uint32_t (&tab)[4], + const int (*act_s)[SB][16], const float* __restrict__ dyb, const int nt, + float (&acc)[TPP]) { + static_assert(TPP / G == 16 && G == 2, "the switch below: 16 token pairs"); + const int b = 2 * p + PAR; // block within the step + int wv[16]; + float dx; + { + int q[4]; + dx = load_blk<PAR>(cw, p, q); + dec(q, tab, wv); + } + // pairs past nt's run on stale shared memory and are not written, as dn_kernel's + auto grp = [&](auto K) { + constexpr int t0 = decltype(K)::value * G; + const float2 d2 = *(const float2*) &dyb[b * TPP + t0]; +#pragma unroll + for (int t = t0; t < t0 + G; ++t) { + const int4* a4 = (const int4*) act_s[t][b]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + int s0 = 0; + s0 = mad2(wv[0], a0.x, s0); s0 = mad2(wv[1], a0.y, s0); s0 = mad2(wv[2], a0.z, s0); s0 = mad2(wv[3], a0.w, s0); + s0 = mad2(wv[4], a1.x, s0); s0 = mad2(wv[5], a1.y, s0); s0 = mad2(wv[6], a1.z, s0); s0 = mad2(wv[7], a1.w, s0); + s0 = mad2(wv[8], a2.x, s0); s0 = mad2(wv[9], a2.y, s0); s0 = mad2(wv[10], a2.z, s0); s0 = mad2(wv[11], a2.w, s0); + s0 = mad2(wv[12], a3.x, s0); s0 = mad2(wv[13], a3.y, s0); s0 = mad2(wv[14], a3.z, s0); s0 = mad2(wv[15], a3.w, s0); + acc[t] = __fmaf_rn(__fmul_rn(dx, t == t0 ? d2.x : d2.y), __int2float_rn(s0), acc[t]); + } + }; + using std::integral_constant; + switch ((nt + G - 1) / G) { + case 16: grp(integral_constant<int, 15>{}); [[fallthrough]]; + case 15: grp(integral_constant<int, 14>{}); [[fallthrough]]; + case 14: grp(integral_constant<int, 13>{}); [[fallthrough]]; + case 13: grp(integral_constant<int, 12>{}); [[fallthrough]]; + case 12: grp(integral_constant<int, 11>{}); [[fallthrough]]; + case 11: grp(integral_constant<int, 10>{}); [[fallthrough]]; + case 10: grp(integral_constant<int, 9>{}); [[fallthrough]]; + case 9: grp(integral_constant<int, 8>{}); [[fallthrough]]; + case 8: grp(integral_constant<int, 7>{}); [[fallthrough]]; + case 7: grp(integral_constant<int, 6>{}); [[fallthrough]]; + case 6: grp(integral_constant<int, 5>{}); [[fallthrough]]; + case 5: grp(integral_constant<int, 4>{}); [[fallthrough]]; + case 4: grp(integral_constant<int, 3>{}); [[fallthrough]]; + case 3: grp(integral_constant<int, 2>{}); [[fallthrough]]; + case 2: grp(integral_constant<int, 1>{}); [[fallthrough]]; + case 1: grp(integral_constant<int, 0>{}); [[fallthrough]]; + default: break; + } +} + +// dn_kernel with blk_compute_fast and dy_s as [SB][TPP]; everything else is dn_kernel's +template <int NT, int TPP, int SB, int G> +__global__ void __launch_bounds__(NT, 1) dn_kernel_fast(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const int64_t xadd, + const block_q8_1_mmq* __restrict__ xq, const int total_rows, + float* __restrict__ dst) { + static_assert((SB == 2 || SB == 4) && NT % 32 == 0 && TPP % G == 0, ""); + constexpr int NW = NT / 32, WPS = 9 * SB / 2, S = WPS | 1, NSTEP = NB / SB, PIECES = DN_ROWS / NT; + constexpr int KI = (NT + 3 * NW - 1) / (3 * NW); + constexpr int AW = 9 * SB; // activation words per token and step (SB d + 8 SB qs words) + constexpr int AI = (TPP * AW + NT - 1) / NT; + using PT = typename std::conditional<SB == 4, int2, int>::type; + __shared__ int wsm[NT * S]; + __shared__ __align__(16) int act_s[TPP][SB][16]; + __shared__ __align__(8) float dy_s[SB * TPP]; // [SB][TPP]: dy of token t, block b at b * TPP + t + uint32_t tab[4]; + load_tab(tab); + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int sub = lane / 9, pc = lane - 9 * sub; // sub 3: lanes 27-31, idle + const int srow0 = 3 * warp + sub; + const bool sact = sub < 3; + const char* __restrict__ Wg = w + xoff[c.j] + xadd + (size_t) (r0 + srow0) * ROWB + pc * (int) sizeof(PT); + int* __restrict__ ws_st = wsm + srow0 * S + pc * (int) (sizeof(PT) / 4); + PT pre[KI]; + int apre[AI]; + auto load_w = [&](const int st) { + if (sact) { + const char* g = Wg + st * (SB * BB); +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) pre[k] = __ldg((const PT*) (g + (size_t) k * 3 * NW * ROWB)); + } + }; + auto store_w = [&]() { + if (sact) { +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) { + if constexpr (SB == 4) { + ws_st[k * 3 * NW * S] = pre[k].x; + ws_st[k * 3 * NW * S + 1] = pre[k].y; + } else { + ws_st[k * 3 * NW * S] = pre[k]; + } + } + } + }; + auto load_a = [&](const int st, const int trow0, const int nt) { + const int kb = (st * SB) >> 2, b0 = (st * SB) & 3; +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + const int* blk = (const int*) (xq + (size_t) kb * total_rows + trow0 + t); + apre[i] = __ldg(blk + (wd < SB ? b0 + wd : 4 + 8 * b0 + (wd - SB))); + } + } + }; + auto store_a = [&](const int nt) { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + if (wd < SB) { + dy_s[wd * TPP + t] = __int_as_float(apre[i]); + } else { + const int m = wd - SB, bb = m >> 3, mm = m & 7; + int lo, hi; + split01(apre[i], lo, hi); + *(int2*) &act_s[t][bb][2 * mm] = make_int2(lo, hi); + } + } + } + }; + load_w(0); + load_a(0, c.row0, min(TPP, c.rows)); + const int* cw = wsm + threadIdx.x * S; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int st = 0; st < NSTEP; ++st) { + __syncthreads(); + store_w(); + store_a(nt); + __syncthreads(); + if (st + 1 < NSTEP) { + load_w(st + 1); + load_a(st + 1, trow0, nt); + } else if (p0 + TPP < c.rows) { + load_w(0); + load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP)); + } +#pragma unroll 1 + for (int p = 0; p < SB / 2; ++p) { + blk_compute_fast<NT, TPP, SB, G, 0>(cw, p, tab, act_s, dy_s, nt, acc); + blk_compute_fast<NT, TPP, SB, G, 1>(cw, p, tab, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace nl4 + +} // namespace + +// Q2_0: 8 tokens per pass below 5 rows per expert, then 16 (equal at 5) +void dn_q2_0(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + const unsigned grid = (unsigned) (L.nchunks * q20::PIECES); + if (u < 5.0) q20::dn_kernel<8><<<grid, q20::NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, L.down_off, (const char*) L.hq, + (int) L.rows, L.dm); + else q20::dn_kernel<16><<<grid, q20::NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, L.down_off, (const char*) L.hq, + (int) L.rows, L.dm); + ck(cudaGetLastError(), "down Q2_0"); +} + +// IQ4_NL: 128 rows x 8 tokens (4-block steps) below 5 rows per expert, 256 x 16 below 20, then 256 x 32 (2-block steps); +// `fast` (STRATA_WS_FAST=1): the 256 x 32 tier runs dn_kernel_fast instead - the same Dm rows +void dn_iq4_nl(const Layer& L, double u, cudaStream_t s, bool fast) { + if (L.nchunks <= 0) return; + const char* w = (const char*) L.w; + const block_q8_1_mmq* x = (const block_q8_1_mmq*) L.hq; + if (u < 5.0) + nl4::dn_kernel<128, 8, 4, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 128)), 128, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x, + (int) L.rows, L.dm); + else if (u < 20.0) + nl4::dn_kernel<256, 16, 4, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x, + (int) L.rows, L.dm); + else if (fast) + nl4::dn_kernel_fast<256, 32, 2, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, + L.down_off, x, + (int) L.rows, L.dm); + else + nl4::dn_kernel<256, 32, 2, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x, + (int) L.rows, L.dm); + ck(cudaGetLastError(), "down IQ4_NL"); +} + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/moe_ws_gu_iq2.cu b/src/prefill/moe_ws_gu_iq2.cu new file mode 100644 index 00000000..4df68b6d --- /dev/null +++ b/src/prefill/moe_ws_gu_iq2.cu @@ -0,0 +1,736 @@ +// src/prefill/moe_ws_gu_iq2.cu - weight-stationary gate/up products (see moe_ws.hpp): IQ2_XXS, IQ2_XS and IQ2_S, +// [1280 x 2560] read in place. A CTA = 128 threads = 128 weight rows of one expert (a row per thread, all of the +// chunk's activation rows TPP at a time, the sums in registers); K advances 128 values a step (half a 256-value block +// = 4 sub-blocks): the step's bytes of the 128 rows and the step's q8_1 block of each token go to shared memory (the +// activations split to int16 pairs once), then each thread decodes its row's 4 sub-blocks once per pass and runs them +// against the tokens. Bits: per 32-value sub-block MMQ's int8 values (ggml_cuda_mmq_load_tiles_iq2_*) and scale +// expressions, then MMQ's epilogue (IQ2_XXS: acc = fma(dx * dy, float(sum), acc); IQ2_XS / IQ2_S, a scale per 16 +// values: t = fma(float(sum 0-15), d0, 0), t = fma(float(sum 16-31), d1, t), acc = fma(t, dy, acc)), sub-blocks in K +// order. (Measured on a GP100 die: ws / per-group MMQ 0.26-0.33 at 2.5 +// rows per expert, 0.46-0.52 at 10, 0.67-0.76 at 35, 0.75-0.82 at 160; bit-identical, compute-sanitizer clean with +// exact-size matrices.) +// +// Decode: every iq2xxs / iq2xs / iq2s_grid byte is 0x08, 0x19 or 0x2B, so a grid entry is 8 nibble codes (0, 1, 2) +// and a value's sign adds 4 to its nibble: __byte_perm(0x002B1908, 0x00D5E7F8, codes | signs) is MMQ's +// __vsub4(g ^ s, s) word, one PRMT per 4 values (checked against MMQ's expressions for every entry and sign byte). +// Staging without per-lane branches: rows are 660 / 740 / 820 B, so block kc starts 2 * (kc & 1) bytes into a 4-byte +// word for the whole CTA - an even block's words are two aligned loads and a funnel shift (the second load ends at most +// 2 bytes into block kc + 1 of the same row), an odd block's are aligned; d sits the other way round (an odd block's d +// is the high half of the word 2 bytes before it, inside block kc - 1). Every load of a lane is issued before its +// stores, and nothing outside a row is read (the last row's last block is odd). Token groups of TG: one `t < nt` +// branch per group, so the XMAD chains of the group's tokens interleave (a group's tokens past the count are not +// written). +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include <cstdio> +#include <cstdlib> + +namespace strata::prefill::ws::detail { +namespace { + +constexpr int GU_ROWS = 1280, GU_K = 2560, NB = GU_K / QK_K, NSTEP = 2 * NB, NT = 128, NW = NT / 32, PIECES = GU_ROWS / NT; +constexpr uint32_t PX = 0x002B1908u, PY = 0x00D5E7F8u; // codes 0-2: +8 +25 +43 | codes 4-6: -8 -25 -43 + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// the step's activations of IQ2_XS / IQ2_S: nt consecutive 144-B block_q8_1_mmq, d4 -> dy_s, int8 -> int16 pairs +template <int TPP> +__device__ __forceinline__ void stage_act(const block_q8_1_mmq* __restrict__ xq, const int hc, const int total_rows, + const int trow0, const int nt, int (*act_s)[4][16], float (*dy_s)[4]) { + constexpr int NA = (TPP * 36 + NT - 1) / NT; + int av[NA]; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) av[i] = __ldg(xr + idx); + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) { + const int t = idx / 36, wd = idx - t * 36; + if (wd < 4) { + dy_s[t][wd] = __int_as_float(av[i]); + } else { + const int m = wd - 4; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][m / 8][2 * (m % 8)] = make_int2(lo, hi); + } + } + } +} + +// IQ2_XS / IQ2_S: sub-block s's 16 int16-pair words wv and scales d0 / d1 against the tokens (vec_dot_q8_0_16_q8_1's +// epilogue). CVT 0: four XMAD chains and I2F; 1: two chains seeded with kMagicI (exact for the 16-value sums, +// |sum| <= 16 * 43 * 127 < 2^22) +template <int TPP, int CVT, int TG> +__device__ __forceinline__ void mac16(const int (&wv)[16], const float dx0, const float dx1, const int s, + const int (*act_s)[4][16], const float (*dy_s)[4], const int nt, float (&acc)[TPP]) { +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const float dy = dy_s[t][s]; + float fa, fb; // float(sum of values 0-15), float(sum of values 16-31): exact + if constexpr (CVT == 0) { + int s0 = 0, s1 = 0, s2 = 0, s3 = 0; + s0 = mad2(wv[0], a0.x, s0); s1 = mad2(wv[1], a0.y, s1); s0 = mad2(wv[2], a0.z, s0); s1 = mad2(wv[3], a0.w, s1); + s0 = mad2(wv[4], a1.x, s0); s1 = mad2(wv[5], a1.y, s1); s0 = mad2(wv[6], a1.z, s0); s1 = mad2(wv[7], a1.w, s1); + s2 = mad2(wv[8], a2.x, s2); s3 = mad2(wv[9], a2.y, s3); s2 = mad2(wv[10], a2.z, s2); s3 = mad2(wv[11], a2.w, s3); + s2 = mad2(wv[12], a3.x, s2); s3 = mad2(wv[13], a3.y, s3); s2 = mad2(wv[14], a3.z, s2); s3 = mad2(wv[15], a3.w, s3); + fa = __int2float_rn(s0 + s1); + fb = __int2float_rn(s2 + s3); + } else { + int sa = kMagicI, sb = kMagicI; + sa = mad2(wv[0], a0.x, sa); sb = mad2(wv[8], a2.x, sb); + sa = mad2(wv[1], a0.y, sa); sb = mad2(wv[9], a2.y, sb); + sa = mad2(wv[2], a0.z, sa); sb = mad2(wv[10], a2.z, sb); + sa = mad2(wv[3], a0.w, sa); sb = mad2(wv[11], a2.w, sb); + sa = mad2(wv[4], a1.x, sa); sb = mad2(wv[12], a3.x, sb); + sa = mad2(wv[5], a1.y, sa); sb = mad2(wv[13], a3.y, sb); + sa = mad2(wv[6], a1.z, sa); sb = mad2(wv[14], a3.z, sb); + sa = mad2(wv[7], a1.w, sa); sb = mad2(wv[15], a3.w, sb); + fa = __fsub_rn(__int_as_float(sa), kMagicF); + fb = __fsub_rn(__int_as_float(sb), kMagicF); + } + float tf = __fmaf_rn(fa, dx0, 0.0f); + tf = __fmaf_rn(fb, dx1, tf); + acc[t] = __fmaf_rn(tf, dy, acc[t]); + } + } + } +} + +// d0 / d1 = ((ls & 15 | ls >> 4) * d + d / 2) / 4 as MMQ's sm_60 SASS computes them +__device__ __forceinline__ void scales16(const int ls, const int dbits, float& d0, float& d1) { + const float d = __half2float(__ushort_as_half((unsigned short) (dbits & 0xFFFF))); + const float dh = __fmul_rn(d, 0.5f); + d0 = __fmul_rn(__fmaf_rn(d, __int2float_rn(ls & 0x0F), dh), 0.25f); + d1 = __fmul_rn(__fmaf_rn(d, __int2float_rn(ls >> 4), dh), 0.25f); +} + +// ---- IQ2_XXS: 66-B blocks; per row and step 8 qs words (4 grid bytes, then aux32: 4 x 7 sign bits + the scale) and +// d (stride 9). Every lane slot is one word type: qs words rows tid/8 + 16 i (word tid%8), d the thread's own row. +// A partial pass's token groups run past the count on copies of row nt - 1 (not written); a full pass has no branch. +namespace xxs2 { +constexpr int BB = (int) sizeof(block_iq2_xxs), ROWB = NB * BB, CWS = 9; +static_assert(BB == 66 && ROWB % 4 == 0, "block_iq2_xxs"); + +// nibble b = the code of byte b of iq2xxs_grid[i] +__device__ __forceinline__ uint32_t grid_codes(const int i) { + const uint2 g = ((const uint2*) iq2xxs_grid)[i]; + uint32_t w = 0; +#pragma unroll + for (int b = 0; b < 8; ++b) { + const uint32_t v = ((b < 4 ? g.x : g.y) >> (8 * (b & 3))) & 0xFF; + w |= ((uint32_t) (v > 0x08u) + (uint32_t) (v > 0x19u)) << (4 * b); + } + return w; +} +// a 7-bit sign field: MMQ's unpack_ksigns byte (bit 7 = parity) spread to bit 2 of nibble b +__device__ __forceinline__ uint32_t sign_spread(const int v) { + const uint32_t s = (uint32_t) v ^ ((uint32_t) (__popc(v) & 1) << 7); + uint32_t w = 0; +#pragma unroll + for (int b = 0; b < 8; ++b) w |= ((s >> b) & 1u) << (4 * b + 2); + return w; +} + +template <int TPP, int CH, int TG, bool FULL> +__device__ __forceinline__ void sb_compute(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ tabA, + const uint32_t* __restrict__ tabB, const int (*act_s)[4][16], + const float (*dy_s)[4], const int nt, float (&acc)[TPP]) { + int wv[16]; + float dx; + { + const uint32_t q2 = (uint32_t) cw[2 * s + 0]; + const uint32_t aux32 = (uint32_t) cw[2 * s + 1]; +#pragma unroll + for (int l = 0; l < QR2_XXS; ++l) { + const uint32_t sel = tabA[(q2 >> (8 * l)) & 0xFF] | tabB[(aux32 >> (7 * l)) & 0x7F]; + split2((int) __byte_perm(PX, PY, sel), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) __byte_perm(PX, PY, sel >> 16), wv[4 * l + 2], wv[4 * l + 3]); + } + const int ls = aux32 >> 27 | 1; + const float d = __ushort_as_half((unsigned short) (cw[8] & 0xFFFF)); + dx = d * ls / 8; // MMQ: (d * scale + d / 2) / 4 + } +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (FULL || t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const int a[16] = {a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w, a2.x, a2.y, a2.z, a2.w, a3.x, a3.y, a3.z, a3.w}; + const float dy = dy_s[t][s]; + int sc[CH]; + sc[0] = kMagicI; +#pragma unroll + for (int c = 1; c < CH; ++c) sc[c] = 0; +#pragma unroll + for (int m = 0; m < 16; ++m) sc[m % CH] = mad2(wv[m], a[m], sc[m % CH]); + int sum = sc[0]; +#pragma unroll + for (int c = 1; c < CH; ++c) sum += sc[c]; + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __fsub_rn(__int_as_float(sum), kMagicF), acc[t]); + } + } + } +} + +template <int TPP, int CH, int TG> +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0 && (TPP * 32) % NT == 0 && TPP * 4 <= NT, ""); + constexpr int NDS = 8; // qs-word slots per lane: rows tid/8 + i*NT/8, word tid%8 + constexpr int RS = NT / 8; // rows per slot + constexpr int NA = TPP * 32 / NT; // activation qs-word slots per lane + __shared__ __align__(16) uint32_t tabA[256]; + __shared__ __align__(16) uint32_t tabB[128]; + __shared__ __align__(16) int act_s[TPP][4][16]; // [token][32-block of the step][8 words split to 16] + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + const int tid = threadIdx.x; + for (int i = tid; i < 256; i += NT) tabA[i] = grid_codes(i); + for (int i = tid; i < 128; i += NT) tabB[i] = sign_spread(i); + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const char* __restrict__ W = w + xoff[c.j] + (size_t) r0 * ROWB; + const char* __restrict__ Wq = W + (size_t) (tid >> 3) * ROWB + 4 * (tid & 7); // + i*RS*ROWB + kc*BB + 32h + const char* __restrict__ Wd = W + (size_t) tid * ROWB; // + kc*BB + int* __restrict__ sq = wsm + (tid >> 3) * CWS + (tid & 7); // + i*RS*CWS + int* __restrict__ sd = wsm + tid * CWS + 8; + const int* cw = wsm + tid * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); // nt consecutive 36-word blocks + __syncthreads(); + int av[NA], dv = 0; +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5; + av[i] = __ldg(xr + min(t, nt - 1) * 36 + 4 + (idx & 31)); // clamped: no branch, never past row nt-1 + } + if (TPP * 4 == NT || tid < TPP * 4) dv = __ldg(xr + min(tid >> 2, nt - 1) * 36 + (tid & 3)); + const char* bq = Wq + kc * BB + 32 * h; + if (kc & 1) { // odd block: qs words aligned; d = high half of the word 2 bytes before the block + int v[NDS]; +#pragma unroll + for (int i = 0; i < NDS; ++i) v[i] = __ldg((const int*) (bq + 2 + (size_t) i * RS * ROWB)); + const int vd = __ldg((const int*) (Wd + kc * BB - 2)); +#pragma unroll + for (int i = 0; i < NDS; ++i) sq[i * RS * CWS] = v[i]; + *sd = (int) ((uint32_t) vd >> 16); + } else { // even block: qs words 2 bytes into a word: two aligned words + funnel shift; d = low half + int lo[NDS], hi[NDS]; +#pragma unroll + for (int i = 0; i < NDS; ++i) { + lo[i] = __ldg((const int*) (bq + (size_t) i * RS * ROWB)); + hi[i] = __ldg((const int*) (bq + 4 + (size_t) i * RS * ROWB)); + } + const int vd = __ldg((const int*) (Wd + kc * BB)); +#pragma unroll + for (int i = 0; i < NDS; ++i) sq[i * RS * CWS] = (int) __funnelshift_r((uint32_t) lo[i], (uint32_t) hi[i], 16); + *sd = vd; + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5, wd = idx & 31; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][wd >> 3][2 * (wd & 7)] = make_int2(lo, hi); + } + if (TPP * 4 == NT || tid < TPP * 4) dy_s[tid >> 2][tid & 3] = __int_as_float(dv); + __syncthreads(); + if (nt == TPP) { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute<TPP, CH, TG, true>(cw, s, tabA, tabB, act_s, dy_s, nt, acc); + } else { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute<TPP, CH, TG, false>(cw, s, tabA, tabB, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + tid] = acc[t]; + } +} +} // namespace xxs2 + +// ---- IQ2_XS: 74-B blocks; per row and step the qs u16 [16h, 16h + 16) (8 words), the scales [4h, 4h + 4) and d: +// 10 words, row stride 11, staged by lanes 0-9 / 16-25 of each warp (two rows per warp and k). The grid codes and +// ksigns' spread signs (q2 & 0x1FF, q2 >> 9) are tables generated from ggml's iq2xs_grid. +namespace xs2 { +constexpr int BB = 74, ROWB = NB * BB, CW = 10, CWS = 11, KR = NT / (2 * NW); + +__device__ const uint32_t kIq2xsCode[512] = { + 0x00000000u, 0x00000002u, 0x00000011u, 0x00000020u, 0x00000022u, 0x00000101u, 0x00000110u, 0x00000112u, + 0x00000121u, 0x00000200u, 0x00000202u, 0x00000211u, 0x00000220u, 0x00001001u, 0x00001010u, 0x00001012u, + 0x00001021u, 0x00001100u, 0x00001102u, 0x00001111u, 0x00001120u, 0x00001201u, 0x00001210u, 0x00002000u, + 0x00002002u, 0x00002011u, 0x00002020u, 0x00002101u, 0x00002110u, 0x00002121u, 0x00002200u, 0x00010001u, + 0x00010010u, 0x00010012u, 0x00010021u, 0x00010100u, 0x00010102u, 0x00010111u, 0x00010120u, 0x00010122u, + 0x00010201u, 0x00010210u, 0x00011000u, 0x00011002u, 0x00011011u, 0x00011020u, 0x00011101u, 0x00011110u, + 0x00011200u, 0x00011220u, 0x00012001u, 0x00012010u, 0x00012100u, 0x00020000u, 0x00020002u, 0x00020011u, + 0x00020020u, 0x00020101u, 0x00020110u, 0x00020200u, 0x00021001u, 0x00021010u, 0x00021100u, 0x00021111u, + 0x00022000u, 0x00022022u, 0x00100001u, 0x00100010u, 0x00100012u, 0x00100021u, 0x00100100u, 0x00100102u, + 0x00100111u, 0x00100120u, 0x00100201u, 0x00100210u, 0x00101000u, 0x00101002u, 0x00101011u, 0x00101020u, + 0x00101101u, 0x00101110u, 0x00101112u, 0x00101200u, 0x00102001u, 0x00102010u, 0x00102100u, 0x00110000u, + 0x00110002u, 0x00110011u, 0x00110020u, 0x00110101u, 0x00110110u, 0x00110200u, 0x00111001u, 0x00111010u, + 0x00111100u, 0x00111201u, 0x00112000u, 0x00120001u, 0x00120010u, 0x00120100u, 0x00120212u, 0x00121000u, + 0x00121002u, 0x00122010u, 0x00200000u, 0x00200002u, 0x00200011u, 0x00200020u, 0x00200022u, 0x00200101u, + 0x00200110u, 0x00200200u, 0x00200211u, 0x00201001u, 0x00201010u, 0x00201100u, 0x00201120u, 0x00202000u, + 0x00202200u, 0x00202222u, 0x00210001u, 0x00210010u, 0x00210100u, 0x00211000u, 0x00212001u, 0x00212021u, + 0x00220000u, 0x00220200u, 0x00220220u, 0x00222112u, 0x00222200u, 0x01000001u, 0x01000010u, 0x01000012u, + 0x01000021u, 0x01000100u, 0x01000102u, 0x01000111u, 0x01000120u, 0x01000201u, 0x01000210u, 0x01001000u, + 0x01001002u, 0x01001011u, 0x01001020u, 0x01001101u, 0x01001110u, 0x01001200u, 0x01001222u, 0x01002001u, + 0x01002010u, 0x01002100u, 0x01010000u, 0x01010002u, 0x01010011u, 0x01010020u, 0x01010101u, 0x01010110u, + 0x01010200u, 0x01011001u, 0x01011010u, 0x01011100u, 0x01012000u, 0x01012110u, 0x01012112u, 0x01020001u, + 0x01020010u, 0x01020012u, 0x01020100u, 0x01021000u, 0x01021200u, 0x01100000u, 0x01100002u, 0x01100011u, + 0x01100020u, 0x01100101u, 0x01100110u, 0x01100200u, 0x01101001u, 0x01101010u, 0x01101021u, 0x01101100u, + 0x01101210u, 0x01102000u, 0x01110001u, 0x01110010u, 0x01110100u, 0x01111000u, 0x01120000u, 0x01120110u, + 0x01121021u, 0x01200001u, 0x01200010u, 0x01200100u, 0x01200102u, 0x01201000u, 0x01201110u, 0x01202012u, + 0x01210000u, 0x01210011u, 0x01211212u, 0x01221101u, 0x01222221u, 0x02000000u, 0x02000002u, 0x02000011u, + 0x02000020u, 0x02000022u, 0x02000101u, 0x02000110u, 0x02000200u, 0x02001001u, 0x02001010u, 0x02001100u, + 0x02002000u, 0x02002200u, 0x02010001u, 0x02010010u, 0x02010100u, 0x02011000u, 0x02011020u, 0x02011211u, + 0x02020000u, 0x02020202u, 0x02022000u, 0x02022220u, 0x02100001u, 0x02100010u, 0x02100100u, 0x02100221u, + 0x02101000u, 0x02110000u, 0x02111001u, 0x02111102u, 0x02112121u, 0x02120001u, 0x02120122u, 0x02122212u, + 0x02200000u, 0x02200020u, 0x02200022u, 0x02200200u, 0x02201111u, 0x02202020u, 0x02202202u, 0x02211220u, + 0x02212100u, 0x02220020u, 0x02220200u, 0x02222002u, 0x02222020u, 0x02222022u, 0x10000001u, 0x10000010u, + 0x10000012u, 0x10000021u, 0x10000100u, 0x10000102u, 0x10000111u, 0x10000120u, 0x10000201u, 0x10000210u, + 0x10001000u, 0x10001002u, 0x10001011u, 0x10001020u, 0x10001022u, 0x10001101u, 0x10001110u, 0x10001200u, + 0x10001211u, 0x10002001u, 0x10002010u, 0x10002100u, 0x10010000u, 0x10010002u, 0x10010011u, 0x10010020u, + 0x10010101u, 0x10010110u, 0x10010200u, 0x10011001u, 0x10011010u, 0x10011100u, 0x10012000u, 0x10012011u, + 0x10012202u, 0x10020001u, 0x10020010u, 0x10020100u, 0x10020102u, 0x10020221u, 0x10021000u, 0x10100000u, + 0x10100002u, 0x10100011u, 0x10100020u, 0x10100101u, 0x10100110u, 0x10100121u, 0x10100200u, 0x10101001u, + 0x10101010u, 0x10101100u, 0x10102000u, 0x10102110u, 0x10110001u, 0x10110010u, 0x10110100u, 0x10110210u, + 0x10111000u, 0x10112122u, 0x10120000u, 0x10120022u, 0x10121010u, 0x10121100u, 0x10200001u, 0x10200010u, + 0x10200100u, 0x10201000u, 0x10201011u, 0x10201110u, 0x10201202u, 0x10210000u, 0x10210101u, 0x10211010u, + 0x10211100u, 0x10211221u, 0x10220010u, 0x11000000u, 0x11000002u, 0x11000011u, 0x11000020u, 0x11000101u, + 0x11000110u, 0x11000200u, 0x11000220u, 0x11001001u, 0x11001010u, 0x11001100u, 0x11002000u, 0x11010001u, + 0x11010010u, 0x11010100u, 0x11010111u, 0x11011000u, 0x11011002u, 0x11020000u, 0x11021010u, 0x11022222u, + 0x11100001u, 0x11100010u, 0x11100100u, 0x11100201u, 0x11101000u, 0x11101200u, 0x11102001u, 0x11102201u, + 0x11110000u, 0x11110020u, 0x11112000u, 0x11112020u, 0x11120201u, 0x11121220u, 0x11122201u, 0x11200000u, + 0x11200110u, 0x11201001u, 0x11201100u, 0x11202121u, 0x11210122u, 0x11211000u, 0x11211002u, 0x11222011u, + 0x12000001u, 0x12000010u, 0x12000100u, 0x12001000u, 0x12001110u, 0x12001202u, 0x12002012u, 0x12002221u, + 0x12010000u, 0x12020210u, 0x12021022u, 0x12022102u, 0x12100000u, 0x12100112u, 0x12110100u, 0x12111000u, + 0x12111011u, 0x12112210u, 0x12200001u, 0x12201222u, 0x12210211u, 0x12220012u, 0x12221110u, 0x12221202u, + 0x20000000u, 0x20000002u, 0x20000011u, 0x20000020u, 0x20000101u, 0x20000110u, 0x20000200u, 0x20000222u, + 0x20001001u, 0x20001010u, 0x20001100u, 0x20002000u, 0x20002002u, 0x20002220u, 0x20002222u, 0x20010001u, + 0x20010010u, 0x20010012u, 0x20010100u, 0x20011000u, 0x20011101u, 0x20011121u, 0x20020000u, 0x20020200u, + 0x20022000u, 0x20022002u, 0x20022200u, 0x20022220u, 0x20100001u, 0x20100010u, 0x20100100u, 0x20100102u, + 0x20100111u, 0x20101000u, 0x20101200u, 0x20102021u, 0x20110000u, 0x20111010u, 0x20112211u, 0x20120120u, + 0x20121222u, 0x20200000u, 0x20200020u, 0x20200211u, 0x20201122u, 0x20202000u, 0x20202002u, 0x20202220u, + 0x20210012u, 0x20220202u, 0x20222000u, 0x20222020u, 0x20222112u, 0x20222220u, 0x21000001u, 0x21000010u, + 0x21000100u, 0x21001000u, 0x21001112u, 0x21002010u, 0x21010000u, 0x21010202u, 0x21011210u, 0x21021112u, + 0x21022021u, 0x21100000u, 0x21100011u, 0x21101010u, 0x21101100u, 0x21101120u, 0x21110221u, 0x21112100u, + 0x21112102u, 0x21121001u, 0x21201101u, 0x21202212u, 0x21211021u, 0x21220111u, 0x21221200u, 0x22000000u, + 0x22000002u, 0x22000020u, 0x22000022u, 0x22000200u, 0x22000222u, 0x22002200u, 0x22011101u, 0x22011121u, + 0x22012212u, 0x22020000u, 0x22020002u, 0x22020020u, 0x22020222u, 0x22022000u, 0x22022200u, 0x22101000u, + 0x22102111u, 0x22121211u, 0x22122120u, 0x22200022u, 0x22200200u, 0x22200202u, 0x22200220u, 0x22202200u, + 0x22202220u, 0x22210010u, 0x22212010u, 0x22212012u, 0x22220220u, 0x22220222u, 0x22222101u, 0x22222222u, +}; +__device__ const uint32_t kIq2xsSign[128] = { + 0x00000000u, 0x40000004u, 0x40000040u, 0x00000044u, 0x40000400u, 0x00000404u, 0x00000440u, 0x40000444u, + 0x40004000u, 0x00004004u, 0x00004040u, 0x40004044u, 0x00004400u, 0x40004404u, 0x40004440u, 0x00004444u, + 0x40040000u, 0x00040004u, 0x00040040u, 0x40040044u, 0x00040400u, 0x40040404u, 0x40040440u, 0x00040444u, + 0x00044000u, 0x40044004u, 0x40044040u, 0x00044044u, 0x40044400u, 0x00044404u, 0x00044440u, 0x40044444u, + 0x40400000u, 0x00400004u, 0x00400040u, 0x40400044u, 0x00400400u, 0x40400404u, 0x40400440u, 0x00400444u, + 0x00404000u, 0x40404004u, 0x40404040u, 0x00404044u, 0x40404400u, 0x00404404u, 0x00404440u, 0x40404444u, + 0x00440000u, 0x40440004u, 0x40440040u, 0x00440044u, 0x40440400u, 0x00440404u, 0x00440440u, 0x40440444u, + 0x40444000u, 0x00444004u, 0x00444040u, 0x40444044u, 0x00444400u, 0x40444404u, 0x40444440u, 0x00444444u, + 0x44000000u, 0x04000004u, 0x04000040u, 0x44000044u, 0x04000400u, 0x44000404u, 0x44000440u, 0x04000444u, + 0x04004000u, 0x44004004u, 0x44004040u, 0x04004044u, 0x44004400u, 0x04004404u, 0x04004440u, 0x44004444u, + 0x04040000u, 0x44040004u, 0x44040040u, 0x04040044u, 0x44040400u, 0x04040404u, 0x04040440u, 0x44040444u, + 0x44044000u, 0x04044004u, 0x04044040u, 0x44044044u, 0x04044400u, 0x44044404u, 0x44044440u, 0x04044444u, + 0x04400000u, 0x44400004u, 0x44400040u, 0x04400044u, 0x44400400u, 0x04400404u, 0x04400440u, 0x44400444u, + 0x44404000u, 0x04404004u, 0x04404040u, 0x44404044u, 0x04404400u, 0x44404404u, 0x44404440u, 0x04404444u, + 0x44440000u, 0x04440004u, 0x04440040u, 0x44440044u, 0x04440400u, 0x44440404u, 0x44440440u, 0x04440444u, + 0x04444000u, 0x44444004u, 0x44444040u, 0x04444044u, 0x44444400u, 0x04444404u, 0x04444440u, 0x44444444u, +}; + +template <int TPP, int CVT, int TG> +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0, ""); + __shared__ uint32_t tabA_s[512]; + __shared__ uint32_t tabB_s[128]; + __shared__ __align__(16) int act_s[TPP][4][16]; // [token][sub-block][8 int8x4 words split to 16 int16 pairs] + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + for (int i = threadIdx.x; i < 512; i += NT) tabA_s[i] = kIq2xsCode[i]; + for (int i = threadIdx.x; i < 128; i += NT) tabB_s[i] = kIq2xsSign[i]; + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int ci = lane & 15, rsub = lane >> 4; // lanes 0-9 stage one row, 16-25 the next; ci = the compact word + const bool cact = ci < CW; + const char* __restrict__ Wr = w + xoff[c.j] + (size_t) (r0 + 2 * warp + rsub) * ROWB; // + k * 2 NW rows + int* __restrict__ wsl = wsm + (2 * warp + rsub) * CWS + ci; // + k * 2 NW * CWS + const int* cw = wsm + threadIdx.x * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + // compact word ci's byte offset inside the block: qs words (ci 0-7), scales (ci 8); d (ci 9) apart + const int boff = ci < 8 ? 2 + 32 * h + 4 * ci : 66 + 4 * h; + __syncthreads(); + if (cact) { + const char* blk0 = Wr + kc * BB; + if (kc & 1) { // odd block: words aligned, one load each; d = high half of the word at blk - 2 + const int o = ci < 9 ? boff : -2, sh = ci < 9 ? 0 : 16; + int v[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) v[k] = __ldg((const int*) (blk0 + (size_t) k * 2 * NW * ROWB + o)); +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v[k], v[k], sh); + } else { // even block: words 2 bytes into a word, two loads + funnel shift; d = low half at blk + const int o0 = ci < 9 ? boff - 2 : 0, o1 = ci < 9 ? boff + 2 : 0, sh = ci < 9 ? 16 : 0; + int v0[KR], v1[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) { + const char* b = blk0 + (size_t) k * 2 * NW * ROWB; + v0[k] = __ldg((const int*) (b + o0)); + v1[k] = __ldg((const int*) (b + o1)); + } +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v0[k], v1[k], sh); + } + } + stage_act<TPP>(xq, hc, total_rows, trow0, nt, act_s, dy_s); + __syncthreads(); +#pragma unroll 1 + for (int s = 0; s < 4; ++s) { // cw: [0..7] qs u16 pairs (sub-block s = words 2s, 2s+1), [8] scales, [9] d + int wv[16]; + float dx0, dx1; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint32_t q2 = ((uint32_t) cw[2 * s + (l >> 1)] >> (16 * (l & 1))) & 0xFFFFu; + const uint32_t sel = tabA_s[q2 & 0x1FFu] | tabB_s[q2 >> 9]; + split2((int) __byte_perm(PX, PY, sel), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) __byte_perm(PX, PY, sel >> 16), wv[4 * l + 2], wv[4 * l + 3]); + } + scales16((cw[8] >> (8 * s)) & 0xFF, cw[9], dx0, dx1); + mac16<TPP, CVT, TG>(wv, dx0, dx1, s, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace xs2 + +// ---- IQ2_S: 82-B blocks; per row and step the grid bytes qs[16h..] (4 words), the sign bytes qs[32 + 16h..] (4), +// qh[4h..4h + 3], scales[4h..4h + 3] and d: 11 words, row stride 11, staged by lanes 0-10 / 16-26 of each warp. The grid +// index is 10 bits (qs | qh bits), the sign byte is explicit: tables generated from ggml's iq2s_grid. +namespace s2 { +constexpr int BB = (int) sizeof(block_iq2_s), ROWB = NB * BB, CW = 11, CWS = 11, KR = NT / (2 * NW); +static_assert(BB == 82, "block_iq2_s"); + +__device__ const uint32_t kIq2sCode[1024] = { + 0x00000000u, 0x00000002u, 0x00000011u, 0x00000020u, 0x00000022u, 0x00000101u, 0x00000110u, 0x00000112u, + 0x00000121u, 0x00000200u, 0x00000202u, 0x00000211u, 0x00000220u, 0x00001001u, 0x00001010u, 0x00001012u, + 0x00001021u, 0x00001100u, 0x00001102u, 0x00001111u, 0x00001120u, 0x00001201u, 0x00001210u, 0x00001212u, + 0x00001221u, 0x00002000u, 0x00002002u, 0x00002011u, 0x00002020u, 0x00002101u, 0x00002110u, 0x00002200u, + 0x00002211u, 0x00002222u, 0x00010001u, 0x00010010u, 0x00010012u, 0x00010021u, 0x00010100u, 0x00010102u, + 0x00010111u, 0x00010120u, 0x00010201u, 0x00010210u, 0x00011000u, 0x00011002u, 0x00011011u, 0x00011020u, + 0x00011101u, 0x00011110u, 0x00011112u, 0x00011121u, 0x00011200u, 0x00011211u, 0x00011220u, 0x00012001u, + 0x00012010u, 0x00012100u, 0x00012102u, 0x00012111u, 0x00012201u, 0x00012210u, 0x00020000u, 0x00020002u, + 0x00020011u, 0x00020020u, 0x00020101u, 0x00020110u, 0x00020200u, 0x00020222u, 0x00021001u, 0x00021010u, + 0x00021012u, 0x00021021u, 0x00021100u, 0x00021111u, 0x00022000u, 0x00022011u, 0x00022022u, 0x00022110u, + 0x00022202u, 0x00100001u, 0x00100010u, 0x00100012u, 0x00100021u, 0x00100100u, 0x00100102u, 0x00100111u, + 0x00100120u, 0x00100201u, 0x00100210u, 0x00100212u, 0x00100221u, 0x00101000u, 0x00101002u, 0x00101011u, + 0x00101020u, 0x00101022u, 0x00101101u, 0x00101110u, 0x00101112u, 0x00101121u, 0x00101200u, 0x00101202u, + 0x00101211u, 0x00102001u, 0x00102010u, 0x00102012u, 0x00102021u, 0x00102100u, 0x00102111u, 0x00102120u, + 0x00102201u, 0x00102210u, 0x00110000u, 0x00110002u, 0x00110011u, 0x00110020u, 0x00110022u, 0x00110101u, + 0x00110110u, 0x00110112u, 0x00110121u, 0x00110200u, 0x00110211u, 0x00110220u, 0x00111001u, 0x00111010u, + 0x00111012u, 0x00111021u, 0x00111100u, 0x00111102u, 0x00111111u, 0x00111120u, 0x00111201u, 0x00111210u, + 0x00112000u, 0x00112002u, 0x00112011u, 0x00112020u, 0x00112101u, 0x00112110u, 0x00112200u, 0x00120001u, + 0x00120010u, 0x00120012u, 0x00120021u, 0x00120100u, 0x00120111u, 0x00121000u, 0x00121011u, 0x00121020u, + 0x00121101u, 0x00121110u, 0x00121200u, 0x00122001u, 0x00122010u, 0x00122100u, 0x00200000u, 0x00200002u, + 0x00200011u, 0x00200020u, 0x00200101u, 0x00200110u, 0x00200112u, 0x00200121u, 0x00200200u, 0x00200211u, + 0x00200222u, 0x00201001u, 0x00201010u, 0x00201012u, 0x00201021u, 0x00201100u, 0x00201102u, 0x00201111u, + 0x00201120u, 0x00201201u, 0x00201210u, 0x00202000u, 0x00202011u, 0x00202110u, 0x00202222u, 0x00210001u, + 0x00210010u, 0x00210100u, 0x00210102u, 0x00210111u, 0x00210120u, 0x00210201u, 0x00211000u, 0x00211011u, + 0x00211020u, 0x00211101u, 0x00211110u, 0x00211200u, 0x00212001u, 0x00212100u, 0x00220000u, 0x00220101u, + 0x00220110u, 0x00220202u, 0x00220220u, 0x00220222u, 0x00221100u, 0x00222121u, 0x01000001u, 0x01000010u, + 0x01000012u, 0x01000021u, 0x01000100u, 0x01000102u, 0x01000111u, 0x01000120u, 0x01000201u, 0x01000210u, + 0x01000212u, 0x01001000u, 0x01001002u, 0x01001011u, 0x01001020u, 0x01001101u, 0x01001110u, 0x01001112u, + 0x01001121u, 0x01001200u, 0x01001202u, 0x01001211u, 0x01001220u, 0x01002001u, 0x01002010u, 0x01002012u, + 0x01002100u, 0x01002111u, 0x01002120u, 0x01002201u, 0x01002210u, 0x01010000u, 0x01010002u, 0x01010011u, + 0x01010020u, 0x01010022u, 0x01010101u, 0x01010110u, 0x01010112u, 0x01010121u, 0x01010200u, 0x01010202u, + 0x01010211u, 0x01010220u, 0x01011001u, 0x01011010u, 0x01011012u, 0x01011021u, 0x01011100u, 0x01011102u, + 0x01011111u, 0x01011120u, 0x01011201u, 0x01011210u, 0x01012000u, 0x01012002u, 0x01012011u, 0x01012020u, + 0x01012101u, 0x01012110u, 0x01020001u, 0x01020010u, 0x01020021u, 0x01020100u, 0x01020111u, 0x01020201u, + 0x01020210u, 0x01021000u, 0x01021011u, 0x01021101u, 0x01021110u, 0x01022001u, 0x01022010u, 0x01022100u, + 0x01100000u, 0x01100002u, 0x01100011u, 0x01100020u, 0x01100101u, 0x01100110u, 0x01100112u, 0x01100121u, + 0x01100200u, 0x01100211u, 0x01100220u, 0x01101001u, 0x01101010u, 0x01101012u, 0x01101021u, 0x01101100u, + 0x01101102u, 0x01101111u, 0x01101120u, 0x01101201u, 0x01101210u, 0x01102000u, 0x01102002u, 0x01102011u, + 0x01102020u, 0x01102101u, 0x01102110u, 0x01102200u, 0x01110001u, 0x01110010u, 0x01110012u, 0x01110021u, + 0x01110100u, 0x01110102u, 0x01110111u, 0x01110120u, 0x01110201u, 0x01110210u, 0x01111000u, 0x01111002u, + 0x01111011u, 0x01111020u, 0x01111101u, 0x01111110u, 0x01111200u, 0x01112001u, 0x01112010u, 0x01112100u, + 0x01120000u, 0x01120011u, 0x01120020u, 0x01120101u, 0x01120110u, 0x01120200u, 0x01121001u, 0x01121010u, + 0x01121100u, 0x01122000u, 0x01122222u, 0x01200001u, 0x01200010u, 0x01200012u, 0x01200021u, 0x01200100u, + 0x01200111u, 0x01200120u, 0x01200201u, 0x01201000u, 0x01201002u, 0x01201011u, 0x01201020u, 0x01201101u, + 0x01201110u, 0x01201200u, 0x01202001u, 0x01202010u, 0x01210000u, 0x01210002u, 0x01210011u, 0x01210020u, + 0x01210101u, 0x01210110u, 0x01210200u, 0x01211001u, 0x01211010u, 0x01211100u, 0x01211221u, 0x01212202u, + 0x01220010u, 0x01220100u, 0x01221000u, 0x01221112u, 0x02000000u, 0x02000002u, 0x02000011u, 0x02000020u, + 0x02000101u, 0x02000110u, 0x02000112u, 0x02000121u, 0x02000200u, 0x02000211u, 0x02000222u, 0x02001001u, + 0x02001010u, 0x02001100u, 0x02001102u, 0x02001111u, 0x02001210u, 0x02002000u, 0x02002022u, 0x02002110u, + 0x02002222u, 0x02010001u, 0x02010010u, 0x02010100u, 0x02010102u, 0x02010111u, 0x02010201u, 0x02011000u, + 0x02011002u, 0x02011011u, 0x02011101u, 0x02011110u, 0x02011200u, 0x02012001u, 0x02012010u, 0x02012100u, + 0x02020000u, 0x02020022u, 0x02020202u, 0x02020220u, 0x02020222u, 0x02021010u, 0x02021100u, 0x02022020u, + 0x02022022u, 0x02022220u, 0x02100001u, 0x02100010u, 0x02100012u, 0x02100021u, 0x02100100u, 0x02100111u, + 0x02100120u, 0x02100201u, 0x02100210u, 0x02101000u, 0x02101002u, 0x02101011u, 0x02101020u, 0x02101101u, + 0x02101110u, 0x02101200u, 0x02102001u, 0x02102010u, 0x02102100u, 0x02110000u, 0x02110011u, 0x02110020u, + 0x02110101u, 0x02110110u, 0x02110200u, 0x02111001u, 0x02111010u, 0x02111100u, 0x02111212u, 0x02112000u, + 0x02120001u, 0x02120010u, 0x02120100u, 0x02121000u, 0x02121121u, 0x02200000u, 0x02200011u, 0x02200101u, + 0x02200110u, 0x02201001u, 0x02201010u, 0x02201100u, 0x02202022u, 0x02202222u, 0x02210001u, 0x02210010u, + 0x02210100u, 0x02212111u, 0x02220022u, 0x02220202u, 0x02221210u, 0x02222020u, 0x02222022u, 0x10000001u, + 0x10000010u, 0x10000012u, 0x10000021u, 0x10000100u, 0x10000102u, 0x10000111u, 0x10000120u, 0x10000122u, + 0x10000201u, 0x10000210u, 0x10000212u, 0x10001000u, 0x10001002u, 0x10001011u, 0x10001020u, 0x10001022u, + 0x10001101u, 0x10001110u, 0x10001112u, 0x10001121u, 0x10001200u, 0x10001202u, 0x10001211u, 0x10002001u, + 0x10002010u, 0x10002100u, 0x10002111u, 0x10002120u, 0x10002201u, 0x10002210u, 0x10010000u, 0x10010002u, + 0x10010011u, 0x10010020u, 0x10010101u, 0x10010110u, 0x10010112u, 0x10010121u, 0x10010200u, 0x10010202u, + 0x10010211u, 0x10011001u, 0x10011010u, 0x10011012u, 0x10011021u, 0x10011100u, 0x10011102u, 0x10011111u, + 0x10011120u, 0x10011201u, 0x10011210u, 0x10012000u, 0x10012002u, 0x10012011u, 0x10012020u, 0x10012101u, + 0x10012110u, 0x10012200u, 0x10020001u, 0x10020010u, 0x10020100u, 0x10020102u, 0x10020111u, 0x10020120u, + 0x10020210u, 0x10021000u, 0x10021011u, 0x10021020u, 0x10021101u, 0x10021110u, 0x10021200u, 0x10022001u, + 0x10022010u, 0x10100000u, 0x10100002u, 0x10100011u, 0x10100020u, 0x10100022u, 0x10100101u, 0x10100110u, + 0x10100112u, 0x10100121u, 0x10100200u, 0x10100202u, 0x10100211u, 0x10100220u, 0x10101001u, 0x10101010u, + 0x10101012u, 0x10101021u, 0x10101100u, 0x10101102u, 0x10101111u, 0x10101120u, 0x10101201u, 0x10101210u, + 0x10102000u, 0x10102002u, 0x10102011u, 0x10102020u, 0x10102101u, 0x10102110u, 0x10102200u, 0x10110001u, + 0x10110010u, 0x10110012u, 0x10110021u, 0x10110100u, 0x10110102u, 0x10110111u, 0x10110120u, 0x10110201u, + 0x10110210u, 0x10111000u, 0x10111002u, 0x10111011u, 0x10111020u, 0x10111101u, 0x10111110u, 0x10111200u, + 0x10111222u, 0x10112001u, 0x10112010u, 0x10112100u, 0x10120000u, 0x10120002u, 0x10120011u, 0x10120020u, + 0x10120101u, 0x10120110u, 0x10120200u, 0x10121001u, 0x10121010u, 0x10121100u, 0x10122000u, 0x10122211u, + 0x10200001u, 0x10200010u, 0x10200021u, 0x10200100u, 0x10200102u, 0x10200111u, 0x10200120u, 0x10200201u, + 0x10200210u, 0x10201000u, 0x10201002u, 0x10201011u, 0x10201020u, 0x10201101u, 0x10201110u, 0x10201200u, + 0x10202010u, 0x10202100u, 0x10210000u, 0x10210002u, 0x10210011u, 0x10210020u, 0x10210101u, 0x10210110u, + 0x10210200u, 0x10211001u, 0x10211010u, 0x10211100u, 0x10212000u, 0x10212112u, 0x10220001u, 0x10220010u, + 0x10220100u, 0x10221000u, 0x11000000u, 0x11000002u, 0x11000011u, 0x11000020u, 0x11000101u, 0x11000110u, + 0x11000112u, 0x11000121u, 0x11000200u, 0x11000202u, 0x11000211u, 0x11000220u, 0x11001001u, 0x11001010u, + 0x11001012u, 0x11001021u, 0x11001100u, 0x11001102u, 0x11001111u, 0x11001120u, 0x11001201u, 0x11001210u, + 0x11002000u, 0x11002002u, 0x11002011u, 0x11002020u, 0x11002101u, 0x11002110u, 0x11010001u, 0x11010010u, + 0x11010012u, 0x11010021u, 0x11010100u, 0x11010102u, 0x11010111u, 0x11010120u, 0x11010201u, 0x11010210u, + 0x11011000u, 0x11011002u, 0x11011011u, 0x11011020u, 0x11011101u, 0x11011110u, 0x11011200u, 0x11012001u, + 0x11012010u, 0x11012100u, 0x11020000u, 0x11020011u, 0x11020020u, 0x11020101u, 0x11020110u, 0x11020200u, + 0x11021001u, 0x11021010u, 0x11021100u, 0x11021221u, 0x11022000u, 0x11100001u, 0x11100010u, 0x11100012u, + 0x11100021u, 0x11100100u, 0x11100102u, 0x11100111u, 0x11100120u, 0x11100201u, 0x11100210u, 0x11101000u, + 0x11101002u, 0x11101011u, 0x11101020u, 0x11101101u, 0x11101110u, 0x11101200u, 0x11102001u, 0x11102010u, + 0x11102100u, 0x11110000u, 0x11110002u, 0x11110011u, 0x11110020u, 0x11110101u, 0x11110110u, 0x11110200u, + 0x11111001u, 0x11111010u, 0x11111100u, 0x11112000u, 0x11120001u, 0x11120010u, 0x11120100u, 0x11120212u, + 0x11121000u, 0x11200000u, 0x11200002u, 0x11200011u, 0x11200020u, 0x11200101u, 0x11200110u, 0x11200200u, + 0x11201001u, 0x11201010u, 0x11201100u, 0x11201122u, 0x11202000u, 0x11210001u, 0x11210010u, 0x11210100u, + 0x11211000u, 0x11220000u, 0x11220121u, 0x11222011u, 0x11222220u, 0x12000001u, 0x12000010u, 0x12000012u, + 0x12000100u, 0x12000102u, 0x12000111u, 0x12000120u, 0x12000201u, 0x12000210u, 0x12001000u, 0x12001011u, + 0x12001020u, 0x12001101u, 0x12001110u, 0x12001200u, 0x12002010u, 0x12002100u, 0x12010000u, 0x12010002u, + 0x12010011u, 0x12010020u, 0x12010101u, 0x12010110u, 0x12010200u, 0x12011001u, 0x12011010u, 0x12011100u, + 0x12012000u, 0x12012121u, 0x12020010u, 0x12020100u, 0x12021000u, 0x12021112u, 0x12022201u, 0x12100000u, + 0x12100011u, 0x12100020u, 0x12100101u, 0x12100110u, 0x12100200u, 0x12101001u, 0x12101010u, 0x12101100u, + 0x12102000u, 0x12110001u, 0x12110010u, 0x12110100u, 0x12111000u, 0x12111022u, 0x12111220u, 0x12112102u, + 0x12120000u, 0x12122110u, 0x12200001u, 0x12200010u, 0x12200100u, 0x12201211u, 0x12202120u, 0x12210000u, + 0x12210222u, 0x12221002u, 0x12222201u, 0x20000000u, 0x20000002u, 0x20000011u, 0x20000020u, 0x20000101u, + 0x20000110u, 0x20000121u, 0x20000200u, 0x20000211u, 0x20001001u, 0x20001010u, 0x20001100u, 0x20001102u, + 0x20001111u, 0x20001120u, 0x20001201u, 0x20002000u, 0x20002011u, 0x20002101u, 0x20002110u, 0x20010001u, + 0x20010010u, 0x20010021u, 0x20010100u, 0x20010102u, 0x20010111u, 0x20010120u, 0x20010201u, 0x20010210u, + 0x20011000u, 0x20011002u, 0x20011011u, 0x20011020u, 0x20011101u, 0x20011110u, 0x20012001u, 0x20012010u, + 0x20012100u, 0x20012221u, 0x20020000u, 0x20020011u, 0x20020022u, 0x20020101u, 0x20020110u, 0x20021001u, + 0x20021010u, 0x20021100u, 0x20100001u, 0x20100010u, 0x20100012u, 0x20100021u, 0x20100100u, 0x20100102u, + 0x20100111u, 0x20100120u, 0x20100201u, 0x20101000u, 0x20101002u, 0x20101011u, 0x20101020u, 0x20101101u, + 0x20101110u, 0x20101200u, 0x20102001u, 0x20102010u, 0x20102100u, 0x20110000u, 0x20110002u, 0x20110011u, + 0x20110020u, 0x20110101u, 0x20110110u, 0x20110200u, 0x20111001u, 0x20111010u, 0x20111100u, 0x20112000u, + 0x20112022u, 0x20120001u, 0x20120010u, 0x20120100u, 0x20120221u, 0x20121000u, 0x20200000u, 0x20200011u, + 0x20200101u, 0x20200110u, 0x20201001u, 0x20201010u, 0x20201100u, 0x20202202u, 0x20210001u, 0x20210010u, + 0x20211000u, 0x20211211u, 0x20220202u, 0x20221120u, 0x20221122u, 0x20222002u, 0x20222202u, 0x21000001u, + 0x21000010u, 0x21000021u, 0x21000100u, 0x21000102u, 0x21000111u, 0x21000120u, 0x21000210u, 0x21001000u, + 0x21001002u, 0x21001011u, 0x21001020u, 0x21001101u, 0x21001110u, 0x21001200u, 0x21002001u, 0x21002010u, + 0x21002100u, 0x21010000u, 0x21010011u, 0x21010101u, 0x21010110u, 0x21011001u, 0x21011010u, 0x21011100u, + 0x21011122u, 0x21020001u, 0x21020010u, 0x21020100u, 0x21021000u, 0x21022212u, 0x21100000u, 0x21100002u, + 0x21100011u, 0x21100020u, 0x21100101u, 0x21100110u, 0x21100200u, 0x21101001u, 0x21101010u, 0x21101100u, + 0x21102000u, 0x21102112u, 0x21110001u, 0x21110010u, 0x21110100u, 0x21111000u, 0x21112120u, 0x21112201u, + 0x21120000u, 0x21121012u, 0x21121210u, 0x21200001u, 0x21200010u, 0x21200100u, 0x21200212u, 0x21201000u, + 0x21202221u, 0x21210000u, 0x21211021u, 0x21211102u, 0x21222100u, 0x22000000u, 0x22000011u, 0x22000022u, + 0x22000110u, 0x22000202u, 0x22000222u, 0x22001001u, 0x22001010u, 0x22001100u, 0x22002202u, 0x22002222u, + 0x22011000u, 0x22011211u, 0x22020002u, 0x22020022u, 0x22020202u, 0x22020220u, 0x22020222u, 0x22022002u, + 0x22022020u, 0x22022022u, 0x22022220u, 0x22100001u, 0x22100010u, 0x22100100u, 0x22101000u, 0x22102021u, + 0x22102210u, 0x22110000u, 0x22110121u, 0x22121101u, 0x22200022u, 0x22200220u, 0x22202202u, 0x22211110u, + 0x22212012u, 0x22220020u, 0x22220022u, 0x22220200u, 0x22220202u, 0x22220220u, 0x22222020u, 0x22222222u, +}; +__device__ const uint32_t kIq2sSign[256] = { + 0x00000000u, 0x00000004u, 0x00000040u, 0x00000044u, 0x00000400u, 0x00000404u, 0x00000440u, 0x00000444u, + 0x00004000u, 0x00004004u, 0x00004040u, 0x00004044u, 0x00004400u, 0x00004404u, 0x00004440u, 0x00004444u, + 0x00040000u, 0x00040004u, 0x00040040u, 0x00040044u, 0x00040400u, 0x00040404u, 0x00040440u, 0x00040444u, + 0x00044000u, 0x00044004u, 0x00044040u, 0x00044044u, 0x00044400u, 0x00044404u, 0x00044440u, 0x00044444u, + 0x00400000u, 0x00400004u, 0x00400040u, 0x00400044u, 0x00400400u, 0x00400404u, 0x00400440u, 0x00400444u, + 0x00404000u, 0x00404004u, 0x00404040u, 0x00404044u, 0x00404400u, 0x00404404u, 0x00404440u, 0x00404444u, + 0x00440000u, 0x00440004u, 0x00440040u, 0x00440044u, 0x00440400u, 0x00440404u, 0x00440440u, 0x00440444u, + 0x00444000u, 0x00444004u, 0x00444040u, 0x00444044u, 0x00444400u, 0x00444404u, 0x00444440u, 0x00444444u, + 0x04000000u, 0x04000004u, 0x04000040u, 0x04000044u, 0x04000400u, 0x04000404u, 0x04000440u, 0x04000444u, + 0x04004000u, 0x04004004u, 0x04004040u, 0x04004044u, 0x04004400u, 0x04004404u, 0x04004440u, 0x04004444u, + 0x04040000u, 0x04040004u, 0x04040040u, 0x04040044u, 0x04040400u, 0x04040404u, 0x04040440u, 0x04040444u, + 0x04044000u, 0x04044004u, 0x04044040u, 0x04044044u, 0x04044400u, 0x04044404u, 0x04044440u, 0x04044444u, + 0x04400000u, 0x04400004u, 0x04400040u, 0x04400044u, 0x04400400u, 0x04400404u, 0x04400440u, 0x04400444u, + 0x04404000u, 0x04404004u, 0x04404040u, 0x04404044u, 0x04404400u, 0x04404404u, 0x04404440u, 0x04404444u, + 0x04440000u, 0x04440004u, 0x04440040u, 0x04440044u, 0x04440400u, 0x04440404u, 0x04440440u, 0x04440444u, + 0x04444000u, 0x04444004u, 0x04444040u, 0x04444044u, 0x04444400u, 0x04444404u, 0x04444440u, 0x04444444u, + 0x40000000u, 0x40000004u, 0x40000040u, 0x40000044u, 0x40000400u, 0x40000404u, 0x40000440u, 0x40000444u, + 0x40004000u, 0x40004004u, 0x40004040u, 0x40004044u, 0x40004400u, 0x40004404u, 0x40004440u, 0x40004444u, + 0x40040000u, 0x40040004u, 0x40040040u, 0x40040044u, 0x40040400u, 0x40040404u, 0x40040440u, 0x40040444u, + 0x40044000u, 0x40044004u, 0x40044040u, 0x40044044u, 0x40044400u, 0x40044404u, 0x40044440u, 0x40044444u, + 0x40400000u, 0x40400004u, 0x40400040u, 0x40400044u, 0x40400400u, 0x40400404u, 0x40400440u, 0x40400444u, + 0x40404000u, 0x40404004u, 0x40404040u, 0x40404044u, 0x40404400u, 0x40404404u, 0x40404440u, 0x40404444u, + 0x40440000u, 0x40440004u, 0x40440040u, 0x40440044u, 0x40440400u, 0x40440404u, 0x40440440u, 0x40440444u, + 0x40444000u, 0x40444004u, 0x40444040u, 0x40444044u, 0x40444400u, 0x40444404u, 0x40444440u, 0x40444444u, + 0x44000000u, 0x44000004u, 0x44000040u, 0x44000044u, 0x44000400u, 0x44000404u, 0x44000440u, 0x44000444u, + 0x44004000u, 0x44004004u, 0x44004040u, 0x44004044u, 0x44004400u, 0x44004404u, 0x44004440u, 0x44004444u, + 0x44040000u, 0x44040004u, 0x44040040u, 0x44040044u, 0x44040400u, 0x44040404u, 0x44040440u, 0x44040444u, + 0x44044000u, 0x44044004u, 0x44044040u, 0x44044044u, 0x44044400u, 0x44044404u, 0x44044440u, 0x44044444u, + 0x44400000u, 0x44400004u, 0x44400040u, 0x44400044u, 0x44400400u, 0x44400404u, 0x44400440u, 0x44400444u, + 0x44404000u, 0x44404004u, 0x44404040u, 0x44404044u, 0x44404400u, 0x44404404u, 0x44404440u, 0x44404444u, + 0x44440000u, 0x44440004u, 0x44440040u, 0x44440044u, 0x44440400u, 0x44440404u, 0x44440440u, 0x44440444u, + 0x44444000u, 0x44444004u, 0x44444040u, 0x44444044u, 0x44444400u, 0x44444404u, 0x44444440u, 0x44444444u, +}; + +template <int TPP, int CVT, int TG> +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0, ""); + __shared__ __align__(16) uint32_t tabA_s[1024]; + __shared__ __align__(16) uint32_t tabB_s[256]; + __shared__ __align__(16) int act_s[TPP][4][16]; + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + for (int i = threadIdx.x; i < 1024; i += NT) tabA_s[i] = kIq2sCode[i]; + for (int i = threadIdx.x; i < 256; i += NT) tabB_s[i] = kIq2sSign[i]; + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int ci = lane & 15, rsub = lane >> 4; // lanes 0-10 stage one row, 16-26 the next; ci = the compact word + const bool cact = ci < CW; + const char* __restrict__ Wr = w + xoff[c.j] + (size_t) (r0 + 2 * warp + rsub) * ROWB; // + k * 2 NW rows + int* __restrict__ wsl = wsm + (2 * warp + rsub) * CWS + ci; // + k * 2 NW * CWS + const int* cw = wsm + threadIdx.x * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + // compact word ci's byte offset inside the block (ci 0-9); d (ci 10) sits at +0 + const int boff = ci < 4 ? 2 + 16 * h + 4 * ci : ci < 8 ? 18 + 16 * h + 4 * ci : ci == 8 ? 66 + 4 * h : 74 + 4 * h; + __syncthreads(); + if (cact) { + const char* blk0 = Wr + kc * BB; + if (kc & 1) { // odd block: words aligned, one load each; d = high half of the word at blk - 2 + const int o = ci < 10 ? boff : -2, sh = ci < 10 ? 0 : 16; + int v[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) v[k] = __ldg((const int*) (blk0 + (size_t) k * 2 * NW * ROWB + o)); +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v[k], v[k], sh); + } else { // even block: words 2 bytes into a word, two loads + funnel shift; d = low half at blk + const int o0 = ci < 10 ? boff - 2 : 0, o1 = ci < 10 ? boff + 2 : 0, sh = ci < 10 ? 16 : 0; + int v0[KR], v1[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) { + const char* b = blk0 + (size_t) k * 2 * NW * ROWB; + v0[k] = __ldg((const int*) (b + o0)); + v1[k] = __ldg((const int*) (b + o1)); + } +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v0[k], v1[k], sh); + } + } + stage_act<TPP>(xq, hc, total_rows, trow0, nt, act_s, dy_s); + __syncthreads(); +#pragma unroll 1 + for (int s = 0; s < 4; ++s) { // cw: [0..3] grid bytes, [4..7] sign bytes, [8] qh, [9] scales, [10] d + int wv[16]; + float dx0, dx1; + const int qs_packed = cw[s], signs_packed_32 = cw[4 + s], qh = (cw[8] >> (8 * s)) & 0xFF; +#pragma unroll + for (int l = 0; l < QR2_S; ++l) { + const int idx = ((qs_packed >> (8 * l)) & 0xFF) | ((qh << (8 - 2 * l)) & 0x300); + const uint32_t sel = tabA_s[idx] | tabB_s[(signs_packed_32 >> (8 * l)) & 0xFF]; + split2((int) __byte_perm(PX, PY, sel), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) __byte_perm(PX, PY, sel >> 16), wv[4 * l + 2], wv[4 * l + 3]); + } + scales16((cw[9] >> (8 * s)) & 0xFF, cw[10], dx0, dx1); + mac16<TPP, CVT, TG>(wv, dx0, dx1, s, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace s2 + +template <typename F> +void go(F kernel, const Layer& L, cudaStream_t s) { + kernel<<<(unsigned) (L.nchunks * PIECES), NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, (const block_q8_1_mmq*) L.xq, + (int) L.rows, L.gu); +} + +} // namespace + +// tokens per pass by u (the measured crossovers): IQ2_XXS 8 below 5 rows per expert, 16 below 25, then 32 (4-token +// groups); IQ2_XS 8 below 6, 16 below 20, then 16 in 4-token groups; IQ2_S 8 below 5, 16 below 25, then 32 +void gu_iq2_xxs(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 5.0) go(xxs2::gu_kernel<8, 3, 2>, L, s); + else if (u < 25.0) go(xxs2::gu_kernel<16, 3, 2>, L, s); + else go(xxs2::gu_kernel<32, 2, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ2_XXS"); +} + +void gu_iq2_xs(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 6.0) go(xs2::gu_kernel<8, 1, 2>, L, s); + else if (u < 20.0) go(xs2::gu_kernel<16, 0, 2>, L, s); + else go(xs2::gu_kernel<16, 1, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ2_XS"); +} + +void gu_iq2_s(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 5.0) go(s2::gu_kernel<8, 0, 2>, L, s); + else if (u < 25.0) go(s2::gu_kernel<16, 1, 2>, L, s); + else go(s2::gu_kernel<32, 1, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ2_S"); +} + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/moe_ws_gu_iq3.cu b/src/prefill/moe_ws_gu_iq3.cu new file mode 100644 index 00000000..efd551dc --- /dev/null +++ b/src/prefill/moe_ws_gu_iq3.cu @@ -0,0 +1,370 @@ +// src/prefill/moe_ws_gu_iq3.cu - weight-stationary gate/up products (see moe_ws.hpp): IQ3_XXS and IQ3_S, [1280 x 2560] +// read in place. A CTA = 128 threads = 128 weight rows of one expert (a row per thread, all of the chunk's activation +// rows TPP at a time, the sums in registers); K advances 128 values a step (half a 256-value block = 4 sub-blocks): +// the step's bytes of the 128 rows and the step's q8_1 block of each token go to shared memory (the activations split +// to int16 pairs once), then each thread decodes its row's 4 sub-blocks once per pass and runs them against the tokens. +// Bits: per 32-value sub-block MMQ's int8 values (ggml_cuda_mmq_load_tiles_iq3_*: grid entries, its __vcmpne4 sign +// masks applied as (g ^ s) + (s & 0x01010101) == __vsub4(g ^ s, s), every grid byte >= 1) and scale expression, then +// MMQ's epilogue acc = fma(dx * dy, float(sum), acc), sub-blocks in K order. (Measured on a GP100 die: +// ws / per-group MMQ 0.31-0.35 at 2.5 rows per expert, 0.49-0.52 at 10, 0.67-0.76 at 35, +// 0.78-0.79 at 160; bit-identical, compute-sanitizer clean with exact-size matrices.) +// +// Staging without per-lane branches: rows are 980 / 1100 B, so block kc starts 2 * (kc & 1) bytes into a 4-byte word +// for the whole CTA - an even block's words are two aligned loads and a funnel shift (the second load ends at most 2 +// bytes into block kc + 1 of the same row), an odd block's are aligned; d sits the other way round (an odd block's d is +// the high half of the word 2 bytes before it, inside block kc - 1). Every load of a lane is issued before its stores, +// and nothing outside a row is read (the last row's last block is odd). +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include <cstdio> +#include <cstdlib> + +namespace strata::prefill::ws::detail { +namespace { + +constexpr int GU_ROWS = 1280, GU_K = 2560, NB = GU_K / QK_K, NSTEP = 2 * NB, NT = 128, PIECES = GU_ROWS / NT; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// ---- IQ3_XXS: 98-B blocks; per row and step 8 grid-index words, 4 aux words (signs + scale) and d (stride 13). +// Every lane slot is one word type: grid words rows tid/8 + 16 i (word tid%8), aux words rows tid/4 + 32 i (word +// tid%4), d the thread's own row. Token groups of TG: one branch per group on a partial pass (a group's tokens past +// the count run on copies of row nt - 1 and are not written), none on a full pass. +namespace xxs3 { +constexpr int BB = (int) sizeof(block_iq3_xxs), ROWB = NB * BB, CWS = 13; +static_assert(BB == 98 && ROWB % 4 == 0, "block_iq3_xxs"); + +template <int TPP, int CH, int TG, bool FULL> +__device__ __forceinline__ void sb_compute(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ grid, + const int2* __restrict__ lut, const int (*act_s)[4][16], + const float (*dy_s)[4], const int nt, float (&acc)[TPP]) { + int wv[16]; + float dx; + { + const uint32_t qa = (uint32_t) cw[2 * s + 0], qb = (uint32_t) cw[2 * s + 1]; // 8 grid indices + const uint32_t aux32 = (uint32_t) cw[8 + s]; +#pragma unroll + for (int l = 0; l < QR3_XXS; ++l) { + const uint32_t qw = l < 2 ? qa : qb; + const uint32_t g0 = grid[(qw >> (16 * (l & 1))) & 0xFF], g1 = grid[(qw >> (16 * (l & 1) + 8)) & 0xFF]; + const int2 sg = lut[(aux32 >> (7 * l)) & 0x7F]; + split2((int) ((g0 ^ (uint32_t) sg.x) + ((uint32_t) sg.x & 0x01010101u)), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) ((g1 ^ (uint32_t) sg.y) + ((uint32_t) sg.y & 0x01010101u)), wv[4 * l + 2], wv[4 * l + 3]); + } + const int ls = aux32 >> 28; + const float d = __ushort_as_half((unsigned short) (cw[12] & 0xFFFF)); + dx = (ls*d + d/2)/2; // MMQ's expression, verbatim + } +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (FULL || t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const int a[16] = {a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w, a2.x, a2.y, a2.z, a2.w, a3.x, a3.y, a3.z, a3.w}; + const float dy = dy_s[t][s]; + int sc[CH]; + sc[0] = kMagicI; +#pragma unroll + for (int c = 1; c < CH; ++c) sc[c] = 0; +#pragma unroll + for (int m = 0; m < 16; ++m) sc[m % CH] = mad2(wv[m], a[m], sc[m % CH]); + int sum = sc[0]; +#pragma unroll + for (int c = 1; c < CH; ++c) sum += sc[c]; + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __fsub_rn(__int_as_float(sum), kMagicF), acc[t]); + } + } + } +} + +template <int TPP, int CH, int TG> +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0 && (TPP * 32) % NT == 0 && TPP * 4 <= NT, ""); + constexpr int NG = 8, RG = NT / 8; // grid-index-word slots: rows tid/8 + i*RG, word tid%8 + constexpr int NX = 4, RX = NT / 4; // aux-word slots: rows tid/4 + i*RX, word tid%4 + constexpr int NA = TPP * 32 / NT; + __shared__ uint32_t grid_s[256]; + __shared__ int2 lut_s[128]; + __shared__ __align__(16) int act_s[TPP][4][16]; + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + const int tid = threadIdx.x; + for (int i = tid; i < 256; i += NT) grid_s[i] = iq3xxs_grid[i]; + for (int i = tid; i < 128; i += NT) { + const uint32_t signs = unpack_ksigns((uint8_t) i); + lut_s[i] = make_int2(__vcmpne4(signs & 0x08040201, 0), __vcmpne4(signs & 0x80402010, 0)); + } + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const char* __restrict__ W = w + xoff[c.j] + (size_t) r0 * ROWB; + const char* __restrict__ Wg = W + (size_t) (tid >> 3) * ROWB + 4 * (tid & 7); // + i*RG*ROWB + kc*BB + 32h + const char* __restrict__ Wx = W + (size_t) (tid >> 2) * ROWB + 64 + 4 * (tid & 3); // + i*RX*ROWB + kc*BB + 16h + const char* __restrict__ Wd = W + (size_t) tid * ROWB; + int* __restrict__ sg_ = wsm + (tid >> 3) * CWS + (tid & 7); + int* __restrict__ sx_ = wsm + (tid >> 2) * CWS + 8 + (tid & 3); + int* __restrict__ sd_ = wsm + tid * CWS + 12; + const int* cw = wsm + tid * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); + __syncthreads(); + int av[NA], dv = 0; +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5; + av[i] = __ldg(xr + min(t, nt - 1) * 36 + 4 + (idx & 31)); // clamped: no branch, never past row nt-1 + } + if (TPP * 4 == NT || tid < TPP * 4) dv = __ldg(xr + min(tid >> 2, nt - 1) * 36 + (tid & 3)); + const char* bg = Wg + kc * BB + 32 * h; // even kc: the aligned word 2 bytes before the data word + const char* bx = Wx + kc * BB + 16 * h; + if (kc & 1) { // odd block: data words aligned (at +2); d = high half of the word 2 bytes before the block + int vg[NG], vx[NX]; +#pragma unroll + for (int i = 0; i < NG; ++i) vg[i] = __ldg((const int*) (bg + 2 + (size_t) i * RG * ROWB)); +#pragma unroll + for (int i = 0; i < NX; ++i) vx[i] = __ldg((const int*) (bx + 2 + (size_t) i * RX * ROWB)); + const int vd = __ldg((const int*) (Wd + kc * BB - 2)); +#pragma unroll + for (int i = 0; i < NG; ++i) sg_[i * RG * CWS] = vg[i]; +#pragma unroll + for (int i = 0; i < NX; ++i) sx_[i * RX * CWS] = vx[i]; + *sd_ = (int) ((uint32_t) vd >> 16); + } else { // even block: data words 2 bytes into a word: two aligned words + funnel shift; d = low half + int lg[NG], hg[NG], lx[NX], hx[NX]; +#pragma unroll + for (int i = 0; i < NG; ++i) { + lg[i] = __ldg((const int*) (bg + (size_t) i * RG * ROWB)); + hg[i] = __ldg((const int*) (bg + 4 + (size_t) i * RG * ROWB)); + } +#pragma unroll + for (int i = 0; i < NX; ++i) { + lx[i] = __ldg((const int*) (bx + (size_t) i * RX * ROWB)); + hx[i] = __ldg((const int*) (bx + 4 + (size_t) i * RX * ROWB)); + } + const int vd = __ldg((const int*) (Wd + kc * BB)); +#pragma unroll + for (int i = 0; i < NG; ++i) sg_[i * RG * CWS] = (int) __funnelshift_r((uint32_t) lg[i], (uint32_t) hg[i], 16); +#pragma unroll + for (int i = 0; i < NX; ++i) sx_[i * RX * CWS] = (int) __funnelshift_r((uint32_t) lx[i], (uint32_t) hx[i], 16); + *sd_ = vd; + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5, wd = idx & 31; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][wd >> 3][2 * (wd & 7)] = make_int2(lo, hi); + } + if (TPP * 4 == NT || tid < TPP * 4) dy_s[tid >> 2][tid & 3] = __int_as_float(dv); + __syncthreads(); + if (nt == TPP) { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute<TPP, CH, TG, true>(cw, s, grid_s, lut_s, act_s, dy_s, nt, acc); + } else { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute<TPP, CH, TG, false>(cw, s, grid_s, lut_s, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + tid] = acc[t]; + } +} +} // namespace xxs3 + +// ---- IQ3_S: 110-B blocks; per row and step a compact copy of the bytes the 4 sub-blocks read - qs 32 B, signs 16 B, +// qh 4 B, d and the 2 scale bytes: 14 words, row stride 15 - staged by lanes 0-13 / 16-29 of each warp (two rows per +// warp and k), each word built from two aligned loads by one PRMT. The sign masks come from a 256-entry table of MMQ's +// own __vcmpne4 expressions. Token groups of TG behind one `t < nt` branch. +namespace s3 { +constexpr int BB = 110, ROWB = NB * BB, CW = 14, CWS = 15, NW = NT / 32, KN = NT / (2 * NW); + +__device__ __forceinline__ int2 mmq_signs(const int sb) { // ggml_cuda_mmq_load_tiles_iq3_s's, verbatim + const int s0 = __vcmpne4(((sb & 0x03) << 7) | ((sb & 0x0C) << 21), 0x00000000); + const int s1 = __vcmpne4(((sb & 0x30) << 3) | ((sb & 0xC0) << 17), 0x00000000); + return make_int2(s0, s1); +} + +// sub-block s of the staged half: kqsx = 4 h + s's 8 int8x4 words and scale. cw: [0..7] qs, [8..11] sign bytes, +// [12] qh, [13] d | the half's 2 scale bytes << 16 +__device__ __forceinline__ float dec(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ grid, + const int2* __restrict__ lut, int (&q)[8]) { + const int2 qs_packed = make_int2(cw[2 * s + 0], cw[2 * s + 1]); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = (cw[12] >> (8 * s)) & 0xFF; + const int signs_packed_32 = cw[8 + s]; + const int w13 = cw[13]; +#pragma unroll + for (int l = 0; l < QR3_S; ++l) { + const int2 grid_pos = make_int2(grid[qs[2 * l + 0] | ((qh << (8 - 2 * l)) & 0x100)], + grid[qs[2 * l + 1] | ((qh << (7 - 2 * l)) & 0x100)]); + const int2 sg = lut[(signs_packed_32 >> (8 * l)) & 0xFF]; + q[2 * l + 0] = (grid_pos.x ^ sg.x) + (sg.x & 0x01010101); + q[2 * l + 1] = (grid_pos.y ^ sg.y) + (sg.y & 0x01010101); + } + const int ls = 1 + 2 * (((w13 >> (16 + 8 * (s >> 1))) >> (4 * (s & 1))) & 0x0F); + const float d = __ushort_as_half((unsigned short) (w13 & 0xFFFF)); + return ls * d; +} + +// compact word ci of step half h in a block of parity odd: its two aligned words (offsets from the block) and selector +__device__ __forceinline__ void stage_map(const int ci, const int h, const int odd, int& o0, int& o1, int& sel) { + const int off = ci < 8 ? 2 + 32 * h + 4 * ci : ci < 12 ? 74 + 16 * h + 4 * (ci - 8) : 66 + 4 * h; + const bool dw = ci == 13; + o0 = dw ? (odd ? -2 : 0) : (odd ? off : off - 2); + o1 = dw ? (odd ? 106 : 104 + 4 * h) : (odd ? off : off + 2); + sel = dw ? (odd ? (h ? 0x7632 : 0x5432) : (h ? 0x5410 : 0x7610)) : (odd ? 0x3210 : 0x5432); +} + +template <int TPP, int TG> +__device__ __forceinline__ void sb_compute(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ grid, + const int2* __restrict__ lut, const int (*act_s)[4][16], const float (*dy_s)[4], + const int nt, float (&acc)[TPP]) { + int q[8]; + const float dx = dec(cw, s, grid, lut, q); + int wv[16]; +#pragma unroll + for (int m = 0; m < 8; ++m) split2(q[m], wv[2 * m], wv[2 * m + 1]); +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const float dy = dy_s[t][s]; + int s0 = 0, s1 = 0, s2 = 0, s3 = 0; + s0 = mad2(wv[0], a0.x, s0); s1 = mad2(wv[1], a0.y, s1); s2 = mad2(wv[2], a0.z, s2); s3 = mad2(wv[3], a0.w, s3); + s0 = mad2(wv[4], a1.x, s0); s1 = mad2(wv[5], a1.y, s1); s2 = mad2(wv[6], a1.z, s2); s3 = mad2(wv[7], a1.w, s3); + s0 = mad2(wv[8], a2.x, s0); s1 = mad2(wv[9], a2.y, s1); s2 = mad2(wv[10], a2.z, s2); s3 = mad2(wv[11], a2.w, s3); + s0 = mad2(wv[12], a3.x, s0); s1 = mad2(wv[13], a3.y, s1); s2 = mad2(wv[14], a3.z, s2); s3 = mad2(wv[15], a3.w, s3); + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __int2float_rn((s0 + s1) + (s2 + s3)), acc[t]); + } + } + } +} + +template <int TPP, int TG> +__global__ void __launch_bounds__(NT) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0, ""); + constexpr size_t KSTR = (size_t) 2 * NW * ROWB; // a staging lane's rows are 2 * NW apart + __shared__ uint32_t grid_s[512]; + __shared__ int2 lut_s[256]; + __shared__ __align__(16) int act_s[TPP][4][16]; + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + for (int i = threadIdx.x; i < 512; i += NT) grid_s[i] = iq3s_grid[i]; + for (int i = threadIdx.x; i < 256; i += NT) lut_s[i] = mmq_signs(i); + int r0; + const Chunk c = cta_work<PIECES, NT>(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int ci = lane & 15, rsub = lane >> 4; // lanes 0-13 stage one row, 16-29 the next; ci = the compact word + const bool cact = ci < CW; + const char* __restrict__ Wr = w + xoff[c.j] + (size_t) (r0 + 2 * warp + rsub) * ROWB; // + k * KSTR + int* __restrict__ wsl = wsm + (2 * warp + rsub) * CWS + ci; // + k * 2 NW * CWS + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + __syncthreads(); + if (cact) { // branch-free inside: every lane issues its 2 * KN loads, then its KN stores + int o0, o1, sel; + stage_map(ci, hc & 1, (hc >> 1) & 1, o0, o1, sel); + const char* b = Wr + (hc >> 1) * BB; + int v0[KN], v1[KN]; +#pragma unroll + for (int k = 0; k < KN; ++k) v0[k] = __ldg((const int*) (b + k * KSTR + o0)); +#pragma unroll + for (int k = 0; k < KN; ++k) v1[k] = __ldg((const int*) (b + k * KSTR + o1)); +#pragma unroll + for (int k = 0; k < KN; ++k) wsl[k * 2 * NW * CWS] = (int) __byte_perm(v0[k], v1[k], sel); + } + { // the step's activations: nt consecutive 144-B blocks, loads first, then split + store + constexpr int NA = (TPP * 36 + NT - 1) / NT; + int av[NA]; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) av[i] = __ldg(xr + idx); + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) { + const int t = idx / 36, wd = idx - t * 36; + if (wd < 4) { + dy_s[t][wd] = __int_as_float(av[i]); + } else { + const int m = wd - 4; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][m / 8][2 * (m % 8)] = make_int2(lo, hi); + } + } + } + } + __syncthreads(); + const int* cw = wsm + threadIdx.x * CWS; +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute<TPP, TG>(cw, s, grid_s, lut_s, act_s, dy_s, nt, acc); + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace s3 + +template <typename F> +void go(F kernel, const Layer& L, cudaStream_t s) { + kernel<<<(unsigned) (L.nchunks * PIECES), NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, (const block_q8_1_mmq*) L.xq, + (int) L.rows, L.gu); +} + +} // namespace + +// tokens per pass by u (the measured crossovers): IQ3_XXS 8 below 5 rows per expert, 16 below 25, then 32 (4-token +// groups); IQ3_S 8 below 4, 16 below 15, then 32 +void gu_iq3_xxs(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 5.0) go(xxs3::gu_kernel<8, 4, 2>, L, s); + else if (u < 25.0) go(xxs3::gu_kernel<16, 4, 2>, L, s); + else go(xxs3::gu_kernel<32, 2, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ3_XXS"); +} + +void gu_iq3_s(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 4.0) go(s3::gu_kernel<8, 2>, L, s); + else if (u < 15.0) go(s3::gu_kernel<16, 2>, L, s); + else go(s3::gu_kernel<32, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ3_S"); +} + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 0f3ee3a0..8a2eb6a3 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -43,6 +43,7 @@ #include "strata/kernels/qsa_select.hpp" #include "strata/prefill/gemm.hpp" #include "strata/prefill/moe_fused.hpp" +#include "strata/prefill/moe_ws.hpp" #include "strata/prefill/moe_fused_iq.hpp" #include "strata/prefill/moe_mmq.hpp" #include "strata/core/peer_experts.hpp" @@ -119,6 +120,17 @@ void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, float*, void*) {} } // namespace strata::prefill::fused #endif +#ifndef STRATA_PREFILL_WS +// the weight-stationary experts (moe_ws.hpp) are in the CUDA STRATA_EXPERIMENTAL_SM60 build only +namespace strata::prefill::ws { +int mode() { return 0; } +bool supported(int, int) { return false; } +bool faster(int, double) { return false; } +size_t chunks(const int32_t*, size_t, const int32_t*, const int32_t*, Chunk*) { return 0; } +bool gate_up(const Layer&, void*) { return false; } +void down(const Layer&, void*) {} +} // namespace strata::prefill::ws +#endif #if defined(STRATA_GPU_METAL) // The Metal backend reads a prompt through its decode window (metal/src/engine/window.cpp): init keeps the chunk, run @@ -925,6 +937,13 @@ struct Prefill::Impl { float *Xscale = nullptr, *Hscale = nullptr, *grp_tail = nullptr; // NVFP4: activation scales, expert tails float* row_sd = nullptr; // NVFP4 in MMQ: each Dm row's s_down, applied by the combine as it reads the row std::vector<int32_t> bounds_host; + // STRATA_MMQ_WS=1 (moe_ws.hpp): a layer whose experts are all resident - their byte offsets from the expert cache's + // base in MMQ order and the CTAs' chunks, built on the host per layer and uploaded with the bounds (the device + // buffers exist only where ws::mode() != 0; the host copies are the unmapped path's) + int64_t* xoff_dev = nullptr; + std::vector<int64_t> xoff_host; + ws::Chunk* ws_chunks = nullptr; + std::vector<ws::Chunk> ws_chunks_host; std::unique_ptr<mmq::Context> mmq_ctx; std::vector<int32_t> ids_host, slot_host, src_host, cnt, off; // set_cpu_pool: a small chunk's CPU experts. The layer's MoE input (T x N, from `mixed`), the rows the pool writes @@ -1493,7 +1512,10 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.steps_up.init(T * strata::kernels::kStepCount); m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1); { - const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)); + // the routing tables, the MMQ group bounds; STRATA_MMQ_WS: the in-place offsets (n_expert int64) and the + // weight-stationary layers' chunks (4 int32 each, 16-byte aligned) + const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)) + + (ws::mode() != 0 ? 2 * (size_t) m.g->n_expert + 4 * ws::max_chunks((int64_t) T * K, m.g->n_expert) + 3 : 0); const char* gc = std::getenv("STRATA_GROUP_COPY"); if (m.grp_n < need && !(gc && gc[0] == '1')) { if (m.grp_host) cudaFreeHost(m.grp_host); @@ -1648,6 +1670,10 @@ bool Prefill::carve(size_t T, void* alloc) { m.bounds_dev = o.take<int32_t>((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok); m.grp_gu = o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); m.grp_d = o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); + if (ws::mode() != 0) { // STRATA_MMQ_WS: the offsets and chunks (bytes_needed_impl takes the same) + m.xoff_dev = o.take<int64_t>((size_t) m.g->n_expert, ok); + m.ws_chunks = (ws::Chunk*) o.take<int32_t>(4 * ws::max_chunks((int64_t) T * K, m.g->n_expert), ok); + } // (written at every run's start, not here: when serving, these are live expert-cache slots until a request // lends them - a write now would corrupt a resident expert) if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>(); @@ -2381,6 +2407,10 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se o.take<int32_t>((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok); o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); + if (ws::mode() != 0) { // carve's STRATA_MMQ_WS offsets and chunks + o.take<int64_t>((size_t) g.n_expert, ok); + o.take<int32_t>(4 * ws::max_chunks((int64_t) T * K, g.n_expert), ok); + } } if (owned_pages) { if (stage_slots(T) > 0) o.take<uint8_t>((size_t) stage_slots(T) * (size_t) MAXBLOB(), ok); // one allocation @@ -4293,6 +4323,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; + bool ws_layer = false; // STRATA_MMQ_WS: this layer's products weight-stationary (below) + ws::Layer wl; pt.mark(kPfGather, cs); // the routed experts' input: `mixed`, or (APR) its rotated copy, which the peer / the layer // split's helper also take (one rotation for both cards; `mixed` itself feeds the shared expert) @@ -4335,6 +4367,67 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri return false; } } + // STRATA_MMQ_WS=1 (moe_ws.hpp, GP100): a layer whose routed experts are ALL resident, on this + // GPU alone (no peer, CPU or streamed share), runs gate/up and down as one weight-stationary + // launch each, with ONE swiglu_quant over all its rows in between, instead of a gate/up, + // swiglu and down MMQ launch per 16-expert group - the same GU, H and Dm bits. The experts + // are read where they lie in the expert cache (offsets from its base). Only where both + // products beat the per-group MMQ at this layer's rows per expert, H can be q8_1 in one pass + // (no Hadamard, NVFP4 or FP4 rows; not STRATA_DBG_NAN, which reads H in floats), and not the + // fused layout (its Hq holds stream_all_min() - 1 tokens' rows). + static const bool ws_dbg = std::getenv("STRATA_DBG_NAN") != nullptr; + const double ws_u = n > 0 ? (double) rows_local / (double) n : 0.0; + if (ws::mode() != 0 && m.xoff_dev != nullptr && m.ws_chunks != nullptr && n > 0 && !ws_dbg && + lay.native && m.cache != nullptr && m.host_res != nullptr && !wmma_l && + !mmq_plan().direct[(size_t) l] && lay.fmt[(size_t) l].up_off == mmq_gub / 2 && + order_peer.empty() && rows_cpu == 0 && rows_local == T * K && !m.fused_bufs && + (!stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]) && !had_gu && !had_d && + !lay.fmt[(size_t) l].tail_off && !mmq::fp4_activations(mmq_gt) && + !mmq::fp4_activations(mmq_dt) && mmq::swiglu_quant_ok(mmq_dt) && + ws::supported(mmq_gt, mmq_dt) && ws::faster(mmq_gt, ws_u) && ws::faster(mmq_dt, ws_u)) { + const uint8_t* ip_base = m.cache->device_slot(0); + m.xoff_host.assign(n, -1); + bool all = true; // every expert resident + uint64_t at = 0; // their offsets' low bits + for (size_t j = 0; j < n && all; ++j) { + const int32_t s = m.host_res[(size_t) l * m.g->n_expert + order[j]]; + if (s < 0) { all = false; break; } + m.xoff_host[j] = (int64_t) (m.cache->device_slot(s) - ip_base); + at |= (uint64_t) m.xoff_host[j]; + } + ws_layer = all && ((uint64_t) (uintptr_t) ip_base | at | lay.fmt[(size_t) l].down_off) % ws::kAlign == 0; + if (ws_layer) { + if (static bool said_ws = false; !said_ws) { + said_ws = true; + std::fprintf(stderr, "strata prefill: a resident layer's experts weight-stationary, one " + "launch per product (STRATA_MMQ_WS=1)\n"); + } + // the offsets after the bounds in the mapped table, the chunks after them (16-byte + // aligned); or the host copies through pinned slots + const size_t xo = 3 * m.grp_tk + 2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2); + ws::Chunk* ch = nullptr; + if (grp_mapped) { + int32_t* xh = m.grp_host + xo; + std::memcpy(xh, m.xoff_host.data(), n * sizeof(int64_t)); + copy_i32((int32_t*) m.xoff_dev, m.grp_dev + xo, (int64_t) (2 * n), m.cs); + ch = (ws::Chunk*) (m.grp_host + (xo + 2 * m.g->n_expert + 3) / 4 * 4); + } else { + m.ws_chunks_host.resize(ws::max_chunks(T * K, m.g->n_expert)); + ch = m.ws_chunks_host.data(); + } + wl.nchunks = (int64_t) ws::chunks(order.data(), n, m.cnt.data(), m.bounds_host.data(), ch); + if (grp_mapped) { + copy_i32((int32_t*) m.ws_chunks, m.grp_dev + ((int32_t*) ch - m.grp_host), 4 * wl.nchunks, m.cs); + } else if (m.up_ring.h2d(m.xoff_dev, m.xoff_host.data(), n * sizeof(int64_t), m.cs) != cudaSuccess || + m.up_ring.h2d(m.ws_chunks, ch, (size_t) wl.nchunks * sizeof(ws::Chunk), m.cs) != cudaSuccess) { + err = "prefill: the weight-stationary tables' upload failed"; + return false; + } + wl.gu_type = mmq_gt; wl.d_type = mmq_dt; wl.w = ip_base; wl.xoff = m.xoff_dev; + wl.down_off = (int64_t) lay.fmt[(size_t) l].down_off; wl.chunks = m.ws_chunks; + wl.rows = T * K; wl.n = (int) n; wl.xq = m.Xq; wl.gu = m.GU; wl.hq = m.Hq; wl.dm = m.Dm; + } + } } else { gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs); // APR: Hadamard-folded gate/up take H (s * x); Xs is this layer's private gathered copy @@ -4909,7 +5002,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640); return true; }; - if (!stream_all) { + if (ws_layer) { + // STRATA_MMQ_WS: the layer's gate/up in one launch, H of all its rows in one pass, its down + // in one launch (no expert of the layer is staged or streamed: nothing to wait for or give + // back beyond what the walk would) + stats_.experts_resident += (int64_t) order.size(); + pt.mark(kPfGemmGU, cs); + if (!ws::gate_up(wl, m.cs)) { // the layer was taken because ws::faster said so + err = "prefill: the weight-stationary gate/up declined a layer it was picked for"; + return false; + } + mmq::swiglu_quant(m.GU, m.Hq, T * K, !lay.native, m.cs); + pt.mark(kPfGemmD, cs); + ws::down(wl, m.cs); + if (stream_all && group_gather) give_back(consumed); + } else if (!stream_all) { size_t staged = 0; size_t pending = 0; const bool stream_ahead = stream_ahead_enabled(); diff --git a/tests/cuda/prefill_ws_parity_test.cpp b/tests/cuda/prefill_ws_parity_test.cpp new file mode 100644 index 00000000..e11a4b90 --- /dev/null +++ b/tests/cuda/prefill_ws_parity_test.cpp @@ -0,0 +1,279 @@ +// prefill_ws_parity_test - the weight-stationary expert products of PR #3752 (STRATA_MMQ_WS, GP100) against the per-group +// MMQ they replace, byte for byte, on random experts (GPU, synthetic data, no model). +// +// A layer of E resident experts (random gate/up [1280 x 2560] and down [2560 x 640] blocks with sane fp16 scales, laid out +// as the expert cache holds them: gate rows then up rows, the down matrix at down_off) gets random activations, quantized +// as the prompt path does (mmq::quantize), and a routing of random row counts per expert (1 .. 300 rows, so u spans the +// measured range, some experts with one row). The reference is mmq::Context::run per expert (gate/up, then +// swiglu + quantize, then down), i.e. what Prefill does per 16-expert group; the candidate is ws::gate_up, ONE +// mmq::swiglu_quant over all rows and ws::down. Compared: GU (floats), Hq (the q8_1 bytes) and Dm (floats) of every row. +// The down is also run alone on the reference Hq, so a difference points at the product. For the IQ4_NL down the run +// repeats with STRATA_WS_FAST on (ws::set_fast(1)); the same Dm is required. +// +// The kernels were written for GP100 (the integer sums are exact, the float epilogue follows MMQ's sm_60 SASS), so the +// verdict is only given on a compute capability 6.0 card; on another card the kernels are run too (ws::set_mode(1)) +// and the counts printed for information, with exit 77. Needs the CUDA build with STRATA_EXPERIMENTAL_SM60. +// +// prefill_ws_parity_test [--device N] [--any] exit 0: all identical (cc 6.0); 77: other card; 1: a difference +#include "strata/prefill/moe_mmq.hpp" +#include "strata/prefill/moe_ws.hpp" + +#include "ggml.h" + +#include <cuda_runtime.h> + +#include <algorithm> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <numeric> +#include <random> +#include <stdexcept> +#include <string> +#include <vector> + +namespace { +namespace mmq = strata::prefill::mmq; +namespace ws = strata::prefill::ws; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + size_t n = 0; + explicit Dev(size_t bytes) : n(bytes) { + ck(cudaMalloc(&p, bytes + 256), "cudaMalloc"); + ck(cudaMemset(p, 0, bytes + 256), "cudaMemset"); + } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template <class T> T* as() const { return (T*) p; } + template <class T> void up(const std::vector<T>& h) { ck(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); } + template <class T> std::vector<T> down(size_t count) const { + std::vector<T> h(count); + ck(cudaMemcpy(h.data(), p, count * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return h; + } +}; + +constexpr int64_t kNEmbd = 2560, kNFF = 640, kGuRows = 1280; + +// random blocks of `type` for a [rows x cols] matrix; every block starts with its fp16 scale d: a finite value in +// [2^-6, 2^-5) (all the formats used here put d first) +std::vector<uint8_t> random_matrix(ggml_type type, int64_t rows, int64_t cols, std::mt19937& rng) { + const size_t bytes = mmq::matrix_bytes((int) type, rows, cols); + const size_t bs = ggml_type_size(type); + std::vector<uint8_t> w(bytes); + for (auto& b : w) b = (uint8_t) rng(); + for (size_t o = 0; o + bs <= bytes; o += bs) { + const uint16_t d = (uint16_t) ((9u << 10) | (rng() & 0x3FFu)); + std::memcpy(&w[o], &d, 2); + } + return w; +} + +size_t count_diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, size_t n) { + size_t d = 0; + for (size_t i = 0; i < n; ++i) d += a[i] != b[i]; + return d; +} + +// the largest |a - b| over the largest |a|, both float arrays in byte form (how far apart two results are in rounding terms) +double max_norm_err(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, size_t bytes) { + const float* x = (const float*) a.data(); + const float* y = (const float*) b.data(); + double mx = 0.0, err = 0.0; + for (size_t i = 0; i < bytes / 4; ++i) { + mx = std::max(mx, (double) std::fabs(x[i])); + err = std::max(err, (double) std::fabs(x[i] - y[i])); + } + return mx > 0.0 ? err / mx : err; +} + +struct Result { + size_t gu = 0, hq = 0, dm = 0, dm_ref_hq = 0, dm_fast = 0, fast_vs_default = 0; + double e_gu = 0, e_dm = 0, e_dm_rh = 0; // normalized max errors against the reference + bool ran = true; +}; + +Result run_case(ggml_type gt, ggml_type dt, const std::vector<int32_t>& cnt, uint32_t seed, bool test_fast) { + std::mt19937 rng(seed); + const int E = (int) cnt.size(); + std::vector<int32_t> bounds(E + 1, 0); + for (int j = 0; j < E; ++j) bounds[j + 1] = bounds[j] + cnt[j]; + const int64_t rows = bounds[E]; + const size_t gub = mmq::matrix_bytes((int) gt, kGuRows, kNEmbd), db = mmq::matrix_bytes((int) dt, kNEmbd, kNFF); + const size_t stride = (gub + db + 255) / 256 * 256; + // the layer's experts, "resident" in one buffer at 256-byte aligned offsets (the expert cache's slots) + std::vector<uint8_t> blob((size_t) E * stride, 0); + std::vector<int64_t> xoff(E); + for (int j = 0; j < E; ++j) { + xoff[j] = (int64_t) j * (int64_t) stride; + const auto g = random_matrix(gt, kGuRows, kNEmbd, rng), d = random_matrix(dt, kNEmbd, kNFF, rng); + std::memcpy(&blob[(size_t) xoff[j]], g.data(), gub); + std::memcpy(&blob[(size_t) xoff[j] + gub], d.data(), db); + } + std::normal_distribution<float> nd(0.0f, 1.0f); + std::vector<float> x((size_t) (rows * kNEmbd)); + for (auto& v : x) v = nd(rng) * 0.7f; + + const size_t xqb = mmq::q8_bytes(rows, kNEmbd), hqb = mmq::q8_bytes(rows, kNFF); + Dev dblob(blob.size()), dx(x.size() * 4), dxq(xqb), dbnd((size_t) (E + 1) * 4), dxoff((size_t) E * 8); + Dev dident((size_t) rows * 4), dgu_ref((size_t) rows * kGuRows * 4), dgu((size_t) rows * kGuRows * 4); + Dev dh((size_t) rows * kNFF * 4), dhq_ref(hqb), dhq(hqb), ddm_ref((size_t) rows * kNEmbd * 4), ddm((size_t) rows * kNEmbd * 4), + ddm_rh((size_t) rows * kNEmbd * 4), ddm_fast((size_t) rows * kNEmbd * 4); + dblob.up(blob); dx.up(x); dbnd.up(bounds); dxoff.up(xoff); + std::vector<int32_t> ident((size_t) rows); + for (int64_t i = 0; i < rows; ++i) ident[(size_t) i] = (int32_t) i; + dident.up(ident); + mmq::quantize(dx.as<float>(), nullptr, dxq.p, (int) gt, kNEmbd, kNEmbd, rows, nullptr); + + // the reference: per expert, as a one-expert group (absolute rows) + mmq::Context ctx; + for (int j = 0; j < E; ++j) { + mmq::Product gu; + gu.w = dblob.as<uint8_t>() + xoff[j]; gu.type = (int) gt; gu.w_rows = kGuRows; gu.w_cols = kNEmbd; gu.expert_bytes = gub; + gu.n = 1; gu.xq = dxq.p; gu.bounds = dbnd.as<int32_t>() + j; gu.ids = dident.as<int32_t>(); + gu.total_rows = rows; gu.max_rows = cnt[j]; gu.dst = dgu_ref.as<float>(); gu.ld_dst = kGuRows; + ctx.run(gu, nullptr); + } + mmq::swiglu(dgu_ref.as<float>(), dh.as<float>(), rows, kNFF, false, nullptr); + mmq::quantize(dh.as<float>(), nullptr, dhq_ref.p, (int) dt, kNFF, kNFF, rows, nullptr); + for (int j = 0; j < E; ++j) { + mmq::Product dn; + dn.w = dblob.as<uint8_t>() + xoff[j] + gub; dn.type = (int) dt; dn.w_rows = kNEmbd; dn.w_cols = kNFF; dn.expert_bytes = db; + dn.n = 1; dn.xq = dhq_ref.p; dn.bounds = dbnd.as<int32_t>() + j; dn.ids = dident.as<int32_t>(); + dn.total_rows = rows; dn.max_rows = cnt[j]; dn.dst = ddm_ref.as<float>(); dn.ld_dst = kNEmbd; + ctx.run(dn, nullptr); + } + ck(cudaDeviceSynchronize(), "reference"); + + // the candidate + std::vector<int32_t> order(E); + for (int j = 0; j < E; ++j) order[j] = j; + std::vector<ws::Chunk> chunks(ws::max_chunks(rows, E)); + const size_t nch = ws::chunks(order.data(), (size_t) E, cnt.data(), bounds.data(), chunks.data()); + chunks.resize(nch); + Dev dch(std::max<size_t>(1, nch) * sizeof(ws::Chunk)); + dch.up(chunks); + ws::Layer L; + L.gu_type = (int) gt; L.d_type = (int) dt; L.w = dblob.p; L.xoff = dxoff.as<int64_t>(); L.down_off = (int64_t) gub; + L.chunks = dch.as<ws::Chunk>(); L.nchunks = (int64_t) nch; L.rows = rows; L.n = E; L.xq = dxq.p; L.gu = dgu.as<float>(); + L.hq = dhq.p; L.dm = ddm.as<float>(); + Result r; + if (!ws::gate_up(L, nullptr)) { r.ran = false; return r; } + mmq::swiglu_quant(dgu.as<float>(), dhq.p, rows, false, nullptr); + ws::down(L, nullptr); + ck(cudaDeviceSynchronize(), "candidate"); + // the down alone on the reference H (a difference above this one is the gate/up's) + ws::Layer L2 = L; + L2.hq = dhq_ref.p; L2.dm = ddm_rh.as<float>(); + ws::down(L2, nullptr); + if (test_fast) { + ws::set_fast(1); + ws::Layer L3 = L; + L3.dm = ddm_fast.as<float>(); + ws::down(L3, nullptr); + ws::set_fast(-1); + } + ck(cudaDeviceSynchronize(), "candidate (down alone, fast)"); + + const size_t gun = (size_t) rows * kGuRows * 4, dmn = (size_t) rows * kNEmbd * 4; + const auto gur = dgu_ref.down<uint8_t>(gun), gun_c = dgu.down<uint8_t>(gun); + r.gu = count_diff(gur, gun_c, gun); + r.e_gu = max_norm_err(gur, gun_c, gun); + r.hq = count_diff(dhq_ref.down<uint8_t>(hqb), dhq.down<uint8_t>(hqb), hqb); + const auto dmr = ddm_ref.down<uint8_t>(dmn); + const auto dmc = ddm.down<uint8_t>(dmn), dmh = ddm_rh.down<uint8_t>(dmn); + r.dm = count_diff(dmr, dmc, dmn); + r.dm_ref_hq = count_diff(dmr, dmh, dmn); + r.e_dm = max_norm_err(dmr, dmc, dmn); + r.e_dm_rh = max_norm_err(dmr, dmh, dmn); + if (test_fast) { + const auto dmf = ddm_fast.down<uint8_t>(dmn); + r.dm_fast = count_diff(dmr, dmf, dmn); + r.fast_vs_default = count_diff(dmc, dmf, dmn); // STRATA_WS_FAST: the same bits as the default kernel, on any card + } + return r; +} + +std::vector<int32_t> counts(int E, int lo, int hi, std::mt19937& rng) { + std::vector<int32_t> c(E); + for (auto& v : c) v = lo + (int32_t) (rng() % (uint32_t) (hi - lo + 1)); + return c; +} +} // namespace + +int main(int argc, char** argv) { + int device = 0; + bool any = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else if (std::strcmp(argv[i], "--any") == 0) any = true; + else { + std::fprintf(stderr, "usage: prefill_ws_parity_test [--device N] [--any]\n"); + return 2; + } + } + int ndev = 0; + if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { + std::puts("prefill_ws_parity_test: no CUDA device (skipped)"); + return 77; + } + try { + ck(cudaSetDevice(device), "cudaSetDevice"); + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + const bool gp100 = prop.major == 6 && prop.minor == 0; + std::printf("prefill_ws_parity_test on %s (%d.%d)%s\n", prop.name, prop.major, prop.minor, + gp100 ? "" : ": not a GP100, so the counts are for information only"); + if (!gp100 && !any) { + std::puts("prefill_ws_parity_test: not a compute capability 6.0 card (skipped; --any runs it for information)"); + return 77; + } + ws::set_mode(1); + std::mt19937 rng(20261026u); + const ggml_type gus[] = {GGML_TYPE_IQ2_XXS, GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S, GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S}; + const ggml_type dns[] = {GGML_TYPE_Q2_0, GGML_TYPE_IQ4_NL}; + size_t total_diff = 0, total_fast = 0; + double worst_err = 0.0; + int cases = 0, declined = 0; + for (ggml_type gt : gus) + for (ggml_type dt : dns) { + // a spread of rows per expert (u from ~2 to ~150), and a tiny layer with one-row experts + const std::vector<std::vector<int32_t>> shapes = {counts(24, 1, 12, rng), counts(24, 5, 40, rng), + counts(20, 60, 300, rng), {1, 2, 65, 1, 64, 63}}; + for (const auto& cnt : shapes) { + const Result r = run_case(gt, dt, cnt, 1000u + (uint32_t) cases, dt == GGML_TYPE_IQ4_NL); + ++cases; + if (!r.ran) { ++declined; std::printf(" %-8s -> %-6s %zu experts: ws declined (not faster here)\n", ggml_type_name(gt), ggml_type_name(dt), cnt.size()); continue; } + const size_t bad = r.gu + r.hq + r.dm + r.dm_ref_hq + r.dm_fast; + total_diff += gp100 ? bad : 0; + total_fast += r.fast_vs_default; + worst_err = std::max(worst_err, std::max(r.e_gu, r.e_dm_rh)); // Dm after the full chain also carries int8 flips of H + std::printf(" %-8s -> %-6s %2zu experts %5d rows: bytes differ GU %zu Hq %zu Dm %zu Dm(down alone) %zu Dm(fast) %zu" + " fast vs default %zu | max error / max value: GU %.2e Dm %.2e Dm(down alone) %.2e%s\n", + ggml_type_name(gt), ggml_type_name(dt), cnt.size(), + (int) std::accumulate(cnt.begin(), cnt.end(), 0), r.gu, r.hq, r.dm, r.dm_ref_hq, r.dm_fast, + r.fast_vs_default, r.e_gu, r.e_dm, r.e_dm_rh, gp100 && bad ? " <-- FAIL" : ""); + } + } + if (!gp100) { // no verdict on this card: the float epilogue of its MMQ is not the one the kernels follow + std::printf("prefill_ws_parity_test (information, %s): %d cases (%d declined), STRATA_WS_FAST vs default: %zu differing bytes, " + "largest GU / down-alone error against this card's MMQ %.2e of the largest value -> %s\n", prop.name, cases, declined, + total_fast, worst_err, total_fast == 0 && worst_err < 1e-5 && declined < cases ? "consistent" : "INCONSISTENT"); + return total_fast == 0 && worst_err < 1e-5 && declined < cases ? 77 : 1; + } + std::printf("prefill_ws_parity_test: %d cases (%d declined), %zu differing bytes, STRATA_WS_FAST vs default %zu -> %s\n", cases, + declined, total_diff, total_fast, total_diff == 0 && total_fast == 0 && declined < cases ? "PASS" : "FAIL"); + return total_diff == 0 && total_fast == 0 && declined < cases ? 0 : 1; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill_ws_parity_test: %s\n", e.what()); + return 1; + } +} From 9067cc64d3177ee9c2c47fea8ed3b6441849ad0f Mon Sep 17 00:00:00 2001 From: ruibeikaa <126486262+ruibeikaa@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:52:54 +0100 Subject: [PATCH 150/177] iq_kernels: GP100 4-bit gate/up expert slots, opt-in STRATA_EXPERT_NIBBLE=1 (#3455) Problem: on a GP100 die the verify window's gate/up kernels for the IQ2_S, IQ3_XXS and IQ3_S expert formats are not held by memory bandwidth but by each block's serial chain (unpack the codebook indices, the emulated dp4a, the 16-lane reduction); the same kernel with every dot product removed still takes about two thirds of its time. Change: with STRATA_EXPERT_NIBBLE=1 the engine, after the expert cache is filled and every expert is resident, transcodes the gate/up blocks of every fully resident IQ2_S / IQ3_XXS / IQ3_S layer (n_embd 2560, n_ff 640) into slots of 4-bit codes, 16 bytes per 32 weights, with the integer scales and fp16 d kept as they are; the down rows stay GGUF. The decode gate/up reads those slots with kernels that run the production integer chain and float tail in the production order (R4S / R4P / R4SV / R4PX by format and group size); the prompt path's MMQ gather rebuilds the GGUF blocks from a slot on the fly. At load every item is round-tripped and every slot's rebuilt GGUF blocks are compared with the staged blob before the cache is sealed (ExpertCache::seal: a later fill_slot stops the engine). New: include/strata/core/expert_nibble.hpp (slot contract, switches, per-layer table), nib_gu_proto.cuh (STRATA_NIB_GU_PROTO=1 variant), the transcoder, hash and rebuild kernels and the 4-bit gate/up kernels in iq_kernels.cu, generate.cpp (the fill, the VRAM accounting, STRATA_EXPERT_NIBBLE_ RECHECK), iq_nibble_parity and native_expert_bench --nibble. Review changes against the PR: - An option the switch cannot work with (--peer-device, --kv-grow, --vram-elastic, remote caches, STRATA_MMQ_DIRECT, ..., a card that is not cc 6.0, a build without the kernels) now prints a warning and the start goes on with the usual GGUF slots, where the PR refused the start. What is known only later (an expert out of VRAM, a loan, the prompt chunk) still refuses, since slots are converted by then. - The checks this switch adds to expert_source.cpp and prefill.cpp are compiled out of every build that has no 4-bit kernels, so the default builds add nothing to the hit split or the prompt loop. - iq_nibble_parity gets --synthetic-only (every gate/up format x both down types on random experts, no model file), skips with 77 on a card that is not a GP100, and the synthetic and --header runs are ctests. - The PR's docs section is rewritten for these changes and its measurements are labeled as the author's. Default path (switch unset): the table is empty, nibble::slot_bytes(l) is expert_layout().blob_bytes(l) and nibble_max_slot_bytes() is max_blob, every sizing the PR touched returns what it returned before, and the new branches in generate.cpp (guard_raw before the adaptive tier's copies, the profile fill's test), expert_cache.cpp (one bool in the fill calls and admit) and verify.cpp (a capture-time layout choice, compiled out without the kernels) are not taken. Proof on the kernels: in the sm_60 build (CUDA 12.9) the SASS of all 446 kernels iq_kernels.cu had before is identical with and without this change, as is that of the 603 in native_mmvq.cu, 29 in qsa_select.cu and 10 in moe_mmq.cu; 21 kernels are new. Tests: iq_nibble_parity --header passes on z440 and boston (the host half of the contract; also a ctest). The GPU parts (--synthetic-only, a model shard) refuse a card that is not a GP100, so they were only compiled here (sm_60, CUDA 12.9, P1004: iq_nibble_parity and native_expert_bench build; the whole tree builds). sm_86 build without the SM60 option (z440): exit 0, the 4-bit paths compiled out. Not covered: no GP100 run. The model gate is phaseA-tests/gh027/gates/3455-expert-nibble.sh: iq_nibble_parity --synthetic-only and on a model's layers on a P100, then identical replies with the switch on and off (a layer is converted only when every expert of every layer is resident, so the rig needs the pack to fit whole), then the decode A/B. The contributor's numbers (four GP100 dies, Swift 1.5 IQ3_S, 47 of 48 layers converted, +12.7 GiB VRAM, decode 47.3 -> 51.9 tok/s, +9.7%; prompt reading 2.3-3.0% slower; replies of 15 requests equal) were not re-measured, and the enabled path was written against an older base than this branch's. --- CMakeLists.txt | 14 + docs/OLDER_GPUS.md | 44 ++ include/strata/core/expert_cache.hpp | 9 + include/strata/core/expert_nibble.hpp | 457 ++++++++++++ include/strata/kernels/iq_kernels.hpp | 15 +- include/strata/prefill/prefill.hpp | 5 + src/core/expert_cache.cpp | 17 + src/core/expert_source.cpp | 9 + src/core/verify.cpp | 19 +- src/kernels/cuda/iq_kernels.cu | 928 ++++++++++++++++++++++++- src/kernels/cuda/nib_gu_proto.cuh | 137 ++++ src/kernels/iq_nibble_parity.cpp | 954 ++++++++++++++++++++++++++ src/kernels/native_expert_bench.cpp | 419 +++++++++++ src/prefill/prefill.cpp | 63 ++ src/program/generate.cpp | 549 ++++++++++++++- 15 files changed, 3605 insertions(+), 34 deletions(-) create mode 100644 include/strata/core/expert_nibble.hpp create mode 100644 src/kernels/cuda/nib_gu_proto.cuh create mode 100644 src/kernels/iq_nibble_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index efb23121..60a25467 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2247,6 +2247,20 @@ if(STRATA_NATIVE_EXPERTS) 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}) + if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + # STRATA_EXPERT_NIBBLE (include/strata/core/expert_nibble.hpp): the 4-bit gate/up expert slots against the + # production kernels and the GGUF blobs, bit for bit, on a real model's layers (needs a GP100); --header: the + # contract's host half, no GPU + add_executable(iq_nibble_parity src/kernels/iq_nibble_parity.cpp) + target_include_directories(iq_nibble_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(iq_nibble_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ggml-base ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_nibble_parity_header COMMAND iq_nibble_parity --header) + # the synthetic experts of every gate/up x down format pair, no model (skips with 77 on a card that is not a GP100) + add_test(NAME iq_nibble_parity_synthetic COMMAND iq_nibble_parity --synthetic-only) + set_tests_properties(iq_nibble_parity_synthetic PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900) + endif() + endif() # 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}) diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 58118faf..88f9f975 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -182,6 +182,50 @@ decode; keep two engines on different logical CPUs. `tools/q8_sm60_check.cu` checks the kernel against a CPU reference on these shapes (1-8 columns). +### Pascal GP100: 4-bit gate/up expert slots (opt-in, `STRATA_EXPERT_NIBBLE=1`) + +On a GP100 die the verify window's gate/up expert kernels wait on each block's serial chain (the weights, two codebook +lookups per four weights, the emulated dp4a, the reduction), not on memory bandwidth. IQ2_S, IQ3_XXS and IQ3_S have +only 3 or 8 magnitudes in their grids, so every weight is one of at most 16 signed values: `STRATA_EXPERT_NIBBLE=1` +keeps those layers' gate/up experts in VRAM as 16 bytes of 4-bit codes per 32 weights (one 16-byte load), with the +integer scale and the fp16 `d` of each block kept as they are, and decodes four weights in 1-4 integer instructions. The +down rows stay GGUF blocks. The host copy, the pack and its tools do not change: the conversion runs on the GPU while +the slots are filled. Only the CUDA build with `STRATA_EXPERIMENTAL_SM60` has the kernels. + +- **The answers are meant to be bit for bit the default's.** The 4-bit kernels run the production integer chain and float tail in + the production order (`native_gu_multi_kernel`'s sub-16 rows), and SwiGLU, the q8_1 step and the down projection are + the layout's own (mode 8 on a GP100). At every start each item is decoded with the production loader, encoded, + decoded from the written code and compared, and the GGUF blocks are rebuilt from every slot and compared with the + blob byte for byte; any difference refuses the start and names the layer. The prompt path's MMQ gathers the GGUF + blocks rebuilt from the slots (the copy it makes today, with the 4-bit codes read instead): the same bytes. The kernels that + existed before this change have the same SASS in the sm_60 build with and without it (446 kernels in `iq_kernels.cu` compared). + `iq_nibble_parity --synthetic-only` checks the codec, the rebuilt blocks and the expert step on random experts of every format + pair with no model file; `iq_nibble_parity <model shard>` does the same on a model's layers, against the GGUF blobs in mode 8 and + in the CUDA layout (`STRATA_SM60_TABLE=0`). Both need a GP100. +- **It needs every expert in VRAM** on the card that runs its layer: a profile that ranks every pair, room for the + larger slots (per layer of 512 experts: +175 MiB for IQ3_S, +250 MiB for IQ3_XXS, +350 MiB for IQ2_S), and a prompt + path with its own buffers, no loan of cache slots (`--no-prefill-borrow` on one GPU; a layer split's stages keep + their own when their cards have room, #340). `STRATA_EXPERT_NIBBLE_SKIP=<layers>` keeps layers in their GGUF slots; + `STRATA_EXPERT_NIBBLE_FMTS=22,18,21` picks the formats. +- **It does not start with what it cannot serve.** With the switch set, a build without `STRATA_EXPERIMENTAL_SM60`, a card other + than compute capability 6.0, `--peer-device`, `--expert-cache-device1..3`, `--kv-grow`, `--vram-elastic`, no `--expert-profile`, + `--expert-cache 0`, `STRATA_MMQ_DIRECT`, `STRATA_PREFILL_MMQ=0`, `STRATA_PF_FUSED=1`, `STRATA_FS_SLOTS`, `STRATA_EXPERT_V2=1` or + `STRATA_EXP_MODE` other than 0 or 8 make the engine say so in a warning and start with the usual GGUF slots. What is only known + later (a layer with an expert out of VRAM, a loan of cache slots, a prompt chunk other than the one the run without the switch + reads) still refuses the start with the reason. The adaptive tier is off with the switch. `STRATA_EXPERT_NIBBLE_RECHECK=1` (debug) + hashes every 4-bit slot again after each request. +- **Opt-in `STRATA_NIB_GU_PROTO=1`** (with `STRATA_EXPERT_NIBBLE=1`): the 4-bit gate/up runs `nibx_gu_kernel` + (`nib_gu_proto.cuh`), the same row dot with the group's activations staged once per two row blocks by 16-byte + loads. The author measured, on one GP100 die, a layer's gate/up at 54-57 us instead of 67-72 us at one token (x1.24-1.27) and + x1.22-1.39 at two to four tokens. +- The author measured the switch on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB each, clocks locked at 715 / + 1050 MHz), Windows 11, CUDA 12.9, engine 0.1.45.3, Swift 1.5 IQ3_S (abliterated) pack, layer split 12,24,36, + `--trim-stage-weights`, MTP with `--spec-min-p 0.85`, `--pipeline-windows 2`, 1M context, every expert resident: 47 of 48 layers + converted (+12.7 GiB of VRAM over the four dies, +3.1 s of start-up). Decode of eight prompts (8K, 26K and 88K-token contexts), + token-weighted: 47.3 -> 51.9 tok/s (+9.7%; each prompt +9.5..+10.9%). Prompt reading 2.3..3.0% slower (the gather rebuilds the + GGUF blocks). The replies of 15 requests, including a 260K-token read, matched the engine without the switch. We have not + measured it on this code. + ## Tesla P40 (sm_61): what was measured and changed Three things run differently on compute capability 6.1 by default and a fourth is opt-in. Each gives the same bits as what it diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 9685aa4d..7de956b9 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -217,6 +217,14 @@ public: /// Slots filled so far, for the startup report. int64_t fills() const { return fills_; } + /// STRATA_EXPERT_NIBBLE=1 (strata/core/expert_nibble.hpp): called once the startup fill has written every slot + /// (some of them as 4-bit codes, not GGUF blocks) and checked them. From then on no slot may be written through + /// this class: the fill_slot calls stop the engine (they would write GGUF bytes, possibly into a 4-bit slot, and a + /// wrong expert gives a plausible token, never an error), and `admit` claims nothing. Never called with the switch + /// off: an unsealed cache is the one above. + void seal() { sealed_ = true; } + bool sealed() const { return sealed_; } + /// The elastic K/V (--kv-grow): the arena in a VMM range (vmm.hpp) instead of one cudaMalloc, so the K/V can take /// single chunks of it and give them back. Applies to the next `open`; ignored where VMM is not available. static void set_vmm(bool enabled); @@ -266,6 +274,7 @@ private: std::vector<int32_t> layer_next_; ///< [n_layers] -> that layer's next free slot std::vector<uint64_t> off_; ///< plan v0.3 P6: slot offsets (slots + 1 entries) when sized int64_t admitted_ = 0; + bool sealed_ = false; ///< STRATA_EXPERT_NIBBLE: `seal` was called (no slot is written after it) }; } // namespace strata::core diff --git a/include/strata/core/expert_nibble.hpp b/include/strata/core/expert_nibble.hpp new file mode 100644 index 00000000..92001956 --- /dev/null +++ b/include/strata/core/expert_nibble.hpp @@ -0,0 +1,457 @@ +// include/strata/core/expert_nibble.hpp - STRATA_EXPERT_NIBBLE=1 (opt-in, default off): the gate/up experts of +// IQ2_S / IQ3_XXS / IQ3_S layers kept as 4-bit codes in their VRAM slots, for Pascal GP100 (sm_60). +// +// **WHY.** On a GP100 the decode window's gate/up expert kernels are not held by memory bandwidth: they use a small +// part of it and wait on each block's serial chain (the weights, the codebook lookups, the emulated dp4a, the +// reduction). Re-encoding each 32-weight item of these three formats as sixteen bytes of 4-bit codes (one aligned +// 16-byte load) and keeping the integer scale and the fp16 d as they are makes the slot 1.25-1.68x the GGUF bytes and +// the decode of four weights 1-4 integer instructions instead of two codebook lookups. +// +// **WHY IT IS LOSSLESS.** Their grids have only 3 (IQ2_S) or 8 (IQ3_XXS, IQ3_S) magnitudes, so each int8 weight the +// production `Split<TG>::load` decodes is one of at most 16 signed values. At every start the transcoder decodes every +// item of every converted slot with the production load, encodes it, decodes the written code again and compares; and +// the GGUF blocks are rebuilt from every slot and compared with the blob byte for byte (`check_gguf`). The decode +// kernels run the production integer chain and float tail in the production order: every gate / up value is the +// production kernel's, bit for bit. The prompt path's MMQ reads the GGUF blocks rebuilt from the slot (`gather_gguf`, +// in place of the copy it does today): the same bytes, so the same bits. +// +// **OFF IS TODAY.** Unset or 0: no layer is converted, `slot_bytes(l)` is `expert_layout().blob_bytes(l)`, nothing is +// transcoded, sealed or hashed, and none of the new branches is entered. Only a CUDA build with +// STRATA_EXPERIMENTAL_SM60 has the kernels (STRATA_EXPERT_NIBBLE_BUILT); every other build refuses the switch at start. +#pragma once + +#include "strata/kernels/cpu/expert_layout.hpp" + +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <string> +#include <vector> + +#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \ + !defined(STRATA_GPU_METAL) +#define STRATA_EXPERT_NIBBLE_BUILT 1 +#else +#define STRATA_EXPERT_NIBBLE_BUILT 0 +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_NIB_HD __host__ __device__ +#else +#define STRATA_NIB_HD +#endif + +namespace strata::core::nibble { + +// ------------------------------------------------------------------------------------------------ the slot layout +// +// A converted layer's expert slot, in order (the host arena and the pack keep the GGUF blocks): +// +// codes kRows x kItems x 16 B row r, item k at (r * kItems + k) * 16; rows 0..kNFf-1 gate, kNFf..kRows-1 up +// scales kRows x kItems x 1 B row r, item k at kScOff + r * kItems + k (the production scale step's input) +// d kRows x kSuper x 2 B row r, superblock s at kDOff + (r * kSuper + s) * 2: the block's fp16 d, bit for bit +// ------ kGuBytes = 1,766,400 B (6900 x 256: the down part starts 256-aligned) +// down the GGUF down rows, copied verbatim from the raw blob's [down_off, bytes) +// ------ slot_bytes = round_up(kGuBytes + down bytes, kSlotAlign) +// +// One item = 32 weights of a row, one 16-byte code (four 32-bit words, see `encode_item`). Only the expert shape +// n_embd 2560, n_ff 640 is converted: every other layer keeps its GGUF blob and its kernels. + +inline constexpr int64_t kNEmbd = 2560; ///< the gate/up rows' width (the activation) +inline constexpr int64_t kNFf = 640; ///< gate rows = up rows = n_ff +inline constexpr int64_t kRows = 2 * kNFf; ///< 1280: gate, then up +inline constexpr int64_t kItems = kNEmbd / 32; ///< 80 items of 32 weights per row +inline constexpr int64_t kSuper = kNEmbd / 256; ///< 10 superblocks (one fp16 d each) per row +inline constexpr uint64_t kItemBytes = 16; ///< one item's code: four words, one 16-byte load + +inline constexpr uint64_t kCodesOff = 0; +inline constexpr uint64_t kUpCodesOff = (uint64_t) kNFf * kItems * kItemBytes; ///< 819,200: row kNFf +inline constexpr uint64_t kScOff = (uint64_t) kRows * kItems * kItemBytes; ///< 1,638,400 +inline constexpr uint64_t kDOff = kScOff + (uint64_t) kRows * kItems; ///< 1,740,800 +inline constexpr uint64_t kGuBytes = kDOff + (uint64_t) kRows * kSuper * 2; ///< 1,766,400 +inline constexpr uint64_t kDownOff = kGuBytes; ///< the down rows +inline constexpr uint64_t kSlotAlign = 256; ///< every slot's size + +static_assert(kGuBytes == 1766400, "the slot layout above"); +static_assert(kGuBytes % kSlotAlign == 0, "the down part starts 256-aligned"); +static_assert(kScOff % 16 == 0 && kDOff % 16 == 0, "each region starts 16-aligned"); + +/// Byte offset of row `row` (0..kRows-1; up rows are kNFf + r) item `k`'s code inside the slot. +STRATA_NIB_HD constexpr uint64_t code_off(int64_t row, int64_t k) { + return kCodesOff + ((uint64_t) row * kItems + (uint64_t) k) * kItemBytes; +} +/// Byte offset of row `row` item `k`'s scale byte. +STRATA_NIB_HD constexpr uint64_t scale_off(int64_t row, int64_t k) { return kScOff + (uint64_t) row * kItems + (uint64_t) k; } +/// Byte offset of row `row` superblock `s`'s fp16 d (s = k / 8 for item k). +STRATA_NIB_HD constexpr uint64_t d_off(int64_t row, int64_t s) { return kDOff + ((uint64_t) row * kSuper + (uint64_t) s) * 2; } +/// A converted slot's size for a raw blob whose down rows are `down_bytes` long. +STRATA_NIB_HD constexpr uint64_t slot_bytes_for(uint64_t down_bytes) { + return (kGuBytes + down_bytes + kSlotAlign - 1) / kSlotAlign * kSlotAlign; +} + +// ------------------------------------------------------------------------------------------------ the formats + +inline constexpr int kIQ3_XXS = 18; +inline constexpr int kIQ3_S = 21; +inline constexpr int kIQ2_S = 22; + +/// Whether `gu_type` is converted (the three formats whose weights take at most 16 values). +STRATA_NIB_HD constexpr bool fmt_built(int gu_type) { return gu_type == kIQ2_S || gu_type == kIQ3_XXS || gu_type == kIQ3_S; } +/// The GGUF gate/up row bytes of `gu_type` at kNEmbd (a converted layer's raw blob must agree; 0 = not a format here). +STRATA_NIB_HD constexpr uint64_t raw_gu_row(int gu_type) { + return gu_type == kIQ2_S ? 820 : gu_type == kIQ3_XXS ? 980 : gu_type == kIQ3_S ? 1100 : 0; +} +inline const char* fmt_name(int gu_type) { + switch (gu_type) { + case kIQ3_XXS: return "IQ3_XXS"; + case kIQ3_S: return "IQ3_S"; + case kIQ2_S: return "IQ2_S"; + default: return "?"; + } +} + +// ------------------------------------------------------------------------------------------------ the item code +// +// `g[32]` below is one item as the production `Split<TG>::load` leaves it: g[4 * j + b] is byte b of W.g[j] +// (j = 0..7, the dp4a order against the q8_1 block's qs words). Word m (0..3) of the 16-byte code holds W.g[2m] +// and W.g[2m + 1]: +// +// IQ2_S bits 4b..4b+3 = c(g[8m + b]), bits 16+4b.. = c(g[8m + 4 + b]), b = 0..3 +// c = magnitude index of {8, 25, 43} | sign << 2: the PRMT selector into {8,25,43,0} {-8,-25,-43,0} +// IQ3_XXS same nibble positions; c = index of {4, 12, 20, 28, 36, 44, 52, 62} | sign << 3 +// IQ3_S byte b = u(g[8m + b]) | u(g[8m + 4 + b]) << 4, u = (v + 15) / 2 (v odd, -15..15); v = 2u - 15 +// +// The scale byte keeps the production integer scale step's input: +// IQ2_S the block's scales byte for the item: ls0 | ls1 << 4 (W.ls0, W.ls1) +// IQ3_XXS aux32 >> 28 (0..15, W.ls) +// IQ3_S 1 + 2 * nibble (1..31, W.ls) + +/// Encodes one item; false when a weight is outside the format's code set (the conversion then refuses to start). +inline bool encode_item(int gu_type, const int8_t g[32], uint32_t q[4]) { + bool ok = true; + auto code = [&](int8_t v) -> uint32_t { + const int a = v < 0 ? -(int) v : (int) v; + if (gu_type == kIQ3_S) { + if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; } + return (uint32_t) (((int) v + 15) / 2); + } + if (gu_type == kIQ3_XXS) { + static constexpr int mag[8] = { 4, 12, 20, 28, 36, 44, 52, 62 }; + for (uint32_t i = 0; i < 8; ++i) + if (a == mag[i]) return i | (v < 0 ? 8u : 0u); + ok = false; + return 0; + } + const uint32_t m = a == 8 ? 0u : a == 25 ? 1u : a == 43 ? 2u : 3u; // IQ2_S + if (m == 3u) { ok = false; return 0; } + return m | (v < 0 ? 4u : 0u); + }; + for (int m = 0; m < 4; ++m) { + uint32_t w = 0; + for (int b = 0; b < 4; ++b) { + const uint32_t c0 = code(g[8 * m + b]), c1 = code(g[8 * m + 4 + b]); + if (gu_type == kIQ3_S) w |= (c0 | c1 << 4) << (8 * b); + else w |= c0 << (4 * b) | c1 << (16 + 4 * b); + } + q[m] = w; + } + return ok; +} + +/// Decodes one item's code back to the production W.g bytes (the host reference the parity program compares with; +/// the device decoders give the same bytes). Codes outside the set decode as the PRMT does: IQ2_S index 3 -> 0. +inline void decode_item(int gu_type, const uint32_t q[4], int8_t g[32]) { + static constexpr int8_t iq2[8] = { 8, 25, 43, 0, -8, -25, -43, 0 }; + static constexpr int8_t iq3[8] = { 4, 12, 20, 28, 36, 44, 52, 62 }; + for (int m = 0; m < 4; ++m) + for (int b = 0; b < 4; ++b) { + uint32_t c0, c1; + if (gu_type == kIQ3_S) { + c0 = q[m] >> (8 * b) & 15u; + c1 = q[m] >> (8 * b + 4) & 15u; + } else { + c0 = q[m] >> (4 * b) & 15u; + c1 = q[m] >> (16 + 4 * b) & 15u; + } + auto val = [&](uint32_t c) -> int8_t { + if (gu_type == kIQ3_S) return (int8_t) (2 * (int) c - 15); + if (gu_type == kIQ3_XXS) return (int8_t) ((c & 8u) ? -iq3[c & 7u] : iq3[c & 7u]); + return iq2[c & 7u]; + }; + g[8 * m + b] = val(c0); + g[8 * m + 4 + b] = val(c1); + } +} + +// ------------------------------------------------------------------------------------------------ the slot hash +// +// STRATA_EXPERT_NIBBLE_RECHECK's fingerprint of a slot: over the slot's first `hashed` bytes (kGuBytes plus the down +// rows; the alignment tail is not written and not hashed) as little-endian 32-bit words w_i, the last one +// zero-extended, H = sum_i (uint64) (w_i ^ i) * kHashMul mod 2^64. A sum, so the device's order of adding does not +// change it; the index term makes a moved word count. + +inline constexpr uint64_t kHashMul = 0x9E3779B97F4A7C15ull; + +/// The host reference of the slot hash (the device hash gives the same value for the same bytes). +inline uint64_t hash_host(const void* p, uint64_t bytes) { + const uint8_t* s = (const uint8_t*) p; + uint64_t h = 0; + const uint64_t n = (bytes + 3) / 4; + for (uint64_t i = 0; i < n; ++i) { + uint32_t w = 0; + const uint64_t at = 4 * i, take = bytes - at < 4 ? bytes - at : 4; + std::memcpy(&w, s + at, (size_t) take); // little-endian hosts only + h += (uint64_t) (w ^ (uint32_t) i) * kHashMul; + } + return h; +} + +// ------------------------------------------------------------------------------------------------ the switches + +struct Config { + bool on = false; ///< STRATA_EXPERT_NIBBLE=1 + bool recheck = false; ///< STRATA_EXPERT_NIBBLE_RECHECK=1 (debug: every slot's hash per request) + std::vector<int> fmts{ kIQ2_S, kIQ3_XXS, kIQ3_S }; ///< STRATA_EXPERT_NIBBLE_FMTS (default 22,18,21) + std::vector<int64_t> skip; ///< STRATA_EXPERT_NIBBLE_SKIP: layers kept in their GGUF blocks + std::string error; ///< non-empty: a malformed value - the start is refused +}; + +namespace detail { +/// "a,b,c" -> integers; false on anything else (empty = an empty list). +inline bool parse_list(const char* s, std::vector<int64_t>& out) { + out.clear(); + while (s != nullptr && *s != '\0') { + char* end = nullptr; + const long long v = std::strtoll(s, &end, 10); + if (end == s) return false; + out.push_back((int64_t) v); + s = end; + if (*s == ',') ++s; + else if (*s != '\0') return false; + } + return true; +} +} // namespace detail + +/// The switches, read once (generate.cpp reads them before anything is allocated). +inline const Config& config() { + static const Config c = [] { + Config r; + const char* e = std::getenv("STRATA_EXPERT_NIBBLE"); + if (e != nullptr && e[0] != '\0' && std::strcmp(e, "0") != 0) { + if (std::strcmp(e, "1") == 0) r.on = true; + else r.error = std::string("STRATA_EXPERT_NIBBLE=") + e + ": expected 0 or 1"; + } + const char* rc = std::getenv("STRATA_EXPERT_NIBBLE_RECHECK"); + r.recheck = rc != nullptr && std::strcmp(rc, "1") == 0; + std::vector<int64_t> v; + if (const char* f = std::getenv("STRATA_EXPERT_NIBBLE_FMTS"); f != nullptr && f[0] != '\0') { + if (!detail::parse_list(f, v)) { + if (r.error.empty()) r.error = std::string("STRATA_EXPERT_NIBBLE_FMTS=") + f + ": expected ggml types, e.g. 22,18,21"; + } else { + r.fmts.clear(); + for (const int64_t t : v) { + if (!fmt_built((int) t) && r.error.empty()) + r.error = "STRATA_EXPERT_NIBBLE_FMTS: type " + std::to_string(t) + + " is not converted (22 IQ2_S, 18 IQ3_XXS, 21 IQ3_S)"; + r.fmts.push_back((int) t); + } + } + } + if (const char* k = std::getenv("STRATA_EXPERT_NIBBLE_SKIP"); k != nullptr && k[0] != '\0') { + if (!detail::parse_list(k, r.skip) && r.error.empty()) + r.error = std::string("STRATA_EXPERT_NIBBLE_SKIP=") + k + ": expected layer numbers, e.g. 40,44"; + } + return r; + }(); + return c; +} + +/// With the switch on, the first environment setting it refuses, as a message (empty = none): the paths that would +/// read a converted slot as GGUF blocks, write GGUF bytes into one, or run other kernels for the converted layers +/// than the ones the 4-bit kernels are bit for bit. The command-line half (--peer-device, remote expert caches, +/// --kv-grow, --vram-elastic), the cc 6.0 check, full residency and no loan are generate.cpp's checks; the prompt +/// path's own (MMQ on every converted layer) is Prefill::nibble_prompt_check. +inline std::string env_conflicts() { + auto set = [](const char* n) -> const char* { + const char* v = std::getenv(n); + return v != nullptr && v[0] != '\0' ? v : nullptr; + }; + const char* v = set("STRATA_MMQ_DIRECT"); + if (v != nullptr && std::atoi(v) != 0) + return "STRATA_MMQ_DIRECT (the prompt MMQ would read a converted slot in place as GGUF blocks)"; + v = set("STRATA_PREFILL_MMQ"); + if (v != nullptr && std::atoi(v) == 0) return "STRATA_PREFILL_MMQ=0 (the FP16 prompt path reads GGUF blocks)"; + v = set("STRATA_PF_FUSED"); + if (v != nullptr && v[0] == '1') return "STRATA_PF_FUSED=1 (the fused prompt kernels read GGUF blocks)"; + v = set("STRATA_FS_SLOTS"); + if (v != nullptr && std::atoi(v) > 0) return "STRATA_FS_SLOTS (Foresight swaps GGUF blobs into slots)"; + v = set("STRATA_EXPERT_V2"); + if (v != nullptr && v[0] == '1') return "STRATA_EXPERT_V2=1 (the S26 kernels, not the CUDA layout, on IQ3_S)"; + v = set("STRATA_KV_GROW"); + if (v != nullptr && v[0] != '0') return "STRATA_KV_GROW (the elastic K/V moves slots at their GGUF size)"; + v = set("STRATA_EXP_MODE"); + if (v != nullptr && std::atoi(v) != 0 && std::atoi(v) != 8) + return "STRATA_EXP_MODE other than 0 or 8 (another layout's gate/up kernels)"; + return {}; +} + +// ------------------------------------------------------------------------------------------------ the VRAM table + +/// One layer's slots. `on` false: the GGUF blob, `slot_bytes == raw_bytes`, the production kernels. +struct LayerVram { + bool on = false; + int gu_type = -1, d_type = -1; + uint64_t down_off = 0; ///< in the slot: kDownOff when on, else the raw blob's down_off + uint64_t down_bytes = 0; ///< the down rows (raw_bytes - raw_down_off) + uint64_t hashed = 0; ///< bytes the slot hash covers: kGuBytes + down_bytes when on, else 0 + uint64_t slot_bytes = 0; ///< what the expert cache allocates per slot (`open_sized`, every estimate) + // the raw blob as the arena and the pack hold it (expert_layout().fmt[l]); the transcoder reads these + uint64_t raw_bytes = 0, raw_gu_row = 0, raw_up_off = 0, raw_down_off = 0; +}; + +/// One layer's entry from its GGUF format and the switches (pure; `plan_layers` calls it per layer). +inline LayerVram plan_layer(int64_t l, const strata::kernels::cpu::NativeFmt& f, const Config& c) { + LayerVram v; + v.gu_type = f.gu_type; + v.d_type = f.d_type; + v.raw_bytes = f.bytes; + v.raw_gu_row = f.gu_row; + v.raw_up_off = f.up_off; + v.raw_down_off = f.down_off; + v.down_bytes = f.bytes - f.down_off; + v.down_off = f.down_off; + v.slot_bytes = f.bytes; + bool listed = false, skipped = false; + for (const int t : c.fmts) listed = listed || t == f.gu_type; + for (const int64_t s : c.skip) skipped = skipped || s == l; + // [gate | up | down] exactly, no NVFP4 tail, the down rows a whole number of 16-byte words (the gathers copy them so) + const bool shape = f.n_embd == kNEmbd && f.n_ff == kNFf && f.gu_row == raw_gu_row(f.gu_type) && + f.up_off == (uint64_t) kNFf * f.gu_row && f.down_off == 2 * f.up_off && f.bytes > f.down_off && + f.tail_off == 0 && (f.bytes - f.down_off) % 16 == 0; + if (c.on && c.error.empty() && listed && !skipped && fmt_built(f.gu_type) && shape) { + v.on = true; + v.down_off = kDownOff; + v.hashed = kGuBytes + v.down_bytes; + v.slot_bytes = slot_bytes_for(v.down_bytes); + } + return v; +} + +/// Every layer's entry for this pack (all off for a Q2_0 pack or with the switch off). `err`: a SKIP layer out of +/// range, or the switch on with a Q2_0 pack. +inline std::vector<LayerVram> plan_layers(const strata::kernels::cpu::ExpertLayout& lay, std::string& err) { + const Config& c = config(); + std::vector<LayerVram> out((size_t) (lay.n_layers > 0 ? lay.n_layers : 0)); + for (int64_t l = 0; l < (int64_t) out.size(); ++l) { + if (lay.native && (size_t) l < lay.fmt.size()) out[(size_t) l] = plan_layer(l, lay.fmt[(size_t) l], c); + else out[(size_t) l].slot_bytes = out[(size_t) l].raw_bytes = lay.blob_bytes(l); + } + if (c.on && !lay.native) err = "STRATA_EXPERT_NIBBLE needs a native pack (native_experts.txt)"; + for (const int64_t s : c.skip) + if (c.on && (s < 0 || s >= lay.n_layers) && err.empty()) + err = "STRATA_EXPERT_NIBBLE_SKIP: layer " + std::to_string(s) + " is not in the model"; + return out; +} + +namespace detail { +inline std::vector<LayerVram>& table() { + static std::vector<LayerVram> t; + return t; +} +} // namespace detail + +/// generate.cpp only: the table, once, after `expert_layout_load` and BEFORE the first slot estimate (placement +/// search, can_start, the cache's auto size, every `open_sized`). Not thread-safe: set before any other thread. +inline void set_layers(std::vector<LayerVram> v) { detail::table() = std::move(v); } + +/// Layer `l`'s entry (an off entry when the table is not set or `l` is outside it). Read-only after `set_layers`. +inline const LayerVram& layer(int64_t l) { + static const LayerVram off; + const auto& t = detail::table(); + return l >= 0 && (size_t) l < t.size() ? t[(size_t) l] : off; +} + +/// Whether any layer is converted (the switch on and the table set). +inline bool any_on() { + for (const LayerVram& v : detail::table()) + if (v.on) return true; + return false; +} + +/// Bytes of one of layer `l`'s VRAM slots: the converted size for a converted layer, else the layout's blob bytes +/// (exactly `expert_layout().blob_bytes(l)`: with the switch off every caller sizes what it sized before). +inline uint64_t slot_bytes(int64_t l) { + const auto& t = detail::table(); + if (l >= 0 && (size_t) l < t.size()) return t[(size_t) l].slot_bytes; + return strata::kernels::cpu::expert_layout().blob_bytes(l); +} + +// ------------------------------------------------------------------------------------------------ fatal paths + +/// A converted layer reached a path that would compute or copy it as GGUF blocks: say where and stop. Never a +/// silent wrong answer. +[[noreturn]] inline void fatal(int64_t l, const char* where, const char* why) { + std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: layer %lld (%s, 4-bit slots) reached %s: %s - stopping\n", + (long long) l, fmt_name(layer(l).gu_type), where != nullptr ? where : "?", why != nullptr ? why : ""); + std::fflush(stderr); + std::abort(); +} + +/// Before each raw slot copy that bypasses the ExpertCache API (the adaptive tier's copies, the elastic K/V's slot +/// moves): fatal when `l` is a converted layer. The startup refusals keep these paths off; this is the backstop +/// (with `ExpertCache::seal()` for the API's own fills). +inline void guard_raw(int64_t l, const char* where) { + if (layer(l).on) fatal(l, where, "a raw slot copy at the GGUF size"); +} + +// ------------------------------------------------------------------------------------------------ the decode kernels +// +// Two skeletons in the shape of native_gu_multi_kernel (16 lanes a row, a group's entries GRP_NC at a time), both bit +// for bit the production gate/up: S stages the entries' q8_1 blocks in shared memory and decodes each item where it +// is used (IQ3_S: v = 2u - 15 restored per byte, then the production apply); P loads the lane's codes, scales and d +// before staging the qs words as 16-byte rows (IQ3_S: sum = 2 dot(u, x) - 15 sum(x), the same int32). Per format the +// faster one on 4x GP100 at T = 1..6 (native_expert_bench --nibble): IQ2_S P, IQ3_XXS S, IQ3_S S. + +inline constexpr int kSkelS = 0, kSkelP = 1; +STRATA_NIB_HD constexpr int gu_skeleton(int gu_type) { return gu_type == kIQ2_S ? kSkelP : kSkelS; } + +// ------------------------------------------------------------------------------------------------ iq_kernels.cu +// +// Device addresses are `unsigned long long` (as native_expert_grouped's grp_ptr), streams `void*`; each returns the +// CUDA error code (0 = success) so the caller can name the layer. A build without STRATA_EXPERT_NIBBLE_BUILT +// returns cudaErrorInvalidValue (1) from each. + +/// The reverse codebooks (grid magnitudes -> GGUF grid index) `check_gguf` and `gather_gguf` use, built on the CURRENT +/// device (once per device; call it at load, before any capture). Non-zero also when a grid entry is not unique. +int prepare(void* stream); + +/// Converts `n` raw blobs of layer `L` (device `staging`, `L.raw_bytes` apart, as the host arena holds them) into +/// the converted slots at `slot_ptrs[0..n)` (a device array): codes, scales, d. The down rows are not touched (the +/// caller copies them to `slot + kDownOff`). Every item is decoded with the production `Split<TG>::load`, encoded, +/// decoded from the written code again and compared with W.g[0..7], the scale and d; each item that differs or holds +/// a weight outside the code set adds 1 to `*bad` (device). L.on must be true. +int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream); + +/// The GGUF gate/up blocks rebuilt from each of the `n` (<= 64) converted slots at `slot_ptrs` and its down rows, +/// compared with the raw blobs in `staging` (`L.raw_bytes` apart) byte for byte: each 32-bit word that differs adds 1 +/// to `*bad`. `prepare` first. +int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream); + +/// The prompt path's gather of a converted layer's experts (prefill.cpp, MMQ): for q in [first, n) (n <= 16), the +/// GGUF [gate | up] blocks rebuilt from slot `slots[q]` (host array of device addresses) into gu_dst + q * gu_stride - +/// the bytes the raw blob holds, byte for byte - and its down rows copied to d_dst + q * d_stride; `zero_bytes` zeroed +/// after expert n - 1's gate/up and down (MMQ's tail). Every address, stride and size 16-byte aligned. `prepare` +/// on this device first. +int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride, + void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream); + +/// The slot hash (`hash_host`'s value) of the `L.hashed` bytes at each `slot_ptrs[i]`, into device `out[0..n)`. +int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out, + void* stream); + +} // namespace strata::core::nibble diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index ce06a9fe..b1f5ae5a 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -51,9 +51,16 @@ struct NativeExpertLayout { // APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before // quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr. int had_block = 0; + bool gu_nib = false; // STRATA_EXPERT_NIBBLE: gate/up as 4-bit codes (strata/core/expert_nibble.hpp's + // slot); set only by native_expert_layout_nib const float* d_signs = nullptr; }; NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +/// STRATA_EXPERT_NIBBLE: a converted VRAM slot - gate/up as 4-bit codes, scales and d (expert_nibble.hpp's layout: +/// up_off = the up rows' codes, down_off = kGuBytes, bytes = the slot), the GGUF down rows after them. IQ2_S / +/// IQ3_XXS / IQ3_S at n_embd 2560, n_ff 640 only, and only in a build with the kernels (`native_expert_nib_supported`). +NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; /// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the /// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated). bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; @@ -83,9 +90,15 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long /// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results /// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs. void native_grouped_set_v1(bool v1); +/// The bench / parity only: the 4-bit gate/up kernel of every format (-1 = expert_nibble.hpp's gu_skeleton, the +/// default; 0 = the S skeleton; 1 = the P skeleton). Bitwise the same results; set before graph capture. +void native_expert_nib_set_variant(int v); +/// gu-proto (nib_gu_proto.cuh): variant v's registers, local bytes and resident 256-thread blocks per SM for gu_type; +/// false when v is not a gu-proto id (>= 10) or the type has none. +bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm); /// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase -/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down). +/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down, 3 gate/up only). void native_expert_set_mode(int mode, int phase); /// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width` diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 39ed8557..fa75c31d 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -169,6 +169,11 @@ public: /// build with the pointer-table MMQ (STRATA_MMQ_TAB). static size_t slot_guard_bytes(); + /// STRATA_EXPERT_NIBBLE=1: whether every converted layer's experts reach the prompt path's MMQ gather only (the + /// GGUF blocks rebuilt from the 4-bit slots); false with the first layer and the reason in `why`. Pure: the + /// layers' formats, the environment and the visible GPUs (generate.cpp asks once, before anything is allocated). + static bool nibble_prompt_check(std::string& why); + /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest /// first, -1 for none) and is advanced to the last two of these. bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index bd98ad71..72523b9c 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -24,6 +24,17 @@ namespace strata::core { +namespace { +// STRATA_EXPERT_NIBBLE: a write into a sealed cache (see ExpertCache::seal). Says which call and stops: the slots hold +// 4-bit codes the GGUF bytes would overwrite, or a GGUF expert where a 4-bit one is expected - a wrong reply, not an error. +[[noreturn]] void sealed_write(const char* call, int32_t slot) { + std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: ExpertCache::%s(slot %d) after the cache was sealed - a GGUF " + "blob would be written into the 4-bit expert slots: stopping\n", call, (int) slot); + std::fflush(stderr); + std::abort(); +} +} // namespace + // See the header. NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same: // not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim. Swap is not counted here (unlike // NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one. @@ -621,6 +632,7 @@ void ExpertCache::close() { next_free_ = 0; fills_ = 0; admitted_ = 0; + sealed_ = false; layer_next_.clear(); } @@ -641,6 +653,7 @@ int32_t ExpertCache::slot_of(int64_t layer, int64_t expert) const { } int32_t ExpertCache::admit(int64_t layer, int64_t expert) { + if (sealed_) return kNotResident; // STRATA_EXPERT_NIBBLE: nothing is admitted (and so filled) after the startup fill if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident; const size_t at = (size_t) (layer * n_expert_ + expert); if (residency_[at] != kNotResident) return residency_[at]; @@ -673,6 +686,7 @@ const uint8_t* ExpertCache::device_slot(int32_t slot) const { } bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes) { + if (sealed_) sealed_write("fill_slot", slot); const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); uint8_t* dst = device_slot(slot); if (dst == nullptr) { @@ -695,6 +709,7 @@ bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream } bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + if (sealed_) sealed_write("fill_slot_blocking", slot); const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); uint8_t* dst = device_slot(slot); if (dst == nullptr) { @@ -726,6 +741,7 @@ bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std } bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + if (sealed_) sealed_write("fill_slot_queued", slot); const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); uint8_t* dst = device_slot(slot); if (dst == nullptr || host_blob == nullptr) { @@ -743,6 +759,7 @@ bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std:: } bool ExpertCache::fill_slot_queued_parts(int32_t slot, const BlobPart* parts, int n, std::string& err) { + if (sealed_) sealed_write("fill_slot_queued_parts", slot); uint8_t* dst = device_slot(slot); if (dst == nullptr || parts == nullptr || n <= 0) { err = "ExpertCache::fill_slot_queued_parts: slot outside the arena or no pieces"; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index b8ad8fb4..ec258c89 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1,5 +1,6 @@ // src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract. #include "strata/core/expert_source.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/foresight_swap.hpp" #include "strata/core/on_device.hpp" #include "strata/platform/aux_cpus.hpp" @@ -5221,6 +5222,14 @@ void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids d.hit_pending = false; if (!d.hits_ready() || ids == nullptr || k <= 0) return; if ((int64_t) d.is_hit.size() < k) d.is_hit.resize((size_t) k); + // STRATA_EXPERT_NIBBLE=1: this split computes a resident expert with the GGUF-block kernels and admits + fills + // a missed one with its GGUF blob - neither may meet a layer whose slots hold 4-bit codes (a native pack's + // experts run in the verify windows, so this is the backstop, never the path) +#if STRATA_EXPERT_NIBBLE_BUILT // compiled out of every other build: nothing is added to the hit split there + if (strata::core::nibble::layer(d.layers).on) + strata::core::nibble::fatal(d.layers, "the expert source's hit split (expert_hit_run)", + "it computes resident experts as GGUF blocks and fills slots with GGUF blobs"); +#endif // ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================ // diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 06306a23..727fea0e 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/expert_nibble.hpp" #include "strata/core/pin_budget.hpp" #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) #include "strata/core/host_graph_launch.hpp" @@ -2127,11 +2128,21 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const auto& lay = strata::kernels::cpu::expert_layout(); // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging. // `gy`: the native launch's groups side by side (0: cap, one block row per possible group). - auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf) { + // `vram`: the groups point into this GPU's expert slots - a layer STRATA_EXPERT_NIBBLE converted holds its + // gate/up there as 4-bit codes (expert_nibble.hpp); the PCIe share's blobs (host memory, staging) never do. + auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf, + bool vram) { if (lay.native) { // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) const auto& f = lay.fmt[(size_t) l]; +#if STRATA_EXPERT_NIBBLE_BUILT + NativeExpertLayout L = vram && strata::core::nibble::layer(l).on + ? native_expert_layout_nib(f.gu_type, f.d_type, f.n_embd, f.n_ff) + : native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); +#else + (void) vram; NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); +#endif if (f.had_d) { L.had_block = f.had_block; L.d_signs = had_sh_; } // APR: h is rotated in there native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap, nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy); @@ -2143,7 +2154,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { bool hits_in_combine = false; if (ar_on()) { stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, parts_out); + grouped(p_ptr, p_start, p_counts, 0, parts_out, true); stamp(l, 20, grp); } else { if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) @@ -2161,7 +2172,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, hit_out); + grouped(p_ptr, p_start, p_counts, 0, hit_out, true); stamp(l, 20, grp); if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); else if (m_bal_ != nullptr) // set_pcie_balance: the PCIe part starts @@ -2176,7 +2187,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { stamp(l, 21, grp); // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them - grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out); + grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out, false); stamp(l, 22, grp); if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs); diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 9cb6894f..50f0a839 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -5,6 +5,7 @@ // MIT license, third_party/ggml/LICENSE). The block structs and codebook grids come from its ggml-common.h, // included unchanged. #include "strata/kernels/iq_kernels.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/sm75_series.hpp" #include "strata/core/sm120_series.hpp" #include "strata/kernels/gfx_arch.hpp" @@ -4476,6 +4477,704 @@ void launch_down_ws(const NativeExpertLayout& L, int64_t gy, int64_t cap_groups, #endif // STRATA_DOWN_WS_BUILT +// ---------------------------------------------------------------- STRATA_EXPERT_NIBBLE: gate/up on 4-bit slots +// (opt-in, default off; strata/core/expert_nibble.hpp has the slot layout and the item code). A converted layer's +// VRAM slot holds each 32-weight item of a gate/up row as 16 bytes of 4-bit codes (one 16-byte load), its integer +// scale byte and the superblock's fp16 d bit for bit; the kernels below decode an item into the production +// Split<TG>::W (or IQ3_S's offset form) with 1-4 instructions per four weights instead of the codebook lookups, then +// run the production integer chain and float tail in the production lane / item / addition order (row_dot_80_sub16: +// k = t, t+32, t+64 into s, t+16, t+48 into s16, __fadd_rn, xor 8, 4, 2, 1), so every gate / up value is bit for bit +// native_gu_multi_kernel<TG, *, true>'s. Two skeletons in the shape of native_gu_multi_kernel (grid (80, gy), 256 +// threads, 16 lanes a row, a group's entries GRP_NC at a time, the group stride): +// S the entries' q8_1 blocks staged in shared memory, each item's code loaded and decoded where it is used, the +// production apply on it (IQ3_S: v = 2u - 15 restored per byte - no sum of x) +// P the lane's five items' codes, scales and d loaded before the staging (in flight during it), the entries' qs +// words staged as 16-byte rows and ds as a float, the production chain written out on the registers (IQ3_S: +// sumi = 2 dot(u, x) - 15 sum(x) with sum(x) from the staged words: the same int32) +// Then the load-time transcoder, the GGUF rebuild (the start-up check and the prompt path's gather) and the slot hash. +// Built only with STRATA_EXPERT_NIBBLE_BUILT (a CUDA build with STRATA_EXPERIMENTAL_SM60); elsewhere a gu_nib layout +// stops in native_expert_grouped, and the switch is refused at start. +#if STRATA_EXPERT_NIBBLE_BUILT +namespace nibk = strata::core::nibble; + +__device__ __forceinline__ uint32_t nib_prmt(uint32_t a, uint32_t b, uint32_t sel) { + uint32_t r; + asm("prmt.b32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(sel)); // the sign-replicate modes too + return r; +} + +// One item's code -> the production W (what Split<TG>::load gives for the same GGUF item, byte for byte). +template<int TG> struct NibLoad; +template<> struct NibLoad<22> { // IQ2_S: the nibble is the PRMT selector into {8,25,43,0} {-8,-25,-43,0} + using W = Split<22>::W; + __device__ static W load(uint4 q, uint32_t sc, __half d) { + constexpr uint32_t T0 = 0x002B1908u, T1 = 0x00D5E7F8u; + W r; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + r.g[2 * m + 0] = (int) nib_prmt(T0, T1, qw[m]); + r.g[2 * m + 1] = (int) nib_prmt(T0, T1, qw[m] >> 16); + } + r.ls0 = sc & 0x0F; + r.ls1 = sc >> 4; + r.dw = __half2float(d); + return r; + } +}; +template<> struct NibLoad<18> { // IQ3_XXS: magnitude PRMT into {4..62}, sign-replicated byte masks, (g ^ m) + (m & 1s) + using W = Split<18>::W; + __device__ static W load(uint4 q, uint32_t sc, __half d) { + constexpr uint32_t T0 = 0x1C140C04u, T1 = 0x3E342C24u; // {4,12,20,28} {36,44,52,62} + W r; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t w = qw[m], ms = w & 0x77777777u, a = w << 4; + const uint32_t m0 = nib_prmt(a, w, 0xD9C8u), m1 = nib_prmt(a, w, 0xFBEAu); + const uint32_t g0 = nib_prmt(T0, T1, ms), g1 = nib_prmt(T0, T1, ms >> 16); + r.g[2 * m + 0] = (int) ((g0 ^ m0) + (m0 & 0x01010101u)); + r.g[2 * m + 1] = (int) ((g1 ^ m1) + (m1 & 0x01010101u)); + } + r.ls = (int) sc; + r.dw = __half2float(d); + return r; + } +}; +template<> struct NibLoad<21> { // IQ3_S: v = 2u - 15 per byte, ((2u | 0x80) - 0x0F) ^ 0x80 (every byte >= 0x80: no borrow) + using W = Split<21>::W; + __device__ static W load(uint4 q, uint32_t sc, __half d) { + W r; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t lo2 = (qw[m] << 1) & 0x1E1E1E1Eu, hi2 = (qw[m] >> 3) & 0x1E1E1E1Eu; // 2u per byte + r.g[2 * m + 0] = (int) (((lo2 | 0x80808080u) - 0x0F0F0F0Fu) ^ 0x80808080u); + r.g[2 * m + 1] = (int) (((hi2 | 0x80808080u) - 0x0F0F0F0Fu) ^ 0x80808080u); + } + r.ls = (int) sc; + r.dw = __half2float(d); + return r; + } +}; + +// S skeleton row dot over one converted row (codes, scales, d of row `row`), x the staged blocks +template<int TG, int NC> +__device__ __forceinline__ void nib_row_dot_s(const uint4* __restrict__ crow, const uint8_t* __restrict__ srow, + const __half* __restrict__ drow, const block_q8_1* x, const int (&off)[NC], + int t, float (&s)[NC]) { + using Q = NibLoad<TG>; + const int iqs = 2 * (t & 7), kb = t >> 3; + const block_q8_1* xb[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) { s[c] = 0.0f; xb[c] = x + off[c] + kb * 8; } +#pragma unroll + for (int i = 0; i < 3; ++i) { + const typename Q::W w = Q::load(crow[t + 32 * i], srow[t + 32 * i], drow[kb + 4 * i]); +#pragma unroll + for (int c = 0; c < NC; ++c) s[c] += Split<TG>::apply(w, xb[c] + 32 * i, iqs); + } + float s16[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const typename Q::W w = Q::load(crow[t + 16 + 32 * i], srow[t + 16 + 32 * i], drow[kb + 2 + 4 * i]); +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] += Split<TG>::apply(w, xb[c] + 16 + 32 * i, iqs); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = __fadd_rn(s[c], s16[c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// One pass of the S skeleton: the n (1..GRP_NC) entries from e staged, then this thread's row against them. +// Block-uniform (e, n): every thread reaches both barriers. +template<int TG> +__device__ __forceinline__ void nib_pass_s(block_q8_1* s_x, const uint4* crow, const uint8_t* srow, const __half* drow, + const int32_t* __restrict__ ent_tok, const block_q8_1* __restrict__ xq, + int e, int n, int t, float* dst, int r) { + int tok[GRP_NC]; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) tok[c] = ent_tok[e + min(c, n - 1)]; + __syncthreads(); + for (int i = threadIdx.x; i < n * 80 * 9; i += 256) { // 80 blocks x 36 B an entry, as 9 words a block + const int c = i / 720, rem = i % 720; + ((int*) s_x)[c * 720 + rem] = ((const int*) (xq + (size_t) tok[c] * 80))[rem]; + } + __syncthreads(); + if (n == 1) { + const int o[1] = { 0 }; float s[1]; + nib_row_dot_s<TG, 1>(crow, srow, drow, s_x, o, t, s); + if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0]; + } else if (n == 2) { + const int o[2] = { 0, 80 }; float s[2]; + nib_row_dot_s<TG, 2>(crow, srow, drow, s_x, o, t, s); + if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else if (n == 3) { + const int o[3] = { 0, 80, 160 }; float s[3]; + nib_row_dot_s<TG, 3>(crow, srow, drow, s_x, o, t, s); + if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else { + const int o[4] = { 0, 80, 160, 240 }; float s[4]; + nib_row_dot_s<TG, 4>(crow, srow, drow, s_x, o, t, s); + if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } +} + +// P skeleton: x as two LDS.128 per item and entry, ds as the float __low2float gives +struct NibXQ { int4 a, b; }; + +template<int TG> +__device__ __forceinline__ float nib_p_apply(const uint4& q, uint32_t sc, __half dh, const NibXQ& x, float dx, int xsum) { + if constexpr (TG == 22) { // SplitLs2::apply on the registers + const typename NibLoad<22>::W w = NibLoad<22>::load(q, sc, dh); + int sumi0 = 0, sumi1 = 0; + sumi0 = ggml_cuda_dp4a(w.g[0], x.a.x, sumi0); sumi0 = ggml_cuda_dp4a(w.g[1], x.a.y, sumi0); + sumi0 = ggml_cuda_dp4a(w.g[2], x.a.z, sumi0); sumi0 = ggml_cuda_dp4a(w.g[3], x.a.w, sumi0); + sumi1 = ggml_cuda_dp4a(w.g[4], x.b.x, sumi1); sumi1 = ggml_cuda_dp4a(w.g[5], x.b.y, sumi1); + sumi1 = ggml_cuda_dp4a(w.g[6], x.b.z, sumi1); sumi1 = ggml_cuda_dp4a(w.g[7], x.b.w, sumi1); + const int sumi = (sumi0 * w.ls0 + sumi1 * w.ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = w.dw * dx; + return d * sumi; + } else if constexpr (TG == 18) { // Split<18>::apply on the registers + const typename NibLoad<18>::W w = NibLoad<18>::load(q, sc, dh); + int sumi = 0; + sumi = ggml_cuda_dp4a(w.g[0], x.a.x, sumi); sumi = ggml_cuda_dp4a(w.g[1], x.a.y, sumi); + sumi = ggml_cuda_dp4a(w.g[2], x.a.z, sumi); sumi = ggml_cuda_dp4a(w.g[3], x.a.w, sumi); + sumi = ggml_cuda_dp4a(w.g[4], x.b.x, sumi); sumi = ggml_cuda_dp4a(w.g[5], x.b.y, sumi); + sumi = ggml_cuda_dp4a(w.g[6], x.b.z, sumi); sumi = ggml_cuda_dp4a(w.g[7], x.b.w, sumi); + sumi = (w.ls * sumi + sumi / 2) / 2; + const float d = w.dw * dx; + return d * sumi; + } else { // IQ3_S, offset form: dot(v, x) = 2 dot(u, x) - 15 sum(x), exact (|2 dot(u, x)| < 2^17); then Split<21>'s + int u[8]; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + u[2 * m + 0] = (int) (qw[m] & 0x0F0F0F0Fu); + u[2 * m + 1] = (int) ((qw[m] >> 4) & 0x0F0F0F0Fu); + } + int sumu = 0; + sumu = ggml_cuda_dp4a(u[0], x.a.x, sumu); sumu = ggml_cuda_dp4a(u[1], x.a.y, sumu); + sumu = ggml_cuda_dp4a(u[2], x.a.z, sumu); sumu = ggml_cuda_dp4a(u[3], x.a.w, sumu); + sumu = ggml_cuda_dp4a(u[4], x.b.x, sumu); sumu = ggml_cuda_dp4a(u[5], x.b.y, sumu); + sumu = ggml_cuda_dp4a(u[6], x.b.z, sumu); sumu = ggml_cuda_dp4a(u[7], x.b.w, sumu); + int sumi = 2 * sumu - 15 * xsum; + sumi *= (int) sc; + const float d = __half2float(dh) * dx; + return d * sumi; + } +} + +// the lane's items in the production order: k = t, t+32, t+64 (sum s), then t+16, t+48 (sum s16) +template<int TG, int NC> +__device__ __forceinline__ void nib_row_dot_p(const uint4 (&q)[5], const uint32_t (&sc)[5], const __half (&dh)[5], + const NibXQ* __restrict__ sx, const float* __restrict__ sd, + const int* __restrict__ sxs, int t, float (&s)[NC]) { + constexpr int K[5] = { 0, 32, 64, 16, 48 }; +#pragma unroll + for (int c = 0; c < NC; ++c) s[c] = 0.0f; +#pragma unroll + for (int i = 0; i < 3; ++i) { + const int k = t + K[i]; +#pragma unroll + for (int c = 0; c < NC; ++c) + s[c] += nib_p_apply<TG>(q[i], sc[i], dh[i], sx[c * 80 + k], sd[c * 80 + k], TG == 21 ? sxs[c * 80 + k] : 0); + } + float s16[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; +#pragma unroll + for (int i = 3; i < 5; ++i) { + const int k = t + K[i]; +#pragma unroll + for (int c = 0; c < NC; ++c) + s16[c] += nib_p_apply<TG>(q[i], sc[i], dh[i], sx[c * 80 + k], sd[c * 80 + k], TG == 21 ? sxs[c * 80 + k] : 0); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = __fadd_rn(s[c], s16[c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// The P skeleton's work on one group: this lane's five items into registers, then the passes. Block-uniform. +template<int TG> +__device__ __forceinline__ void nib_group_p(NibXQ* s_x, float* s_d, int* s_xs, const uint4* crow, const uint8_t* srow, + const __half* drow, const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, int e0, int e1, int t, float* dst, int r) { + const int kb = t >> 3; + uint4 q[5]; uint32_t sc[5]; __half dh[5]; + q[0] = crow[t]; q[1] = crow[t + 32]; q[2] = crow[t + 64]; q[3] = crow[t + 16]; q[4] = crow[t + 48]; + sc[0] = srow[t]; sc[1] = srow[t + 32]; sc[2] = srow[t + 64]; sc[3] = srow[t + 16]; sc[4] = srow[t + 48]; + dh[0] = drow[kb]; dh[1] = drow[kb + 4]; dh[2] = drow[kb + 8]; dh[3] = drow[kb + 2]; dh[4] = drow[kb + 6]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + __syncthreads(); + for (int i = threadIdx.x; i < n * 80; i += 256) { + const int c = i >= 240 ? 3 : i >= 160 ? 2 : i >= 80 ? 1 : 0, kk = i - 80 * c; + const int tok = ent_tok[e + c]; + const int* src = (const int*) (xq + (size_t) tok * 80 + kk); + NibXQ v; + v.a = make_int4(src[1], src[2], src[3], src[4]); + v.b = make_int4(src[5], src[6], src[7], src[8]); + s_x[i] = v; + s_d[i] = __low2float(xq[(size_t) tok * 80 + kk].ds); + if constexpr (TG == 21) { // sum(x): the production dp4a against 0x01010101 over the 8 qs words + int xs = 0; + xs = ggml_cuda_dp4a(v.a.x, 0x01010101, xs); xs = ggml_cuda_dp4a(v.a.y, 0x01010101, xs); + xs = ggml_cuda_dp4a(v.a.z, 0x01010101, xs); xs = ggml_cuda_dp4a(v.a.w, 0x01010101, xs); + xs = ggml_cuda_dp4a(v.b.x, 0x01010101, xs); xs = ggml_cuda_dp4a(v.b.y, 0x01010101, xs); + xs = ggml_cuda_dp4a(v.b.z, 0x01010101, xs); xs = ggml_cuda_dp4a(v.b.w, 0x01010101, xs); + s_xs[i] = xs; + } + } + __syncthreads(); + if (n == 1) { + float s[1]; nib_row_dot_p<TG, 1>(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0]; + } else if (n == 2) { + float s[2]; nib_row_dot_p<TG, 2>(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else if (n == 3) { + float s[3]; nib_row_dot_p<TG, 3>(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else { + float s[4]; nib_row_dot_p<TG, 4>(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } + } +} + +// SKEL kSkelS or kSkelP for every group. grid (80, gy): 2 x 640 rows = 80 x 16, so every thread has a row and +// reaches every barrier. +constexpr int kNibSWords = GRP_NC * 80 * (int) (sizeof(block_q8_1) / 4); // S: the blocks +constexpr int kNibXqWords = GRP_NC * 80 * (int) (sizeof(NibXQ) / 4); // P: the qs rows, then ds, then sum(x) +template<int TG, int SKEL> +inline constexpr int kNibSmemWords = SKEL == nibk::kSkelS ? kNibSWords : kNibXqWords + GRP_NC * 80 + (TG == 21 ? GRP_NC * 80 : 0); +template<int TG, int SKEL> +__global__ void __launch_bounds__(256) nib_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, float* __restrict__ gate, + float* __restrict__ up) { + const int ng = *n_groups; + if (blockIdx.y >= (unsigned) ng) return; + STRATA_SHARED_ALIGN16_U32(s_buf, kNibSmemWords<TG, SKEL>); + const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15; + const int row = blockIdx.x * 16 + subwarp; // 0 .. 2 n_ff + const bool is_up = row >= nibk::kNFf; + const int r = is_up ? row - (int) nibk::kNFf : row; + float* dst = is_up ? up : gate; + for (int g = blockIdx.y; g < ng; g += gridDim.y) { + const uint8_t* slot = (const uint8_t*) grp_ptr[g]; + const uint4* crow = (const uint4*) (slot + nibk::kCodesOff) + (size_t) row * nibk::kItems; + const uint8_t* srow = slot + nibk::kScOff + (size_t) row * nibk::kItems; + const __half* drow = (const __half*) (slot + nibk::kDOff) + (size_t) row * nibk::kSuper; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + if constexpr (SKEL == nibk::kSkelP) { + nib_group_p<TG>((NibXQ*) s_buf, (float*) (s_buf + kNibXqWords), (int*) (s_buf + kNibXqWords + GRP_NC * 80), + crow, srow, drow, ent_tok, xq, e0, e1, t, dst, r); + } else { + for (int e = e0; e < e1; e += GRP_NC) + nib_pass_s<TG>((block_q8_1*) s_buf, crow, srow, drow, ent_tok, xq, e, min(GRP_NC, e1 - e), t, dst, r); + } + } +} + +#include "nib_gu_proto.cuh" // STRATA_NIB_GU_PROTO: the staged-once 4-bit gate/up kernel (id 31) + +int g_nib_variant = -1; // native_expert_nib_set_variant (the bench / parity); -1 = expert_nibble.hpp's gu_skeleton + +// STRATA_NIB_GU_PROTO: unset / 0 = off (the S / P skeleton per format); 1 (or 31) = gu-proto 31 (the activations staged +// once per two row blocks with 16-byte loads, the production row dot). Read once. +int nib_gu_proto_env() { + static const int v = [] { + const char* e = std::getenv("STRATA_NIB_GU_PROTO"); + int id = e != nullptr ? std::atoi(e) : 0; + if (id == 1) id = 31; + if (id != 31) id = 0; + if (id != 0) std::fprintf(stderr, "native_expert_grouped: STRATA_NIB_GU_PROTO: 4-bit gate/up kernel gu-proto %d\n", id); + return id; + }(); + return v; +} + +// The gate/up of a converted layer's VRAM groups: native_gu_multi_kernel's grid and outputs. +void launch_gu_nib(const NativeExpertLayout& L, dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, + float* gate, float* up) { + if (g_nib_variant >= 10) { // gu-proto (nib_gu_proto.cuh), forced by the bench / parity + if (((uintptr_t) X & 15) != 0 || + !nibx_launch(L.gu_type, g_nib_variant, grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) { + std::fprintf(stderr, "native_expert_grouped: gu-proto variant %d for type %d is not built (or x is not 16-aligned)\n", + g_nib_variant, L.gu_type); + std::exit(1); + } + return; + } + // STRATA_NIB_GU_PROTO (opt-in, default off): the gu-proto kernel in place of the S / P skeleton - bitwise the + // same gate / up (iq_nibble_parity (7), native_expert_bench --nibble --vs). The 16-byte staging needs x 16-aligned + // (verify's nat_xq_ rows are: a 256-aligned buffer, 2,880 B a token); otherwise the production kernel runs. + if (g_nib_variant < 0) { + const int pv = nib_gu_proto_env(); + if (pv != 0 && ((uintptr_t) X & 15) == 0 && + nibx_launch(L.gu_type, pv, grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) + return; + } + const int skel = g_nib_variant >= 0 ? (g_nib_variant == 1 ? nibk::kSkelP : nibk::kSkelS) : nibk::gu_skeleton(L.gu_type); +#define STRATA_NIB_GU(TG, S) \ + case TG * 2 + S: nib_gu_kernel<TG, S><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, gate, up); break; + switch (L.gu_type * 2 + skel) { + STRATA_NIB_GU(22, 0) STRATA_NIB_GU(22, 1) + STRATA_NIB_GU(18, 0) STRATA_NIB_GU(18, 1) + STRATA_NIB_GU(21, 0) STRATA_NIB_GU(21, 1) + default: + std::fprintf(stderr, "native_expert_grouped: 4-bit gate/up type %d at %lld x %lld is not built\n", L.gu_type, + (long long) L.n_embd, (long long) L.n_ff); + std::exit(1); + } +#undef STRATA_NIB_GU +} + +// ---- the load-time transcoder (expert_nibble.hpp's transcode) +template<int TG> +__device__ __forceinline__ uint32_t nib_code(int v, bool& ok) { + if constexpr (TG == 21) { // v odd in -15..15 -> u = (v + 15) / 2 + if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; } + return (uint32_t) ((v + 15) >> 1); + } else if constexpr (TG == 18) { // index of {4, 12, ..., 52, 62} | sign << 3 + const int a = v < 0 ? -v : v; + const int i = a == 62 ? 7 : ((a & 7) == 4 && a <= 52) ? (a - 4) >> 3 : -1; + if (i < 0) { ok = false; return 0; } + return (uint32_t) i | (v < 0 ? 8u : 0u); + } else { // IQ2_S: index of {8, 25, 43} | sign << 2 + const int a = v < 0 ? -v : v; + const int i = a == 8 ? 0 : a == 25 ? 1 : a == 43 ? 2 : -1; + if (i < 0) { ok = false; return 0; } + return (uint32_t) i | (v < 0 ? 4u : 0u); + } +} + +// The GGUF blocks (ggml-common.h): their size and the fp16 d at their start +template<int TG> struct NibBlk; +template<> struct NibBlk<22> { using B = block_iq2_s; }; +template<> struct NibBlk<18> { using B = block_iq3_xxs; }; +template<> struct NibBlk<21> { using B = block_iq3_s; }; + +// One thread per (expert, row, item): the production load, the code, scale and d written, read back from memory and +// decoded with the kernels' own decoders, compared with the load's W (and, for IQ3_S, the P skeleton's u against v); +// `bad` counts the items that differ or hold a weight outside the code set. +template<int TG> +__global__ void __launch_bounds__(256) nib_transcode_kernel(const uint8_t* __restrict__ src, uint64_t raw_bytes, + uint64_t gu_row, uint64_t up_off, + const unsigned long long* __restrict__ slots, long long n, + unsigned long long* __restrict__ bad) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * nibk::kRows * nibk::kItems) return; + const int k = (int) (i % nibk::kItems); + const int row = (int) ((i / nibk::kItems) % nibk::kRows); + const long long ex = i / (nibk::kItems * nibk::kRows); + const bool is_up = row >= nibk::kNFf; + const int r = is_up ? row - (int) nibk::kNFf : row; + const uint8_t* wr = src + (size_t) ex * raw_bytes + (is_up ? up_off : 0) + (size_t) r * gu_row; + const int kbx = k / Fmt<TG>::ipb, iqs = Fmt<TG>::step * (k % Fmt<TG>::ipb); + using S = Split<TG>; + const typename S::W w = S::template load<false>(wr, kbx, iqs, nullptr); + bool ok = true; + uint32_t words[4]; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t g0 = (uint32_t) w.g[2 * m], g1 = (uint32_t) w.g[2 * m + 1]; + uint32_t word = 0; +#pragma unroll + for (int b = 0; b < 4; ++b) { + const uint32_t c0 = nib_code<TG>((int) (int8_t) (g0 >> (8 * b)), ok); + const uint32_t c1 = nib_code<TG>((int) (int8_t) (g1 >> (8 * b)), ok); + if constexpr (TG == 21) word |= (c0 | c1 << 4) << (8 * b); + else word |= c0 << (4 * b) | c1 << (16 + 4 * b); + } + words[m] = word; + } + uint32_t sc; + if constexpr (TG == 22) sc = (uint32_t) (w.ls0 | w.ls1 << 4); + else sc = (uint32_t) w.ls; + ok = ok && sc < 256u; + uint8_t* slot = (uint8_t*) slots[ex]; + uint4* cp = (uint4*) (slot + nibk::code_off(row, k)); + uint8_t* sp = slot + nibk::scale_off(row, k); + *cp = make_uint4(words[0], words[1], words[2], words[3]); + *sp = (uint8_t) sc; + const __half dsrc = ((const typename NibBlk<TG>::B*) wr + kbx)->d; // the block's d, bit for bit + __half dread = dsrc; + if (k % Fmt<TG>::ipb == 0) { // the superblock's first item writes its d + __half* dp = (__half*) (slot + nibk::d_off(row, kbx)); + *dp = dsrc; + dread = __ushort_as_half(*(volatile const unsigned short*) dp); + ok = ok && __half_as_ushort(dread) == __half_as_ushort(dsrc); + } + // the code and the scale read back from memory and decoded as the kernels do + const uint4 qb = __ldcv(cp); + const uint32_t sb = *(volatile const uint8_t*) sp; + const typename NibLoad<TG>::W v = NibLoad<TG>::load(qb, sb, dread); +#pragma unroll + for (int j = 0; j < 8; ++j) ok = ok && v.g[j] == w.g[j]; + if constexpr (TG == 22) ok = ok && v.ls0 == w.ls0 && v.ls1 == w.ls1; + else ok = ok && v.ls == w.ls; + ok = ok && __float_as_uint(v.dw) == __float_as_uint(w.dw); + if constexpr (TG == 21) { // the P skeleton's u: 2u - 15 per byte is v + const uint32_t qw[4] = { qb.x, qb.y, qb.z, qb.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t u0 = qw[m] & 0x0F0F0F0Fu, u1 = (qw[m] >> 4) & 0x0F0F0F0Fu; + ok = ok && __vsub4(__vadd4(u0, u0), 0x0F0F0F0Fu) == (uint32_t) w.g[2 * m] && + __vsub4(__vadd4(u1, u1), 0x0F0F0F0Fu) == (uint32_t) w.g[2 * m + 1]; + } + } + if (!ok) atomicAdd(bad, 1ull); +} + +// ---- the GGUF rebuild (expert_nibble.hpp's check_gguf and gather_gguf) +// The reverse codebooks: a group's magnitude pattern -> its grid index (0xFFFFFFFF: not in the grid). 32-bit +// entries for atomicCAS, which also counts a pattern two grid entries share (none in ggml's grids; then refused). +constexpr int kNibRev22 = 6561, kNibRev18 = 4096, kNibRev21 = 4096; // 3^8 (IQ2_S: 8 weights), 8^4, 8^4 (4 weights) +__device__ uint32_t g_nib_rev22[kNibRev22]; +__device__ uint32_t g_nib_rev18[kNibRev18]; +__device__ uint32_t g_nib_rev21[kNibRev21]; +__device__ unsigned long long g_nib_rev_bad; + +__device__ __forceinline__ int nib_mag22(uint32_t b) { return b == 8 ? 0 : b == 25 ? 1 : b == 43 ? 2 : -1; } +__device__ __forceinline__ int nib_mag18(uint32_t b) { return b == 62 ? 7 : ((b & 7) == 4 && b <= 52) ? (int) (b - 4) >> 3 : -1; } +__device__ __forceinline__ int nib_mag21(uint32_t b) { return (b & 1) && b <= 15 ? (int) (b - 1) >> 1 : -1; } + +__global__ void nib_rev_clear_kernel() { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < kNibRev22) g_nib_rev22[i] = 0xFFFFFFFFu; + if (i < kNibRev18) g_nib_rev18[i] = 0xFFFFFFFFu; + if (i < kNibRev21) g_nib_rev21[i] = 0xFFFFFFFFu; + if (i == 0) g_nib_rev_bad = 0; +} +__global__ void nib_rev_fill_kernel() { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + uint32_t* tab = nullptr; + int key = 0; + bool ok = true; + uint32_t idx = 0; + if (i < 1024) { // iq2s_grid: 8 bytes of {8, 25, 43} + const uint64_t g = iq2s_grid[i]; + for (int j = 7; j >= 0; --j) { const int m = nib_mag22((uint32_t) (g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 3 + (m < 0 ? 0 : m); } + tab = g_nib_rev22; idx = (uint32_t) i; + } else if (i < 1024 + 256) { // iq3xxs_grid: 4 bytes of {4, ..., 62} + const uint32_t g = iq3xxs_grid[i - 1024]; + for (int j = 3; j >= 0; --j) { const int m = nib_mag18((g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 8 + (m < 0 ? 0 : m); } + tab = g_nib_rev18; idx = (uint32_t) (i - 1024); + } else if (i < 1024 + 256 + 512) { // iq3s_grid: 4 bytes of {1, 3, ..., 15} + const uint32_t g = iq3s_grid[i - 1280]; + for (int j = 3; j >= 0; --j) { const int m = nib_mag21((g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 8 + (m < 0 ? 0 : m); } + tab = g_nib_rev21; idx = (uint32_t) (i - 1280); + } else { + return; + } + if (!ok || atomicCAS(tab + key, 0xFFFFFFFFu, idx) != 0xFFFFFFFFu) atomicAdd(&g_nib_rev_bad, 1ull); +} + +// The bytes of GGUF block `s` of row `row`'s item `ib` (0..7) rebuilt from the slot into `blk` (shared memory, the +// block's first byte): the codes give each weight's magnitude index and sign, the reverse codebook the grid index, +// the scale byte and d are the block's own. Disjoint bytes per item (IQ3_S: the even item writes the shared scale +// byte); item 0 writes d. +template<int TG> +__device__ __forceinline__ void nib_gguf_item(uint8_t* blk, int ib, const uint8_t* __restrict__ slot, int row, int k) { + const uint4 q4 = *(const uint4*) (slot + nibk::code_off(row, k)); + const uint32_t w[4] = { q4.x, q4.y, q4.z, q4.w }; + const uint32_t sc = slot[nibk::scale_off(row, k)]; + if (ib == 0) { + const uint8_t* dp = slot + nibk::d_off(row, k / 8); + blk[0] = dp[0]; + blk[1] = dp[1]; + } + if constexpr (TG == 22) { // block_iq2_s: d, qs[32] grid low bits, qs[32] signs, qh[8], scales[8] + uint32_t qh = 0; +#pragma unroll + for (int l = 0; l < 4; ++l) { + int key = 0; + uint32_t sg = 0; +#pragma unroll + for (int j = 7; j >= 0; --j) { + const uint32_t c = j < 4 ? (w[l] >> (4 * j)) & 15u : (w[l] >> (16 + 4 * (j - 4))) & 15u; + key = key * 3 + (int) (c & 3u); + sg |= ((c >> 2) & 1u) << j; + } + const uint32_t idx = key < kNibRev22 ? g_nib_rev22[key] : 0xFFFFFFFFu; + blk[2 + 4 * ib + l] = (uint8_t) idx; + blk[2 + 32 + 4 * ib + l] = (uint8_t) sg; + qh |= ((idx >> 8) & 3u) << (2 * l); + } + blk[66 + ib] = (uint8_t) qh; + blk[74 + ib] = (uint8_t) sc; + } else if constexpr (TG == 18) { // block_iq3_xxs: d, qs[64] grid indices, 8 x aux32 (4 x 7 sign bits | scale << 28) + uint32_t aux = sc << 28; +#pragma unroll + for (int l = 0; l < 4; ++l) { + uint32_t sg = 0; +#pragma unroll + for (int h = 0; h < 2; ++h) { + int key = 0; +#pragma unroll + for (int j = 3; j >= 0; --j) { + const uint32_t c = (w[l] >> (16 * h + 4 * j)) & 15u; + key = key * 8 + (int) (c & 7u); + sg |= ((c >> 3) & 1u) << (4 * h + j); + } + blk[2 + 8 * ib + 2 * l + h] = (uint8_t) g_nib_rev18[key]; + } + aux |= (sg & 0x7Fu) << (7 * l); // the 8th sign is the parity of the other 7 (ksigns_iq2xs) + } + blk[2 + 64 + 4 * ib + 0] = (uint8_t) aux; + blk[2 + 64 + 4 * ib + 1] = (uint8_t) (aux >> 8); + blk[2 + 64 + 4 * ib + 2] = (uint8_t) (aux >> 16); + blk[2 + 64 + 4 * ib + 3] = (uint8_t) (aux >> 24); + } else { // block_iq3_s: d, qs[64] grid low bits, qh[8], signs[32], scales[4] (two items' nibbles each) + uint32_t qh = 0; +#pragma unroll + for (int l = 0; l < 4; ++l) { + uint32_t sg = 0; +#pragma unroll + for (int h = 0; h < 2; ++h) { + int key = 0; +#pragma unroll + for (int j = 3; j >= 0; --j) { + const uint32_t u = (w[l] >> (8 * j + 4 * h)) & 15u; // v = 2u - 15: negative for u <= 7 + key = key * 8 + (int) (u <= 7u ? 7u - u : u - 8u); + sg |= (u <= 7u ? 1u : 0u) << (4 * h + j); + } + const uint32_t idx = g_nib_rev21[key]; + blk[2 + 8 * ib + 2 * l + h] = (uint8_t) idx; + qh |= ((idx >> 8) & 1u) << (2 * l + h); + } + blk[74 + 4 * ib + l] = (uint8_t) sg; + } + blk[66 + ib] = (uint8_t) qh; + if ((ib & 1) == 0) { + const uint32_t sc1 = slot[nibk::scale_off(row, k + 1)]; + blk[106 + ib / 2] = (uint8_t) (((sc - 1u) >> 1) | (((sc1 - 1u) >> 1) << 4)); + } + } +} + +constexpr int kNibGgufRows = 8; // gate/up rows a block rebuilds (in shared memory, then one coalesced pass) +constexpr int kNibGgufThreads = 128; +constexpr int kNibGgufWords = 8; // uint4 per thread in the down / tail part +struct NibGgufArgs { + const unsigned long long* dev; // the slots' device addresses (check), or nullptr: `p` + const uint8_t* p[16]; // the slots (gather: an MMQ group, at most mmq::kGatherGroupMax) + int first, n; + uint8_t* gu; // gather: the rebuilt [gate | up]; check: the raw blobs' first byte + uint64_t gu_stride; + uint8_t* d; // gather: the down rows; check: the raw blobs' down rows + uint64_t d_stride; + uint64_t gu_row, down16, zero16; // GGUF row bytes; down rows and MMQ tail in uint4 + unsigned long long* bad; // check: 32-bit words / uint4 that differ +}; +// blockIdx.y: expert first + y. blockIdx.x < kRows / kNibGgufRows: rows [8x, 8x + 8) rebuilt into shared memory, +// then written (gather) or compared (check) as 32-bit words; the rest: the down rows as uint4, and (gather, the last +// expert) the zeroed tails after gate/up and down. +template<int TG, bool CHECK> +__global__ void __launch_bounds__(kNibGgufThreads) nib_gguf_kernel(NibGgufArgs a) { + constexpr int BB = (int) sizeof(typename NibBlk<TG>::B); + __shared__ uint32_t s_rows[kNibGgufRows * 1100 / 4]; + const int q = a.first + (int) blockIdx.y; + const uint8_t* slot = a.dev != nullptr ? (const uint8_t*) a.dev[q] : a.p[q]; + constexpr int kRowBlocks = (int) (nibk::kRows / kNibGgufRows); + unsigned long long nbad = 0; + if ((int) blockIdx.x < kRowBlocks) { + const int r0 = (int) blockIdx.x * kNibGgufRows; + uint8_t* sb = (uint8_t*) s_rows; + for (int u = threadIdx.x; u < kNibGgufRows * (int) nibk::kItems; u += kNibGgufThreads) { + const int rr = u / (int) nibk::kItems, k = u % (int) nibk::kItems; + nib_gguf_item<TG>(sb + (size_t) rr * a.gu_row + (size_t) (k >> 3) * BB, k & 7, slot, r0 + rr, k); + } + __syncthreads(); + const int nw = (int) (kNibGgufRows * a.gu_row / 4); + uint32_t* dst = (uint32_t*) (a.gu + (size_t) q * a.gu_stride + (size_t) r0 * a.gu_row); + for (int i = threadIdx.x; i < nw; i += kNibGgufThreads) { + if constexpr (CHECK) nbad += dst[i] != s_rows[i]; + else dst[i] = s_rows[i]; + } + } else { + const uint4* src = (const uint4*) (slot + nibk::kDownOff); + uint4* dd = (uint4*) (a.d + (size_t) q * a.d_stride); + const int64_t base = ((int64_t) blockIdx.x - kRowBlocks) * (kNibGgufThreads * kNibGgufWords); +#pragma unroll + for (int w = 0; w < kNibGgufWords; ++w) { + const int64_t i = base + (int64_t) w * kNibGgufThreads + threadIdx.x; + if (i < (int64_t) a.down16) { + if constexpr (CHECK) { + const uint4 x = src[i], y = dd[i]; + nbad += x.x != y.x || x.y != y.y || x.z != y.z || x.w != y.w; + } else { + dd[i] = src[i]; + } + } else if (!CHECK && q == a.n - 1 && i < (int64_t) (a.down16 + 2 * a.zero16)) { + const int64_t z = i - (int64_t) a.down16; + if (z < (int64_t) a.zero16) ((uint4*) (a.gu + (size_t) a.n * a.gu_stride))[z] = make_uint4(0, 0, 0, 0); + else ((uint4*) (a.d + (size_t) a.n * a.d_stride))[z - (int64_t) a.zero16] = make_uint4(0, 0, 0, 0); + } + } + } + if constexpr (CHECK) { + if (nbad) atomicAdd(a.bad, nbad); + } +} + +// sum_i (w_i ^ i) * kHashMul mod 2^64 over the first `bytes` bytes of each slot (little-endian words, the last one +// zero-extended): expert_nibble.hpp's hash_host. A sum, so the blocks' order of adding does not change it. +__global__ void __launch_bounds__(256) nib_hash_kernel(const unsigned long long* __restrict__ slots, uint64_t bytes, + unsigned long long* __restrict__ out) { + const uint8_t* p = (const uint8_t*) slots[blockIdx.y]; + const uint64_t n16 = bytes / 16, nw = (bytes + 3) / 4; + uint64_t h = 0; + for (uint64_t q = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; q < n16; q += (uint64_t) gridDim.x * blockDim.x) { + const uint4 v = ((const uint4*) p)[q]; + const uint32_t i = (uint32_t) (4 * q); + h += (uint64_t) (v.x ^ i) * nibk::kHashMul + (uint64_t) (v.y ^ (i + 1)) * nibk::kHashMul + + (uint64_t) (v.z ^ (i + 2)) * nibk::kHashMul + (uint64_t) (v.w ^ (i + 3)) * nibk::kHashMul; + } + if (blockIdx.x == 0) + for (uint64_t i = 4 * n16 + threadIdx.x; i < nw; i += blockDim.x) { + uint32_t w = 0; + for (uint64_t b = 4 * i; b < 4 * i + 4 && b < bytes; ++b) w |= (uint32_t) p[b] << (8 * (b - 4 * i)); + h += (uint64_t) (w ^ (uint32_t) i) * nibk::kHashMul; + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) h += __shfl_xor_sync(0xffffffffu, h, o); + __shared__ uint64_t s_h[8]; + if ((threadIdx.x & 31) == 0) s_h[threadIdx.x >> 5] = h; + __syncthreads(); + if (threadIdx.x == 0) { + uint64_t t = 0; + for (int w = 0; w < (int) (blockDim.x >> 5); ++w) t += s_h[w]; + atomicAdd(out + blockIdx.y, (unsigned long long) t); + } +} +#endif // STRATA_EXPERT_NIBBLE_BUILT + +// STRATA_EXPERT_NIBBLE: whether a layout's gate/up is a converted slot's 4-bit codes (constant false in a build +// without the kernels, so its dispatch below is today's code) +constexpr bool nib_layout(const NativeExpertLayout& L) { +#if STRATA_EXPERT_NIBBLE_BUILT + return L.gu_nib; +#else + static_cast<void>(L); + return false; +#endif +} + } // namespace void iq_set_old_kernels(bool old) { g_old_kernels = old; } @@ -4660,6 +5359,50 @@ NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, return L; } +NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) { + namespace nb = strata::core::nibble; + NativeExpertLayout L = native_expert_layout(gu_type, d_type, n_embd, n_ff); + L.gu_nib = true; + L.gu_row = (size_t) (nb::kItems * nb::kItemBytes); // a row's codes (the scales and d follow all the codes) + L.up_off = nb::kUpCodesOff; + L.down_off = nb::kDownOff; + L.bytes = nb::slot_bytes_for((uint64_t) n_embd * L.d_row); + return L; +} + +bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { +#if STRATA_EXPERT_NIBBLE_BUILT + namespace nb = strata::core::nibble; + return nb::fmt_built(gu_type) && n_embd == nb::kNEmbd && n_ff == nb::kNFf && d_type != 40 && + native_expert_supported(gu_type, d_type, n_embd, n_ff); +#else + (void) gu_type; (void) d_type; (void) n_embd; (void) n_ff; + return false; +#endif +} + +void native_expert_nib_set_variant(int v) { +#if STRATA_EXPERT_NIBBLE_BUILT + g_nib_variant = v; +#else + (void) v; +#endif +} + +bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm) { +#if STRATA_EXPERT_NIBBLE_BUILT + cudaFuncAttributes a{}; + if (!nibx_launch(gu_type, v, dim3(80, 1), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &a)) return false; + *regs = a.numRegs; + *local_bytes = (int) a.localSizeBytes; + *blocks_per_sm = g_nibx_occ; + return true; +#else + (void) v; (void) gu_type; (void) regs; (void) local_bytes; (void) blocks_per_sm; + return false; +#endif +} + size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float); return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255); @@ -5315,7 +6058,7 @@ int exp_mode() { #endif } #endif -int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only +int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only, 3 gate/up only #if STRATA_EXP_LAYOUTS && !defined(__HIPCC__) // The down projection's mode on Turing's default: mode 4 is slower than the CUDA layout once groups have 3+ entries // (12 x 3: 36.5 -> 40.8 us, 16 x 4: 56.9 -> 68.9) - windows of 4+ tokens (cap_groups > 30) keep mode 0 there. @@ -5389,8 +6132,16 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long float* h = (float*) ((uint8_t*) scratch + 2 * fa); block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa); const auto* X = (const block_q8_1*) x_q8_1; +#if !STRATA_EXPERT_NIBBLE_BUILT + if (L.gu_nib) { // STRATA_EXPERT_NIBBLE's slots: the switch is refused at start in a build without the kernels + std::fprintf(stderr, "native_expert_grouped: 4-bit gate/up slots are not built into this engine\n"); + std::exit(1); + } +#endif + // STRATA_EXPERT_NIBBLE (nib_layout): only the gate/up step below takes another kernel (launch_gu_nib, in place of + // launch_gu); SwiGLU, the q8_1 quantization and the down rows (GGUF, at L.down_off) are the layout's own static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }(); - if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel + if (v2 && !nib_layout(L) && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values) static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); // (+ down rows' items spread evenly over the lanes, one load group: bitwise, harness 1.09-1.12x vs 1.03-1.06x; @@ -5460,7 +6211,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #endif #endif #if STRATA_EXP_LAYOUTS - const bool fused_gu = em0 == 8 && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && + const bool fused_gu = !nib_layout(L) && em0 == 8 && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && L.n_ff % 32 == 0; if (fused_gu && g_exp_phase != 2) { const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups); @@ -5482,7 +6233,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #else const bool gs_layout = true; #endif - if (gs_layout && g_exp_phase == 0 && !v1 && gu_swiglu_on() && !(expdec_mode() && !g_old_kernels && expdec_gu_ok(L))) { + if (gs_layout && !nib_layout(L) && g_exp_phase == 0 && !v1 && gu_swiglu_on() && !(expdec_mode() && !g_old_kernels && expdec_gu_ok(L))) { switch (L.gu_type) { #define STRATA_GS(T) case T: gs_done = launch_gu_swiglu<T>(L, gy, s, grp_ptr, grp_start, n_groups, ent_tok, X, hq); break; STRATA_GU_FMTS(STRATA_GS) @@ -5497,7 +6248,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long if (g_exp_phase != 2 && !gs_done) { #endif #if STRATA_EXP_LAYOUTS - const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); + const bool lds_gu = !nib_layout(L) && (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); if (lds_gu) { const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); @@ -5518,13 +6269,19 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42; - if ((em == 1 || em == 2 || em == 4) && amd_gu) { + if ((em == 1 || em == 2 || em == 4) && amd_gu && !nib_layout(L)) { switch (L.gu_type) { STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23) STRATA_GU_AMD(29) STRATA_GU_AMD(42) } } else #undef STRATA_GU_AMD +#endif +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_layout(L)) // STRATA_EXPERT_NIBBLE: a converted layer's VRAM slots, native_gu_multi_kernel's grid and bits + launch_gu_nib(L, dim3((unsigned) (strata::core::nibble::kRows / 16), (unsigned) gy), s, grp_ptr, grp_start, + n_groups, ent_tok, X, gate, up); + else #endif if (!expdec_gu(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) // STRATA_EXPDEC=1 switch (L.gu_type) { @@ -5537,6 +6294,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } #endif check("native_expert_grouped/gu"); + if (g_exp_phase == 3) return; // the bench: gate/up only const long long nh = (long long) cap_entries * L.n_ff; #if defined(STRATA_HIP_GFX906) // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass @@ -5611,6 +6369,164 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } // namespace strata::kernels +// ---------------------------------------------------------------- STRATA_EXPERT_NIBBLE: expert_nibble.hpp's functions +namespace strata::core::nibble { + +#if STRATA_EXPERT_NIBBLE_BUILT +namespace { +int g_rev_ready[64]; // per device: 0 not built, 1 built, 2 a grid entry not unique (refused) + +bool rev_ready() { + int dev = 0; + return cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < 64 && g_rev_ready[dev] == 1; +} +} // namespace +#endif + +int prepare(void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return (int) cudaErrorInvalidDevice; + if (g_rev_ready[dev] == 1) return 0; + if (g_rev_ready[dev] == 2) return (int) cudaErrorInvalidValue; + cudaStream_t s = (cudaStream_t) stream; + strata::kernels::nib_rev_clear_kernel<<<(strata::kernels::kNibRev22 + 255) / 256, 256, 0, s>>>(); + strata::kernels::nib_rev_fill_kernel<<<(1024 + 256 + 512 + 255) / 256, 256, 0, s>>>(); + cudaError_t e = cudaGetLastError(); + unsigned long long bad = 0; + if (e == cudaSuccess) e = cudaStreamSynchronize(s); + if (e == cudaSuccess) e = cudaMemcpyFromSymbol(&bad, strata::kernels::g_nib_rev_bad, sizeof bad); + if (e != cudaSuccess) return (int) e; + g_rev_ready[dev] = bad == 0 ? 1 : 2; + return bad == 0 ? 0 : (int) cudaErrorInvalidValue; +#else + (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (n <= 0) return 0; + if (!L.on || !fmt_built(L.gu_type) || L.raw_gu_row != raw_gu_row(L.gu_type) || + L.raw_up_off != (uint64_t) kNFf * L.raw_gu_row || L.raw_bytes < 2 * L.raw_up_off) + return (int) cudaErrorInvalidValue; + const long long nthr = (long long) n * kRows * kItems; + const dim3 grid((unsigned) ((nthr + 255) / 256)); + cudaStream_t s = (cudaStream_t) stream; + const uint8_t* src = (const uint8_t*) staging; +#define STRATA_NIB_TC(TG) \ + strata::kernels::nib_transcode_kernel<TG><<<grid, 256, 0, s>>>(src, L.raw_bytes, L.raw_gu_row, L.raw_up_off, slot_ptrs, n, bad) + switch (L.gu_type) { + case kIQ2_S: STRATA_NIB_TC(22); break; + case kIQ3_XXS: STRATA_NIB_TC(18); break; + case kIQ3_S: STRATA_NIB_TC(21); break; + default: return (int) cudaErrorInvalidValue; + } +#undef STRATA_NIB_TC + return (int) cudaGetLastError(); +#else + (void) L; (void) staging; (void) n; (void) slot_ptrs; (void) bad; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +#if STRATA_EXPERT_NIBBLE_BUILT +namespace { +int launch_gguf(const LayerVram& L, strata::kernels::NibGgufArgs& a, bool check, cudaStream_t s) { + namespace K = strata::kernels; + if (!L.on || !fmt_built(L.gu_type) || L.raw_gu_row != raw_gu_row(L.gu_type) || L.down_bytes % 16 != 0 || + L.raw_up_off != (uint64_t) kNFf * L.raw_gu_row || L.raw_down_off != 2 * L.raw_up_off) + return (int) cudaErrorInvalidValue; + if (!rev_ready()) return (int) cudaErrorNotReady; // prepare() was not run on this device + a.gu_row = L.raw_gu_row; + a.down16 = L.down_bytes / 16; + const int64_t tail = (int64_t) (a.down16 + 2 * a.zero16); + const int64_t per = (int64_t) K::kNibGgufThreads * K::kNibGgufWords; + const dim3 grid((unsigned) (kRows / K::kNibGgufRows + (tail + per - 1) / per), (unsigned) (a.n - a.first)); +#define STRATA_NIB_GG(TG) \ + (check ? K::nib_gguf_kernel<TG, true><<<grid, K::kNibGgufThreads, 0, s>>>(a) \ + : K::nib_gguf_kernel<TG, false><<<grid, K::kNibGgufThreads, 0, s>>>(a)) + switch (L.gu_type) { + case kIQ2_S: STRATA_NIB_GG(22); break; + case kIQ3_XXS: STRATA_NIB_GG(18); break; + case kIQ3_S: STRATA_NIB_GG(21); break; + default: return (int) cudaErrorInvalidValue; + } +#undef STRATA_NIB_GG + return (int) cudaGetLastError(); +} +} // namespace +#endif + +int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (n <= 0) return 0; + if (n > 65535) return (int) cudaErrorInvalidValue; + strata::kernels::NibGgufArgs a{}; + a.dev = slot_ptrs; + a.first = 0; + a.n = (int) n; + a.gu = (uint8_t*) staging; + a.gu_stride = L.raw_bytes; + a.d = (uint8_t*) staging + L.raw_down_off; + a.d_stride = L.raw_bytes; + a.zero16 = 0; + a.bad = bad; + if (((uintptr_t) staging | L.raw_bytes) % 16 != 0) return (int) cudaErrorInvalidValue; + return launch_gguf(L, a, true, (cudaStream_t) stream); +#else + (void) L; (void) staging; (void) n; (void) slot_ptrs; (void) bad; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride, + void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (first < 0 || n <= first || n > 16) return (int) cudaErrorInvalidValue; + uintptr_t al = (uintptr_t) gu_dst | (uintptr_t) d_dst | gu_stride | d_stride | zero_bytes; + for (int q = first; q < n; ++q) al |= (uintptr_t) slots[q]; + if (al % 16 != 0 || gu_stride < (uint64_t) kRows * L.raw_gu_row || d_stride < L.down_bytes) return (int) cudaErrorInvalidValue; + strata::kernels::NibGgufArgs a{}; + a.dev = nullptr; + for (int q = first; q < n; ++q) a.p[q] = slots[q]; + a.first = first; + a.n = n; + a.gu = (uint8_t*) gu_dst; + a.gu_stride = gu_stride; + a.d = (uint8_t*) d_dst; + a.d_stride = d_stride; + a.zero16 = zero_bytes / 16; + a.bad = nullptr; + return launch_gguf(L, a, false, (cudaStream_t) stream); +#else + (void) L; (void) slots; (void) first; (void) n; (void) gu_dst; (void) gu_stride; (void) d_dst; (void) d_stride; + (void) zero_bytes; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (n <= 0) return 0; + if (L.hashed == 0) return (int) cudaErrorInvalidValue; + cudaStream_t s = (cudaStream_t) stream; + const cudaError_t e = cudaMemsetAsync(out, 0, (size_t) n * sizeof(unsigned long long), s); + if (e != cudaSuccess) return (int) e; + // ~2.7 MB a slot: 32 blocks of 256 threads each, ~21 16-byte loads a thread + strata::kernels::nib_hash_kernel<<<dim3(32, (unsigned) n), 256, 0, s>>>(slot_ptrs, L.hashed, out); + return (int) cudaGetLastError(); +#else + (void) L; (void) slot_ptrs; (void) n; (void) out; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +} // namespace strata::core::nibble + // ---- Volta prompt experts (STRATA_PF_WMMA): a group's experts as one launch of FP16 tensor-core tiles, the weights // dequantized into shared memory by dq_dispatch (the FP16 path's own formulas), the activations FP16, FP32 sums. // Replaces MMQ's dp4a products on sm_70, and the FP16 path's dequantize-to-global + one cuBLAS call per expert. diff --git a/src/kernels/cuda/nib_gu_proto.cuh b/src/kernels/cuda/nib_gu_proto.cuh new file mode 100644 index 00000000..368eeb33 --- /dev/null +++ b/src/kernels/cuda/nib_gu_proto.cuh @@ -0,0 +1,137 @@ +// src/kernels/cuda/nib_gu_proto.cuh - STRATA_NIB_GU_PROTO: a staging variant of nib_gu_kernel (STRATA_EXPERT_NIBBLE's +// 4-bit gate/up), included by iq_kernels.cu inside its anonymous namespace after nib_gu_kernel. +// +// The kernel keeps the S skeleton's per-row arithmetic by calling nib_row_dot_s itself (16 lanes a row, lane t's items +// k = t, t+32, t+64 into s and t+16, t+48 into s16, NibLoad<TG>::load then Split<TG>::apply on the staged block_q8_1, +// __fadd_rn(s, s16), xor 8, 4, 2, 1). Only the staging and the block -> (group, rows) mapping change: +// - a block takes RB row blocks (16 rows each) of one group: grid (80 / RB, gy). The group's entries are staged +// once and the RB row blocks run one after another on them; +// - the staging reads the entries' q8_1 rows (2,880 B = 180 x 16 B each, 16-aligned when xq is) as 16-byte loads, +// every load issued before the first store, so only the stores sit between the two barriers. The S skeleton's +// word loop (nib_pass_s) has a serial load -> store chain there that stalls all eight warps of the block. +// The outputs are written without nib_pass_s's dynamically indexed s[t] (a select on t), the same values. +// Id 31 = RB 2, the one STRATA_NIB_GU_PROTO=1 selects: one GP100 die (PH402), T=1, gate/up alone, IQ2_S / IQ3_XXS / +// IQ3_S x1.25-1.27 against the S / P skeleton, every gate and up row bitwise equal (iq_nibble_parity (7), +// native_expert_bench --nibble --vs 31). +#pragma once + +// The n (1..GRP_NC) entries from e into s_x (block_q8_1 rows of 80). Block-uniform (e, n): every thread reaches both +// barriers. 16-byte loads, all in flight before the first store. +__device__ __forceinline__ void nibx_stage(block_q8_1* s_x, const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, int e, int n) { + constexpr int kV = (GRP_NC * 180 + 255) / 256; // 3 + const int nv = n * 180; + uint4 v[kV]; +#pragma unroll + for (int j = 0; j < kV; ++j) { + const int i = threadIdx.x + 256 * j; + if (i < nv) { + const int c = i >= 540 ? 3 : i >= 360 ? 2 : i >= 180 ? 1 : 0; + v[j] = ((const uint4*) (xq + (size_t) ent_tok[e + c] * 80))[i - 180 * c]; + } + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < kV; ++j) { + const int i = threadIdx.x + 256 * j; + if (i < nv) ((uint4*) s_x)[i] = v[j]; + } + __syncthreads(); +} + +// nib_pass_s's compute on the staged entries (nib_row_dot_s, the production function), stored without the dynamically +// indexed s[t] +template<int TG> +__device__ __forceinline__ void nibx_run(const uint8_t* slot, int row, const block_q8_1* s_x, int e, int n, int t, + float* dst, int r) { + const uint4* crow = (const uint4*) (slot + nibk::kCodesOff) + (size_t) row * nibk::kItems; + const uint8_t* srow = slot + nibk::kScOff + (size_t) row * nibk::kItems; + const __half* drow = (const __half*) (slot + nibk::kDOff) + (size_t) row * nibk::kSuper; + if (n == 1) { + const int o[1] = { 0 }; float s[1]; + nib_row_dot_s<TG, 1>(crow, srow, drow, s_x, o, t, s); + if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0]; + } else if (n == 2) { + const int o[2] = { 0, 80 }; float s[2]; + nib_row_dot_s<TG, 2>(crow, srow, drow, s_x, o, t, s); + if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = t == 0 ? s[0] : s[1]; + } else if (n == 3) { + const int o[3] = { 0, 80, 160 }; float s[3]; + nib_row_dot_s<TG, 3>(crow, srow, drow, s_x, o, t, s); + if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = t == 0 ? s[0] : t == 1 ? s[1] : s[2]; + } else { + const int o[4] = { 0, 80, 160, 240 }; float s[4]; + nib_row_dot_s<TG, 4>(crow, srow, drow, s_x, o, t, s); + if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = t == 0 ? s[0] : t == 1 ? s[1] : t == 2 ? s[2] : s[3]; + } +} + +template<int TG, int RB> +__global__ void __launch_bounds__(256) nibx_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, float* __restrict__ gate, + float* __restrict__ up) { + static_assert(80 % RB == 0, "row blocks per block divide 80"); + const int ng = *n_groups; + if (blockIdx.y >= (unsigned) ng) return; + STRATA_SHARED_ALIGN16_U32(s_buf, kNibSWords); + block_q8_1* s_x = (block_q8_1*) s_buf; + const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15; + const int rb0 = blockIdx.x * RB; + for (int g = blockIdx.y; g < ng; g += gridDim.y) { + const uint8_t* slot = (const uint8_t*) grp_ptr[g]; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int nt = e1 - e0; + if (nt <= 0) continue; // an empty group: nothing to write (block-uniform, no barrier skipped unevenly) + if (nt <= GRP_NC) { + nibx_stage(s_x, ent_tok, xq, e0, nt); +#pragma unroll 1 + for (int j = 0; j < RB; ++j) { + const int row = (rb0 + j) * 16 + subwarp; + const bool is_up = row >= nibk::kNFf; + nibx_run<TG>(slot, row, s_x, e0, nt, t, is_up ? up : gate, is_up ? row - (int) nibk::kNFf : row); + } + } else { // more entries than one pass holds: per row block, the passes as nib_pass_s runs them +#pragma unroll 1 + for (int j = 0; j < RB; ++j) { + const int row = (rb0 + j) * 16 + subwarp; + const bool is_up = row >= nibk::kNFf; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + nibx_stage(s_x, ent_tok, xq, e, n); + nibx_run<TG>(slot, row, s_x, e, n, t, is_up ? up : gate, is_up ? row - (int) nibk::kNFf : row); + } + } + } + } +} + +int g_nibx_occ = 0; // the last attribute query's resident blocks per SM + +template<int TG, int RB> +void nibx_launch_one(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, + const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, + cudaFuncAttributes* attr) { + if (attr) { + cudaFuncGetAttributes(attr, nibx_gu_kernel<TG, RB>); + cudaOccupancyMaxActiveBlocksPerMultiprocessor(&g_nibx_occ, nibx_gu_kernel<TG, RB>, 256, 0); + return; + } + nibx_gu_kernel<TG, RB><<<dim3(80 / RB, grid.y), 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, gate, up); +} + +// false: not the gu-proto id (31) or not a converted format. attr != nullptr: only the kernel's attributes, nothing +// launched. +bool nibx_launch(int gu_type, int id, dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, + float* gate, float* up, cudaFuncAttributes* attr = nullptr) { + if (id != 31) return false; + switch (gu_type) { + case 22: nibx_launch_one<22, 2>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up, attr); return true; + case 18: nibx_launch_one<18, 2>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up, attr); return true; + case 21: nibx_launch_one<21, 2>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up, attr); return true; + default: return false; + } +} diff --git a/src/kernels/iq_nibble_parity.cpp b/src/kernels/iq_nibble_parity.cpp new file mode 100644 index 00000000..40196bdd --- /dev/null +++ b/src/kernels/iq_nibble_parity.cpp @@ -0,0 +1,954 @@ +// src/kernels/iq_nibble_parity.cpp - STRATA_EXPERT_NIBBLE (strata/core/expert_nibble.hpp): the 4-bit gate/up expert +// slots against the production kernels and the GGUF blobs, bit for bit. +// +// build/iq_nibble_parity --header the host half of expert_nibble.hpp (no GPU) +// build/iq_nibble_parity <shard.gguf> [<shard.gguf> ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512] +// [--plans 8] [--synthetic 64] [--no-ggml] [--negative] +// build/iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml] no model, no shard +// +// Each model (any shard of it; its other shards are opened beside it) gives `--layers-per-fmt` layers of each +// converted format (IQ2_S, IQ3_XXS, IQ3_S; or `--layers`), `--ne` experts each, read from the GGUF tensors into the +// blob the pack holds (gate rows, up rows, down rows). Per layer: +// (1) nibble::transcode, 64 blobs a batch as the startup fill runs it: 0 items that do not round-trip; +// (2) every gate/up byte of a slot is written (8 slots transcoded again into another pre-fill byte); +// (3) nibble::hash_slots against nibble::hash_host on every slot read back (and a flipped byte must change it); +// (4) the host codec on every item: decode_item then encode_item gives the code back; +// (5) ggml's reference dequantizer (to_float) on every GGUF row against the weight the 4-bit slot gives through +// dequantize_row_iq2_s / _iq3_xxs / _iq3_s's own expression (code, scale byte, fp16 d): every weight, bit for bit; +// (6) nibble::check_gguf (the start-up check: the GGUF blocks rebuilt from every slot against the blob): 0 words +// differ; nibble::gather_gguf (the prompt path's MMQ gather) in groups of 16 and of 1..15 from a later first +// position: the rebuilt [gate | up] and the down rows byte for byte the blob's, the MMQ tail after the group zero; +// (7) native_expert_grouped on the converted slots (native_expert_layout_nib) against the same call on the GGUF +// blobs (native_expert_layout): hq and out byte for byte for every entry, and gate / up where the reference +// layout writes them - in the card's default layout (a GP100: mode 8, whose gate/up kernel writes hq) and in the +// CUDA layout (native_expert_set_mode(0)), each with native_grouped_set_v1 off and on (h too, in mode 0 + v1); +// top-10 routing T = 1..6 at 0% and 50% sharing (`--plans` each), one group of T entries (G = 1) per T, plans of +// groups with 0..11 entries (more than one GRP_NC pass, empty groups); grid_groups 0 (cap) and 4 (the PCIe +// call's stride); the default kernel per format and each skeleton forced (S, P); q8_1 activations random, all +// +127, all -127 and alternating +-127 (the sum of x at its extremes, +-4064). +// `--synthetic N`: per format, N experts whose gate/up blocks are random bytes (every grid index, sign byte and scale +// nibble the format has; the coverage is counted and must be complete) and whose fp16 d cycle through +-the smallest +// subnormal, +-65504, +-1, the smallest normal and two ordinary values; checks (1)-(7) on them. +// `--synthetic-only`: the synthetic experts alone, for every gate/up format x both down types (IQ4_NL, Q2_0), the down rows +// random bytes with ordinary fp16 scales: checks (1)-(7) with no model file (a GP100 is still needed). +// `--negative`: the control - one code byte per slot changed after the transcode; (6) and (7) must then report differences. +// Exit 0 when every check is equal; 1 otherwise; 2 on a usage or setup error. A build without STRATA_EXPERT_NIBBLE_BUILT +// (the CUDA build with STRATA_EXPERIMENTAL_SM60) has no 4-bit kernels: --header only. +#include "strata/artifact/gguf_reader.hpp" +#include "strata/core/expert_nibble.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/iq_kernels.hpp" + +#include "ggml.h" + +#include <cuda_runtime.h> + +#include <algorithm> +#include <atomic> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <memory> +#include <random> +#include <set> +#include <string> +#include <thread> +#include <vector> + +namespace { + +namespace nib = strata::core::nibble; +namespace K = strata::kernels; +namespace cpu = strata::kernels::cpu; + +int fails = 0; +void expect(bool ok, const char* what) { + if (!ok) { + std::printf("FAIL %s\n", what); + ++fails; + } +} + +// Every value the format holds at every one of an item's 32 positions (the other positions cycle through the set), +// encoded, decoded and compared; and one value outside the set must be refused. +void round_trip(int fmt, const std::vector<int8_t>& set, int8_t outside) { + int8_t g[32], back[32]; + uint32_t q[4]; + for (size_t shift = 0; shift < set.size(); ++shift) { + for (int i = 0; i < 32; ++i) g[i] = set[(shift + (size_t) i) % set.size()]; + const bool ok = nib::encode_item(fmt, g, q); + nib::decode_item(fmt, q, back); + expect(ok && std::memcmp(g, back, 32) == 0, (std::string(nib::fmt_name(fmt)) + " round trip").c_str()); + } + for (int i = 0; i < 32; ++i) g[i] = set[0]; + g[17] = outside; + expect(!nib::encode_item(fmt, g, q), (std::string(nib::fmt_name(fmt)) + " refuses a value outside the set").c_str()); +} + +int header_check() { + expect(nib::kGuBytes == 1766400 && nib::kScOff == 1638400 && nib::kDOff == 1740800, "layout sizes"); + expect(nib::code_off(nib::kNFf, 0) == nib::kUpCodesOff, "up rows' codes"); + expect(nib::slot_bytes_for(921600) % nib::kSlotAlign == 0, "slot alignment"); + round_trip(nib::kIQ2_S, { 8, 25, 43, -8, -25, -43 }, 9); + round_trip(nib::kIQ3_XXS, { 4, 12, 20, 28, 36, 44, 52, 62, -4, -12, -20, -28, -36, -44, -52, -62 }, 5); + std::vector<int8_t> s3; + for (int v = -15; v <= 15; v += 2) s3.push_back((int8_t) v); + round_trip(nib::kIQ3_S, s3, 2); + // IQ2_S's nibble is the decode kernel's PRMT selector into {8,25,43,0} {-8,-25,-43,0} + { + int8_t g[32] = {}, back[32]; + uint32_t q[4]; + for (int i = 0; i < 32; ++i) g[i] = (int8_t) (i % 2 ? -25 : 43); + nib::encode_item(nib::kIQ2_S, g, q); + expect((q[0] & 0xFu) == 2u && (q[0] >> 4 & 0xFu) == 5u, "IQ2_S selector nibbles"); + nib::decode_item(nib::kIQ2_S, q, back); + expect(std::memcmp(g, back, 32) == 0, "IQ2_S selector decode"); + } + expect(nib::gu_skeleton(nib::kIQ2_S) == nib::kSkelP && nib::gu_skeleton(nib::kIQ3_XXS) == nib::kSkelS && + nib::gu_skeleton(nib::kIQ3_S) == nib::kSkelS, + "kernel table"); + { + const uint8_t b[6] = { 1, 2, 3, 4, 5, 6 }; + const uint64_t h = nib::hash_host(b, 6); + const uint64_t want = (uint64_t) (0x04030201u ^ 0u) * nib::kHashMul + (uint64_t) (0x00000605u ^ 1u) * nib::kHashMul; + expect(h == want, "hash_host"); + } + std::printf("%s (%d failures)\n", fails == 0 ? "header OK" : "header FAILED", fails); + return fails == 0 ? 0 : 1; +} + +// ------------------------------------------------------------------------------------------------ the GPU parity + +#define CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); \ + std::exit(2); \ + } \ + } while (0) + +struct Q81 { // block_q8_1: fp16 d, fp16 s (= d * sum), 32 int8 + uint16_t d, s; + int8_t qs[32]; +}; +static_assert(sizeof(Q81) == 36, "block_q8_1"); + +constexpr int64_t kEmbd = nib::kNEmbd, kFf = nib::kNFf; +constexpr int kTok = 12; // activation rows: T <= 6 for routing plans, 12 for the 0..11-entry plans + +// One layer: `ne` GGUF blobs (gate rows | up rows | down rows, as the pack and the host arena hold them) on the host +// and the device, and their converted slots. +struct Layer { + std::string tag; + int layer = -1; + cpu::NativeFmt f; + nib::LayerVram V; + K::NativeExpertLayout Lr, Ln; + int ne = 0; + std::vector<uint8_t> host; // ne x f.bytes + uint8_t* raw = nullptr; // device copy of `host` + uint8_t* slots = nullptr; // ne x V.slot_bytes (the last one only `hashed` long: nothing past it is readable) +}; + +bool layer_fmt(const strata::GgufModel& m, int l, int& gt, int& dt) { + const auto* g = m.find("blk." + std::to_string(l) + ".ffn_gate_exps.weight"); + const auto* d = m.find("blk." + std::to_string(l) + ".ffn_down_exps.weight"); + if (g == nullptr || d == nullptr) return false; + gt = (int) g->type; + dt = (int) d->type; + return true; +} + +// The blobs of experts [0, ne) of layer l. +bool read_layer(const strata::GgufModel& m, int l, int ne, Layer& Y) { + const char* roles[3] = { "gate", "up", "down" }; + const strata::TensorInfo* t[3] = {}; + size_t sh[3] = {}; + for (int r = 0; r < 3; ++r) t[r] = m.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &sh[r]); + if (!t[0] || !t[1] || !t[2]) return false; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, kEmbd, kFf, Y.f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); + return false; + } + const size_t gu_role = Y.f.up_off, dn_role = Y.f.bytes - Y.f.down_off; + Y.layer = l; + Y.ne = ne; + Y.host.resize((size_t) ne * Y.f.bytes); + const uint8_t* G = m.shard(sh[0]).tensor_data(*t[0]); + const uint8_t* U = m.shard(sh[1]).tensor_data(*t[1]); + const uint8_t* D = m.shard(sh[2]).tensor_data(*t[2]); + for (int e = 0; e < ne; ++e) { + uint8_t* b = Y.host.data() + (size_t) e * Y.f.bytes; + std::memcpy(b, G + (size_t) e * gu_role, gu_role); + std::memcpy(b + Y.f.up_off, U + (size_t) e * gu_role, gu_role); + std::memcpy(b + Y.f.down_off, D + (size_t) e * dn_role, dn_role); + } + return true; +} + +// check (6): nibble::check_gguf over every slot (the start-up check), and nibble::gather_gguf (the prompt path's gather) +// in groups of 16 and from later first positions, against the blobs byte for byte (and the MMQ tail zeroed). +// `expect_diff`: the negative control (only the report says so: the counts must then be > 0). +long long gguf_parity(const Layer& Y, const unsigned long long* dp, bool expect_diff) { + long long bad_total = 0; + const int ne = Y.ne; + unsigned long long* dbad = nullptr; + CK(cudaMalloc(&dbad, 8)); + CK(cudaMemset(dbad, 0, 8)); + for (int e0 = 0; e0 < ne; e0 += 64) { + const int rc = nib::check_gguf(Y.V, Y.raw + (size_t) e0 * Y.V.raw_bytes, std::min(64, ne - e0), dp + e0, dbad, nullptr); + if (rc != 0) { + std::printf("check_gguf: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + } + CK(cudaDeviceSynchronize()); + unsigned long long cbad = 0; + CK(cudaMemcpy(&cbad, dbad, 8, cudaMemcpyDeviceToHost)); + CK(cudaFree(dbad)); + // the gathers: MMQ's group buffers (16 experts of [gate | up] and of down, each followed by the 4096-byte tail) + const uint64_t gub = (uint64_t) nib::kRows * Y.f.gu_row, db = Y.V.down_bytes, zero = 4096; + uint8_t *ggu = nullptr, *gd = nullptr; + CK(cudaMalloc(&ggu, 16 * gub + zero)); + CK(cudaMalloc(&gd, 16 * db + zero)); + std::vector<uint8_t> hgu(16 * gub + zero), hd(16 * db + zero); + std::vector<unsigned long long> hp(ne); + CK(cudaMemcpy(hp.data(), dp, (size_t) ne * 8, cudaMemcpyDeviceToHost)); + long long gbad = 0, groups = 0; + for (int e0 = 0; e0 < ne; e0 += 16) { + const int first = (e0 / 16) % 4 == 3 ? 1 + (e0 / 64) % 15 : 0; // every 4th group from a later position + const int n = std::min(16, ne - e0); + if (first >= n) continue; + const uint8_t* sl[16] = {}; + for (int q = first; q < n; ++q) sl[q] = (const uint8_t*) (uintptr_t) hp[(size_t) (e0 + q)]; + CK(cudaMemset(ggu, 0xA5, 16 * gub + zero)); + CK(cudaMemset(gd, 0xA5, 16 * db + zero)); + const int rc = nib::gather_gguf(Y.V, sl, first, n, ggu, gub, gd, db, zero, nullptr); + if (rc != 0) { + std::printf("gather_gguf: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + CK(cudaDeviceSynchronize()); + CK(cudaMemcpy(hgu.data(), ggu, hgu.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(hd.data(), gd, hd.size(), cudaMemcpyDeviceToHost)); + for (int q = first; q < n; ++q) { + const uint8_t* raw = Y.host.data() + (size_t) (e0 + q) * Y.f.bytes; + gbad += std::memcmp(hgu.data() + (size_t) q * gub, raw, gub) != 0; + gbad += std::memcmp(hd.data() + (size_t) q * db, raw + Y.f.down_off, db) != 0; + } + for (uint64_t i = 0; i < zero; ++i) gbad += hgu[(size_t) n * gub + i] != 0 || hd[(size_t) n * db + i] != 0 ? 1 : 0; + ++groups; + } + CK(cudaFree(ggu)); + CK(cudaFree(gd)); + std::printf(" check_gguf: %llu words differ; gather_gguf (%lld groups, the tail zeroed): %lld matrices or tail bytes differ%s\n", + cbad, groups, gbad, expect_diff ? " (NEGATIVE CONTROL: both must be > 0)" : ""); + bad_total += (long long) cbad + gbad; // the negative control fails the run, as (7) does: it must + return bad_total; +} + +// Plans the layer, uploads the blobs, transcodes them into slots (checks 1-6). +long long convert(Layer& Y, bool ggml_check) { + long long bad_total = 0; + nib::Config c; + c.on = true; + Y.V = nib::plan_layer(Y.layer, Y.f, c); + Y.Lr = K::native_expert_layout(Y.f.gu_type, Y.f.d_type, kEmbd, kFf); + Y.Ln = K::native_expert_layout_nib(Y.f.gu_type, Y.f.d_type, kEmbd, kFf); + if (!Y.V.on || Y.V.slot_bytes != Y.Ln.bytes || Y.V.down_off != Y.Ln.down_off || Y.Lr.bytes != Y.f.bytes) { + std::printf("layer %d: plan_layer / native_expert_layout_nib disagree (on %d, slot %llu vs %zu)\n", Y.layer, + (int) Y.V.on, (unsigned long long) Y.V.slot_bytes, Y.Ln.bytes); + return 1; + } + const int ne = Y.ne; + const size_t slots_bytes = (size_t) (ne - 1) * Y.V.slot_bytes + Y.V.hashed; + CK(cudaMalloc(&Y.raw, Y.host.size())); + CK(cudaMemcpy(Y.raw, Y.host.data(), Y.host.size(), cudaMemcpyHostToDevice)); + CK(cudaMalloc(&Y.slots, slots_bytes)); + CK(cudaMemset(Y.slots, 0xA5, slots_bytes)); + std::vector<unsigned long long> hp(ne); + for (int e = 0; e < ne; ++e) hp[e] = (unsigned long long) (Y.slots + (size_t) e * Y.V.slot_bytes); + unsigned long long *dp = nullptr, *dbad = nullptr, *dhash = nullptr; + CK(cudaMalloc(&dp, (size_t) ne * 8)); + CK(cudaMalloc(&dbad, 8)); + CK(cudaMalloc(&dhash, (size_t) ne * 8)); + CK(cudaMemcpy(dp, hp.data(), (size_t) ne * 8, cudaMemcpyHostToDevice)); + CK(cudaMemset(dbad, 0, 8)); + // (1) the startup fill's batches: 64 blobs at a time, then the down rows behind the codes + for (int e0 = 0; e0 < ne; e0 += 64) { + const int n = std::min(64, ne - e0); + const int rc = nib::transcode(Y.V, Y.raw + (size_t) e0 * Y.V.raw_bytes, n, dp + e0, dbad, nullptr); + if (rc != 0) { + std::printf("transcode: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + } + for (int e = 0; e < ne; ++e) + CK(cudaMemcpyAsync(Y.slots + (size_t) e * Y.V.slot_bytes + nib::kDownOff, + Y.raw + (size_t) e * Y.V.raw_bytes + Y.V.raw_down_off, Y.V.down_bytes, cudaMemcpyDeviceToDevice)); + CK(cudaDeviceSynchronize()); + unsigned long long bad = 0; + CK(cudaMemcpy(&bad, dbad, 8, cudaMemcpyDeviceToHost)); + std::printf("%s layer %2d %-7s / down %-6s: %d experts, blob %zu B, slot %llu B (x%.3f); transcode: %llu of %lld items do not round-trip\n", + Y.tag.c_str(), Y.layer, nib::fmt_name(Y.f.gu_type), ggml_type_name((ggml_type) Y.f.d_type), ne, Y.f.bytes, + (unsigned long long) Y.V.slot_bytes, (double) Y.V.slot_bytes / (double) Y.f.bytes, bad, + (long long) ne * nib::kRows * nib::kItems); + bad_total += (long long) bad; + bad_total += gguf_parity(Y, dp, false); + // (2) every gate/up byte written: the first 8 blobs again into slots pre-filled with 0x5A + { + const int n8 = std::min(8, ne); + uint8_t* alt = nullptr; + unsigned long long* ap = nullptr; + CK(cudaMalloc(&alt, (size_t) n8 * Y.V.slot_bytes)); + CK(cudaMemset(alt, 0x5A, (size_t) n8 * Y.V.slot_bytes)); + std::vector<unsigned long long> ah(n8); + for (int e = 0; e < n8; ++e) ah[e] = (unsigned long long) (alt + (size_t) e * Y.V.slot_bytes); + CK(cudaMalloc(&ap, (size_t) n8 * 8)); + CK(cudaMemcpy(ap, ah.data(), (size_t) n8 * 8, cudaMemcpyHostToDevice)); + CK(cudaMemset(dbad, 0, 8)); + if (nib::transcode(Y.V, Y.raw, n8, ap, dbad, nullptr) != 0) std::exit(2); + CK(cudaDeviceSynchronize()); + std::vector<uint8_t> a(nib::kGuBytes), b(nib::kGuBytes); + long long wbad = 0; + for (int e = 0; e < n8; ++e) { + CK(cudaMemcpy(a.data(), Y.slots + (size_t) e * Y.V.slot_bytes, nib::kGuBytes, cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(b.data(), alt + (size_t) e * Y.V.slot_bytes, nib::kGuBytes, cudaMemcpyDeviceToHost)); + wbad += std::memcmp(a.data(), b.data(), nib::kGuBytes) != 0; + } + std::printf(" every gate/up byte written (0xA5 vs 0x5A pre-fill, %d slots): %lld differ\n", n8, wbad); + bad_total += wbad; + CK(cudaFree(alt)); + CK(cudaFree(ap)); + } + // (3) the device hash of every slot against the host reference over the slot read back + const int rc = nib::hash_slots(Y.V, dp, ne, dhash, nullptr); + if (rc != 0) { + std::printf("hash_slots: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + std::vector<unsigned long long> hh(ne); + CK(cudaMemcpy(hh.data(), dhash, (size_t) ne * 8, cudaMemcpyDeviceToHost)); + std::vector<uint8_t> sl(slots_bytes); + CK(cudaMemcpy(sl.data(), Y.slots, slots_bytes, cudaMemcpyDeviceToHost)); + std::atomic<long long> hbad{ 0 }, cbad{ 0 }, dnbad{ 0 }, gbad{ 0 }; + std::atomic<long long> grows{ 0 }; + std::string first_ggml; + std::atomic<int> first_set{ 0 }; + const ggml_type_traits* tr = ggml_get_type_traits((ggml_type) Y.f.gu_type); + const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + std::vector<std::thread> th; + for (unsigned ti = 0; ti < nth; ++ti) + th.emplace_back([&, ti]() { + std::vector<float> ref((size_t) kEmbd), got((size_t) kEmbd); + for (int e = (int) ti; e < ne; e += (int) nth) { + const uint8_t* s = sl.data() + (size_t) e * Y.V.slot_bytes; + const uint8_t* raw = Y.host.data() + (size_t) e * Y.f.bytes; + hbad += nib::hash_host(s, Y.V.hashed) != hh[e]; + if (e == 0) { // the hash sees every byte: one flipped must change it + std::vector<uint8_t> t2(s, s + Y.V.hashed); + t2[Y.V.hashed - 1] ^= 1; + hbad += nib::hash_host(t2.data(), Y.V.hashed) == hh[e]; + } + dnbad += std::memcmp(s + nib::kDownOff, raw + Y.V.raw_down_off, Y.V.down_bytes) != 0; + for (int64_t r = 0; r < nib::kRows; ++r) { + // (4) the host codec + for (int64_t k = 0; k < nib::kItems; ++k) { + uint32_t q[4], q2[4]; + int8_t g[32]; + std::memcpy(q, s + nib::code_off(r, k), 16); + nib::decode_item(Y.f.gu_type, q, g); + const bool ok = nib::encode_item(Y.f.gu_type, g, q2); + cbad += !ok || std::memcmp(q, q2, 16) != 0; + } + if (!ggml_check) continue; + // (5) ggml's dequantizer of the GGUF row against the slot's weights through its expression + const uint8_t* row = raw + (r < kFf ? (size_t) r * Y.f.gu_row : Y.f.up_off + (size_t) (r - kFf) * Y.f.gu_row); + tr->to_float(row, ref.data(), kEmbd); + for (int64_t k = 0; k < nib::kItems; ++k) { + uint32_t q[4]; + std::memcpy(q, s + nib::code_off(r, k), 16); + int8_t gv[32]; + nib::decode_item(Y.f.gu_type, q, gv); + const int sc = s[nib::scale_off(r, k)]; + ggml_fp16_t dh; + std::memcpy(&dh, s + nib::d_off(r, k / 8), sizeof dh); + const float d = ggml_fp16_to_fp32(dh); + for (int j = 0; j < 32; ++j) { + const float db = Y.f.gu_type == nib::kIQ2_S ? d * (0.5f + ((j < 16 ? sc : sc >> 4) & 0xf)) * 0.25f + : Y.f.gu_type == nib::kIQ3_XXS ? d * (0.5f + sc) * 0.5f + : d * sc; + const int a = gv[j] < 0 ? -(int) gv[j] : (int) gv[j]; + float v = db * a; + if (gv[j] < 0) v = -v; + got[(size_t) (k * 32 + j)] = v; + } + } + ++grows; + if (std::memcmp(ref.data(), got.data(), ref.size() * sizeof(float)) != 0) { + ++gbad; + if (first_set.exchange(1) == 0) { + size_t cc = 0; + while (cc < ref.size() && std::memcmp(&ref[cc], &got[cc], 4) == 0) ++cc; + char buf[200]; + std::snprintf(buf, sizeof buf, "expert %d row %lld column %zu: slot %.9g, GGUF %.9g", e, + (long long) r, cc, (double) got[cc], (double) ref[cc]); + first_ggml = buf; + } + } + } + } + }); + for (auto& t : th) t.join(); + std::printf(" hash_slots vs hash_host: %lld of %d slots differ (+1 flipped-byte check); down rows: %lld of %d slots differ;" + " host codec: %lld of %lld items differ\n", + hbad.load(), ne, dnbad.load(), ne, cbad.load(), (long long) ne * nib::kRows * nib::kItems); + if (ggml_check) + std::printf(" ggml to_float of the GGUF rows vs the slot's weights: %lld of %lld rows differ%s%s\n", gbad.load(), + grows.load(), first_ggml.empty() ? "" : "; first: ", first_ggml.c_str()); + bad_total += hbad + dnbad + cbad + gbad; + CK(cudaFree(dp)); + CK(cudaFree(dbad)); + CK(cudaFree(dhash)); + return bad_total; +} + +// ---- plans: synthetic top-10 routing and resident_plan_kernel's grouping (groups by first appearance) +struct Plan { + int ng = 0, ne = 0, ntok = 0, maxn = 0; + std::vector<int> gid, start, tok, dst; +}; + +void make_routing(std::mt19937& rng, int NE, int T, int share_pct, std::vector<int>& ids) { + ids.clear(); + std::vector<int> prev, cur; + for (int t = 0; t < T; ++t) { + cur.clear(); + const bool sh = t > 0 && share_pct > 0; + if (sh) { + std::vector<int> p = prev; + std::shuffle(p.begin(), p.end(), rng); + cur.assign(p.begin(), p.begin() + 10 * share_pct / 100); + } + while ((int) cur.size() < 10) { + const int e = (int) (rng() % (unsigned) NE); + if (std::find(cur.begin(), cur.end(), e) != cur.end()) continue; + if (sh && std::find(prev.begin(), prev.end(), e) != prev.end()) continue; + cur.push_back(e); + } + std::shuffle(cur.begin(), cur.end(), rng); + ids.insert(ids.end(), cur.begin(), cur.end()); + prev = cur; + } +} + +Plan build_plan(const std::vector<int>& ids) { + const int n = (int) ids.size(); + Plan p; + std::vector<int> first(n), cnt, grp_of(n, -1); + for (int j = 0; j < n; ++j) { + int f = j; + for (int i = 0; i < j; ++i) + if (ids[i] == ids[j]) { f = i; break; } + first[j] = f; + } + for (int j = 0; j < n; ++j) + if (first[j] == j) { + grp_of[j] = p.ng++; + p.gid.push_back(ids[j]); + cnt.push_back(0); + } + for (int j = 0; j < n; ++j) cnt[grp_of[first[j]]]++; + p.start.assign(p.ng + 1, 0); + int acc = 0; + for (int g = 0; g < p.ng; ++g) { + p.start[g] = acc; + acc += cnt[g]; + p.maxn = std::max(p.maxn, cnt[g]); + } + p.start[p.ng] = acc; + p.tok.assign(n, 0); + p.dst.assign(n, 0); + std::vector<int> fill(p.ng, 0); + for (int j = 0; j < n; ++j) { + const int g = grp_of[first[j]]; + const int at = p.start[g] + fill[g]++; + p.tok[at] = j / 10; + p.dst[at] = j; + } + p.ne = n; + p.ntok = n / 10; + return p; +} + +// one group of T entries (G = 1): an expert every token of the window routes to +Plan single_group(std::mt19937& rng, int NE, int T) { + Plan p; + p.ntok = T; + p.ng = 1; + p.gid.push_back((int) (rng() % (unsigned) NE)); + p.start = { 0, T }; + for (int t = 0; t < T; ++t) { + p.tok.push_back(t); + p.dst.push_back(T - 1 - t); + } + p.ne = T; + p.maxn = T; + return p; +} + +// groups of 0..11 entries (more than one GRP_NC pass, empty groups), 12 tokens, distinct tokens within a group, +// destination rows in any order +Plan synthetic_plan(std::mt19937& rng, int NE) { + Plan p; + p.ntok = kTok; + std::vector<int> ids(NE); + for (int i = 0; i < NE; ++i) ids[i] = i; + std::shuffle(ids.begin(), ids.end(), rng); + const int sizes[] = { 3, 0, 11, 1, 5, 8, 0, 2, 4, 9, 6, 7, 10, 1 }; + int acc = 0; + for (int g = 0; g < (int) (sizeof sizes / sizeof sizes[0]); ++g) { + p.gid.push_back(ids[(size_t) g % ids.size()]); + p.start.push_back(acc); + std::vector<int> toks(kTok); + for (int i = 0; i < kTok; ++i) toks[i] = i; + std::shuffle(toks.begin(), toks.end(), rng); + std::sort(toks.begin(), toks.begin() + sizes[g]); + for (int i = 0; i < sizes[g]; ++i) { + p.tok.push_back(toks[i]); + p.dst.push_back(acc + i); + } + acc += sizes[g]; + p.maxn = std::max(p.maxn, sizes[g]); + } + p.start.push_back(acc); + p.ng = (int) p.gid.size(); + p.ne = acc; + std::vector<int> perm(acc); + for (int i = 0; i < acc; ++i) perm[i] = i; + std::shuffle(perm.begin(), perm.end(), rng); + for (int i = 0; i < acc; ++i) p.dst[i] = perm[i]; + return p; +} + +std::vector<Q81> make_x(std::mt19937& rng) { + std::vector<Q81> x((size_t) kTok * (kEmbd / 32)); + for (size_t i = 0; i < x.size(); ++i) { + Q81& b = x[i]; + const int tok = (int) (i / (kEmbd / 32)); + const float d = 0.002f + 0.03f * (float) (rng() % 1000) / 1000.0f; + int sum = 0; + for (int j = 0; j < 32; ++j) { + int q = (int) (rng() % 255) - 127; + if (tok == 1) q = 127; // the sum of x at its extremes (+-4064) + if (tok == 2) q = -127; + if (tok == 3 && (i % (kEmbd / 32)) < 8) q = (j & 1) ? 127 : -127; + b.qs[j] = (int8_t) q; + sum += q; + } + b.d = ggml_fp32_to_fp16(d); + b.s = ggml_fp32_to_fp16(d * (float) sum); + } + return x; +} + +struct Dev { + unsigned long long* ptr = nullptr; + int32_t *start = nullptr, *ng = nullptr, *tok = nullptr, *dst = nullptr; +}; +Dev upload(const Plan& p, const Layer& Y, bool conv) { + Dev d; + std::vector<unsigned long long> hp(std::max(1, p.ng)); + for (int g = 0; g < p.ng; ++g) + hp[g] = conv ? (unsigned long long) (Y.slots + (size_t) p.gid[g] * Y.V.slot_bytes) + : (unsigned long long) (Y.raw + (size_t) p.gid[g] * Y.f.bytes); + CK(cudaMalloc(&d.ptr, (size_t) std::max(1, p.ng) * 8)); + CK(cudaMalloc(&d.start, (size_t) (p.ng + 1) * 4)); + CK(cudaMalloc(&d.ng, 4)); + CK(cudaMalloc(&d.tok, (size_t) std::max(1, p.ne) * 4)); + CK(cudaMalloc(&d.dst, (size_t) std::max(1, p.ne) * 4)); + CK(cudaMemcpy(d.ptr, hp.data(), hp.size() * 8, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d.start, p.start.data(), (size_t) (p.ng + 1) * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d.ng, &p.ng, 4, cudaMemcpyHostToDevice)); + if (p.ne) { + CK(cudaMemcpy(d.tok, p.tok.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d.dst, p.dst.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + } + return d; +} +void release(Dev& d) { + CK(cudaFree(d.ptr)); + CK(cudaFree(d.start)); + CK(cudaFree(d.ng)); + CK(cudaFree(d.tok)); + CK(cudaFree(d.dst)); +} + +struct Outs { + std::vector<uint8_t> gate, up, h, hq, out; +}; +// one native_expert_grouped call; scratch and out pre-filled with `fill` so an unwritten value shows +Outs run(const Layer& Y, const Plan& p, bool conv, const void* dx, void* scr, float* dout, int64_t gy, int mode, + uint8_t fill) { + // the window's capacity, as verify sizes it: T x 10 groups and entries (the blocks past the plan's groups idle) + const int64_t cap_e = std::max<int64_t>((int64_t) p.ntok * 10, std::max(p.ne, p.ng)), cap_g = cap_e; + Dev d = upload(p, Y, conv); + CK(cudaMemset(scr, fill, K::native_expert_scratch_bytes(cap_e, kFf))); + CK(cudaMemset(dout, fill, (size_t) cap_e * kEmbd * 4)); + K::native_expert_set_mode(mode, 0); + K::native_expert_grouped(conv ? Y.Ln : Y.Lr, d.ptr, d.start, d.ng, d.dst, d.tok, cap_g, cap_e, dx, scr, dout, nullptr, gy); + K::native_expert_set_mode(-1, 0); + CK(cudaGetLastError()); + CK(cudaDeviceSynchronize()); + const size_t f = (size_t) cap_e * kFf * 4, fa = (f + 255) & ~(size_t) 255; + Outs o; + o.gate.resize((size_t) p.ne * kFf * 4); + o.up.resize(o.gate.size()); + o.h.resize(o.gate.size()); + o.hq.resize((size_t) p.ne * (kFf / 32) * 36); + o.out.resize((size_t) p.ne * kEmbd * 4); + const uint8_t* s = (const uint8_t*) scr; + if (p.ne) { + CK(cudaMemcpy(o.gate.data(), s, o.gate.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(o.up.data(), s + fa, o.up.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(o.h.data(), s + 2 * fa, o.h.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(o.hq.data(), s + 3 * fa, o.hq.size(), cudaMemcpyDeviceToHost)); + std::vector<uint8_t> all((size_t) cap_e * kEmbd * 4); + CK(cudaMemcpy(all.data(), dout, all.size(), cudaMemcpyDeviceToHost)); + for (int e = 0; e < p.ne; ++e) + std::memcpy(o.out.data() + (size_t) e * kEmbd * 4, all.data() + (size_t) p.dst[e] * kEmbd * 4, kEmbd * 4); + } + release(d); + return o; +} + +long long diff_rows(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, size_t row) { + long long n = 0; + for (size_t i = 0; i + row <= a.size(); i += row) n += std::memcmp(a.data() + i, b.data() + i, row) != 0; + return n; +} + +// check (7): every plan, both grid strides, every kernel choice, both layouts, v1 off / on, against the GGUF blobs +// through the production kernels +long long grouped_parity(const Layer& Y, std::mt19937& rng, int plans, const void* dx, void* scr, float* dout) { + struct Case { + Plan p; + int T; + }; + std::vector<Case> cases; + for (int T = 1; T <= 6; ++T) { + for (int share : { 0, 50 }) + for (int i = 0; i < plans; ++i) { + std::vector<int> ids; + make_routing(rng, Y.ne, T, share, ids); + cases.push_back({ build_plan(ids), T }); + } + cases.push_back({ single_group(rng, Y.ne, T), T }); + } + for (int i = 0; i < 4; ++i) cases.push_back({ synthetic_plan(rng, Y.ne), kTok }); + int hist[13] = {}; + for (const Case& cs : cases) + for (int g = 0; g < cs.p.ng; ++g) hist[std::min(12, cs.p.start[g + 1] - cs.p.start[g])]++; + struct Var { + int v, mode; + bool v1; + const char* name; + }; + // mode -1: the card's default layout (a GP100: mode 8 - its reference gate/up kernel writes hq, not gate / up); + // mode 0: the CUDA layout + const Var vars[] = { { -1, -1, false, "default, card" }, { 0, -1, false, "S, card" }, { 1, -1, false, "P, card" }, + { -1, -1, true, "default, card, V1" }, { -1, 0, false, "default, mode 0" }, + { 0, 0, false, "S, mode 0" }, { 1, 0, false, "P, mode 0" }, { -1, 0, true, "default, mode 0, V1" }, + // STRATA_NIB_GU_PROTO (nib_gu_proto.cuh): the staged-once kernel, id 31 + { 31, -1, false, "gu-proto 31, card" }, { 31, 0, false, "gu-proto 31, mode 0" }, + { 31, 0, true, "gu-proto 31, mode 0, V1" } }; + constexpr int NV = (int) (sizeof vars / sizeof vars[0]); + long long rows[NV] = {}, bad[NV][5] = {}, total = 0; + for (const Case& cs : cases) + for (int64_t gy : { (int64_t) 0, (int64_t) 4 }) { + Outs ref[2][2]; // [mode 0][v1] + bool have[2][2] = {}; + for (int vi = 0; vi < NV; ++vi) { + const int m0 = vars[vi].mode == 0 ? 1 : 0, r1 = vars[vi].v1 ? 1 : 0; + K::native_grouped_set_v1(vars[vi].v1); + if (!have[m0][r1]) { + K::native_expert_nib_set_variant(-1); + ref[m0][r1] = run(Y, cs.p, false, dx, scr, dout, gy, vars[vi].mode, 0xFF); + have[m0][r1] = true; + } + K::native_expert_nib_set_variant(vars[vi].v); + const Outs o = run(Y, cs.p, true, dx, scr, dout, gy, vars[vi].mode, 0x00); + rows[vi] += cs.p.ne; + // gate / up: written by both arms in the CUDA layout, and by every arm of a striding call (gy 4: mode 0) + const bool gu = vars[vi].mode == 0 || gy == 4; + if (gu) { + bad[vi][0] += diff_rows(ref[m0][r1].gate, o.gate, kFf * 4); + bad[vi][1] += diff_rows(ref[m0][r1].up, o.up, kFf * 4); + } + if (vars[vi].v1 && gu) bad[vi][2] += diff_rows(ref[m0][r1].h, o.h, kFf * 4); + bad[vi][3] += diff_rows(ref[m0][r1].hq, o.hq, (kFf / 32) * 36); + bad[vi][4] += diff_rows(ref[m0][r1].out, o.out, kEmbd * 4); + } + } + K::native_expert_nib_set_variant(-1); + K::native_grouped_set_v1(false); + std::printf(" plans: %zu (T 1..6 x sharing 0/50%% x %d, G=1 per T, 4 of 0..11 entries); groups by entries:", cases.size(), + plans); + for (int n = 0; n <= 12; ++n) std::printf(" %d:%d", n, hist[n]); + std::printf("\n"); + for (int vi = 0; vi < NV; ++vi) { + const long long b = bad[vi][0] + bad[vi][1] + bad[vi][2] + bad[vi][3] + bad[vi][4]; + std::printf(" native_expert_grouped %-20s: %6lld entries x 2 strides, rows differing: gate %lld, up %lld, h %s, hq %lld, out %lld\n", + vars[vi].name, rows[vi], bad[vi][0], bad[vi][1], + vars[vi].v1 ? std::to_string(bad[vi][2]).c_str() : "-", bad[vi][3], bad[vi][4]); + total += b; + } + return total; +} + +// --synthetic: random gate/up blocks, d cycling through the fp16 extremes; the coverage of each field is counted +long long synthesize(Layer& Y, std::mt19937& rng) { + static const uint16_t kD[] = { 0x0001, 0x8001, 0x7BFF, 0xFBFF, 0x3C00, 0xBC00, 0x0400, 0x1A00, 0x2400 }; + const int gt = Y.f.gu_type; + const size_t bb = gt == nib::kIQ2_S ? 82 : gt == nib::kIQ3_XXS ? 98 : 110; // block_iq2_s / iq3_xxs / iq3_s + const size_t nblk = (size_t) nib::kRows * nib::kSuper; + std::set<int> grid, sign, scale, dset; + for (int e = 0; e < Y.ne; ++e) { + uint8_t* b = Y.host.data() + (size_t) e * Y.f.bytes; + for (size_t i = 0; i < 2 * Y.f.up_off; ++i) b[i] = (uint8_t) rng(); + for (size_t k = 0; k < nblk; ++k) { + uint8_t* blk = b + k * bb; + const uint16_t d = kD[((size_t) e * nblk + k) % (sizeof kD / sizeof kD[0])]; + std::memcpy(blk, &d, 2); + dset.insert(d); + const uint8_t* qs = blk + 2; + for (int ib = 0; ib < 8; ++ib) { + if (gt == nib::kIQ2_S) { + const uint8_t* qh = blk + 66; + const uint8_t* sc = blk + 74; + for (int l = 0; l < 4; ++l) { + grid.insert(qs[4 * ib + l] | ((qh[ib] << (8 - 2 * l)) & 0x300)); + sign.insert(qs[32 + 4 * ib + l]); + } + scale.insert(sc[ib] & 15); + scale.insert(sc[ib] >> 4); + } else if (gt == nib::kIQ3_XXS) { + uint32_t aux; + std::memcpy(&aux, blk + 66 + 4 * ib, 4); + for (int l = 0; l < 8; ++l) grid.insert(qs[8 * ib + l]); + for (int l = 0; l < 4; ++l) sign.insert((int) ((aux >> (7 * l)) & 127)); + scale.insert((int) (aux >> 28)); + } else { + const uint8_t qh = blk[66 + ib]; + const uint8_t* sg = blk + 74; + const uint8_t* sc = blk + 106; + for (int l = 0; l < 4; ++l) { + grid.insert(qs[8 * ib + 2 * l] | ((qh << (8 - 2 * l)) & 256)); + grid.insert(qs[8 * ib + 2 * l + 1] | ((qh << (7 - 2 * l)) & 256)); + sign.insert(sg[4 * ib + l]); + } + scale.insert((sc[ib / 2] >> (4 * (ib & 1))) & 15); + } + } + } + } + const size_t want_grid = gt == nib::kIQ2_S ? 1024 : gt == nib::kIQ3_XXS ? 256 : 512; + const size_t want_sign = gt == nib::kIQ3_XXS ? 128 : 256; + const bool ok = grid.size() == want_grid && sign.size() == want_sign && scale.size() == 16 && + dset.size() == sizeof kD / sizeof kD[0]; + std::printf("synthetic %-7s: %d experts, coverage: grid indices %zu/%zu, sign %s %zu/%zu, scale nibbles %zu/16, d values %zu/%zu" + " (+-min subnormal, +-65504, +-1, min normal, 2 ordinary) %s\n", + nib::fmt_name(gt), Y.ne, grid.size(), want_grid, gt == nib::kIQ3_XXS ? "indices" : "bytes", sign.size(), + want_sign, scale.size(), dset.size(), sizeof kD / sizeof kD[0], ok ? "complete" : "INCOMPLETE"); + return ok ? 0 : 1; +} + +std::vector<int> split_ints(const std::string& s) { + std::vector<int> v; + size_t p = 0; + while (p < s.size()) { + v.push_back(std::atoi(s.c_str() + p)); + p = s.find(',', p); + if (p == std::string::npos) break; + ++p; + } + return v; +} + +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + if (argc == 2 && std::strcmp(argv[1], "--header") == 0) return header_check(); + std::vector<std::string> shards; + int per_fmt = 2, NE = 512, plans = 8, syn = 64; + bool ggml_check = true, negative = false, syn_only = false; + std::vector<int> only; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s needs a value\n", a.c_str()); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--layers-per-fmt") per_fmt = std::atoi(next()); + else if (a == "--layers") only = split_ints(next()); + else if (a == "--ne") NE = std::atoi(next()); + else if (a == "--plans") plans = std::atoi(next()); + else if (a == "--synthetic") syn = std::atoi(next()); + else if (a == "--no-ggml") ggml_check = false; + else if (a == "--negative") negative = true; + else if (a == "--synthetic-only") syn_only = true; + else if (a.size() > 5 && a.substr(a.size() - 5) == ".gguf") shards.push_back(a); + else { + std::fprintf(stderr, + "usage: iq_nibble_parity --header\n" + " iq_nibble_parity <shard.gguf> [<shard.gguf> ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512]\n" + " [--plans 8] [--synthetic 64] [--no-ggml] [--negative]\n" + " iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml]\n"); + return 2; + } + } + if ((shards.empty() && !syn_only) || NE < 16 || NE > 512) { + std::fprintf(stderr, "iq_nibble_parity: give at least one model shard (.gguf); --ne 16..512\n"); + return 2; + } + CK(cudaSetDevice(0)); + cudaDeviceProp prop{}; + CK(cudaGetDeviceProperties(&prop, 0)); + char bus[64] = {}; + CK(cudaDeviceGetPCIBusId(bus, sizeof bus, 0)); + std::printf("device 0: %s, bus %s, cc %d.%d, %d SMs\n", prop.name, bus, prop.major, prop.minor, prop.multiProcessorCount); + if (prop.major != 6 || prop.minor != 0) { + std::fprintf(stderr, "iq_nibble_parity: the 4-bit kernels are the sm_60 build's; this GPU is cc %d.%d (skipped)\n", + prop.major, prop.minor); + return 77; + } + if (!STRATA_EXPERT_NIBBLE_BUILT || nib::prepare(nullptr) != 0) { + std::fprintf(stderr, "iq_nibble_parity: no 4-bit kernels in this build, or the GGUF codebooks are not unique\n"); + return 2; + } + std::mt19937 rng(20261019); + void* scr = nullptr; + float* dout = nullptr; + void* dx = nullptr; + const int64_t capmax = (int64_t) kTok * 10; + CK(cudaMalloc(&scr, K::native_expert_scratch_bytes(capmax, kFf))); + CK(cudaMalloc((void**) &dout, (size_t) capmax * kEmbd * 4)); + const std::vector<Q81> hx = make_x(rng); + CK(cudaMalloc(&dx, hx.size() * sizeof(Q81))); + CK(cudaMemcpy(dx, hx.data(), hx.size() * sizeof(Q81), cudaMemcpyHostToDevice)); + + if (syn_only) { // no model: every gate/up format with each down type, random experts + long long total_s = 0; + int done = 0; + for (const int gt : {nib::kIQ2_S, nib::kIQ3_XXS, nib::kIQ3_S}) + for (const int dt : {20, 42}) { // the packs' down types: IQ4_NL, Q2_0 + Layer S; + std::string err; + if (!cpu::native_fmt(gt, dt, kEmbd, kFf, S.f, err)) { + std::printf("%s / down type %d: %s\n", nib::fmt_name(gt), dt, err.c_str()); + ++total_s; + continue; + } + S.tag = "syn"; + S.layer = 0; + S.ne = std::max(16, std::min(syn, NE)); + S.host.resize((size_t) S.ne * S.f.bytes); + for (auto& b : S.host) b = (uint8_t) rng(); + // block_iq4_nl and block_q2_0 are 18 bytes, the fp16 scale first: an ordinary scale in every block of the down rows + for (int e = 0; e < S.ne; ++e) + for (size_t o = S.f.down_off; o + 18 <= S.f.bytes; o += 18) { + const uint16_t sc = (uint16_t) ((9u << 10) | (rng() & 0x3FFu)); + std::memcpy(S.host.data() + (size_t) e * S.f.bytes + o, &sc, 2); + } + long long sb = synthesize(S, rng); + sb += convert(S, ggml_check); + sb += grouped_parity(S, rng, plans, dx, scr, dout); + total_s += sb; + ++done; + CK(cudaFree(S.raw)); + CK(cudaFree(S.slots)); + } + std::printf("\n%s: %d synthetic format pairs, %lld differences\n", total_s == 0 && done == 6 ? "PASS" : "FAIL", done, total_s); + return total_s == 0 && done == 6 ? 0 : 1; + } + long long total = 0; + int layers_done = 0; + std::vector<int> syn_done; + for (size_t si = 0; si < shards.size(); ++si) { + std::unique_ptr<strata::GgufModel> model; + try { + model = std::make_unique<strata::GgufModel>(strata::GgufModel::open(shards[si])); + } catch (const std::exception& ex) { + std::fprintf(stderr, "iq_nibble_parity: %s\n", ex.what()); + return 2; + } + const std::string tag(1, (char) ('A' + si)); + std::printf("\n#### model %s: %s (%zu shards)\n", tag.c_str(), shards[si].c_str(), model->size()); + std::vector<int> pick; + int count[64] = {}; + for (int l = 0; l < 256; ++l) { + int gt = -1, dt = -1; + if (!layer_fmt(*model, l, gt, dt)) break; + if (!nib::fmt_built(gt)) continue; + const bool want = only.empty() ? count[gt]++ < per_fmt : std::find(only.begin(), only.end(), l) != only.end(); + if (want) pick.push_back(l); + } + for (int l : pick) { + Layer Y; + Y.tag = tag; + if (!read_layer(*model, l, NE, Y)) { + std::printf("layer %d: cannot read its experts\n", l); + ++total; + continue; + } + long long b = convert(Y, ggml_check); + if (negative) { // the control: one code byte changed per slot (item 3 of row 5), which (6) must see + for (int e = 0; e < Y.ne; ++e) { + uint8_t* at = Y.slots + (size_t) e * Y.V.slot_bytes + nib::code_off(5, 3); + uint8_t v = 0; + CK(cudaMemcpy(&v, at, 1, cudaMemcpyDeviceToHost)); + v ^= 0x11; + CK(cudaMemcpy(at, &v, 1, cudaMemcpyHostToDevice)); + } + std::printf(" NEGATIVE CONTROL: one code byte changed per slot - the rows below must differ\n"); + std::vector<unsigned long long> hp(Y.ne); + for (int e = 0; e < Y.ne; ++e) hp[e] = (unsigned long long) (Y.slots + (size_t) e * Y.V.slot_bytes); + unsigned long long* dp = nullptr; + CK(cudaMalloc(&dp, (size_t) Y.ne * 8)); + CK(cudaMemcpy(dp, hp.data(), (size_t) Y.ne * 8, cudaMemcpyHostToDevice)); + b += gguf_parity(Y, dp, true); + CK(cudaFree(dp)); + } + b += grouped_parity(Y, rng, plans, dx, scr, dout); + total += b; + ++layers_done; + // the synthetic experts of this format, once: this layer's blobs with random gate/up blocks + if (syn > 0 && std::find(syn_done.begin(), syn_done.end(), Y.f.gu_type) == syn_done.end() && !negative) { + syn_done.push_back(Y.f.gu_type); + Layer S; + S.tag = "syn"; + S.layer = Y.layer; + S.f = Y.f; + S.ne = std::min(syn, Y.ne); + S.host.assign(Y.host.begin(), Y.host.begin() + (ptrdiff_t) ((size_t) S.ne * Y.f.bytes)); + long long sb = synthesize(S, rng); + sb += convert(S, ggml_check); + sb += grouped_parity(S, rng, std::max(1, plans / 2), dx, scr, dout); + total += sb; + CK(cudaFree(S.raw)); + CK(cudaFree(S.slots)); + } + CK(cudaFree(Y.raw)); + CK(cudaFree(Y.slots)); + } + } + std::printf("\n%s: %d layers (+ %zu synthetic formats), %lld differences\n", total == 0 ? "PASS" : "FAIL", layers_done, + syn_done.size(), total); + return total == 0 ? 0 : 1; +} diff --git a/src/kernels/native_expert_bench.cpp b/src/kernels/native_expert_bench.cpp index 3263ee7a..e51bf774 100644 --- a/src/kernels/native_expert_bench.cpp +++ b/src/kernels/native_expert_bench.cpp @@ -2,11 +2,21 @@ // another, bit for bit, and each one's time. // // build/native_expert_bench <shard1.gguf> <layer[,layer...]> <groups> <tokens per group> <ref mode> <mode> [iters] +// build/native_expert_bench --nibble <shard.gguf> <layer[,layer...]> [--t 1,2,3,4,5,6] [--share 0,50] [--plans 200] +// [--trials 7] [--mode -1|0] [--variant -1|0|1] // // Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit // in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the // reference mode's: the verify window's text depends on it. +// +// --nibble (STRATA_EXPERT_NIBBLE, strata/core/expert_nibble.hpp): the layer's 512 experts as GGUF blobs (P, the +// production kernels) and as 4-bit slots made by the engine's transcoder (N: native_expert_layout_nib); the verify +// window's whole expert step (gate/up + SwiGLU/q8_1 + down) and its gate/up phase alone, per (T, sharing) over +// `--plans` top-10 routings (0% or 50% of a token's experts shared with the previous token's), every plan's out rows +// compared byte for byte first; interleaved trials, medians. `--mode`: both arms' layout (-1 the card's default, a +// GP100's mode 8; 0 the CUDA layout); `--variant`: the 4-bit gate/up kernel (-1 per format, 0 S, 1 P). #include "strata/artifact/gguf_reader.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/kernels/cpu/native_expert.hpp" #include "strata/kernels/iq_kernels.hpp" @@ -20,6 +30,8 @@ #include <cstdio> #include <cstdlib> #include <cstring> +#include <map> +#include <memory> #include <random> #include <sstream> #include <string> @@ -28,8 +40,11 @@ namespace cpu = strata::kernels::cpu; namespace K = strata::kernels; +int nibble_main(int argc, char** argv); + int main(int argc, char** argv) { setvbuf(stdout, nullptr, _IONBF, 0); + if (argc >= 2 && std::strcmp(argv[1], "--nibble") == 0) return nibble_main(argc, argv); if (argc < 7) { std::fprintf(stderr, "usage: native_expert_bench <shard1.gguf> <layer[,layer]> <groups> <tokens> <ref mode> <mode> [iters]\n"); return 2; @@ -175,3 +190,407 @@ int main(int argc, char** argv) { std::printf("native_expert_bench: %d differing\n", failures); return failures ? 1 : 0; } + +// ------------------------------------------------------------------------------------------------ --nibble +#if STRATA_EXPERT_NIBBLE_BUILT +namespace { + +namespace nib = strata::core::nibble; + +#define NB_CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); \ + std::exit(2); \ + } \ + } while (0) + +struct NbPlan { + int ng = 0, ne = 0, t = 0; + std::vector<int> gid, start, tok, dst; +}; + +// synthetic routing: t tokens of top-10, `share` % of each token's experts the previous token's; groups by first +// appearance (resident_plan_kernel's order), entries in token order +NbPlan nb_route(std::mt19937& rng, int t, int share) { + std::vector<int> ids, prev, cur; + for (int k = 0; k < t; ++k) { + cur.clear(); + const bool sh = k > 0 && share > 0; + if (sh) { + std::vector<int> p = prev; + std::shuffle(p.begin(), p.end(), rng); + cur.assign(p.begin(), p.begin() + 10 * share / 100); + } + while ((int) cur.size() < 10) { + const int e = (int) (rng() % 512u); + if (std::find(cur.begin(), cur.end(), e) != cur.end()) continue; + if (sh && std::find(prev.begin(), prev.end(), e) != prev.end()) continue; + cur.push_back(e); + } + std::shuffle(cur.begin(), cur.end(), rng); + ids.insert(ids.end(), cur.begin(), cur.end()); + prev = cur; + } + NbPlan p; + p.t = t; + std::map<int, std::vector<int>> by; // expert -> its entries (j = token * 10 + k) + std::vector<int> first; + for (int j = 0; j < (int) ids.size(); ++j) { + if (by.find(ids[j]) == by.end()) first.push_back(ids[j]); + by[ids[j]].push_back(j); + } + for (int e : first) { + p.gid.push_back(e); + p.start.push_back(p.ne); + for (int j : by[e]) { + p.tok.push_back(j / 10); + p.dst.push_back(j); + ++p.ne; + } + } + p.start.push_back(p.ne); + p.ng = (int) p.gid.size(); + return p; +} + +struct NbDev { + unsigned long long* ptr = nullptr; + int32_t *start = nullptr, *ng = nullptr, *tok = nullptr, *dst = nullptr; +}; +NbDev nb_upload(const NbPlan& p, const uint8_t* base, size_t stride) { + NbDev d; + std::vector<unsigned long long> hp(std::max(1, p.ng)); + for (int g = 0; g < p.ng; ++g) hp[g] = (unsigned long long) (base + (size_t) p.gid[g] * stride); + NB_CK(cudaMalloc((void**) &d.ptr, hp.size() * 8)); + NB_CK(cudaMalloc((void**) &d.start, (size_t) (p.ng + 1) * 4)); + NB_CK(cudaMalloc((void**) &d.ng, 4)); + NB_CK(cudaMalloc((void**) &d.tok, (size_t) std::max(1, p.ne) * 4)); + NB_CK(cudaMalloc((void**) &d.dst, (size_t) std::max(1, p.ne) * 4)); + NB_CK(cudaMemcpy(d.ptr, hp.data(), hp.size() * 8, cudaMemcpyHostToDevice)); + NB_CK(cudaMemcpy(d.start, p.start.data(), (size_t) (p.ng + 1) * 4, cudaMemcpyHostToDevice)); + NB_CK(cudaMemcpy(d.ng, &p.ng, 4, cudaMemcpyHostToDevice)); + if (p.ne) { + NB_CK(cudaMemcpy(d.tok, p.tok.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + NB_CK(cudaMemcpy(d.dst, p.dst.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + } + return d; +} +void nb_free(NbDev& d) { + cudaFree(d.ptr); + cudaFree(d.start); + cudaFree(d.ng); + cudaFree(d.tok); + cudaFree(d.dst); +} + +std::vector<int> nb_ints(const std::string& s) { + std::vector<int> v; + std::stringstream ss(s); + std::string t; + while (std::getline(ss, t, ',')) v.push_back(std::atoi(t.c_str())); + return v; +} + +} // namespace + +int nibble_main(int argc, char** argv) { + if (argc < 4) { + std::fprintf(stderr, "usage: native_expert_bench --nibble <shard.gguf> <layer[,layer]> [--t 1,2,3,4,5,6] [--share 0,50] " + "[--plans 200] [--trials 7] [--mode -1|0] [--variant -1|0|1]\n"); + return 2; + } + const std::string shard = argv[2]; + const std::vector<int> layers = nb_ints(argv[3]); + std::vector<int> Ts = { 1, 2, 3, 4, 5, 6 }, shares = { 0, 50 }; + int plans = 200, trials = 7, mode = -1, variant = -1; + std::vector<int> vs; // gu-proto: the nibble gate/up kernels compared with the production one (-1), gate/up only + for (int i = 4; i + 1 < argc; i += 2) { + const std::string a = argv[i]; + if (a == "--t") Ts = nb_ints(argv[i + 1]); + else if (a == "--share") shares = nb_ints(argv[i + 1]); + else if (a == "--plans") plans = std::atoi(argv[i + 1]); + else if (a == "--trials") trials = std::atoi(argv[i + 1]); + else if (a == "--mode") mode = std::atoi(argv[i + 1]); + else if (a == "--variant") variant = std::atoi(argv[i + 1]); + else if (a == "--vs") vs = nb_ints(argv[i + 1]); + else { + std::fprintf(stderr, "unknown option %s\n", a.c_str()); + return 2; + } + } + std::unique_ptr<strata::GgufModel> model; + try { + model = std::make_unique<strata::GgufModel>(strata::GgufModel::open(shard)); + } catch (const std::exception& ex) { + std::fprintf(stderr, "native_expert_bench: %s\n", ex.what()); + return 2; + } + cudaDeviceProp prop{}; + NB_CK(cudaGetDeviceProperties(&prop, 0)); + char bus[64] = {}; + NB_CK(cudaDeviceGetPCIBusId(bus, sizeof bus, 0)); + std::printf("device 0: %s, bus %s, cc %d.%d; layout %s, 4-bit kernel %s\n", prop.name, bus, prop.major, prop.minor, + mode < 0 ? "the card's default" : ("mode " + std::to_string(mode)).c_str(), + variant < 0 ? "per format" : variant == 1 ? "P" : "S"); + K::native_expert_nib_set_variant(variant); + const int64_t H = nib::kNEmbd, FF = nib::kNFf; + constexpr int kTokMax = 8; + int failures = 0; + cudaStream_t s; + NB_CK(cudaStreamCreate(&s)); + cudaEvent_t e0, e1; + NB_CK(cudaEventCreate(&e0)); + NB_CK(cudaEventCreate(&e1)); + // the activations: kTokMax tokens of normal floats, quantized as the verify window quantizes them + std::mt19937 rng(20261019); + std::normal_distribution<float> nd(0.f, 1.f); + std::vector<float> x((size_t) kTokMax * H); + for (auto& v : x) v = nd(rng); + void *dx = nullptr, *dxq = nullptr, *dscr = nullptr; + float* dout = nullptr; + const int64_t cap = (int64_t) kTokMax * 10; + NB_CK(cudaMalloc(&dx, x.size() * 4)); + NB_CK(cudaMalloc(&dxq, (size_t) kTokMax * H / 32 * 36)); + NB_CK(cudaMalloc(&dscr, K::native_expert_scratch_bytes(cap, FF))); + NB_CK(cudaMalloc((void**) &dout, (size_t) cap * H * 4)); + NB_CK(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice)); + K::quantize_q8_1_rows((const float*) dx, kTokMax, H, dxq, s); + for (int l : layers) { + const char* roles[3] = { "gate", "up", "down" }; + const strata::TensorInfo* t[3] = {}; + size_t sh[3] = {}; + for (int r = 0; r < 3; ++r) t[r] = model->find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &sh[r]); + if (!t[0] || !t[1] || !t[2]) { + std::printf("layer %d: no expert tensors\n", l); + ++failures; + continue; + } + cpu::NativeFmt f; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); + ++failures; + continue; + } + nib::Config c; + c.on = true; + const nib::LayerVram V = nib::plan_layer(l, f, c); + if (!V.on) { + std::printf("layer %d: %s is not converted\n", l, ggml_type_name((ggml_type) f.gu_type)); + continue; + } + // the 512 blobs (P) and their 4-bit slots (N, the engine's transcoder) + std::vector<uint8_t> host((size_t) 512 * f.bytes); + const size_t dn_role = f.bytes - f.down_off; + for (int e = 0; e < 512; ++e) { + uint8_t* b = host.data() + (size_t) e * f.bytes; + std::memcpy(b, model->shard(sh[0]).tensor_data(*t[0]) + (size_t) e * f.up_off, f.up_off); + std::memcpy(b + f.up_off, model->shard(sh[1]).tensor_data(*t[1]) + (size_t) e * f.up_off, f.up_off); + std::memcpy(b + f.down_off, model->shard(sh[2]).tensor_data(*t[2]) + (size_t) e * dn_role, dn_role); + } + uint8_t *raw = nullptr, *slots = nullptr; + unsigned long long *dp = nullptr, *dbad = nullptr; + NB_CK(cudaMalloc((void**) &raw, host.size())); + NB_CK(cudaMalloc((void**) &slots, (size_t) 512 * V.slot_bytes)); + NB_CK(cudaMalloc((void**) &dp, 512 * 8)); + NB_CK(cudaMalloc((void**) &dbad, 8)); + NB_CK(cudaMemcpy(raw, host.data(), host.size(), cudaMemcpyHostToDevice)); + std::vector<unsigned long long> hp(512); + for (int e = 0; e < 512; ++e) hp[e] = (unsigned long long) (slots + (size_t) e * V.slot_bytes); + NB_CK(cudaMemcpy(dp, hp.data(), 512 * 8, cudaMemcpyHostToDevice)); + NB_CK(cudaMemset(dbad, 0, 8)); + for (int b0 = 0; b0 < 512; b0 += 64) + if (nib::transcode(V, raw + (size_t) b0 * V.raw_bytes, 64, dp + b0, dbad, s) != 0) return 2; + for (int e = 0; e < 512; ++e) + NB_CK(cudaMemcpyAsync(slots + (size_t) e * V.slot_bytes + nib::kDownOff, raw + (size_t) e * V.raw_bytes + V.raw_down_off, + V.down_bytes, cudaMemcpyDeviceToDevice, s)); + unsigned long long bad = 0; + NB_CK(cudaMemcpyAsync(&bad, dbad, 8, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaStreamSynchronize(s)); + if (bad) { + std::printf("layer %d: %llu items do not round-trip\n", l, bad); + ++failures; + continue; + } + const auto Lr = K::native_expert_layout(f.gu_type, f.d_type, H, FF); + const auto Ln = K::native_expert_layout_nib(f.gu_type, f.d_type, H, FF); + std::printf("layer %2d %-7s/%-6s: 512 experts, blob %zu B, 4-bit slot %llu B\n", l, nib::fmt_name(f.gu_type), + ggml_type_name((ggml_type) f.d_type), f.bytes, (unsigned long long) V.slot_bytes); + // one set of plans: every plan's out rows compared first, then P and N timed interleaved, phase 0 (the whole + // step) and 1 (gate/up + SwiGLU/q8_1), us per launch (median of the trials) + auto bench = [&](const std::vector<NbPlan>& ps, int tt, double us[2][2]) -> long long { + std::vector<NbDev> dr(ps.size()), dn(ps.size()); + for (size_t i = 0; i < ps.size(); ++i) { + dr[i] = nb_upload(ps[i], raw, f.bytes); + dn[i] = nb_upload(ps[i], slots, V.slot_bytes); + } + const int64_t cp = std::max<int64_t>((int64_t) tt * 10, 1); + auto launch = [&](int arm, size_t i) { + const NbDev& d = arm ? dn[i] : dr[i]; + K::native_expert_grouped(arm ? Ln : Lr, d.ptr, d.start, d.ng, d.dst, d.tok, std::max<int64_t>(cp, ps[i].ng), + std::max<int64_t>(cp, ps[i].ne), dxq, dscr, dout, s, 0); + }; + long long diff = 0; + std::vector<uint8_t> a((size_t) cap * H * 4), b(a.size()); + K::native_expert_set_mode(mode, 0); + for (size_t i = 0; i < ps.size(); ++i) { + const size_t n = (size_t) ps[i].ne * H * 4; + NB_CK(cudaMemsetAsync(dout, 0xFF, a.size(), s)); + launch(0, i); + NB_CK(cudaMemcpyAsync(a.data(), dout, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaMemsetAsync(dout, 0x00, a.size(), s)); + launch(1, i); + NB_CK(cudaMemcpyAsync(b.data(), dout, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaStreamSynchronize(s)); + diff += std::memcmp(a.data(), b.data(), n) != 0; + } + for (int ph = 0; ph < 2; ++ph) { + K::native_expert_set_mode(mode, ph); + std::vector<float> tm[2]; + for (int arm = 0; arm < 2; ++arm) + for (size_t i = 0; i < std::min<size_t>(ps.size(), 20); ++i) launch(arm, i); + for (int tr = 0; tr < trials; ++tr) + for (int arm = 0; arm < 2; ++arm) { + NB_CK(cudaEventRecord(e0, s)); + for (size_t i = 0; i < ps.size(); ++i) launch(arm, i); + NB_CK(cudaEventRecord(e1, s)); + NB_CK(cudaEventSynchronize(e1)); + float ms = 0; + NB_CK(cudaEventElapsedTime(&ms, e0, e1)); + tm[arm].push_back(1e3f * ms / (float) ps.size()); + } + for (int arm = 0; arm < 2; ++arm) { + std::sort(tm[arm].begin(), tm[arm].end()); + us[ph][arm] = tm[arm][tm[arm].size() / 2]; + } + } + K::native_expert_set_mode(mode, 0); + for (size_t i = 0; i < ps.size(); ++i) { + nb_free(dr[i]); + nb_free(dn[i]); + } + return diff; + }; + if (!vs.empty()) { // gu-proto: nibble production (-1) against each id in --vs, gate/up only (phase 3) + std::vector<int> arms = { -1 }; + arms.insert(arms.end(), vs.begin(), vs.end()); + for (int v : vs) { + int regs = 0, loc = 0, occ = 0; + if (K::native_expert_nib_variant_attr(v, f.gu_type, ®s, &loc, &occ)) + std::printf(" variant %d: %d registers, %d B local, %d blocks/SM\n", v, regs, loc, occ); + } + const size_t fsz = (size_t) cap * FF * 4, fa = (fsz + 255) & ~(size_t) 255; + for (int tt : Ts) { + if (tt < 1 || tt > kTokMax) continue; + for (int share : shares) { + std::vector<NbPlan> ps; + double G = 0; + for (int i = 0; i < plans; ++i) { + ps.push_back(nb_route(rng, tt, share)); + G += ps.back().ng; + } + std::vector<NbDev> dn(ps.size()); + for (size_t i = 0; i < ps.size(); ++i) dn[i] = nb_upload(ps[i], slots, V.slot_bytes); + const int64_t cp = std::max<int64_t>((int64_t) tt * 10, 1); + auto launch = [&](int v, size_t i) { + K::native_expert_nib_set_variant(v); + K::native_expert_grouped(Ln, dn[i].ptr, dn[i].start, dn[i].ng, dn[i].dst, dn[i].tok, + std::max<int64_t>(cp, ps[i].ng), std::max<int64_t>(cp, ps[i].ne), dxq, dscr, + dout, s, 0); + }; + K::native_expert_set_mode(mode, 3); + // every plan: each arm's gate and up rows (the plan's entries) byte for byte the production arm's + std::vector<long long> drows(arms.size(), 0); + std::vector<uint8_t> ref(2 * fsz), got(2 * fsz); + for (size_t i = 0; i < ps.size(); ++i) { + const size_t n = (size_t) ps[i].ne * FF * 4; + // native_expert_grouped's up rows start after cap_entries gate rows (256-aligned) + const size_t fi = (size_t) std::max<int64_t>(cp, ps[i].ne) * FF * 4, fai = (fi + 255) & ~(size_t) 255; + for (size_t a = 0; a < arms.size(); ++a) { + NB_CK(cudaMemsetAsync(dscr, a == 0 ? 0xFF : 0x00, 2 * fa, s)); + launch(arms[a], i); + std::vector<uint8_t>& o = a == 0 ? ref : got; + NB_CK(cudaMemcpyAsync(o.data(), dscr, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaMemcpyAsync(o.data() + fsz, (const uint8_t*) dscr + fai, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaStreamSynchronize(s)); + if (a == 0) continue; + for (size_t r = 0; r < (size_t) ps[i].ne; ++r) { + drows[a] += std::memcmp(ref.data() + r * FF * 4, got.data() + r * FF * 4, FF * 4) != 0; + drows[a] += std::memcmp(ref.data() + fsz + r * FF * 4, got.data() + fsz + r * FF * 4, FF * 4) != 0; + } + } + } + long long rows = 0; + for (const NbPlan& p : ps) rows += 2LL * p.ne; + std::vector<std::vector<float>> tm(arms.size()); + for (size_t a = 0; a < arms.size(); ++a) + for (size_t i = 0; i < std::min<size_t>(ps.size(), 20); ++i) launch(arms[a], i); + for (int tr = 0; tr < trials; ++tr) + for (size_t a = 0; a < arms.size(); ++a) { + NB_CK(cudaEventRecord(e0, s)); + for (size_t i = 0; i < ps.size(); ++i) launch(arms[a], i); + NB_CK(cudaEventRecord(e1, s)); + NB_CK(cudaEventSynchronize(e1)); + float ms = 0; + NB_CK(cudaEventElapsedTime(&ms, e0, e1)); + tm[a].push_back(1e3f * ms / (float) ps.size()); + } + K::native_expert_set_mode(mode, 0); + K::native_expert_nib_set_variant(variant); + std::printf(" T=%d share %2d%% (G %.2f, %lld gate/up rows a plan set), gate/up us per launch (median, min..max of %d):\n", + tt, share, G / plans, rows, trials); + double base = 0; + for (size_t a = 0; a < arms.size(); ++a) { + std::sort(tm[a].begin(), tm[a].end()); + const double med = tm[a][tm[a].size() / 2]; + if (a == 0) base = med; + std::printf(" %4d: %8.2f (%7.2f..%7.2f) x%.3f %s\n", arms[a], med, tm[a].front(), tm[a].back(), + base / med, a == 0 ? "reference" : drows[a] ? ("rows differ: " + std::to_string(drows[a])).c_str() : "bitwise equal"); + } + for (size_t i = 0; i < ps.size(); ++i) nb_free(dn[i]); + } + } + cudaFree(raw); + cudaFree(slots); + cudaFree(dp); + cudaFree(dbad); + continue; + } + for (int tt : Ts) { + if (tt < 1 || tt > kTokMax) continue; + for (int share : shares) { + std::vector<NbPlan> ps; + double G = 0; + for (int i = 0; i < plans; ++i) { + ps.push_back(nb_route(rng, tt, share)); + G += ps.back().ng; + } + double us[2][2]; + const long long diff = bench(ps, tt, us); + std::printf(" T=%d share %2d%% (G %.2f): step P %7.2f N %7.2f us x%.3f | gate/up+swiglu P %7.2f N %7.2f us x%.3f | %s\n", + tt, share, G / plans, us[0][0], us[0][1], us[0][0] / us[0][1], us[1][0], us[1][1], + us[1][0] / us[1][1], diff ? "DIFFERS" : "bitwise equal"); + if (diff) { + std::printf(" %lld of %d plans differ\n", diff, plans); + ++failures; + } + } + } + cudaFree(raw); + cudaFree(slots); + cudaFree(dp); + cudaFree(dbad); + } + K::native_expert_set_mode(-1, 0); + K::native_expert_nib_set_variant(-1); + std::printf("native_expert_bench --nibble: %d failing\n", failures); + return failures ? 1 : 0; +} +#else +int nibble_main(int, char**) { + std::fprintf(stderr, "native_expert_bench --nibble: no 4-bit kernels in this build (STRATA_EXPERIMENTAL_SM60, CUDA)\n"); + return 2; +} +#endif diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 8a2eb6a3..2e628967 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -47,6 +47,7 @@ #include "strata/prefill/moe_fused_iq.hpp" #include "strata/prefill/moe_mmq.hpp" #include "strata/core/peer_experts.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/prefill/kernels.hpp" #include "strata/prefill/kva.hpp" // STRATA_KVA: the optional approximate-prefill plan (research, off by default) @@ -2467,6 +2468,31 @@ void Prefill::arm_cpu_share(bool applies, bool by_default) { bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); } size_t Prefill::slot_guard_bytes() { return mmq::direct_slot_guard(); } +bool Prefill::nibble_prompt_check(std::string& why) { + const auto& lay = strata::kernels::cpu::expert_layout(); + if (mmq::direct_mode() != 0) { + why = "STRATA_MMQ_DIRECT (the prompt MMQ would read the 4-bit slots in place)"; + return false; + } + for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) { + if (!core::nibble::layer(l).on) continue; + const auto& f = lay.fmt[(size_t) l]; + const char* w = !mmq_plan().any || (size_t) l >= mmq_plan().layer.size() || !mmq_plan().layer[(size_t) l] + ? "no prompt MMQ for it (the FP16 path dequantizes GGUF blocks)" + : mmq_plan().wmma_only[(size_t) l] ? "the WMMA tiles read GGUF blocks" + : fused::native_supported(f.gu_type, f.d_type) ? "the fused prompt kernels read GGUF blocks" + : mmq::matrix_bytes(f.gu_type, 1280, N) != (size_t) core::nibble::kRows * f.gu_row || + mmq::matrix_bytes(f.d_type, N, 640) != f.bytes - f.down_off + ? "MMQ's matrices are not the blob's [gate | up] and down" + : nullptr; + if (w != nullptr) { + why = "layer " + std::to_string(l) + ": " + w; + return false; + } + } + return true; +} + namespace { const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) { @@ -3881,6 +3907,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const bool had_gu = lay.native && lay.fmt[(size_t) l].had_gu; const bool had_d = lay.native && lay.fmt[(size_t) l].had_d; const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; + // STRATA_EXPERT_NIBBLE=1: a layer whose gate/up experts are 4-bit codes in their slots is gathered + // for MMQ as the GGUF blocks rebuilt from them (core::nibble::gather_gguf); every other expert path + // reads GGUF blocks in the slot, so it stops there instead (never a wrong answer) +#if STRATA_EXPERT_NIBBLE_BUILT // every guard of this switch is compiled out of the other builds + const core::nibble::LayerVram& nib_l = core::nibble::layer(l); +#endif const int had_block = lay.native ? lay.fmt[(size_t) l].had_block : 0; const float* had_sx = had_gu ? m.had_sx[(size_t) l] : nullptr; // resolved in init const float* had_sh = had_d ? m.had_sh[(size_t) l] : nullptr; @@ -3918,6 +3950,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri bool cpu_arm = true; // auto: this layer may share (false: the arm without) int cpu_set = -1; // auto: the wall events' set, -1 when not measured bool cpu_cold = false; // auto: one-time costs in the window (no reading) +#if STRATA_EXPERT_NIBBLE_BUILT + if (fused_l && nib_l.on) core::nibble::fatal(l, "the prompt path's fused experts", "they read GGUF blocks"); +#endif if (fused_l) { if (static bool said = false; !said) { said = true; @@ -4823,6 +4858,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri cudaStreamWaitEvent(m.cs, m.copied[gg_slots[gg_nslots - 1]], 0); pt.mark(kPfDequant, cs); } +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_l.on) { // the GGUF blocks rebuilt from the 4-bit slots: the bytes the copy gives + if (const int rc = core::nibble::gather_gguf(nib_l, gg.blob, gg.first, gg.n, m.grp_gu, mmq_gub, + m.grp_d, mmq_db, zero, m.cs); rc != 0) + core::nibble::fatal(l, "the prompt path's group gather", cudaGetErrorString((cudaError_t) rc)); + } else +#endif // NVFP4: each expert's scales go next to its group slot in the same launch if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub, m.grp_d, mmq_db, m.cs, f.tail_off, @@ -4848,6 +4890,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // a ring slot or the peer's), which STRATA_MMQ_DIRECT reads in place auto compute = [&](size_t j, const uint8_t* blob_dev, int slot, int32_t cslot) -> bool { const int32_t e = order[j]; +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_l.on && (!use_mmq || direct || wmma_l || cslot < 0 || !lay.native || + mmq_gub != (size_t) core::nibble::kRows * nib_l.raw_gu_row || + mmq_db != nib_l.down_bytes)) + core::nibble::fatal(l, "the prompt path", + !use_mmq ? "no MMQ for the layer (the FP16 path dequantizes GGUF blocks)" + : direct ? "STRATA_MMQ_DIRECT reads the slots in place" + : wmma_l ? "the WMMA tiles read GGUF blocks" + : cslot < 0 ? "an expert not in this GPU's slots (streamed or the peer's)" + : "the MMQ group buffers are not the blob's [gate | up] and down"); +#endif pt.mark(kPfDequant, cs); if (use_mmq) { // gather the expert into its group slot (GGUF blocks, unchanged or converted) @@ -4894,6 +4947,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri gg = mmq::GatherGroup{}; } else if (lay.native) { const auto& f = lay.fmt[(size_t) l]; +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_l.on) { // as the group gather (flush), one expert at its group position q + const uint8_t* one[mmq::kGatherGroupMax] = {}; + one[q] = blob_dev; + if (const int rc = core::nibble::gather_gguf(nib_l, one, (int) q, (int) q + 1, m.grp_gu, + mmq_gub, m.grp_d, mmq_db, + last_of_group ? MMQ_TAIL : 0, m.cs); rc != 0) + core::nibble::fatal(l, "the prompt path's gather", cudaGetErrorString((cudaError_t) rc)); + } else +#endif // NVFP4: this expert's scales go next to its group slot in the same launch mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs, diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 75d404ac..d0de8560 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -25,6 +25,7 @@ #include "strata/core/device.hpp" #include "strata/core/remote_expert_opt.hpp" #include "strata/core/expert_cache.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/conversation_snapshot.hpp" #include "strata/core/conversation_file.hpp" #include "strata/core/session_save_reclaim.hpp" @@ -156,6 +157,7 @@ namespace strata::metal_engine { void set_model_shard(const char* shard1); } / #include <vector> namespace { +namespace nib = strata::core::nibble; // Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, // pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); // a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). @@ -388,6 +390,7 @@ bool resident_stage_swaps(strata::core::FileExpertSource& src, const std::vector if (slot < 0) continue; const SwapHome home = locate(s.layer); const strata::core::OnDevice on(home.dev); + nib::guard_raw(s.layer, "the adaptive tier's copy back (resident_stage_swaps)"); if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q, s.layer), home.cache->device_slot(slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, home.stream); e != cudaSuccess) { @@ -2248,6 +2251,297 @@ struct PcieAuto { } }; +// ---- STRATA_EXPERT_NIBBLE=1 (strata/core/expert_nibble.hpp): the gate/up experts of IQ2_S / IQ3_XXS / IQ3_S layers as +// 4-bit codes in their VRAM slots. Everything below runs only with the switch on. + +/// The largest slot an expert cache can hold for this pack: the GGUF `max_blob`, or a converted layer's 4-bit slot when +/// that is larger (the sizings that count slots of the largest blob would otherwise come out short of a full cache and +/// leave converted experts out of VRAM, which the switch refuses). `max_blob` exactly with the switch off. +uint64_t nibble_max_slot_bytes() { + const auto& lay = strata::kernels::cpu::expert_layout(); + uint64_t m = lay.max_blob; + if (nib::any_on()) + for (int64_t l = 0; l < lay.n_layers; ++l) m = std::max<uint64_t>(m, nib::slot_bytes(l)); + return m; +} + +#if STRATA_EXPERT_NIBBLE_BUILT +/// One expert cache's converted slots. The startup fill hands a converted layer's pairs to `add` instead of +/// `fill_slot_blocking`; per layer, `kBatch` GGUF blobs at a time go H2D into one staging buffer (the bytes +/// fill_slot_blocking would copy, from the source's `blob_stable`, which stays valid) and, per batch, the +/// transcoder writes the codes, scales and d into the slots and round-trips every item, the GGUF down rows are copied +/// behind them, the GGUF blocks are rebuilt from every slot and compared with the blob (both count against the layer +/// in `d_bad`), and each slot's hash is recorded for STRATA_EXPERT_NIBBLE_RECHECK. One stream, so the staging +/// buffer's reuse is ordered without events. The device arrays live as long as the process (RECHECK reads them); +/// `finish` frees the staging buffer. +struct NibbleCache { + static constexpr int64_t kBatch = 64; + struct Pending { int32_t expert, slot; const uint8_t* blob; }; + struct Batch { int32_t layer; int64_t at, n; }; + strata::core::ExpertCache* cache = nullptr; + int dev = 0; ///< the cache's device + std::vector<std::vector<Pending>> pending; ///< per layer: queued, at most kBatch + std::vector<Batch> batches; ///< what was transcoded and hashed, in that order + std::vector<std::pair<int32_t, int32_t>> pairs; ///< (layer, expert) of each converted slot, in that order + std::vector<int32_t> slots; ///< and its slot + unsigned long long* h_ptrs = nullptr; ///< pinned: the slots' device addresses, in that order + unsigned long long* d_ptrs = nullptr; ///< the same on the device (the transcoder's and hash's input) + unsigned long long* d_ref = nullptr; ///< each slot's hash as loaded + unsigned long long* d_now = nullptr; ///< RECHECK's + unsigned long long* d_bad = nullptr; ///< per layer: items that did not round-trip, words that differ + uint8_t* staging = nullptr; + uint64_t raw_max = 0; + cudaStream_t stream = nullptr; + int64_t cap = 0, n = 0; + double seconds = 0; + + bool active() const { return cache != nullptr; } + + static std::string cuda_fail(const char* what, cudaError_t e) { return std::string(what) + ": " + cudaGetErrorString(e); } + + /// For `c` on the current device, `want` converted pairs at most. + bool begin(strata::core::ExpertCache& c, int64_t want, std::string& err) { + if (cudaGetDevice(&dev) != cudaSuccess) dev = 0; + cache = &c; + cap = want > 0 ? want : 1; + const auto& lay = strata::kernels::cpu::expert_layout(); + pending.assign((size_t) lay.n_layers, {}); + for (int64_t l = 0; l < lay.n_layers; ++l) + if (nib::layer(l).on) raw_max = std::max<uint64_t>(raw_max, nib::layer(l).raw_bytes); + cudaError_t e = cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking); + if (e == cudaSuccess) e = cudaMallocHost((void**) &h_ptrs, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_ptrs, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_ref, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_now, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_bad, (size_t) lay.n_layers * 8); + if (e == cudaSuccess) e = cudaMemsetAsync(d_bad, 0, (size_t) lay.n_layers * 8, stream); + if (e == cudaSuccess) e = cudaMalloc((void**) &staging, (size_t) ((uint64_t) kBatch * raw_max)); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill's buffers", e); + return false; + } + if (const int rc = nib::prepare((void*) stream); rc != 0) { + err = std::string("the 4-bit fill's GGUF codebooks: ") + + (rc == (int) cudaErrorInvalidValue ? "a grid entry is not unique" : cudaGetErrorString((cudaError_t) rc)); + return false; + } + return true; + } + + bool add(int32_t layer, int32_t expert, int32_t slot, const uint8_t* blob, std::string& err) { + auto& q = pending[(size_t) layer]; + q.push_back({expert, slot, blob}); + return (int64_t) q.size() < kBatch || flush(layer, err); + } + + bool flush(int32_t layer, std::string& err) { + auto& q = pending[(size_t) layer]; + if (q.empty()) return true; + const auto t0 = std::chrono::steady_clock::now(); + const nib::LayerVram& L = nib::layer(layer); + const int64_t k = (int64_t) q.size(); + if (n + k > cap) { + err = "the 4-bit fill was given more converted pairs than it counted"; + return false; + } + cudaError_t e = cudaSuccess; + for (int64_t i = 0; i < k && e == cudaSuccess; ++i) { + uint8_t* dst = cache->device_slot(q[(size_t) i].slot); + if (dst == nullptr || cache->slot_room(q[(size_t) i].slot) < L.hashed) { // a slot sized for the GGUF blob + err = "the 4-bit fill: slot " + std::to_string(q[(size_t) i].slot) + + (dst == nullptr ? " is outside the cache" : " is smaller than a 4-bit slot"); + return false; + } + h_ptrs[n + i] = (unsigned long long) (uintptr_t) dst; + e = cudaMemcpyAsync(staging + (uint64_t) i * L.raw_bytes, q[(size_t) i].blob, (size_t) L.raw_bytes, + cudaMemcpyHostToDevice, stream); + } + if (e == cudaSuccess) e = cudaMemcpyAsync(d_ptrs + n, h_ptrs + n, (size_t) k * 8, cudaMemcpyHostToDevice, stream); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill's copies in", e); + return false; + } + auto m2 = [&](const char* what, int rc) -> bool { // iq_kernels.cu's: a CUDA error code + if (rc == 0) return true; + err = std::string("the 4-bit ") + what + ": " + cudaGetErrorString((cudaError_t) rc); + return false; + }; + if (!m2("transcoder", nib::transcode(L, staging, k, d_ptrs + n, d_bad + layer, (void*) stream))) return false; + for (int64_t i = 0; i < k && e == cudaSuccess; ++i) + e = cudaMemcpyAsync((uint8_t*) (uintptr_t) h_ptrs[n + i] + nib::kDownOff, + staging + (uint64_t) i * L.raw_bytes + L.raw_down_off, (size_t) L.down_bytes, + cudaMemcpyDeviceToDevice, stream); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill's down rows", e); + return false; + } + if (!m2("GGUF check", nib::check_gguf(L, staging, k, d_ptrs + n, d_bad + layer, (void*) stream))) return false; + if (!m2("slot hash", nib::hash_slots(L, d_ptrs + n, k, d_ref + n, (void*) stream))) return false; + // the next batch's copies in land in the same staging bytes: they wait for this batch's kernels (one stream) + for (const Pending& p : q) { + pairs.emplace_back(layer, p.expert); + slots.push_back(p.slot); + } + batches.push_back({layer, n, k}); + n += k; + q.clear(); + seconds += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); + return true; + } + + /// The rest of the queue, then waits: false (with `err` naming every layer) when an item did not round-trip or a + /// rebuilt GGUF block differs from its blob. + bool finish(std::string& err) { + for (int32_t l = 0; l < (int32_t) pending.size(); ++l) + if (!flush(l, err)) return false; + const auto t0 = std::chrono::steady_clock::now(); + cudaError_t e = cudaStreamSynchronize(stream); + std::vector<unsigned long long> bad(pending.size(), 0); + if (e == cudaSuccess) e = cudaMemcpy(bad.data(), d_bad, bad.size() * 8, cudaMemcpyDeviceToHost); + if (staging != nullptr) (void) cudaFree(staging); + staging = nullptr; + seconds += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill", e); + return false; + } + for (size_t l = 0; l < bad.size(); ++l) + if (bad[l] != 0) { + char b[192]; + std::snprintf(b, sizeof b, "%slayer %zu (%s): %llu items or words do not round-trip", err.empty() ? "" : "; ", + l, nib::fmt_name(nib::layer((int64_t) l).gu_type), bad[l]); + err += b; + } + if (!err.empty()) { + err += " - the 4-bit code does not hold these weights (STRATA_EXPERT_NIBBLE_SKIP=<layers> keeps a layer's " + "GGUF blocks)"; + return false; + } + return true; + } + + /// The end-to-end check of the fill as it is wired, on converted pair (layer, expert) with `raw` its GGUF blob: the + /// slot read back, its hash against expert_nibble.hpp's host reference of what the device recorded, its down rows + /// against the blob's. (Every item and every GGUF block of every slot was checked on the device by `finish`.) + bool check(int32_t layer, int32_t expert, const uint8_t* raw, std::string& err) const { + int64_t at = -1; + for (size_t i = 0; i < pairs.size() && at < 0; ++i) + if (pairs[i].first == layer && pairs[i].second == expert) at = (int64_t) i; + if (at < 0 || raw == nullptr) { + err = "the 4-bit check: no converted slot or no GGUF blob for layer " + std::to_string(layer) + " expert " + + std::to_string(expert); + return false; + } + const nib::LayerVram& L = nib::layer(layer); + std::vector<uint8_t> got((size_t) L.hashed); + unsigned long long h = 0; + cudaError_t e = cudaMemcpy(got.data(), cache->device_slot(slots[(size_t) at]), got.size(), cudaMemcpyDeviceToHost); + if (e == cudaSuccess) e = cudaMemcpy(&h, d_ref + at, 8, cudaMemcpyDeviceToHost); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit check's read back", e); + return false; + } + const char* why = nib::hash_host(got.data(), L.hashed) != h ? "the device slot hash differs from the host reference" + : std::memcmp(got.data() + nib::kDownOff, raw + L.raw_down_off, (size_t) L.down_bytes) != 0 + ? "the down rows differ from the GGUF blob's" + : nullptr; + if (why != nullptr) { + err = "layer " + std::to_string(layer) + " expert " + std::to_string(expert) + " (" + nib::fmt_name(L.gu_type) + + "): " + why; + return false; + } + return true; + } + + /// STRATA_EXPERT_NIBBLE_RECHECK: every converted slot's hash again, on the device, against the one recorded at load. + /// False with the first slot that differs (or a CUDA error) in `err`; `bad_layer` its layer (-1: an error). + bool recheck(std::string& err, int64_t& bad_layer) { + bad_layer = -1; + if (n == 0) return true; + const strata::core::OnDevice on(dev); + for (const Batch& b : batches) { + const int rc = nib::hash_slots(nib::layer(b.layer), d_ptrs + b.at, b.n, d_now + b.at, (void*) stream); + if (rc != 0) { + err = cuda_fail("the slot hash", (cudaError_t) rc); + return false; + } + } + std::vector<unsigned long long> ref((size_t) n), now((size_t) n); + cudaError_t e = cudaStreamSynchronize(stream); + if (e == cudaSuccess) e = cudaMemcpy(ref.data(), d_ref, (size_t) n * 8, cudaMemcpyDeviceToHost); + if (e == cudaSuccess) e = cudaMemcpy(now.data(), d_now, (size_t) n * 8, cudaMemcpyDeviceToHost); + if (e != cudaSuccess) { + err = cuda_fail("the slot hash read back", e); + return false; + } + for (int64_t i = 0; i < n; ++i) + if (ref[(size_t) i] != now[(size_t) i]) { + char b[224]; + std::snprintf(b, sizeof b, "CUDA%d: layer %d expert %d (slot %d) hashes %016llx, %016llx at load", dev, + (int) pairs[(size_t) i].first, (int) pairs[(size_t) i].second, (int) slots[(size_t) i], + now[(size_t) i], ref[(size_t) i]); + err = b; + bad_layer = pairs[(size_t) i].first; + return false; + } + return true; + } +}; +#else +// A build without the 4-bit kernels (STRATA_EXPERT_NIBBLE_BUILT 0: HIP, Metal, a CUDA build without +// STRATA_EXPERIMENTAL_SM60): nibble_refusal refuses the switch, so no cache is ever converted and none of this is entered. +struct NibbleCache { + int64_t n = 0; + double seconds = 0; + std::vector<std::pair<int32_t, int32_t>> pairs; + bool active() const { return false; } + bool begin(strata::core::ExpertCache&, int64_t, std::string& err) { err = "the 4-bit slots are not in this build"; return false; } + bool add(int32_t, int32_t, int32_t, const uint8_t*, std::string& err) { err = "the 4-bit slots are not in this build"; return false; } + bool finish(std::string&) { return true; } + bool check(int32_t, int32_t, const uint8_t*, std::string& err) const { err = "the 4-bit slots are not in this build"; return false; } + bool recheck(std::string&, int64_t& bad_layer) { bad_layer = -1; return true; } +}; +#endif + +/// With STRATA_EXPERT_NIBBLE=1, why this start cannot have 4-bit slots (empty: nothing here stops it): what the build, +/// the GPUs, the environment and the options decide, before anything is allocated. The full residency, the loans and +/// the prompt chunk are checked where they are known. +std::string nibble_refusal(const Options& o) { + const nib::Config& c = nib::config(); + if (!c.error.empty()) return c.error; +#if !STRATA_EXPERT_NIBBLE_BUILT || !defined(STRATA_NATIVE_EXPERTS) + (void) o; + return "the 4-bit slots and their kernels are in the CUDA build with STRATA_EXPERIMENTAL_SM60 and native experts only"; +#else + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess || count <= 0) { + (void) cudaGetLastError(); + return "no CUDA device"; + } + for (int d = 0; d < count; ++d) { + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, d) != cudaSuccess) { + (void) cudaGetLastError(); + return "cannot read CUDA" + std::to_string(d) + "'s properties"; + } + if (p.major != 6 || p.minor != 0) + return "CUDA" + std::to_string(d) + " (" + p.name + ") is compute capability " + std::to_string(p.major) + "." + + std::to_string(p.minor) + ": the 4-bit slots are for compute capability 6.0 (GP100) only"; + } + if (std::string e = nib::env_conflicts(); !e.empty()) return e; + if (o.peer_device >= 1) return "--peer-device (its cache holds GGUF blobs)"; + for (size_t r = 0; r < o.expert_cache_remote.size(); ++r) + if (o.expert_cache_remote[r] > 0 || o.expert_cache_remote_auto[r]) + return "remote expert caches (--expert-cache-device1..3 hold GGUF blobs)"; + if (o.kv_grow) return "--kv-grow (the elastic K/V moves slots at their GGUF size)"; + if (o.vram_elastic) return "--vram-elastic (it refills slots with GGUF blobs)"; + if (o.expert_profile.empty()) + return "no --expert-profile (every expert must be VRAM-resident from the profile fill)"; + if (o.expert_cache == 0) return "--expert-cache 0 (no VRAM slots to convert)"; + return {}; +#endif +} + } // namespace // #1425 #1549 #1629: --ple-io direct (the default) does unbuffered random reads of the n-gram table; on some drives @@ -3564,6 +3858,49 @@ int main(int argc, char** argv) { } std::fprintf(stderr, "strata generate: primary device from STRATA_PRIMARY_DEVICE: CUDA%d\n", primary_device); } + // ---- STRATA_EXPERT_NIBBLE=1 keeps the gate/up experts of IQ2_S / IQ3_XXS / IQ3_S layers as 4-bit codes in their VRAM + // slots (strata/core/expert_nibble.hpp). Unset or 0: nothing here runs, no table is set, and every slot size below is + // the GGUF blob's, as before. On: if anything would read a converted slot as GGUF blocks or write GGUF bytes into + // one, the switch is ignored for this start with a warning (before anything is allocated); else the per-layer table + // is set before the first slot estimate and the adaptive tier is off (it swaps GGUF blobs in and out of slots). + // The residency, the loans and the prompt chunk are checked where they are known (those refuse the start). + const bool nib_asked = nib::config().on || nib::config().error.rfind("STRATA_EXPERT_NIBBLE=", 0) == 0; + const int64_t nib_chunk_asked = o.prefill_chunk; // an explicit --prefill N must stay N (the chunking is in the bits) + if (nib_asked) { + std::string why = nibble_refusal(o); + if (why.empty()) { + nib::set_layers(nib::plan_layers(strata::kernels::cpu::expert_layout(), why)); + if (why.empty() && !nib::any_on()) + why = "no layer of this pack is IQ2_S / IQ3_XXS / IQ3_S at 2560 x 640 among STRATA_EXPERT_NIBBLE_FMTS " + "and outside STRATA_EXPERT_NIBBLE_SKIP"; + if (why.empty()) (void) strata::prefill::Prefill::nibble_prompt_check(why); + } + if (!why.empty()) { + // a warning, not a refusal: this start goes on as it would without the switch (the usual GGUF slots) + std::fprintf(stderr, "strata generate: WARNING: STRATA_EXPERT_NIBBLE is off for this start: %s; the expert slots " + "stay GGUF blocks\n", why.c_str()); + nib::set_layers({}); + } else { + o.adapt_swaps = 0; + o.peer_adapt_swaps = 0; + const auto& lay = strata::kernels::cpu::expert_layout(); + int64_t n_on = 0, by_fmt[3] = {0, 0, 0}; + uint64_t more = 0; + for (int64_t l = 0; l < lay.n_layers; ++l) { + const nib::LayerVram& v = nib::layer(l); + if (!v.on) continue; + ++n_on; + ++by_fmt[v.gu_type == nib::kIQ2_S ? 0 : v.gu_type == nib::kIQ3_XXS ? 1 : 2]; + more += (v.slot_bytes - (v.raw_bytes + 255) / 256 * 256) * (uint64_t) lay.n_expert; + } + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: %lld of %lld layers keep their gate/up experts as 4-bit " + "codes in VRAM (IQ2_S %lld, IQ3_XXS %lld, IQ3_S %lld), %.2f GiB more VRAM than their GGUF " + "blobs for all %lld experts of each; the adaptive tier is off (--adapt-swaps 0)%s\n", + (long long) n_on, (long long) lay.n_layers, (long long) by_fmt[0], (long long) by_fmt[1], + (long long) by_fmt[2], (double) more / 1073741824.0, (long long) lay.n_expert, + nib::config().recheck ? "; STRATA_EXPERT_NIBBLE_RECHECK: every slot's hash after each request" : ""); + } + } // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). @@ -4291,7 +4628,7 @@ int main(int argc, char** argv) { const auto& lay = strata::kernels::cpu::expert_layout(); int64_t pairs_bytes = 0; for (const auto& pr : prof) - pairs_bytes += native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard) + pairs_bytes += native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard) : (int64_t) lay.max_blob; size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); @@ -4754,7 +5091,7 @@ int main(int argc, char** argv) { total_mass += (mass[r] = hi - lo); } auto cost = [&](int64_t l) -> int64_t { - return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(l), slot_guard) + return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard) : (int64_t) lay.max_blob; }; // the predicted window time (ms) of a placement, and the routed mass its caches hold @@ -4870,7 +5207,7 @@ int main(int argc, char** argv) { }; struct PartStat { int64_t lb, le; int64_t used; int64_t cnt; int64_t cap; }; auto can_start = [&](const std::vector<PartStat>& parts) -> bool { - const int64_t kMaxBlob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + const int64_t kMaxBlob = (int64_t) nibble_max_slot_bytes(); // max_blob (or a larger 4-bit slot) auto slots_est_of = [&](int i, uint64_t cn) -> int64_t { if (parts[i].cnt <= 0) return -1; const uint64_t avg = (parts[i].used > 0) @@ -5966,7 +6303,7 @@ int main(int argc, char** argv) { // which only ever grants MORE slots) uint64_t cap_bytes; if (o.expert_cache > 0) { - cap_bytes = (uint64_t) o.expert_cache * pl.max_blob; + cap_bytes = (uint64_t) o.expert_cache * nibble_max_slot_bytes(); } else { const int64_t pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; int64_t mtp_b = (!o.mtp.empty() && native_head.loaded()) @@ -5986,7 +6323,7 @@ int main(int argc, char** argv) { uint64_t used = 0; skip = 0; for (const auto& pr : profile) { - const uint64_t b = pl.native ? (pl.blob_bytes(pr.first) + 255) / 256 * 256 : (uint64_t) pl.max_blob; + const uint64_t b = pl.native ? (nib::slot_bytes(pr.first) + 255) / 256 * 256 : (uint64_t) pl.max_blob; if (used + b > cap_bytes) break; used += b; ++skip; @@ -6222,7 +6559,7 @@ int main(int argc, char** argv) { if (use_df2 && native_head.loaded()) mtp_bind += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20); // DFlash2's own draft head and logits, bound after this #endif const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + const int64_t blob = (int64_t) nibble_max_slot_bytes(); // max_blob (STRATA_EXPERT_NIBBLE: or a larger 4-bit slot) int64_t slots = ((int64_t) free_b - reserve) / blob; if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size()); #if defined(STRATA_GPU_METAL) @@ -6320,7 +6657,7 @@ int main(int argc, char** argv) { free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t prefill_mib = owned_prefill_mib(); const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first; - const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); + const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) nibble_max_slot_bytes(), 0); if (o.expert_cache > fit) { // a WARNING that names the knob: the user asked for this size, and gets fewer slots std::fprintf(stderr, "strata generate: WARNING: layer split: --expert-cache %d leaves no room for the " @@ -6342,19 +6679,19 @@ int main(int argc, char** argv) { const size_t free_b = strata::core::device_free_bytes(); // the same reading the shared-cache sizing uses const auto& lay = strata::kernels::cpu::expert_layout(); const int asked = o.expert_cache; - const uint64_t budget = (uint64_t) asked * lay.max_blob; + const uint64_t budget = (uint64_t) asked * nibble_max_slot_bytes(); size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0; const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room); uint64_t sum = 0; for (int64_t l = 0; l < g.n_layers; ++l) - sum += (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(l), slot_guard); + sum += (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard); int64_t q = sum > 0 ? (int64_t) (cap / sum) : 0; if (q > g.n_expert) q = g.n_expert; if (q > 0) { per_layer_bytes = sum; sized_slots.reserve((size_t) q * (size_t) g.n_layers); for (int64_t l = 0; l < g.n_layers; ++l) { - const int64_t b = (int64_t) lay.blob_bytes(l); + const int64_t b = (int64_t) nib::slot_bytes(l); for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b); } o.expert_cache = (int) sized_slots.size(); @@ -6370,16 +6707,16 @@ int main(int argc, char** argv) { // what the uniform sizing granted, in the 256-byte slots the loop below counts: the blob formats of 1280 / 2560 // rows are whole multiples of 256 already; an NVFP4 blob's 16-byte scale tail is not, and the unrounded budget // held one slot fewer than asked (--expert-cache 1: none) - const uint64_t budget = (uint64_t) o.expert_cache * ((lay.max_blob + 255) / 256 * 256); + const uint64_t budget = (uint64_t) o.expert_cache * ((nibble_max_slot_bytes() + 255) / 256 * 256); uint64_t used = 0; const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first; size_t free_room = free_b > keep_free ? free_b - keep_free : 0; const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room); for (const auto& pr : profile) { - const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard); + const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard); if (used + b > cap) break; used += b; - sized_slots.push_back((int64_t) lay.blob_bytes(pr.first)); + sized_slots.push_back((int64_t) nib::slot_bytes(pr.first)); } // #831: the sized-slots loop walks the profile's pairs, so the profile's length is the ceiling; an explicit // --expert-cache above it used to be cut with no word. A warning only (what is allocated does not change). @@ -6429,7 +6766,7 @@ int main(int argc, char** argv) { sized_slots.clear(); if (q <= 0) { o.expert_cache = 0; return false; } for (int64_t l = 0; l < g.n_layers; ++l) { - const int64_t b = (int64_t) lay.blob_bytes(l); + const int64_t b = (int64_t) nib::slot_bytes(l); for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b); } o.expert_cache = (int) sized_slots.size(); @@ -6554,6 +6891,10 @@ int main(int argc, char** argv) { // admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile // the policy rather than a hint. int64_t prefilled = 0; + // STRATA_EXPERT_NIBBLE: each cache's converted slots (RECHECK reads them per request) + NibbleCache nib_x; + std::vector<NibbleCache> nib_st; + nib_st.reserve(stages.size()); if (!profile.empty() && srcp != nullptr) { // #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until // its range is full (one full layer used to end the whole fill, leaving most layers empty) @@ -6574,6 +6915,14 @@ int main(int argc, char** argv) { } const auto fill_t0 = std::chrono::steady_clock::now(); uint64_t fill_bytes = 0; + if (nib::any_on()) { // STRATA_EXPERT_NIBBLE: the converted layers' pairs go through the 4-bit fill instead + int64_t conv = 0; + for (int64_t i = 0; i < want; ++i) conv += nib::layer(profile[(size_t) i].first).on ? 1 : 0; + if (conv > 0 && !nib_x.begin(xcache, conv, err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: %s\n", err.c_str()); + return 1; + } + } for (int64_t i = 0; i < want; ++i) { if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { if (ahead.valid()) ahead.get(); @@ -6587,8 +6936,10 @@ int main(int argc, char** argv) { break; } const uint8_t* b = srcp->blob_stable(profile[(size_t) i].first, profile[(size_t) i].second); - if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err, - (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first))) { + const bool nib_pair = nib_x.active() && nib::layer(profile[(size_t) i].first).on; // STRATA_EXPERT_NIBBLE + if (b == nullptr || !(nib_pair ? nib_x.add(profile[(size_t) i].first, profile[(size_t) i].second, slot, b, err) + : xcache.fill_slot_blocking(slot, b, err, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first)))) { std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n", (long long) i, err.c_str()); return 1; @@ -6596,16 +6947,39 @@ int main(int argc, char** argv) { fill_bytes += strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first); ++prefilled; } + if (nib_x.active() && !nib_x.finish(err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %s\n", err.c_str()); + return 1; + } const double fill_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - fill_t0).count(); // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong // about bytes produces a plausible token, which is this project's most expensive failure mode; the // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. - if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), + // (STRATA_EXPERT_NIBBLE: a converted slot holds 4-bit codes, not the blob's bytes - the 4-bit check below is its check) + if (prefilled > 0 && !nib::layer(profile[0].first).on && + !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), srcp->blob_stable(profile[0].first, profile[0].second), err, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (nib_x.active() && nib_x.n > 0) { + // STRATA_EXPERT_NIBBLE: the hottest converted pair read back (its hash, its down rows); every item and every + // rebuilt GGUF block of every converted slot was already checked on the device + size_t c = 0; + while (c < (size_t) want && !nib::layer(profile[c].first).on) ++c; + if (!nib_x.check(profile[c].first, profile[c].second, srcp->blob_stable(profile[c].first, profile[c].second), + err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %s\n", err.c_str()); + return 1; + } + std::set<int32_t> ls; + for (const auto& pr : nib_x.pairs) ls.insert(pr.first); + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %lld slots of %zu layers transcoded to 4-bit " + "codes (%.2f s; every item round-tripped, every slot's GGUF blocks rebuilt and compared, " + "slot hashes recorded); layer %d expert %d read back\n", (long long) nib_x.n, ls.size(), + nib_x.seconds, (int) profile[c].first, (int) profile[c].second); + } mem_mark("the profile fill"); std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile in %.1f s (%.0f MB/s); " "slot 0 verified\n", @@ -6662,11 +7036,11 @@ int main(int argc, char** argv) { std::vector<int64_t> sized; int64_t used = 0; for (const auto& pr : st.profile) { - const int64_t b = native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard) + const int64_t b = native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard) : (int64_t) lay.max_blob; if (used + b > room) break; used += b; - sized.push_back((int64_t) lay.blob_bytes(pr.first)); + sized.push_back((int64_t) nib::slot_bytes(pr.first)); } // #841: a stage's cache can fail to open with the VRAM free (the card's allocation is also charged to the // Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each @@ -6691,25 +7065,57 @@ int main(int argc, char** argv) { return 1; } int64_t filled = 0; + NibbleCache& nib_c = nib_st.emplace_back(); // STRATA_EXPERT_NIBBLE: this stage's converted slots + if (nib::any_on()) { + int64_t conv = 0; + for (const auto& pr : st.profile) conv += nib::layer(pr.first).on ? 1 : 0; + if (conv > 0 && !nib_c.begin(st.cache, conv, err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + } for (const auto& pr : st.profile) { if (filled >= st.cache.slots()) break; const int32_t slot = st.cache.admit(pr.first, pr.second); if (slot == strata::core::kNotResident) break; const uint8_t* b = srcp->blob_stable(pr.first, pr.second); - if (b == nullptr || !st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first))) { + const bool nib_pair = nib_c.active() && nib::layer(pr.first).on; // STRATA_EXPERT_NIBBLE + if (b == nullptr || !(nib_pair ? nib_c.add(pr.first, pr.second, slot, b, err) + : st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first)))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n", st.dev, (long long) filled, err.c_str()); return 1; } ++filled; } - if (filled == 0 || !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), - srcp->blob_stable(st.profile[0].first, st.profile[0].second), err, - (int64_t) lay.blob_bytes(st.profile[0].first))) { + if (nib_c.active() && !nib_c.finish(err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + // (STRATA_EXPERT_NIBBLE: a converted slot holds 4-bit codes, not the blob's bytes - the 4-bit check below is its check) + if (filled == 0 || (!nib::layer(st.profile[0].first).on && + !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), + srcp->blob_stable(st.profile[0].first, st.profile[0].second), err, + (int64_t) lay.blob_bytes(st.profile[0].first)))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, filled == 0 ? "nothing filled" : err.c_str()); return 1; } + if (nib_c.active() && nib_c.n > 0) { // STRATA_EXPERT_NIBBLE: as CUDA0's above + size_t c = 0; + while (c < st.profile.size() && !nib::layer(st.profile[c].first).on) ++c; + const auto& pc = st.profile[c]; + if (!nib_c.check(pc.first, pc.second, srcp->blob_stable(pc.first, pc.second), err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + std::set<int32_t> ls; + for (const auto& pr : nib_c.pairs) ls.insert(pr.first); + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %lld slots of %zu layers transcoded to 4-bit " + "codes (%.2f s; every item round-tripped, every slot's GGUF blocks rebuilt and compared, " + "slot hashes recorded); layer %d expert %d read back\n", st.dev, (long long) nib_c.n, + ls.size(), nib_c.seconds, (int) pc.first, (int) pc.second); + } std::fprintf(stderr, "strata generate: layer split: CUDA%d runs layers %lld-%lld, expert cache %lld slots " "(%.2f GiB), %lld of its %zu profiled pairs; slot 0 verified\n", st.dev, (long long) st.lb, (long long) (st.le - 1), (long long) st.cache.slots(), st.cache.gib(), @@ -6717,6 +7123,40 @@ int main(int argc, char** argv) { } if (multi_gpu) std::fprintf(stderr, "strata generate: layer split: CUDA0 runs layers 0-%lld\n", (long long) (split_at[0] - 1)); + if (nib::any_on()) { + // STRATA_EXPERT_NIBBLE: every expert of every layer must be in VRAM, in the cache of the card that runs the layer. + // A converted layer's miss would be computed from the GGUF blob by the CPU or over PCIe, and a non-converted + // layer's residency would differ from the switch-off run's (its smaller slots leave room for more), so the + // replies' bits would too. Then no slot is written again. + for (int64_t l = 0; l < g.n_layers; ++l) { + const strata::core::ExpertCache* owner = &xcache; + int owner_dev = 0; + if (multi_gpu && !split_at.empty() && l >= split_at[0]) { + owner = nullptr; + for (const auto& stp : stages) + if (l >= stp->lb && l < stp->le) { owner = &stp->cache; owner_dev = stp->dev; } + } + int64_t missing = 0, first = -1; + for (int64_t e = 0; e < g.n_expert; ++e) + if (owner == nullptr || owner->slot_of(l, e) == strata::core::kNotResident) { + if (first < 0) first = e; + ++missing; + } + if (missing > 0) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE refuses the start: layer %lld has %lld of its %lld " + "experts out of CUDA%d's VRAM (expert %lld the first) - every expert must be resident " + "(a profile that ranks every pair and room on the card; STRATA_EXPERT_NIBBLE_SKIP=" + "<layers> keeps some layers' smaller GGUF slots)\n", (long long) l, (long long) missing, + (long long) g.n_expert, owner_dev, (long long) first); + return 1; + } + } + xcache.seal(); + for (auto& stp : stages) stp->cache.seal(); + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: all %lld experts of all %lld layers are VRAM-resident; " + "the expert caches are sealed (nothing writes a slot from here on)\n", + (long long) g.n_expert, (long long) g.n_layers); + } // ---- LAYER 2: exact startability probe on the live free figures. Every session, cache and batch slot is // carved by now, so `cudaMemGetInfo` reads what serve's own_fits (5855-5869) will read. Run serve's own @@ -8043,6 +8483,7 @@ int main(int argc, char** argv) { if (!cold.empty() && cold.back().first < heat(oi)) { vi = cold.back().second; const int32_t vs = host_res[(size_t) vi]; + nib::guard_raw(layer, "the elastic K/V's slot move (kvg_ensure)"); if (xcache.slot_offset(vs + 1) - xcache.slot_offset(vs) < lay.blob_bytes(layer) || cudaMemcpy(xcache.device_slot(vs), xcache.device_slot((int32_t) kvg.lo), (size_t) lay.blob_bytes(layer), cudaMemcpyDeviceToDevice) != cudaSuccess) @@ -8145,6 +8586,7 @@ int main(int argc, char** argv) { if (host_res[i] >= 0 || lay.blob_bytes(l) > room) continue; const uint8_t* b = srcp->blob_stable(l, e); if (b == nullptr) continue; + nib::guard_raw(l, "the elastic K/V's refill (kvg_trim)"); cudaMemcpyAsync(xcache.device_slot((int32_t) s), b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, nullptr); filled.emplace_back(i, (int32_t) s); @@ -8872,6 +9314,37 @@ int main(int argc, char** argv) { #endif bool any_loan = borrow != nullptr; for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; + if (nib::any_on()) { + // STRATA_EXPERT_NIBBLE: the prompt path keeps its own buffers (a loan is refilled with GGUF blobs) and reads in + // the chunk it reads without the switch (the chunking is part of the replies' bits: auto's ceiling, or + // --prefill N, and no host-aware plan of smaller chunks). Otherwise refused, never a quietly different reply. + std::string why; + const int64_t expect = o.prefill_auto ? auto_ceiling : nib_chunk_asked; + if (any_loan) why = "the prompt path borrows expert-cache slots (a loan is refilled with GGUF blobs)"; + else if (o.prefill_chunk != expect) + why = "the prompt chunk is " + std::to_string(o.prefill_chunk) + " tokens, not the " + std::to_string(expect) + + " it is without the switch when nothing limits it (that would change the replies' bits; an explicit " + "--prefill N that fits keeps N)"; + else if (pf_plan_chunk > 0) + why = "the host-aware plan reads long prompts in chunks of " + std::to_string(pf_plan_chunk) + " tokens"; + std::string room; + for (size_t i = 0; why.empty() && i <= stages.size(); ++i) { + const int dev = i == 0 ? -1 : stages[i - 1]->dev; + const strata::core::OnDevice on(dev); + size_t fb = 0, tb = 0; + if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } + char b[64]; + std::snprintf(b, sizeof b, "CUDA%d %.2f GiB", dev < 0 ? 0 : dev, (double) fb / 1073741824.0); + room += (room.empty() ? "" : ", ") + std::string(b); + } + if (!why.empty()) { + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE refuses the start: %s (STRATA_EXPERT_NIBBLE_SKIP=<layers> " + "keeps some layers' GGUF blocks and their smaller slots)\n", why.c_str()); + return 1; + } + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE: prompt chunk %lld, no loan; free after the prompt " + "buffers: %s\n", (long long) o.prefill_chunk, room.c_str()); + } if (any_loan) { if (borrow != nullptr) std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", @@ -10544,6 +11017,7 @@ int main(int argc, char** argv) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si]; const uint8_t* b = srcp->blob_stable(s.layer, s.in); + nib::guard_raw(s.layer, "the adaptive tier's copy in"); const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; const strata::core::OnDevice on(gs ? gs->dev : -1); @@ -10778,6 +11252,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(h.dev); for (const ASwap& w : aswaps) { if (w.home != hi || !w.exchange) continue; + nib::guard_raw(w.layer, "the async adaptive tier's copy back (a_back)"); if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(w.j, w.layer), h.cache->device_slot(w.slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), cudaMemcpyDeviceToHost, h.stream); e != cudaSuccess) { @@ -10815,6 +11290,7 @@ int main(int argc, char** argv) { auto a_in_one = [&](const ASwap& w, const uint8_t* b) { // step 2: one copy in (H2D), on its home's stream AHome& h = ahomes[(size_t) w.home]; const strata::core::OnDevice on(h.dev); + nib::guard_raw(w.layer, "the async adaptive tier's copy in (a_in_one)"); if (const cudaError_t e = cudaMemcpyAsync(h.cache->device_slot(w.slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), cudaMemcpyHostToDevice, h.stream); e != cudaSuccess) { @@ -15459,6 +15935,27 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: cancelled request keeps its conversation: %lld tokens live\n", (long long) pp_reached); } + if (nib::config().recheck && nib::any_on() && !cancelled) { + // STRATA_EXPERT_NIBBLE_RECHECK=1 (debug): every converted slot's hash again on its own device, against the + // hash recorded at load - a path that wrote a slot after the seal is found here + std::string rerr; + int64_t bad_layer = -1; + const auto rt0 = Clock::now(); + bool ok = nib_x.recheck(rerr, bad_layer); + int64_t checked = nib_x.n; + for (size_t i = 0; ok && i < nib_st.size(); ++i) { + ok = nib_st[i].recheck(rerr, bad_layer); + checked += nib_st[i].n; + } + if (!ok) { + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE_RECHECK: %s\n", rerr.c_str()); + if (bad_layer >= 0) nib::fatal(bad_layer, "STRATA_EXPERT_NIBBLE_RECHECK", "a slot changed after the load"); + std::fflush(stderr); + std::abort(); + } + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE_RECHECK: %lld 4-bit slots hash as at load (%.0f ms)\n", + (long long) checked, std::chrono::duration<double, std::milli>(Clock::now() - rt0).count()); + } static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates) // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and @@ -15967,6 +16464,11 @@ int main(int argc, char** argv) { } else if (chunk != o.prefill_chunk) { k = 0; // a fixed chunk that does not fit: its own buffers, as before } + if (k > 0 && nib::any_on()) { // STRATA_EXPERT_NIBBLE: the lent slots would be refilled with GGUF blobs + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE refuses the start: the prompt path would borrow %lld " + "cache slots (--no-prefill-borrow keeps its own buffers)\n", (long long) k); + return 1; + } const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; #if defined(STRATA_GPU_METAL) k = 0; // Metal: no loan of expert-cache slots (the prompt buffers are the Metal window's own); the refill after it copied into given-back allocations @@ -16555,6 +17057,7 @@ int main(int argc, char** argv) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = host_res[out]; const uint8_t* b = srcp->blob_stable(s.layer, s.in); + nib::guard_raw(s.layer, "the adaptive refill's copy in"); const size_t blob_n = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer); // asynchronous: the copies run while the MTP drafts; the next window waits for them if (slot < 0 || b == nullptr) { From 52a558abbed8415104ece1b66fdd8ea16c7d853e Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:57:57 +0100 Subject: [PATCH 151/177] App: French as the ninth interface language (#3970) fr.json, fix-fr.json, tune-fr.json and tools-fr.json (3,654 strings, vous, plain short words), the Francais entry in the language picker, every locale test and gap check now covers fr, a french-catalog test (spacing before ? ! : ;, apostrophes, short labels, no leftover English), scripts/fr_sync.py to list and merge strings added later, and scripts/language-shots.mjs for screenshots of the app in one language. --- apps/host/README.md | 12 + apps/host/scripts/fr_sync.py | 156 + apps/host/scripts/language-shots.mjs | 64 + apps/host/server/agent/context-fit.mjs | 2 +- apps/host/server/agent/turn-guard.mjs | 2 +- apps/host/src/lib/i18n.ts | 10 +- apps/host/src/locales/fix-fr.json | 81 + apps/host/src/locales/fr.json | 3530 +++++++++++++++++ apps/host/src/locales/tools-fr.json | 6 + apps/host/src/locales/tune-fr.json | 45 + apps/host/tests/agent-events.test.mjs | 4 +- apps/host/tests/agent-status.test.mjs | 4 +- apps/host/tests/agent-turn-guard.test.mjs | 4 +- apps/host/tests/card-labels.test.mjs | 2 +- apps/host/tests/context-ui.test.mjs | 6 +- apps/host/tests/cors-help.test.mjs | 4 +- apps/host/tests/deepseek-context.test.mjs | 4 +- apps/host/tests/drafting.test.mjs | 6 +- apps/host/tests/french-catalog.test.mjs | 60 + .../host/tests/languages-and-catalog.test.mjs | 2 +- apps/host/tests/locale-gaps.test.mjs | 4 +- apps/host/tests/mcp-rows.test.mjs | 2 +- apps/host/tests/models-folder.test.mjs | 4 +- apps/host/tests/plain-errors.test.mjs | 4 +- apps/host/tests/qa1-downloads.test.mjs | 2 +- apps/host/tests/reliability.test.mjs | 2 +- apps/host/tests/run-config-check.test.mjs | 4 +- apps/host/tests/speed-switches.test.mjs | 4 +- apps/host/tests/tools-locales.test.mjs | 2 +- apps/host/tests/tune-locales.test.mjs | 2 +- apps/host/tests/web-ask.test.mjs | 4 +- tests/terminal/test_drafting.py | 2 +- 32 files changed, 3999 insertions(+), 41 deletions(-) create mode 100644 apps/host/scripts/fr_sync.py create mode 100644 apps/host/scripts/language-shots.mjs create mode 100644 apps/host/src/locales/fix-fr.json create mode 100644 apps/host/src/locales/fr.json create mode 100644 apps/host/src/locales/tools-fr.json create mode 100644 apps/host/src/locales/tune-fr.json create mode 100644 apps/host/tests/french-catalog.test.mjs diff --git a/apps/host/README.md b/apps/host/README.md index 25c8f531..182a525b 100644 --- a/apps/host/README.md +++ b/apps/host/README.md @@ -10,3 +10,15 @@ npm run preview:ui The built UI is included. To rebuild after source edits, run `npm run build`. `preview:ui` uses isolated simulated data; `npm run dev` connects the normal host. The previous project README is retained in [docs/README-historical.md](docs/README-historical.md). It contains older implementation status and is historical reference. + +## Languages + +The app speaks English, Chinese, Japanese, German, French, Spanish, Russian, Portuguese and Korean. The English text is the key: `src/locales/en.json` +(with `fix-en.json`, `tune-en.json` and `tools-en.json`) holds every string, and each language has the same four files (`fr.json`, `fix-fr.json`, ...). + +- **A new string.** Write it with `tr("...")`, then add it to the English catalog (`node scripts/append-localization.mjs`, or the next `fx` number in + `scripts/make-fix-locales.py`). The language tests fail until every language has it. +- **French.** `python scripts/fr_sync.py missing todo.tsv` lists the English strings that have no French yet, one per line (`id`, a tab, the text). + Translate the second column ("vous", short plain words, one next step; a lone `=` keeps the English), then `python scripts/fr_sync.py apply todo.tsv` merges it + (it also sets the French spacing before `: ; ? !` and the typographic apostrophe) and `python scripts/fr_sync.py check` confirms nothing is missing. +- **Screenshots in a language.** `npm run build`, then `node scripts/language-shots.mjs fr <folder> models settings setup` (hermetic preview host, scratch profile, headless Chrome). diff --git a/apps/host/scripts/fr_sync.py b/apps/host/scripts/fr_sync.py new file mode 100644 index 00000000..90bf8970 --- /dev/null +++ b/apps/host/scripts/fr_sync.py @@ -0,0 +1,156 @@ +"""French (fr) catalog tooling for the desktop app (#3970). + +The French texts live in src/locales/fr.json, fix-fr.json, tune-fr.json and tools-fr.json, next to the other languages. +They are edited by hand (they are the translations, not generated), so a string added to an English catalog later has no +French yet. This script lists and merges those. From apps/host: + + python scripts/fr_sync.py missing [out.tsv] write every English string that has no French yet + python scripts/fr_sync.py apply done.tsv merge translations, rewrite the four fr files in English key order + python scripts/fr_sync.py check exit 1 if a French string is missing, empty or breaks a placeholder / tag + +The TSV has one string per line: <id><TAB><text>. In the text, a newline is written \\n and a backslash \\\\. +In the "done" file a lone = means "keep the English text as it is" (class names, product names, file names). +The id prefix picks the file: s0001 -> fr.json, fx01 -> fix-fr.json, tune01 -> tune-fr.json, tl01 -> tools-fr.json. +Use "vous", plain short words, a next step, and a no-break space (U+00A0) before : ; ? ! and inside guillemets. +""" +import json +import re +import sys +from pathlib import Path + +LOCALES = Path(__file__).resolve().parent.parent / "src" / "locales" +PAIRS = [("en.json", "fr.json"), ("fix-en.json", "fix-fr.json"), ("tune-en.json", "tune-fr.json"), ("tools-en.json", "tools-fr.json")] +SLOT = re.compile(r"\{\d+\}") +TAG = re.compile(r"</?[A-Za-z][^>]*>") + + +def load(name): + path = LOCALES / name + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + + +def file_of(identifier): + for en_name, fr_name in PAIRS: + if identifier in load(en_name): + return fr_name + raise SystemExit(f"unknown id {identifier}: it is in no English catalog") + + +def escape(text): + return text.replace("\\", "\\\\").replace("\n", "\\n") + + +def unescape(text): + out, i = [], 0 + while i < len(text): + if text[i] == "\\" and i + 1 < len(text): + out.append({"n": "\n", "\\": "\\"}.get(text[i + 1], text[i + 1])) + i += 2 + else: + out.append(text[i]) + i += 1 + return "".join(out) + + +NBSP = " " + + +def typography(text): + """French spacing and apostrophes, applied to every translated (not kept) string. + l'image -> l'image with a typographic apostrophe (also before a {0} slot); a no-break space before : ; ? ! % and inside the guillemets.""" + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + text = re.sub("« ?", "«" + NBSP, text) + text = re.sub(" ?»", NBSP + "»", text) + return text + + +def problems(identifier, source, text): + found = [] + if not text.strip(): + found.append("empty") + expected = [slot for slot in SLOT.findall(source) if not (identifier == "s2463" and slot == "{1}")] # the tests allow this one to drop {1} (the plural suffix) + if sorted(expected) != sorted(SLOT.findall(text)): + found.append("placeholders differ") + if sorted(TAG.findall(source)) != sorted(TAG.findall(text)): + found.append("markup differs") + return found + + +def missing(): + todo = {} + for en_name, fr_name in PAIRS: + en, fr = load(en_name), load(fr_name) + for identifier, text in en.items(): + if identifier not in fr: + todo[identifier] = text + return todo + + +def main(argv): + command = argv[1] if len(argv) > 1 else "" + if command == "missing": + todo = missing() + lines = [f"{identifier}\t{escape(text)}" for identifier, text in todo.items()] + if len(argv) > 2: + Path(argv[2]).write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8") + print(f"{len(lines)} strings without French written to {argv[2]}") + else: + print("\n".join(lines)) + print(f"{len(lines)} strings without French", file=sys.stderr) + return 0 + if command == "apply" and len(argv) > 2: + incoming = {} + for number, line in enumerate(Path(argv[2]).read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + if "\t" not in line: + raise SystemExit(f"{argv[2]}:{number}: no tab") + identifier, text = line.split("\t", 1) + incoming[identifier.strip()] = text + bad = 0 + for en_name, fr_name in PAIRS: + en, fr = load(en_name), load(fr_name) + changed = False + for identifier, source in en.items(): + if identifier in incoming: + text = source if incoming[identifier] == "=" else typography(unescape(incoming[identifier])) + for why in problems(identifier, source, text): + print(f"{identifier}: {why}: {source!r} -> {text!r}") + bad += 1 + fr[identifier] = text + changed = True + if changed: + ordered = {identifier: fr[identifier] for identifier in en if identifier in fr} + (LOCALES / fr_name).write_text(json.dumps(ordered, ensure_ascii=False, indent=1 if en_name != "en.json" else 2) + "\n", encoding="utf-8") + unknown = [identifier for identifier in incoming if not any(identifier in load(en_name) for en_name, _ in PAIRS)] + for identifier in unknown: + print(f"{identifier}: not in any English catalog") + bad += 1 + print(f"applied {len(incoming)} strings, {bad} problems") + return 1 if bad else 0 + if command == "check": + bad = 0 + for en_name, fr_name in PAIRS: + en, fr = load(en_name), load(fr_name) + for identifier, source in en.items(): + if identifier not in fr: + print(f"{fr_name}: {identifier} has no French yet: {source!r}") + bad += 1 + continue + for why in problems(identifier, source, fr[identifier]): + print(f"{fr_name}: {identifier}: {why}") + bad += 1 + for identifier in fr: + if identifier not in en: + print(f"{fr_name}: {identifier} is not in {en_name}") + bad += 1 + print("French catalogs complete" if not bad else f"{bad} problems") + return 1 if bad else 0 + print(__doc__) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/apps/host/scripts/language-shots.mjs b/apps/host/scripts/language-shots.mjs new file mode 100644 index 00000000..4a371007 --- /dev/null +++ b/apps/host/scripts/language-shots.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +/** + * Screenshots of the app screens in one interface language, from a hermetic preview host (simulated hardware and models, + * scratch profile, no engine, no weights). The browser is a throw-away headless Chrome profile. + * + * node scripts/language-shots.mjs <lang> <outDir> [route ...] (needs `npm run build` first) + * example: node scripts/language-shots.mjs fr C:/Users/me/Desktop/fr-screens models settings setup + * + * Env: CHROME (path to Chrome/Edge), WIDTH (default 1280), HEIGHT (default 800). + */ +import { spawn } from 'node:child_process'; +import { chromium } from 'playwright-core'; +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const [, , language = 'fr', outDir = 'language-shots', ...routes] = process.argv; +const screens = routes.length ? routes : ['models', 'settings', 'setup']; +if (!existsSync(join(root, 'dist/index.html'))) { console.error('Run npm run build first.'); process.exit(1); } +const chrome = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync); +if (!chrome) { console.error('No Chrome or Edge found; set CHROME.'); process.exit(1); } + +const home = mkdtempSync(join(tmpdir(), 'strata-language-shots-')); +const hostPort = 8830 + Math.floor(Math.random() * 40), webPort = hostPort + 100; +const scratch = { STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_WORKSPACE: home, STRATA_REAL_ENGINE: '0', STRATA_NATIVE_REPO: join(home, 'no-native-installation'), + STRATA_SETTINGS_FILE: join(home, 'app-settings.json'), STRATA_COMPONENTS_DIR: join(home, 'components'), LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'), + XDG_DATA_HOME: join(home, 'xdg-data'), XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config'), STRATA_PORT: String(hostPort) }; +const children = []; +const run = (args, extra = {}) => { const child = spawn(process.execPath, args, { cwd: root, env: { ...process.env, ...scratch, ...extra }, stdio: 'ignore' }); children.push(child); return child; }; +const stop = () => { for (const child of children) { try { child.kill(); } catch {} } try { rmSync(home, { recursive: true, force: true }); } catch {} }; +process.on('exit', stop); + +run(['server/index.mjs']); +for (let attempt = 0; ; attempt++) { + try { if ((await fetch(`http://127.0.0.1:${hostPort}/api/health`)).ok) break; } catch {} + if (attempt > 200) { console.error('The preview host did not start.'); process.exit(1); } + await new Promise(done => setTimeout(done, 150)); +} +run(['tests/fixtures/onboarding-ui-host.mjs'], { STRATA_UI_PREVIEW: '1', STRATA_ONBOARDING_UPSTREAM: `http://127.0.0.1:${hostPort}`, STRATA_ONBOARDING_PORT: String(webPort), STRATA_ONBOARDING_START: 'ready', STRATA_ONBOARDING_SCENARIO: 'telemetry', STRATA_ONBOARDING_PREVIEW: '1' }); +for (let attempt = 0; ; attempt++) { + try { if ((await fetch(`http://127.0.0.1:${webPort}/`)).ok) break; } catch {} + if (attempt > 200) { console.error('The preview page did not start.'); process.exit(1); } + await new Promise(done => setTimeout(done, 150)); +} + +mkdirSync(resolve(outDir), { recursive: true }); +const browser = await chromium.launch({ executablePath: chrome, headless: true, args: ['--no-sandbox', '--disable-gpu', '--force-device-scale-factor=1'] }); +const page = await browser.newPage({ viewport: { width: Number(process.env.WIDTH ?? 1280), height: Number(process.env.HEIGHT ?? 800) }, deviceScaleFactor: 1 }); +await page.addInitScript(code => { try { localStorage.setItem('strata.prefs.v2', JSON.stringify({ language: code, onboardingSeen: true })); } catch {} }, language); +const problems = []; +page.on('pageerror', error => problems.push(`pageerror: ${error.message}`)); +for (const screen of screens) { + await page.goto(`http://127.0.0.1:${webPort}/#/${screen}`, { waitUntil: 'load' }); + await page.reload({ waitUntil: 'load' }); + await page.waitForTimeout(2500); + const file = join(resolve(outDir), `${language}-${screen}.png`); + await page.screenshot({ path: file }); + console.log(`${screen}: ${file} (lang=${await page.evaluate(() => document.documentElement.lang)})`); +} +await browser.close(); +if (problems.length) console.log(problems.join('\n')); +stop(); +process.exit(0); diff --git a/apps/host/server/agent/context-fit.mjs b/apps/host/server/agent/context-fit.mjs index 0abcb08a..7bc12e79 100644 --- a/apps/host/server/agent/context-fit.mjs +++ b/apps/host/server/agent/context-fit.mjs @@ -58,7 +58,7 @@ export async function countTokens({ baseUrl, key = '', model = '', text, fetchIm } catch { return null; } } -/** The plain sentences (also in the interface catalog in all eight languages). `{0}` slots are filled by the page. */ +/** The plain sentences (also in the interface catalog in all nine languages). `{0}` slots are filled by the page. */ export const FIT_TEXT = Object.freeze({ tooLarge: 'This message is about {0} tokens long, and this model can read about {1} at a time. It is too large to send as it is.', tooLargeNext: 'Attach it as a file for the assistant to read in parts, or send a shortened preview.', diff --git a/apps/host/server/agent/turn-guard.mjs b/apps/host/server/agent/turn-guard.mjs index f28ce3f4..14566d5b 100644 --- a/apps/host/server/agent/turn-guard.mjs +++ b/apps/host/server/agent/turn-guard.mjs @@ -10,7 +10,7 @@ * rewrites a plan turn wrote its numbered plan from "1." again this many times * context the context is nearly full: the Harness compaction did not keep up * - * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all eight languages (the page + * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all nine languages (the page * translates a `delta` frame that carries `key`). Each says what happened and gives one next step. */ diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 952e3ca2..0c398be8 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -7,6 +7,7 @@ import tune_es from '../locales/tune-es.json'; import tune_ru from '../locales/tune-ru.json'; import tune_pt from '../locales/tune-pt.json'; import tune_ko from '../locales/tune-ko.json'; +import tune_fr from '../locales/tune-fr.json'; import tools_en from '../locales/tools-en.json'; import tools_zh from '../locales/tools-zh.json'; import tools_ja from '../locales/tools-ja.json'; @@ -15,6 +16,7 @@ import tools_es from '../locales/tools-es.json'; import tools_ru from '../locales/tools-ru.json'; import tools_pt from '../locales/tools-pt.json'; import tools_ko from '../locales/tools-ko.json'; +import tools_fr from '../locales/tools-fr.json'; import fix_en from '../locales/fix-en.json'; import fix_zh from '../locales/fix-zh.json'; import fix_ja from '../locales/fix-ja.json'; @@ -23,6 +25,7 @@ import fix_es from '../locales/fix-es.json'; import fix_ru from '../locales/fix-ru.json'; import fix_pt from '../locales/fix-pt.json'; import fix_ko from '../locales/fix-ko.json'; +import fix_fr from '../locales/fix-fr.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -30,15 +33,16 @@ import base_es from '../locales/es.json'; import base_ru from '../locales/ru.json'; import base_pt from '../locales/pt.json'; import base_ko from '../locales/ko.json'; +import base_fr from '../locales/fr.json'; -export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; +export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'fr',label:'Français'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */ const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en}; -const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja},{...base_de,...tune_de,...tools_de,...fix_de},{...base_es,...tune_es,...tools_es,...fix_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko}] as Record<string,string>[]; -const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,es,ru,pt,ko}; +const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja},{...base_de,...tune_de,...tools_de,...fix_de},{...base_es,...tune_es,...tools_es,...fix_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr}] as Record<string,string>[]; +const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,fr,es,ru,pt,ko}; const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); const ids=new Map(Object.entries(english).map(([id,value])=>[decode(value),id])); diff --git a/apps/host/src/locales/fix-fr.json b/apps/host/src/locales/fix-fr.json new file mode 100644 index 00000000..0b0ab157 --- /dev/null +++ b/apps/host/src/locales/fix-fr.json @@ -0,0 +1,81 @@ +{ + "fx01": "ne s’exécutera plus et sera retirée.", + "fx02": "Téléchargé, mais pas chargé. Ouvrez Modèles pour le charger.", + "fx03": "{0} lignes ajoutées, {1} supprimées", + "fx04": "{0} fichiers modifiés", + "fx05": "Déposez des fichiers pour les ajouter", + "fx06": "Images et fichiers texte", + "fx07": "Garder l’objectif", + "fx08": "Supprimer l’objectif", + "fx09": "L’assistant cesse de travailler à l’atteindre. Votre conversation et vos fichiers restent comme ils sont.", + "fx10": "Ce modèle peut lire les images, mais le moteur installé ici n’inclut pas encore le lecteur d’images : Lire les images est donc désactivé. Mettez à jour le moteur dans Paramètres → À propos pour l’activer.", + "fx11": "Affichage des valeurs de votre optimisation « {0} ».", + "fx12": "Votre optimisation « {0} » règle", + "fx13": "était {0}", + "fx14": "· {0} de RAM", + "fx15": "Le message n’a pas été annulé", + "fx16": "Réglages supplémentaires pour le programme", + "fx17": "Rédiger avec l’IA", + "fx18": "Temps de réflexion", + "fx19": "Temps de rédaction", + "fx20": "tokens/s", + "fx21": "% du contexte", + "fx22": "Cette page demande des fichiers à internet, que l’aperçu ne charge pas : elle peut donc paraître incomplète. Voir le code montre exactement ce qui a été écrit.", + "fx23": "Garder A", + "fx24": "Garder B", + "fx25": "A pris", + "fx26": "Variante", + "fx27": "Modifié", + "fx28": "Rien", + "fx29": "Les deux versions sont prêtes. Comparez A et B, puis gardez-en une.", + "fx30": "L’assistant répond encore", + "fx31": "Envoyez votre message quand il a terminé.", + "fx32": "Le message n’a pas été mis en file d’attente", + "fx33": "Aller au dernier message", + "fx34": "Retirer la tâche", + "fx35": "Ouvrir une nouvelle conversation ; garder celle-ci", + "fx36": "Faire d’abord rédiger un plan à l’assistant ; rien ne s’exécute tant que vous ne l’avez pas approuvé", + "fx37": "Chercher sur le web, lire les pages et répondre avec des sources", + "fx38": "Copié", + "fx39": "Réponse", + "fx40": "Message", + "fx41": "PDF ajouté", + "fx42": "Sélectionnez le texte et copiez-le avec Ctrl+C.", + "fx43": "{0} est dans cette conversation. Posez une question à son sujet dans votre prochain message.", + "fx44": "Le moteur est prêt.", + "fx45": "Étape suivante : choisir un modèle.", + "fx46": "Téléchargement du moteur", + "fx47": "Vous pouvez fermer Strata ; le téléchargement reprendra là où il s’est arrêté.", + "fx48": "Bienvenue dans Strata", + "fx49": "Examen de votre carte graphique…", + "fx50": "Strata a trouvé votre carte graphique :", + "fx51": "{0} cartes trouvées. Strata utilise la première pour le moteur ; vous pourrez changer cela plus tard dans les Paramètres.", + "fx52": "Strata n’a pas reconnu de carte graphique prise en charge.", + "fx53": "Pour y exécuter des modèles, Strata a besoin d’un téléchargement :", + "fx54": "Le moteur pour cette carte", + "fx55": "Le moteur a besoin d’environ {0} Go d’espace libre sur ce disque et il n’y en a que {1} Go. Libérez de l’espace, puis continuez.", + "fx56": "Il vient du serveur de mise à jour de Strata et il est vérifié avant utilisation. Vos modèles et vos conversations ne sont jamais touchés.", + "fx57": "Strata n’a pas pu joindre github.com. Vérifiez votre connexion et réessayez, ou téléchargez le fichier du moteur sur un autre PC et choisissez-le ici.", + "fx58": "Le moteur installé ici est prévu pour une autre marque de carte graphique.", + "fx59": "Strata ne peut pas choisir de moteur pour ce PC dans sa liste de mises à jour.", + "fx60": "Continuer sans moteur", + "fx61": "Le téléchargement s’est arrêté. Continuer le reprend là où il s’est arrêté.", + "fx62": "C’est un très gros modèle. Le téléchargement fait {0} Go et il faut à peu près autant d’espace disque libre. Il tourne sur une carte graphique de 12 Go avec 46 à 64 Go de RAM, lentement : environ 5 à 7 mots par seconde. Ce qui ne tient pas en mémoire est lu depuis votre SSD, un disque NVMe compte donc beaucoup.", + "fx63": "Vous pouvez arrêter le téléchargement et le continuer plus tard ; il reprend là où il s’est arrêté. Strata vous avertit ici mais ne vous bloque jamais.", + "fx64": "Plus rapide", + "fx65": "Qualité maximale", + "fx66": "Par défaut (Plus rapide sur ce PC)", + "fx67": "Par défaut (Qualité maximale sur ce PC)", + "fx68": "Plus rapide (par défaut sur ce PC)", + "fx69": "Qualité maximale (par défaut sur ce PC)", + "fx70": "Longs prompts plus rapides", + "fx71": "Réponses plus rapides sur Radeon RX 9000 / AI PRO R9700", + "fx72": "Accélérations DeepSeek", + "fx73": "Lit les très longs prompts plus vite en approximant une partie du travail. Désactivé par défaut : les réponses sur de longs documents peuvent manquer ou mélanger des détails.", + "fx74": "Répartit le travail entre la carte graphique et le processeur d’une façon qui accélère les réponses sur ces cartes. Désactivez pour revenir au réglage précédent, plus lent.", + "fx75": "Lit les longs prompts plus vite et charge plus vite les parties du modèle dont il a besoin. Désactivez si DeepSeek cesse de fonctionner ou si ses réponses semblent fausses ; il fonctionne alors comme dans la version 0.2.6.", + "fx76": "Activé (recommandé)", + "fx77": "C’est un très gros modèle. Le téléchargement fait {0} Go et il faut à peu près autant d’espace disque libre. Il tourne sur les cartes NVIDIA RTX 30, 40 et 50, sur une Radeon AI PRO R9700 (Linux) ou sur un PC Ryzen AI Max / Strix Halo (Windows) ; sa vitesse dépend de la mémoire et de la carte (la ligne ci-dessous indique à quoi s’attendre sur cet ordinateur). Ce qui ne tient pas en mémoire est lu depuis votre SSD, un disque NVMe compte donc beaucoup.", + "fx78": "Pas encore testé. Un contexte aussi long prend de la mémoire graphique au modèle et lit lentement les longs prompts.", + "fx79": "Désactivé (recommandé)" +} diff --git a/apps/host/src/locales/fr.json b/apps/host/src/locales/fr.json new file mode 100644 index 00000000..1f9094c4 --- /dev/null +++ b/apps/host/src/locales/fr.json @@ -0,0 +1,3530 @@ +{ + "s0001": "% PCIe", + "s7331": "Les résultats viennent de DuckDuckGo, ou de Bing quand DuckDuckGo est saturé. Vous n’avez besoin ni de compte ni de clé.", + "s7321": "La recherche web est limitée en ce moment, j’ai donc arrêté de chercher et poursuivi avec ce que j’ai. Réessayez dans une minute, ou ajoutez une clé de recherche dans Paramètres → Outils → Recherche web.", + "s7322": "J’ai beaucoup cherché et je me suis arrêté pour que cette conversation ne se remplisse pas. Voici ce que j’ai jusqu’ici. Dites-moi ce qu’il faut explorer ensuite.", + "s7323": "J’ai réécrit le plan plusieurs fois, je m’arrête donc ici avec la dernière version. Dites-moi quoi changer, ou approuvez-la.", + "s7324": "Je n’ai plus de place dans cette conversation, je me suis donc arrêté. Strata résume les anciens messages pour libérer de la place. Dites « continue » pour poursuivre, ou ouvrez une nouvelle conversation.", + "s7325": "Je me suis arrêté sans écrire de réponse. Renvoyez votre message, ou dites « continue ».", + "s7301": "Tapez /loop, la fréquence, puis ce qu’il faut faire. Par exemple : /loop 10m vérifiez si la compilation réussit. Ajoutez « stop after 3 answers » pour l’arrêter tout seul. Tapez /loop stop pour l’arrêter.", + "s7302": "Dites ce qu’il faut faire à chaque fois, pas seulement quand s’arrêter.", + "s7303": "La boucle est terminée : elle s’est exécutée {0} fois, comme demandé. Tapez /loop pour en lancer une autre.", + "s7304": "La boucle s’est arrêtée parce que la dernière réponse indique que le travail est terminé. Tapez /loop pour en lancer une autre.", + "s7305": "La boucle s’est arrêtée parce que le temps que vous aviez fixé est écoulé. Tapez /loop pour en lancer une autre.", + "s7306": "La boucle s’est arrêtée parce que {0} exécutions de suite ont échoué. Vérifiez le modèle, puis tapez /loop pour la relancer.", + "s7307": "Elle s’arrête toute seule après la première réponse.", + "s7308": "Elle s’arrête toute seule après {0} réponses.", + "s7309": "Elle s’arrête toute seule après {0} minutes.", + "s7310": "Elle s’arrête toute seule quand une réponse indique que le travail est terminé.", + "s7311": "Les applications Anthropic ajoutent /v1/messages elles-mêmes : cette adresse ne se termine donc pas par /v1. Dans Claude Code, indiquez-la dans ANTHROPIC_BASE_URL.", + "s0002": "(facultatif)", + "s0003": ", le cache de contexte ne tient pas", + "s0004": "-y @modelcontextprotocol/server-filesystem /your/folder", + "s0005": "0 utilise la valeur par défaut du moteur.", + "s0006": "20 % de marge pour le reste", + "s0007": "Classe 32 Go de RAM", + "s0008": "Classe 48 Go de RAM", + "s0009": "Classe 60–64 Go de RAM", + "s0010": "Classe 8 Go de RAM", + "s0011": "8 testeurs sur 10 terminent l’installation.", + "s0012": "Un serveur Strata tourne déjà en dehors de cette interface. Arrêtez-le avant de charger ici, ou connectez son API dans Paramètres → Modèles.", + "s0013": "Un prompt fixe, sans réflexion, avec jusqu’à 200 tokens de sortie. Dure en général 10 à 60 secondes. Les résultats sont mesurés par votre moteur.", + "s0014": "Une correction ciblée, à partir du même point de départ.", + "s0015": "Un nouveau point de situation, chaque matin", + "s0016": "Un objectif décrit le résultat voulu. Strata planifie le travail, suit son avancement et continue jusqu’à l’atteindre.", + "s0017": "Un bon point de départ.", + "s0018": "Une clé permet à vos autres applications de se connecter à Strata.", + "s0019": "Un petit coup de pouce.", + "s0020": "Un peu de réglage. Un meilleur résultat.", + "s0021": "Bien plus de possibilités.", + "s0022": "Une opération sur un modèle est en cours.", + "s0023": "Un nouveau candidat part du point de départ de B.", + "s0024": "Une visite rapide de Strata", + "s0025": "Un petit exercice quotidien pour affûter votre écriture.", + "s0026": "Une adresse stable sur un domaine que vous gérez avec Cloudflare.", + "s0027": "Une configuration de moteur validée est requise.", + "s0028": "A → B · détail manquant ajouté, aucune vérification en recul.", + "s0029": "API", + "s0030": "URL de base de l’API", + "s0031": "Clé API", + "s0032": "Clé API prête", + "s0033": "Clé API requise", + "s0034": "Clé API enregistrée", + "s0035": "API à l’écoute", + "s0036": "Alias des modèles API", + "s0037": "Les modèles API utilisent les réglages de réponse de leur fournisseur.", + "s0038": "Protocole de l’API", + "s0039": "Fournisseur d’API", + "s0040": "API arrêtée", + "s0041": "À propos", + "s0042": "Au-dessus de 1, le texte répété est découragé.", + "s0043": "Accès", + "s0044": "Accès configuré dans le serveur MCP", + "s0045": "Actions pour {0}", + "s0046": "Actif", + "s0047": "Actives / en file d’attente", + "s0048": "Jours actifs", + "s0049": "Ajoutez un objet de réglages pour débutant.", + "s0050": "Ajoutez un dossier contenant SKILL.md.", + "s0051": "Ajoutez un prompt après /time-skip", + "s0052": "Ajoutez une route d’application publiée pour ce nom d’hôte avec cette URL de service :", + "s0053": "Ajouter une tâche", + "s0054": "Ajouter un dossier de travail", + "s0055": "Ajoutez un objet de réglages experts.", + "s0056": "Ajouter des fichiers ou des photos", + "s0057": "Ajouter un dossier", + "s0058": "Ajoutez des programmes locaux ou des serveurs MCP HTTP. Les outils connectés peuvent lire ou modifier les ressources auxquelles vous leur donnez accès. Activez les outils dans la conversation quand vous voulez que le modèle les utilise.", + "s0059": "Ajouter un modèle", + "s0060": "Ajouter un fournisseur de modèles", + "s0061": "Ajouter des modèles à votre sélecteur de conversation", + "s0062": "Ajouter ou ouvrir", + "s0063": "Ajouter une compétence", + "s0064": "Ajouter aux paramètres", + "s0065": "Ajouter un serveur d’outils", + "s0066": "Ajoutez deux fois, remettez à 0, puis vérifiez à 320 px.", + "s0067": "Vérification de réussite reproductible ajoutée", + "s0068": "Vérification de réussite ajoutée", + "s0069": "Compétences ajoutées", + "s0070": "Ajout…", + "s0071": "Réglages supplémentaires", + "s0072": "Adresse", + "s0073": "Ajuster", + "s0074": "Avancé", + "s0075": "JSON avancé", + "s0076": "Agentique", + "s0077": "Les agents travaillent en parallèle", + "s0078": "Tout", + "s0079": "Tous les GPU ({0})", + "s0080": "Toutes les conversations", + "s0081": "Tous les groupes", + "s0082": "Toutes les couches", + "s0083": "Tous les modèles", + "s0084": "Tous les modèles ({0})", + "s0085": "Tous les processeurs ({0})", + "s0086": "Tous les espaces de travail", + "s0087": "Les {0} modèles chargés seront tous déchargés.", + "s0088": "Autoriser des origines de navigateur", + "s0089": "Déjà attribué à {0}. Effacez ou modifiez d’abord cette association.", + "s0090": "Vous avez déjà téléchargé le modèle ?", + "s0091": "Vous savez déjà vous en servir ?", + "s0092": "Un argument du moteur désigne un fichier GGUF introuvable. Restaurez les arguments enregistrés ou réparez les fichiers.", + "s0093": "GIF animé", + "s0094": "Réponse", + "s0095": "Réponse de", + "s0096": "Anthropic", + "s0097": "Anthropic Messages", + "s0098": "Réflexion Anthropic", + "s0099": "Hôte de l’application :", + "s0100": "Apparence", + "s0101": "Appliqué sous la forme --vram-reserve-mib au chargement.", + "s0102": "Appliquer", + "s0103": "Appliquer la police", + "s0104": "Appliquer maintenant…", + "s0105": "Appliquer les réglages maintenant ?", + "s0106": "Approuver", + "s0107": "Approuvé", + "s0108": "Les applications de cet ordinateur pourront envoyer des requêtes sans clé. Les clients existants peuvent garder leur champ de clé actuel.", + "s0109": "Architecture", + "s0110": "Archivée", + "s0111": "Arguments · un par ligne", + "s0112": "Redemander", + "s0113": "Demander avant de modifier", + "s0114": "Écrivez « spawn subagents » dans la conversation et décrivez les tâches. Des agents distincts peuvent chercher, rédiger et relire en parallèle, puis vous rapporter leur travail.", + "s0115": "Ressource introuvable", + "s0116": "GPU attribués", + "s0117": "Joignez une image PNG, JPEG ou WebP. Les autres images peuvent s’ouvrir dans l’aperçu.", + "s0118": "Joignez jusqu’à trois images par message.", + "s0119": "Outil connecté autorisé", + "s0120": "Optimiser pour mon PC", + "s0121": "Optimiser pour cet ordinateur", + "s0122": "Automatique", + "s0123": "GPU automatique", + "s0124": "La configuration automatique du connecteur n’est pas disponible pour ce système d’exploitation et ce processeur.", + "s0125": "La configuration automatique doit être retentée.", + "s0126": "Automatique utilise le placement GPU de l’installation. Choisissez un GPU, ou répartissez ce modèle sur plusieurs GPU.", + "s0127": "Automatique · GPU 1", + "s0128": "Automatique · tous les GPU", + "s0129": "Automatique · recommandé : 2 048", + "s0130": "Disponible", + "s0131": "Modèles API disponibles", + "s0132": "Disponible dans", + "s0133": "Modèles disponibles", + "s0134": "Délai moyen avant le premier token", + "s0135": "B comble les lacunes et garde les bons éléments de A.", + "s0136": "B est enregistré. Une dernière révision ciblée est en cours dans l’autre flux.", + "s0137": "B sélectionné · les trois vérifications d’exemple réussissent.", + "s0138": "Retour", + "s0139": "Retour à la conversation", + "s0140": "Revenir au réglage recommandé", + "s0141": "Équilibré", + "s0142": "URL de base", + "s0143": "Taille du lot", + "s0144": "En dessous du minimum de 16 Go", + "s0145": "Test de performance", + "s0146": "Tester le modèle", + "s0147": "Le corps doit être du JSON", + "s0148": "Style botanique", + "s0149": "Style botanique conservé", + "s0150": "Créer une branche à partir d’ici", + "s0151": "Rassembler les résultats", + "s0152": "Le stockage du navigateur est plein. Libérez de la place avant d’enregistrer les réglages.", + "s0153": "Création de B à partir du brouillon enregistré.", + "s0154": "Compétences intégrées", + "s0155": "Ignorer les autorisations", + "s0156": "CPU", + "s0157": "Le CPU et le GPU partagent un même pool de mémoire.", + "s0158": "Le CPU et le GPU utilisent le même pool de mémoire. La VRAM partagée n’est comptée qu’une fois dans le total.", + "s0159": "Charge du CPU", + "s0160": "CPU uniquement", + "s0161": "CPU uniquement · aucun GPU attribué", + "s0162": "Threads CPU", + "s0163": "Threads CPU.", + "s0164": "Utilisation du CPU", + "s0165": "CPU {0} ·", + "s0166": "CPU {0} · {1}", + "s0167": "Les détails du cache apparaissent quand le moteur signale une réutilisation du prompt.", + "s0168": "Calibrer le moteur…", + "s0169": "Calibrer cet ordinateur ?", + "s0170": "La calibration est disponible sur le matériel NVIDIA pris en charge par la version installée. Les tests courts fonctionnent avec toute instance native en cours d’exécution.", + "s0171": "Peut-on aller plus loin ?", + "s0172": "Annuler", + "s0173": "Annuler le téléchargement", + "s0174": "Échec de l’annulation", + "s0175": "Annuler l’aperçu", + "s0176": "Annuler la requête", + "s0177": "Annulé", + "s0178": "Annulation…", + "s0179": "Tokens candidats. Zéro supprime cette limite.", + "s0180": "Estimation de capacité : {0} Go de GPU, {1} Go de {2}, {3} Go de débordement sur SSD{4}", + "s0181": "Plan de capacité d’après les métadonnées du modèle. Le placement réel, la mémoire libre et les lectures SSD doivent être vérifiés par le moteur.", + "s0182": "Mesures capturées par Strata Monitor", + "s0183": "Préférence du catalogue parmi les modèles qui tiennent. {0}.", + "s0184": "Modifier", + "s0185": "Changer la clé API", + "s0186": "Changer de dossier", + "s0187": "Changer de fichier", + "s0188": "Changer la clé", + "s0189": "Changer le raccourci de {0}", + "s0190": "Changez l’adresse d’écoute de l’hôte et redémarrez pour mettre à jour l’accès réseau.", + "s0191": "Modifications seulement", + "s0192": "Modifications seulement (", + "s0193": "Les modifications sont enregistrées dans Strata. Le fichier d’origine de la compétence reste intact.", + "s0194": "Modifications en surbrillance", + "s0195": "Chat", + "s0196": "Chat Completions", + "s0197": "Mémoire de conversation nécessaire", + "s0198": "Modèle de conversation", + "s0199": "Modèle de conversation modifié", + "s0200": "Nom de la conversation", + "s0201": "Options de la conversation", + "s0202": "Démo du chat · code, outils et médias", + "s0203": "Statistiques de la conversation", + "s0204": "Conversation {0}", + "s0205": "Vérifier", + "s0206": "Vérifier à nouveau", + "s0207": "Vérifiez l’ordinateur, choisissez une version et chargez-la", + "s0208": "Vérifier chaque page", + "s0209": "Échec de la vérification", + "s0210": "Vérifier le dossier", + "s0211": "Rechercher des mises à jour", + "s0212": "Vérification conservée", + "s0213": "Vérifier le résultat", + "s0214": "Vérification indisponible", + "s0215": "Analysez votre ordinateur pour savoir quels modèles lui conviennent.", + "s0216": "Vérifié à", + "s0217": "Vérification d’une révision ultérieure", + "s0218": "Vérification des modifications…", + "s0219": "Vérification de l’exhaustivité et de ce qui fonctionnait déjà.", + "s0220": "Vérification du brouillon…", + "s0221": "Vérification des fichiers…", + "s0222": "Recherche de nouvelles versions…", + "s0223": "Analyse du matériel", + "s0224": "Vérification des menus, des commandes et de la navigation au clavier.", + "s0225": "Vérification des espacements et de l’alignement des composants.", + "s0226": "Vérification du stockage…", + "s0227": "Vérification…", + "s0228": "Vérifications et historique", + "s0229": "Chinois", + "s0230": "Choisissez CPU uniquement comme périphérique d’exécution, ou activez les couches GPU.", + "s0231": "Choisir les GPU…", + "s0232": "Choisissez Désactivé, Q4, Q5, Q6 ou Q8.", + "s0233": "Choisissez Ouvrir ou Afficher dans l’explorateur de fichiers.", + "s0234": "Choisissez un fichier GGUF.", + "s0235": "Choisissez un fichier de moins de 20 Mo.", + "s0236": "Choisissez d’abord un dossier.", + "s0237": "Choisissez un dossier à parcourir.", + "s0238": "Choisissez un dossier, pas un fichier.", + "s0239": "Choisissez l’ID d’un modèle chargé.", + "s0240": "Choisissez un modèle local qui lit les images avant d’envoyer des images jointes.", + "s0241": "Choisir un modèle", + "s0242": "Indiquez l’ID du modèle dans votre requête quand plusieurs modèles sont chargés.", + "s0243": "Choisissez un fichier de modèle ou saisissez son chemin complet.", + "s0244": "Choisissez un dossier de modèles.", + "s0245": "Choisissez une image de moins de 2 Mo.", + "s0246": "Choisissez un port entre 1024 et 65535.", + "s0247": "Choisissez un fournisseur, saisissez sa clé API, puis sélectionnez les modèles à ajouter.", + "s0248": "Choisissez une préférence de ressources.", + "s0249": "Choisissez un dossier distinct pour les modèles, en dehors des données de l’application Strata.", + "s0250": "Choisir un modèle plus petit", + "s0251": "Choisissez un contexte de conversation pris en charge.", + "s0252": "Choisissez une opération native prise en charge.", + "s0253": "Choisissez une planification prise en charge.", + "s0254": "Choisir une police système", + "s0255": "Choisissez une URL temporaire ou votre propre domaine.", + "s0256": "Choisissez une heure valide.", + "s0257": "Choisir une version", + "s0258": "Choisissez une version, puis chargez-la depuis Modèles. Les fichiers natifs partagés sont regroupés dans Stockage.", + "s0259": "Choisir une version…", + "s0260": "Choisissez un jour de la semaine.", + "s0261": "Choisissez une version d’image à télécharger.", + "s0262": "Choisir un modèle qui lit les images", + "s0263": "Choisir une installation", + "s0264": "Choisissez une police installée pour l’interface et les conversations.", + "s0265": "Choisissez un modèle installé.", + "s0266": "Choisir un autre fichier", + "s0267": "Choisir un autre dossier", + "s0268": "Choisissez un autre dossier ou un modèle plus petit.", + "s0269": "Choisissez les GPU détectés, ou CPU uniquement.", + "s0270": "Choisissez des GPU détectés différents. L’inférence de texte sur CPU seul n’est pas prise en charge par cet adaptateur natif.", + "s0271": "Choisissez des alias de modèle distincts, de 80 caractères maximum chacun.", + "s0272": "Choisir un fichier", + "s0273": "Choisir un dossier", + "s0274": "Choisir un modèle : {0}", + "s0275": "Choisissez un point de répartition des couches entre chaque paire de GPU.", + "s0276": "Choisissez des images de moins de 2 Mo.", + "s0277": "Choisir la planification", + "s0278": "Choisissez l’exécution d’un seul modèle ou de plusieurs.", + "s0279": "Choisissez le dossier du dépôt Strata qui contient setup.py et tools/strata_mcp.py.", + "s0280": "Choisir le meilleur travail", + "s0281": "Choisissez le dossier et nous démarrerons vos modèles avec Strata.", + "s0282": "Choisissez la langue utilisée dans tout Strata.", + "s0283": "Choisissez le", + "s0284": "Choisissez si la lecture des images doit être activée.", + "s0285": "Choisissez votre adresse", + "s0286": "Choisissez votre dossier de modèles", + "s0287": "Choix des réglages recommandés", + "s0288": "Choisi pendant l’installation. Les modèles déjà préparés continuent d’utiliser leurs fichiers actuels.", + "s0289": "Effacer les filtres", + "s0290": "Résultat clair · progression mesurable", + "s0291": "Effacer la recherche", + "s0292": "Effacer le raccourci de {0}", + "s0293": "Point de départ clair", + "s0294": "Moyen clair de vérifier", + "s0295": "Étapes suivantes plus claires", + "s0296": "Cliquez sur un raccourci, puis appuyez sur les touches de votre choix. Les modifications sont enregistrées dans ce navigateur. Échap annule l’enregistrement.", + "s0297": "Client / point d’accès", + "s0298": "Client, modèle ou ID de requête…", + "s0299": "Fermer", + "s0300": "Fermer la recherche de conversations", + "s0301": "Fermer le contexte de la conversation", + "s0302": "Fermer la dictée", + "s0303": "Fermer le mode expert", + "s0304": "Fermer la navigation", + "s0305": "Fermer {0}", + "s0306": "Type de connexion Cloudflare", + "s0307": "Tableau de bord Cloudflare ↗", + "s0308": "Tunnel Cloudflare", + "s0309": "Cloudflare créera votre adresse quand vous vous connecterez.", + "s0310": "Le service de téléchargement de Cloudflare est indisponible. Réessayez dans un instant.", + "s0311": "Coder", + "s0312": "Coder · IQ1_M", + "s0313": "Programmation", + "s0314": "Réduire le panneau d’aperçu", + "s0315": "Recueillir les retours", + "s0316": "Recueillir les retours d’ici vendredi", + "s0317": "Collecte et journaux", + "s0318": "Confortable", + "s0319": "Tient confortablement · estimation", + "s0320": "Espacement confortable par défaut.", + "s0321": "Bientôt disponible", + "s0322": "Noms séparés par des virgules que les clients peuvent utiliser pour ce modèle.", + "s0323": "Palette de commandes", + "s0324": "Commandes", + "s0325": "Compact", + "s0326": "Comparer", + "s0327": "Comparer et garder", + "s0328": "Comparer les résultats", + "s0329": "Comparaison du candidat avec l’original sur les mêmes vérifications.", + "s0330": "La compatibilité et les tailles dépendent de la version de Strata installée.", + "s0331": "GPU compatible trouvé", + "s0332": "Terminé", + "s0333": "Mémoire de l’ordinateur", + "s0334": "Préférence de ressources de l’ordinateur", + "s0335": "Utilisation de l’ordinateur", + "s0336": "Requêtes simultanées", + "s0337": "Configuration vérifiée. Aucune erreur de validation.", + "s0338": "Brouillon de configuration", + "s0339": "Exemple de configuration", + "s0340": "La configuration doit être un objet JSON.", + "s0341": "Connecter Strata à une application", + "s0342": "Connectez un fournisseur d’API ou un serveur de modèles sur un autre ordinateur.", + "s0343": "Connecter une application", + "s0344": "Connecter un domaine", + "s0345": "Connecter le moteur", + "s0346": "Connecter l’installation", + "s0347": "Connectez le moteur pour configurer un modèle.", + "s0348": "Connectez le moteur pour modifier ses réglages.", + "s0349": "Se connecter avec Cloudflare", + "s0350": "Connectez votre installation de Strata", + "s0351": "Connectez votre installation locale pour choisir un modèle optimisé.", + "s0352": "Connecté", + "s0353": "Connecté. Réinitialiser pour remettre le compteur à zéro", + "s0354": "Les serveurs connectés peuvent agir sur les ressources que vous avez configurées. Les appels s’exécutent automatiquement quand le modèle les choisit, et leurs résultats apparaissent dans la conversation.", + "s0355": "Outil connecté", + "s0356": "Outils connectés", + "s0357": "Connexion à Cloudflare…", + "s0358": "Connexion au moteur local…", + "s0359": "Connexion…", + "s0360": "Détails de la connexion", + "s0361": "Échec de la connexion", + "s0362": "Guide de connexion", + "s0363": "Modèle du guide de connexion", + "s0364": "Progression de la connexion", + "s0365": "Réglages de connexion", + "s0366": "Type de connexion", + "s0367": "Connecteur", + "s0368": "Connecteur prêt", + "s0369": "La configuration du connecteur est déjà en cours.", + "s0370": "Le contenu déborde", + "s0371": "Contexte", + "s0372": "Cache de contexte", + "s0373": "Le cache de contexte a besoin de plus de mémoire", + "s0374": "Remplissage du contexte", + "s0375": "Longueur du contexte", + "s0376": "Limite de contexte", + "s0377": "Mémoire de contexte", + "s0378": "Le contexte a besoin de plus de mémoire", + "s0379": "Contexte non pris en charge", + "s0380": "Préréglages de contexte", + "s0381": "Contexte trop long", + "s0382": "Contexte trop court", + "s0383": "Contexte utilisé", + "s0384": "Fenêtre de contexte utilisée", + "s0385": "Continuer", + "s0386": "Reprenez là où vous vous êtes arrêté. Ne répétez pas ce que vous avez déjà écrit.", + "s0387": "Passer à la conversation sans résultat de vitesse", + "s0388": "Contraste", + "s0389": "Contrôle", + "s0390": "Cache de conversation", + "s0391": "Mémoire du cache de conversation", + "s0392": "Contexte de la conversation", + "s0393": "Contexte de la conversation ·", + "s0394": "Taille du texte des conversations. Les commandes de l’interface restent à part.", + "s0395": "Copier l’URL de base de l’API", + "s0396": "Copier l’URL du tunnel Cloudflare", + "s0397": "Copier l’ID du modèle", + "s0398": "Copier le code", + "s0399": "Copier l’URL du réseau local", + "s0400": "Copier le message", + "s0401": "Copier l’ID du modèle {0}", + "s0402": "Copier la nouvelle clé API", + "s0403": "Copier le modèle de requête", + "s0404": "Copier la réponse", + "s0405": "Copier l’évaluation", + "s0406": "Copiez cette clé dans votre client. Elle prend effet quand vous choisissez Utiliser cette clé.", + "s0407": "Copier l’URL du tunnel", + "s0408": "Copier l’URL du service du tunnel", + "s0409": "Mise en page de base", + "s0410": "Corrigez la configuration avant d’enregistrer un profil.", + "s0411": "Impossible de calculer la prochaine exécution.", + "s0412": "Impossible de rechercher les mises à jour.", + "s0413": "Impossible de rechercher les mises à jour. Réessayez.", + "s0414": "Impossible de supprimer cette version. Consultez la notification et réessayez.", + "s0415": "Impossible de récupérer les modèles. Vous pouvez ajouter un ID de modèle ci-dessous.", + "s0416": "Impossible de récupérer la liste des modèles.", + "s0417": "Impossible de charger le modèle", + "s0418": "Impossible de lire les métadonnées GGUF.", + "s0419": "Impossible de lire l’image jointe.", + "s0420": "Impossible de lire le fichier.", + "s0421": "Impossible de lire ce fichier.", + "s0422": "Impossible de lire cette image.", + "s0423": "Impossible de supprimer la connexion.", + "s0424": "Impossible d’enregistrer la connexion.", + "s0425": "Impossible de stocker cette image. Vérifiez le stockage du navigateur.", + "s0426": "Impossible de décharger le modèle. Réessayez quand le moteur est inactif.", + "s0427": "Impossible d’ajouter ce dossier", + "s0428": "Impossible de retirer cet espace de travail", + "s0429": "Copie impossible", + "s0430": "Impossible de charger les tâches.", + "s0431": "Impossible de charger cette image.", + "s0432": "Impossible d’ouvrir ce PDF.", + "s0433": "Composant compteur", + "s0434": "Créez une clé API Strata avant de connecter Cloudflare.", + "s0435": "Créez une clé pour protéger votre API. Vous reviendrez ici quand elle sera prête.", + "s0436": "Créer un plan avant de modifier quoi que ce soit", + "s0437": "Créez un tunnel dans votre", + "s0438": "Créer une clé API", + "s0439": "Créez d’abord une clé API", + "s0440": "Créer la tâche", + "s0441": "Créer une URL temporaire", + "s0442": "Créer avec l’IA", + "s0443": "Identifiants et environnement", + "s0444": "Ctrl", + "s0445": "Ctrl+Maj+A", + "s0446": "Contexte actuel", + "s0447": "Moteur actuel", + "s0448": "Progression du téléchargement du fichier en cours", + "s0449": "Réglages actuels", + "s0450": "Personnalisé", + "s0451": "Contexte personnalisé en K tokens", + "s0452": "API de modèle personnalisée", + "s0453": "Modèle personnalisé · la compatibilité avec le moteur est vérifiée au chargement. Les estimations de mémoire s’appuient sur les métadonnées du fichier.", + "s0454": "Tous les jours", + "s0455": "Point quotidien", + "s0456": "Activité quotidienne des messages. {0} jours actifs sur cette période.", + "s0457": "Sombre", + "s0458": "Jour", + "s0459": "Jour de la semaine", + "s0460": "Décodage", + "s0461": "Décodage de la dernière requête", + "s0462": "Décodage actuel", + "s0463": "Décodage :", + "s0464": "Par défaut", + "s0465": "Valeur par défaut pour ce modèle", + "s0466": "Supprimer", + "s0467": "Supprimer la conversation", + "s0468": "Supprimer la version téléchargée du modèle", + "s0469": "Supprimer les fichiers", + "s0470": "Supprimer les fichiers…", + "s0471": "Supprimer la tâche", + "s0472": "Supprimer la tâche {0}", + "s0473": "Supprimer cette conversation ?", + "s0474": "Supprimer cette tâche ?", + "s0475": "Supprimer cette version ?", + "s0476": "Supprimer la version", + "s0477": "Supprimer {0}", + "s0478": "Supprimer {0} ?", + "s0479": "Tâches supprimées", + "s0480": "Suppression…", + "s0481": "Simulé", + "s0482": "Votre approbation est nécessaire", + "s0483": "Refusé. Rien n’a été exécuté.", + "s0484": "Approbation enregistrée. Rien n’a été exécuté.", + "s0485": "Estimation indicative", + "s0486": "État d’installation d’exemple effacé.", + "s0487": "Installation d’exemple lancée", + "s0488": "État de chargement d’exemple effacé.", + "s0489": "Modèle d’exemple prêt", + "s0490": "Modèle d’exemple · réponses fictives.", + "s0491": "Aperçu terminé. Aucune mesure n’a été effectuée.", + "s0492": "Progression", + "s0493": "Suggestion d’exemple.", + "s0494": "Tokens en entrée / sortie (exemple)", + "s0495": "Refusé", + "s0496": "Zone de texte dense", + "s0497": "Refuser", + "s0498": "Décrivez les tâches", + "s0499": "Décrivez d’abord la tâche.", + "s0500": "Décrivez cette image.", + "s0501": "Description", + "s0502": "Descriptions", + "s0503": "Aperçu du design · les réponses sont fictives.", + "s0504": "Revue du design · six aperçus", + "s0505": "Détails", + "s0506": "Deutsch", + "s0507": "Diagnostic", + "s0508": "Dictée", + "s0509": "Impossible de lancer la dictée. Réessayez ou utilisez la dictée intégrée à votre ordinateur.", + "s0510": "Dictée terminée", + "s0511": "Dictée arrêtée", + "s0512": "Dictée indisponible", + "s0513": "Chemin du dossier", + "s0514": "Désactivé", + "s0515": "Abandonner", + "s0516": "Abandonner toutes les modifications non enregistrées du moteur et revenir à la configuration enregistrée.", + "s0517": "Abandonner les modifications", + "s0518": "Abandonner les modifications de la configuration ?", + "s0519": "Abandon de la révision la plus faible et reprise à partir de B.", + "s0520": "Lecture disque", + "s0521": "Ignorer", + "s0522": "Nom affiché", + "s0523": "Texte du document", + "s0524": "Documents / Strata / Models", + "s0525": "La modification tient-elle la route ?", + "s0526": "Terminé", + "s0527": "Comparaison terminée", + "s0528": "Télécharger", + "s0529": "Télécharger et charger", + "s0530": "Télécharger et préparer", + "s0531": "Téléchargement annulé.", + "s0532": "Échec du téléchargement", + "s0533": "Télécharger le modèle", + "s0534": "Télécharger la version du modèle", + "s0535": "Télécharger le journal de session", + "s0536": "Taille du téléchargement", + "s0537": "Téléchargement lancé", + "s0538": "Téléchargement arrêté. Reprenez quand vous voulez.", + "s0539": "Télécharger la conversation active au format Markdown", + "s0540": "Téléchargez d’abord la version sélectionnée du modèle d’image.", + "s0541": "Téléchargez ce modèle avant de le charger.", + "s0542": "Téléchargez cette version du modèle avant de la charger.", + "s0543": "Téléchargez cette version pour l’utiliser.", + "s0544": "Le téléchargement a expiré. Réessayez depuis Modèles.", + "s0545": "Télécharger la version", + "s0546": "Télécharger {0}", + "s0547": "Télécharger · {0}", + "s0548": "Téléchargé", + "s0549": "Modèles téléchargés", + "s0550": "Versions téléchargées de {0}", + "s0551": "Téléchargé · moteur d’image requis", + "s0552": "Téléchargement", + "s0553": "Téléchargement et préparation des fichiers du modèle…", + "s0554": "Téléchargement des fichiers du modèle…", + "s0555": "Téléchargement du modèle...", + "s0556": "Téléchargement : {0} %", + "s0557": "Téléchargement…", + "s0558": "Les téléchargements ne démarrent que lorsque vous êtes prêt.", + "s0559": "Les échecs de téléchargement, de préparation et du moteur affichent ici leurs messages d’origine.", + "s0560": "Brouillon", + "s0561": "Brouillon / spéculation", + "s0562": "Profondeur du brouillon", + "s0563": "Brouillon : {0}{1} Go estimés", + "s0564": "Rédaction…", + "s0565": "Faites glisser pour comparer", + "s0566": "Faites glisser pour redimensionner · les flèches ajustent · double-clic pour réinitialiser", + "s0567": "Durée", + "s0568": "Mode simple", + "s0569": "Facile à utiliser", + "s0570": "Modifier", + "s0571": "Modifier le serveur MCP {0}", + "s0572": "Modifier les réglages enregistrés…", + "s0573": "Modifier les raccourcis", + "s0574": "Modifier la compétence", + "s0575": "Modifier la tâche", + "s0576": "Modifier la tâche {0}", + "s0577": "Modifier le serveur d’outils", + "s0578": "Modifier {0}", + "s0579": "Modification à partir d’un message précédent. Mettez à jour le prompt ci-dessous.", + "s0580": "Cache d’experts GPU élastique", + "s0581": "Activer le serveur MCP {0}", + "s0582": "Activez Lire les images pour ce modèle avant d’envoyer des images.", + "s0583": "Activez Lire les images dans Modèles pour envoyer cette image au modèle. Elle est ouverte dans l’aperçu.", + "s0584": "Activer les outils connectés ?", + "s0585": "Activer les outils", + "s0586": "Activer {0}", + "s0587": "Activé", + "s0588": "Moteur", + "s0589": "Les arguments du moteur et les variables d’environnement STRATA se modifient ici. Les chemins des programmes et l’accès réseau restent gérés par l’hôte.", + "s0590": "Les arguments du moteur doivent être des valeurs de texte. L’accès réseau reste géré par Strata.", + "s0591": "Moteur modifié · réoptimisez avant de lancer", + "s0592": "Le moteur n’est pas devenu opérationnel à temps", + "s0593": "L’environnement du moteur doit être un objet.", + "s0594": "Erreur du moteur", + "s0595": "Hôte du moteur injoignable", + "s0596": "Installation du moteur", + "s0597": "Journal du moteur", + "s0598": "Niveau de journalisation du moteur", + "s0599": "Opération du moteur", + "s0600": "Emplacements de requêtes du moteur", + "s0601": "Moteur redémarré", + "s0602": "Délai de blocage du moteur (secondes)", + "s0603": "Moteur décompressé, mais aucun binaire llama-server n’a été trouvé", + "s0604": "La recherche de mises à jour du moteur n’est pas disponible dans cette version.", + "s0605": "Anglais", + "s0606": "Suffisant pour un modèle", + "s0607": "Suffisant pour le modèle recommandé", + "s0608": "Suffisant pour le plus petit modèle", + "s0609": "Saisir la clé API", + "s0610": "Saisissez un nom affiché de 160 caractères maximum.", + "s0611": "Saisissez un nom affiché.", + "s0612": "Saisissez le nom d’une famille de polices", + "s0613": "Saisissez une adresse complète en http:// ou https://.", + "s0614": "Saisissez un chemin complet.", + "s0615": "Saisissez un nom d’hôte comme ai.example.com, sans https:// ni chemin.", + "s0616": "Saisissez un dossier de modèles.", + "s0617": "Saisissez un nombre positif.", + "s0618": "Saisissez le chemin complet d’un dossier existant.", + "s0619": "Saisissez l’URL du serveur ou le programme.", + "s0620": "Saisissez votre clé API existante dans le client.", + "s0621": "Erreur", + "s0622": "Erreurs", + "s0623": "Échap", + "s0624": "Estimé", + "s0625": "Mémoire estimée", + "s0626": "Mémoire de travail estimée (", + "s0627": "Tous les jours", + "s0628": "Toutes les heures", + "s0629": "Toutes les valeurs sont revenues à la valeur par défaut sûre.", + "s0630": "Toutes les semaines", + "s0631": "Au quotidien", + "s0632": "Choix au quotidien", + "s0633": "Travail au quotidien", + "s0634": "Tout ce qu’il faut pour le modèle recommandé est présent.", + "s0635": "Valeur exacte", + "s0636": "Exemple", + "s0637": "Exemple : Passez en revue ce projet et résumez ce qui a changé.", + "s0638": "Dépasse le budget de mémoire estimé", + "s0639": "Dépasse le budget de mémoire", + "s0640": "Périphérique d’exécution", + "s0641": "Les fichiers existants sont vérifiés et réutilisés. Les modèles natifs actuellement chargés seront déchargés avant la préparation des fichiers.", + "s0642": "Les fichiers existants restent où ils sont. Strata cherche dans ce dossier les fichiers GGUF pris en charge.", + "s0643": "Dossier de modèles existant", + "s0644": "Quitter l’aperçu plein écran", + "s0645": "Une capture d’écran PNG de moins de 18 Mo était attendue.", + "s0646": "Expérience attendue", + "s0647": "Vecteur de contrôle expérimental. Nécessite un moteur compatible avec le vecteur chargé.", + "s0648": "Cache d’experts", + "s0649": "Cache d’experts / mode RAM", + "s0650": "Emplacements du cache d’experts", + "s0651": "Éditeur expert", + "s0652": "Mode expert", + "s0653": "Réglages experts", + "s0654": "Valeur experte", + "s0655": "Experts en VRAM", + "s0656": "Experts signalés par ce moteur.", + "s0657": "Explique en langage simple ce que cette machine peut exécuter, d’après le CPU, le GPU et la mémoire détectés.", + "s0658": "Explorer une révision", + "s0659": "Explorez le déroulement du test. Les valeurs de l’aperçu ne sont jamais enregistrées comme des performances mesurées ni utilisées comme preuve pour une vraie recommandation.", + "s0660": "Exploration d’une idée", + "s0661": "Exporter", + "s0662": "Exporter la conversation", + "s0663": "Marge supplémentaire", + "s0664": "Échec", + "s0665": "Adéquation rapide", + "s0666": "Réponses plus rapides", + "s0667": "Le plus rapide", + "s0668": "IA la plus rapide", + "s0669": "Modèle favori", + "s0670": "Récupérer les modèles disponibles", + "s0671": "Récupération…", + "s0672": "Peu de cœurs : attendez-vous à une lecture lente du prompt", + "s0673": "Fieldnotes cover.svg", + "s0674": "Fieldnotes — site web", + "s0675": "Emplacement du fichier", + "s0676": "Le fichier a renvoyé {0}", + "s0677": "Les mises à jour de fichiers ne peuvent pas être annulées sans risque pendant le remplacement des fichiers.", + "s0678": "Fichiers installés", + "s0679": "Fichiers supprimés", + "s0680": "Les fichiers restent sur votre ordinateur. Ajoutez à nouveau ce dossier pour rouvrir ses conversations.", + "s0681": "Filtrer les modèles disponibles", + "s0682": "Filtrer les modèles…", + "s0683": "Filtrer les lignes…", + "s0684": "Filtrer le tableau", + "s0685": "Trouvez un point de départ pour votre matériel, puis vérifiez avant d’enregistrer.", + "s0686": "Trouver les réglages les plus rapides pour ce PC", + "s0687": "Prise de rythme", + "s0688": "Terminer plus tard", + "s0689": "Terminez ou annulez les téléchargements et les chargements pour changer de dossier.", + "s0690": "Terminez ou annulez les téléchargements et les chargements de modèles avant de changer de dossier.", + "s0691": "Terminez ou annulez les requêtes du modèle avant de changer de dossier.", + "s0692": "Terminez ou annulez les requêtes natives avant de changer de modèle.", + "s0693": "Terminez ou annulez les requêtes avant de préparer les fichiers du modèle.", + "s0694": "Terminez ou annulez d’abord l’opération en cours du moteur.", + "s0695": "Terminez ou annulez d’abord le téléchargement du modèle d’image en cours.", + "s0696": "Terminez ou annulez d’abord le téléchargement de l’image.", + "s0697": "Terminez ou annulez les requêtes de ce modèle avant de le décharger.", + "s0698": "Terminez ou annulez d’abord les requêtes de ce modèle.", + "s0699": "Terminez les requêtes avant de changer de moteur.", + "s0700": "Terminez les requêtes avant d’optimiser.", + "s0701": "Terminez l’opération en cours avant de changer de dossier.", + "s0702": "Terminez l’opération en cours avant d’enregistrer les réglages natifs.", + "s0703": "Terminez les requêtes de ce modèle avant d’enregistrer ses réglages.", + "s0704": "Fin de la dictée…", + "s0705": "Finalisation…", + "s0706": "Adéquation", + "s0707": "Ajuster la sortie au contexte restant", + "s0708": "Adéquation inconnue", + "s0709": "Tient en mémoire", + "s0710": "Tient dans la fenêtre", + "s0711": "Corriger la réinitialisation et l’affichage mobile en conservant la mise en page.", + "s0712": "Corrigez le JSON avant de changer d’onglet.", + "s0713": "Corrigez le JSON de configuration de l’outil.", + "s0714": "Corriger les 3 principaux problèmes", + "s0715": "Flash attention", + "s0716": "Se concentrer sur la conversation", + "s0717": "Lecture ciblée", + "s0718": "Concentrez cet ordinateur sur votre IA.", + "s0719": "Dossier contenant setup.py", + "s0720": "Suivre le système", + "s0721": "Suivre le réglage par défaut du modèle, ou ne réfléchir que sur demande.", + "s0722": "Les requêtes suivantes peuvent réutiliser les tokens en cache du prompt précédent.", + "s0723": "Police", + "s0724": "Famille de polices", + "s0725": "Par exemple : /time-skip Faites un plan de lancement pour mon application", + "s0726": "{0} modèles trouvés. Choisissez ceux à afficher dans la conversation.", + "s0727": "Stockage libre", + "s0728": "URL temporaire gratuite", + "s0729": "Libère la mémoire du modèle", + "s0730": "Pénalité de fréquence", + "s0731": "Vendredis", + "s0732": "D’après les métadonnées GGUF", + "s0733": "Complet", + "s0734": "Chemin complet du dossier", + "s0735": "Chemin complet d’un dossier existant", + "s0736": "Performances maximales", + "s0737": "Priorité maximale pour Strata", + "s0738": "Aperçu plein écran", + "s0739": "Pleine vitesse", + "s0740": "Go", + "s0741": "Go de RAM", + "s0742": "Go de RAM", + "s0743": "Go de marge en RAM · les estimations incluent tous les modèles chargés", + "s0744": "Go de VRAM", + "s0745": "Go de budget", + "s0746": "Go restants dans ce fichier", + "s0747": "Go restants à télécharger", + "s0748": "Go requis", + "s0749": "Go à télécharger", + "s0750": "Go/s", + "s0751": "Le GGUF contient des noms de tenseurs en double.", + "s0752": "Fichiers GGUF de ce dossier. Les téléchargements dans des sous-dossiers sont vérifiés par l’installateur.", + "s0753": "Un entier du GGUF est trop grand.", + "s0754": "Un tableau de métadonnées GGUF est trop grand.", + "s0755": "Les tableaux de métadonnées GGUF sont imbriqués trop profondément.", + "s0756": "Les métadonnées GGUF contiennent une clé en double.", + "s0757": "Les métadonnées GGUF contiennent une chaîne trop longue.", + "s0758": "Les métadonnées GGUF contiennent un entier non pris en charge.", + "s0759": "Les métadonnées GGUF contiennent trop d’entrées.", + "s0760": "Les métadonnées GGUF utilisent un type de valeur non pris en charge.", + "s0761": "L’alignement des tenseurs du GGUF n’est pas valide.", + "s0762": "Les dimensions des tenseurs du GGUF ne sont pas valides.", + "s0763": "La disposition des tenseurs du GGUF n’est pas valide.", + "s0764": "GPU", + "s0765": "GPU / répartition des couches", + "s0766": "GPU et pilote", + "s0767": "L’attribution des GPU nécessite un adaptateur de moteur natif. Utilisez Automatique avec cet hôte.", + "s0768": "Charge du GPU", + "s0769": "Mémoire du GPU", + "s0770": "Détail de la mémoire du GPU", + "s0771": "Mémoire GPU réservée aux autres applications (Mio)", + "s0772": "Ordre des GPU", + "s0773": "Puissance du GPU", + "s0774": "Consommation du GPU", + "s0775": "Les mesures du GPU incluent tout le travail effectué sur ce périphérique. La RAM système est partagée par tous les modèles.", + "s0776": "Temp. GPU", + "s0777": "Température du GPU", + "s0778": "GPU indisponible", + "s0779": "GPU {0}", + "s0780": "GPU {0} ·", + "s0781": "GPU {0} · {1}", + "s0782": "GPU", + "s0783": "GPU connectés", + "s0784": "Général", + "s0785": "Générer", + "s0786": "Générer une autre", + "s0787": "Générer un exemple de réponse", + "s0788": "Génération", + "s0789": "Génération en tok/s", + "s0790": "Échec de la génération", + "s0791": "Vitesse de génération", + "s0792": "Obtenir Strata", + "s0793": "Préparez mon portfolio pour la publication.", + "s0794": "Faites avancer vos projets sur du matériel qui vous appartient.", + "s0795": "Obtenir la mise à jour", + "s0796": "Préparation des fichiers…", + "s0797": "Préparation de votre installation…", + "s0798": "Git n’a pas pu mettre à jour cette installation. Ouvrez le diagnostic.", + "s0799": "Donner la priorité à Strata", + "s0800": "Donnez à chaque serveur d’outils un nom simple et unique.", + "s0801": "Donnez-moi un court exercice d’écriture et un exemple de réponse. Restez pratique et sous les 200 mots.", + "s0802": "Donner plus de threads CPU au moteur", + "s0803": "Donnez une ligne d’arrivée à votre IA.", + "s0804": "Donnez à votre IA les ressources disponibles pour travailler sans distraction.", + "s0805": "Donnez à votre API locale une adresse HTTPS qu’une autre application peut atteindre.", + "s0806": "Donner plus de ressources à votre modèle", + "s0807": "Global · toutes les conversations", + "s0808": "Aller", + "s0809": "Aller directement à l’application", + "s0810": "Aller à", + "s0811": "Objectif", + "s0812": "Grammaire", + "s0813": "Aperçu HTML", + "s0814": "Serveur HTTP", + "s0815": "Marge pour vos autres applications", + "s0816": "Bonjour, je suis Strata.", + "s0817": "Aidez-moi à pratiquer l’espagnol chaque matin…", + "s0818": "Masquer", + "s0819": "Masquer la clé API", + "s0820": "Masquer les journaux", + "s0821": "Masquer la barre latérale", + "s0822": "Masque la navigation dans la conversation. Les Paramètres restent ouverts au-dessus de la conversation.", + "s0823": "Élevé", + "s0824": "Haute qualité", + "s0825": "Plus haute borne inférieure de {0} prise en charge parmi les candidats comparables qui tiennent. {1}.", + "s0826": "Historique", + "s0827": "GPU sélectionné le plus chaud", + "s0828": "Ce que votre modèle peut garder en tête.", + "s0829": "Comment fonctionne le partage des ressources", + "s0830": "Comment souhaitez-vous travailler avec Strata ?", + "s0831": "ID", + "s0832": "INT8", + "s0833": "Inactif", + "s0834": "Illustratif", + "s0835": "Exemple d’interface illustratif · ni une mesure ni une prévision matérielle", + "s0836": "Estimations illustratives", + "s0837": "Aperçu de design illustratif avec contexte, utilisation de l’ordinateur et débordement sur SSD. Pas un test de performance.", + "s0838": "Image", + "s0839": "Séparateur de comparaison d’images", + "s0840": "Périphérique de l’encodeur d’images", + "s0841": "Génération d’images", + "s0842": "La génération d’images nécessite un moteur d’images, un encodeur de texte et un VAE compatibles.", + "s0843": "Modèle d’image", + "s0844": "Progression du téléchargement du modèle d’image", + "s0845": "La mémoire du modèle d’image n’est pas incluse dans cette estimation.", + "s0846": "Version du modèle d’image", + "s0847": "Lecture d’images", + "s0848": "Importer", + "s0849": "Échec de l’importation : {0}", + "s0850": "Améliorez ce plan de lancement.", + "s0851": "Amélioration du brouillon enregistré.", + "s0852": "En cours", + "s0853": "Dans votre client, choisissez un fournisseur compatible.", + "s0854": "Inclure les conversations archivées", + "s0855": "Incluez le préfixe de l’API, comme /v1, mais sans /models ni /chat/completions.", + "s0856": "Augmenter le contraste du texte et des bordures.", + "s0857": "Augmenté", + "s0858": "Tokens en entrée", + "s0859": "Installez un moteur llama-server compatible avant de quitter Strata natif.", + "s0860": "Dossier d’installation", + "s0861": "Installé", + "s0862": "Polices installées", + "s0863": "Version installée", + "s0864": "Instructions", + "s0865": "Instructions envoyées :", + "s0866": "Revue des interactions", + "s0867": "Taille de l’interface", + "s0868": "Espacement de l’interface", + "s0869": "Port interne du moteur", + "s0870": "Clé API non valide", + "s0871": "JSON non valide", + "s0872": "Capture d’écran PNG non valide.", + "s0873": "Inviter quelques testeurs", + "s0874": "Ses fichiers seront supprimés de cet ordinateur.", + "s0875": "Ses modèles seront retirés du sélecteur de conversation. Vos conversations restent enregistrées.", + "s0876": "JSON", + "s0877": "Japonais", + "s0878": "K de contexte · lot", + "s0879": "K tokens", + "s0880": "K. Choisissez un contexte pris en charge pour l’exécuter.", + "s0881": "Mode KV", + "s0882": "Conserver les métadonnées des requêtes API", + "s0883": "Gardez une clé tant que l’API est accessible à d’autres appareils.", + "s0884": "Garder la conversation", + "s0885": "Garder la connexion", + "s0886": "Continuer à modifier", + "s0887": "Garder le moteur prêt", + "s0888": "Garder les experts en RAM", + "s0889": "Garder la clé", + "s0890": "Garder les modèles chargés quand vous en ajoutez un autre.", + "s0891": "Garder la tâche", + "s0892": "Garder le style botanique et rendre le titre plus facile à parcourir.", + "s0893": "Conserver la progression réalisée.", + "s0894": "Garder l’idée la plus solide.", + "s0895": "Garder cet ordinateur réactif", + "s0896": "Garder les outils désactivés", + "s0897": "Garder le résultat mis à jour", + "s0898": "Garder la version", + "s0899": "Garder l’espace de travail", + "s0900": "Gardez votre navigateur et vos outils à côté de votre IA.", + "s0901": "Conservation de B", + "s0902": "L’original est conservé pendant qu’un candidat comble ses lacunes.", + "s0903": "Résultat conservé", + "s0904": "Conservé de la mise à jour", + "s0905": "Détail clé supprimé", + "s0906": "Raccourcis clavier", + "s0907": "Coréen", + "s0908": "Libellés et descriptions relus.", + "s0909": "Langue", + "s0910": "Dernière requête", + "s0911": "Taille de la dernière requête", + "s0912": "Dernier résultat", + "s0913": "Dernière exécution échouée · Voir", + "s0914": "Dernier changement", + "s0915": "Révision ultérieure non conservée", + "s0916": "Dernière version", + "s0917": "Vitesse de la dernière réponse", + "s0918": "Plan de lancement", + "s0919": "Répartition des couches", + "s0920": "Les points de répartition des couches doivent augmenter de 1 à 47, par exemple 16,32.", + "s0921": "Revue de la mise en page", + "s0922": "Mise en page simplifiée", + "s0923": "Apprenez une notion utile à la fois.", + "s0924": "Prompt d’apprentissage", + "s0925": "Garder 20 % pour mon travail", + "s0926": "Laissez vide pour utiliser la valeur par défaut du modèle.", + "s0927": "Laissez vide pour garder la clé enregistrée", + "s0928": "Quitter le mode concentration", + "s0929": "Laisser de la place aux autres applications", + "s0930": "Moins", + "s0931": "Laissez un autre appareil de votre réseau utiliser vos modèles chargés.", + "s0932": "Laissez le travail utile se répéter.", + "s0933": "C’est parti", + "s0934": "Clair", + "s0935": "Clair par défaut. Système suit votre ordinateur.", + "s0936": "Devrait tenir (estimation)", + "s0937": "Limite l’échantillonnage aux mots les plus probables.", + "s0938": "Ligne {0}, colonne {1} : {2}", + "s0939": "Je vous écoute…", + "s0940": "Estimation en direct d’après la longueur de la réponse et le temps écoulé. L’utilisation finale vient du moteur.", + "s0941": "Charger", + "s0942": "Chargez à nouveau un modèle après le changement.", + "s0943": "Chargez un modèle avant de terminer l’installation.", + "s0944": "Chargez un modèle dans Modèles pour le rendre disponible ici.", + "s0945": "Chargez un modèle Strata natif pour utiliser l’API Responses.", + "s0946": "Chargez d’abord un modèle natif.", + "s0947": "Charger le modèle", + "s0948": "Charger à la première requête", + "s0949": "Les réglages de chargement s’appliquent au prochain chargement. Les valeurs d’échantillonnage par défaut s’appliquent à la prochaine requête.", + "s0950": "Les réglages de chargement s’appliquent quand vous lancez le modèle.", + "s0951": "Chargez le modèle pour démarrer une requête.", + "s0952": "Charger {0} pour toutes les conversations. Le chargement peut prendre quelques instants.", + "s0953": "Chargé", + "s0954": "Modèle chargé", + "s0955": "Modèles chargés", + "s0956": "Chargement", + "s0957": "Le chargement ajoute un modèle. Les modèles existants gardent leurs réglages et leurs GPU.", + "s0958": "Charger un autre modèle laisse les autres chargés.", + "s0959": "Le chargement applique ces réglages à cette instance. Les autres modèles restent chargés.", + "s0960": "Chargement du document…", + "s0961": "Chargement des polices installées…", + "s0962": "Chargement du modèle", + "s0963": "Chargement des versions du modèle…", + "s0964": "Chargement des réglages…", + "s0965": "Chargement des tâches…", + "s0966": "Chargement de vos modèles et de vos réglages…", + "s0967": "Chargement…", + "s0968": "L’IA en local. La vôtre.", + "s0969": "GGUF local ·", + "s0970": "Fichier local", + "s0971": "Fichiers de modèle locaux", + "s0972": "Modèle local retiré", + "s0973": "Modèle local ·", + "s0974": "Modèles locaux", + "s0975": "Les modèles locaux ne sont pas téléchargés. Choisissez à nouveau leur fichier GGUF pour les reconnecter.", + "s0976": "Réseau local", + "s0977": "Programme local", + "s0978": "Partage local", + "s0979": "Verrouiller le modèle en mémoire", + "s0980": "Contexte long", + "s0981": "Phrase plus longue", + "s0982": "Boucle", + "s0983": "Mode peu de RAM", + "s0984": "Mo/s", + "s0985": "Réglages de connexion avancés MCP", + "s0986": "Programme MCP", + "s0987": "Arguments du programme MCP", + "s0988": "URL du serveur MCP", + "s0989": "Configuration du serveur MCP", + "s0990": "Nom du serveur MCP", + "s0991": "Serveurs MCP", + "s0992": "Les serveurs MCP doivent former un objet de 30 entrées au maximum.", + "s0993": "Outils MCP", + "s0994": "Transport MCP", + "s0995": "Les 3 étapes ont été précisées", + "s0996": "Mise en page adaptée aux petits écrans", + "s0997": "Idée principale", + "s0998": "Navigation principale", + "s0999": "Apporter des améliorations", + "s1000": "Personnalisez", + "s1001": "Tirez le meilleur de cet ordinateur", + "s1002": "Rendre les étapes concrètes et ajouter un moyen de vérifier le résultat.", + "s1003": "Clarification de l’étape suivante.", + "s1004": "Gérer / arrêter", + "s1005": "Gérer les modèles API", + "s1006": "Gérer le tunnel Cloudflare", + "s1007": "Gérer la famille de modèles", + "s1008": "Gérer les modèles", + "s1009": "Manuel", + "s1010": "Vue Markdown", + "s1011": "Tokens de sortie max.", + "s1012": "Tokens max.", + "s1013": "Tokens d’image maximum", + "s1014": "Performances maximales", + "s1015": "Nombre maximal de caractères d’un résultat d’outil", + "s1016": "Nombre maximal de tours d’outils", + "s1017": "Peut être plus lent", + "s1018": "Peut être plus lent · Les données du modèle peuvent être lues sur le SSD.", + "s1019": "Mesurer les performances", + "s1020": "Mesurer la vitesse", + "s1021": "Mesurez la vitesse avec un test court. La calibration experte essaie des réglages du moteur et enregistre la configuration mesurée la plus rapide.", + "s1022": "Mesuré", + "s1023": "Mesure en cours…", + "s1024": "Mémoire", + "s1025": "Détail de la mémoire", + "s1026": "La mémoire pourrait être juste", + "s1027": "La mémoire pourrait être juste (estimation)", + "s1028": "Mémoire nécessaire", + "s1029": "Le placement en mémoire n’est pas disponible pour cette configuration.", + "s1030": "Mémoire · Non estimée ·", + "s1031": "Mapper les fichiers du modèle en mémoire", + "s1032": "Écrire à Strata", + "s1033": "Écrire à Strata…", + "s1034": "Messages", + "s1035": "Meta", + "s1036": "Mesures indisponibles", + "s1037": "L’accès au microphone a été refusé. Autorisez-le dans votre navigateur, puis réessayez.", + "s1038": "Tokens d’image minimum", + "s1039": "Mode", + "s1040": "Modèle", + "s1041": "Modèle / périphérique", + "s1042": "ID du modèle", + "s1043": "ID du modèle donné par votre fournisseur ou votre serveur", + "s1044": "Activité du modèle", + "s1045": "Changement de modèle indisponible", + "s1046": "Dossier des modèles", + "s1047": "Exécution du modèle", + "s1048": "Famille de modèles", + "s1049": "Chemin du fichier ou du dossier du modèle", + "s1050": "Fichiers du modèle", + "s1051": "Fichiers du modèle supprimés du disque.", + "s1052": "Modèle pour cette application", + "s1053": "Liste des modèles :", + "s1054": "Modèle chargé", + "s1055": "Mémoire du modèle libérée.", + "s1056": "Nom du modèle", + "s1057": "Le modèle a besoin de plus de mémoire", + "s1058": "Modèle pas prêt", + "s1059": "Performances du modèle", + "s1060": "Priorité du modèle", + "s1061": "Progression du modèle", + "s1062": "Modèle prêt", + "s1063": "Raisonnement du modèle", + "s1064": "Réglages du modèle", + "s1065": "Réglages et outils du modèle", + "s1066": "État du modèle", + "s1067": "Modèle optimisé", + "s1068": "Modèle déchargé", + "s1069": "Version du modèle", + "s1070": "Versions du modèle", + "s1071": "Poids du modèle", + "s1072": "Modèle {0} Go, contexte {1} Go, exécution {2} Go. {3}", + "s1073": "Modèles", + "s1074": "Modèles ajoutés. Choisissez-en un dans le sélecteur de modèle de la conversation.", + "s1075": "Modèles dans la conversation", + "s1076": "Moniteur", + "s1077": "Surveiller le GPU", + "s1078": "Surveiller le modèle", + "s1079": "Surveiller le processeur", + "s1080": "Capture d’écran du moniteur", + "s1081": "Plus", + "s1082": "Autres actions Time-skip", + "s1083": "Autres actions", + "s1084": "Plus concis", + "s1085": "Plus d’historique de conversation utilise plus de mémoire.", + "s1086": "D’autres paramètres du moteur deviennent disponibles après la préparation de cette version.", + "s1087": "Plus de mains, une seule conversation.", + "s1088": "Autres actions sur le message", + "s1089": "Plus d’espace libre", + "s1090": "Autres actions sur la réponse", + "s1091": "Plus d’emplacements demandent plus de mémoire et peuvent ralentir chaque réponse.", + "s1092": "Plus de texte utilise plus de mémoire.", + "s1093": "Plus — Serveur API et Paramètres", + "s1094": "Animations", + "s1095": "Cet hôte ne prend pas encore en charge plusieurs moteurs natifs ni l’attribution des GPU.", + "s1096": "Les performances de mon IA locale avec Strata", + "s1097": "Mon autre PC", + "s1098": "Mon propre domaine", + "s1099": "Politique NUMA", + "s1100": "Nom", + "s1101": "Nom affiché dans la conversation", + "s1102": "Format KV natif", + "s1103": "JSON de configuration native", + "s1104": "La connexion de contrôle native est fermée.", + "s1105": "Réglages du moteur natif", + "s1106": "Mode peu de RAM natif", + "s1107": "Modèle natif", + "s1108": "Éditeur de réglages natifs", + "s1109": "Modèle des réglages natifs", + "s1110": "Les réglages natifs doivent former un objet.", + "s1111": "{0} natif", + "s1112": "Un test de vitesse est nécessaire", + "s1113": "Les nouvelles requêtes API sont en pause.", + "s1114": "Les nouvelles requêtes API sont en pause. Reprenez-les dans Serveur API.", + "s1115": "Nouvelle conversation", + "s1116": "Nouvelle conversation", + "s1117": "Nouvelle tâche", + "s1118": "Page suivante", + "s1119": "Prochaine exécution", + "s1120": "Étapes suivantes", + "s1121": "Astuce suivante", + "s1122": "Aucune clé API", + "s1123": "Aucun fichier GGUF ici", + "s1124": "Aucun accélérateur GPU trouvé — Strata fonctionnera sur le CPU", + "s1125": "Aucun GPU détecté", + "s1126": "Aucune mesure du GPU pour l’instant", + "s1127": "Aucun PDF à afficher.", + "s1128": "Ni compte ni domaine nécessaires. Idéal pour une connexion rapide.", + "s1129": "Aucun candidat agent approuvé ne convient à cette configuration. Essayez Équilibré ou envisagez un contexte plus court.", + "s1130": "Aucune conversation pour l’instant", + "s1131": "Aucune commande ne correspond à « /", + "s1132": "Aucune mesure de vitesse comparable pour cette configuration.", + "s1133": "Aucun modèle compatible ne tient dans ce contexte et ce budget de mémoire. Envisagez un contexte plus court.", + "s1134": "Aucune conversation sélectionnée", + "s1135": "Aucune tâche supprimée", + "s1136": "Aucun modèle téléchargé", + "s1137": "Aucun message du moteur pour l’instant.", + "s1138": "Aucun contenu de fichier n’a été fourni.", + "s1139": "Aucun port privé libre n’a été trouvé pour le moteur.", + "s1140": "Aucun fichier local n’est disponible.", + "s1141": "Aucun modèle local téléchargé pour l’instant.", + "s1142": "Aucune conversation correspondante", + "s1143": "Aucune conversation correspondante. Essayez une autre recherche.", + "s1144": "Aucune version de llama.cpp correspondante pour cette plateforme", + "s1145": "Aucune requête correspondante", + "s1146": "Aucune compétence correspondante", + "s1147": "Aucune tâche correspondante", + "s1148": "Aucun message pour l’instant", + "s1149": "Aucun microphone disponible. Vérifiez la connexion de votre microphone.", + "s1150": "Aucun modèle n’est chargé.", + "s1151": "Aucun modèle n’est chargé. Choisissez-en un dans Modèles, puis réessayez.", + "s1152": "Aucun modèle chargé", + "s1153": "Aucun modèle chargé — rien à redémarrer", + "s1154": "Aucune version de modèle disponible.", + "s1155": "Aucun modèle sélectionné pour l’instant. Récupérez la liste ou ajoutez un ID de modèle.", + "s1156": "Aucun connecteur officiel à télécharger n’a été trouvé pour cet ordinateur.", + "s1157": "Aucun paramètre ne correspond à vos filtres.", + "s1158": "Aucun paramètre ne correspond.", + "s1159": "Aucune utilisation de requête enregistrée", + "s1160": "Aucun échantillon de vitesse enregistré pour l’instant", + "s1161": "Aucune version publiée", + "s1162": "Aucune utilisation de modèle signalée sur cette période.", + "s1163": "Aucune requête pour l’instant", + "s1164": "Aucune requête pour l’instant", + "s1165": "Aucun résultat pour l’instant.", + "s1166": "Aucune conversation enregistrée à cette position.", + "s1167": "Aucun moteur précédent enregistré n’est disponible.", + "s1168": "Aucune version précédente enregistrée", + "s1169": "Aucune tâche planifiée pour l’instant", + "s1170": "Aucune compétence pour l’instant", + "s1171": "Aucune parole détectée. Essayez de parler plus près du microphone.", + "s1172": "Aucune version stable de Strata n’est encore publiée dans ce flux.", + "s1173": "Aucun sous-agent enregistré", + "s1174": "Aucun GPU pris en charge n’a été signalé par cette installation.", + "s1175": "Aucune longueur de contexte prise en charge.", + "s1176": "Aucune tâche pour l’instant", + "s1177": "Aucun texte n’a été ajouté. Votre brouillon est prêt à être modifié.", + "s1178": "Aucun appel d’outil dans cette conversation.", + "s1179": "Aucun message de l’utilisateur trouvé", + "s1180": "Aucune version disponible.", + "s1181": "Aucune version téléchargée pour l’instant. Choisissez-en une ci-dessus pour commencer.", + "s1182": "Aucun dossier de données accessible en écriture trouvé — définissez STRATA_HOME sur un chemin accessible en écriture", + "s1183": "Indisponible", + "s1184": "Pas disponible pour toutes les requêtes", + "s1185": "Non défini", + "s1186": "Pas encore défini", + "s1187": "Non téléchargé", + "s1188": "Espace disque insuffisant", + "s1189": "Stockage insuffisant", + "s1190": "Non estimé", + "s1191": "Introuvable", + "s1192": "Non installé", + "s1193": "Non conservé", + "s1194": "Non communiqué", + "s1195": "Non évalué pour les tâches d’agent", + "s1196": "Non pris en charge par ce moteur", + "s1197": "Non utilisé par ce moteur", + "s1198": "Pas encore disponible", + "s1199": "Rien ne correspond à « ", + "s1200": "Maintenant", + "s1201": "Désactivé", + "s1202": "Activé", + "s1203": "Dans les temps", + "s1204": "Sur cet ordinateur", + "s1205": "Sur cet ordinateur. Restaurez-le quand vous voulez depuis Modèles.", + "s1206": "Une seule URL d’API · routage par ID de modèle", + "s1207": "Une seule configuration pour toutes les commandes.", + "s1208": "Un seul fichier", + "s1209": "Un modèle à la fois. Le chargement bascule vers le modèle sélectionné.", + "s1210": "Un plan, tout réuni", + "s1211": "Une vérification qui passait auparavant échoue maintenant.", + "s1212": "Un seul pool de mémoire partagé", + "s1213": "Mesure unique · environ 5 à 10 minutes. Votre ordinateur sera occupé.", + "s1214": "Seules les applications dotées de votre clé API Strata peuvent utiliser cette connexion.", + "s1215": "Seuls les dossiers et les fichiers GGUF sont affichés. Les adaptateurs LoRA et les projecteurs d’images demandent une prise en charge distincte.", + "s1216": "Seulement dans {0}", + "s1217": "Seule l’API d’inférence est partagée. Votre ordinateur et Strata doivent rester allumés.", + "s1218": "Opaque", + "s1219": "Ouvrir", + "s1220": "Ouvrez Modèles et déchargez d’abord les modèles natifs en cours d’exécution.", + "s1221": "Ouvrir le moniteur", + "s1222": "Ouvrir les tâches", + "s1223": "Ouvrez une conversation et attendez la fin de la réponse en cours.", + "s1224": "Ouvrez d’abord une conversation qui contient des messages.", + "s1225": "Ouvrir un fichier local dans le panneau d’aperçu", + "s1226": "Ouvrir un site web", + "s1227": "Ouvrir un site web dans le panneau d’aperçu", + "s1228": "Ouvrez un autre dossier ou saisissez plus haut le chemin complet du modèle.", + "s1229": "Ouvrir le dossier", + "s1230": "Ouvrir avec l’application par défaut", + "s1231": "Ouvrir dans le panneau latéral", + "s1232": "Ouvrir la navigation", + "s1233": "Ouvrir l’original", + "s1234": "Ouvrir hors de l’aperçu", + "s1235": "Ouvrir l’aperçu", + "s1236": "Aperçus ouverts", + "s1237": "Ouvrir le résultat", + "s1238": "Ouvrez six types de sorties différents pour que je puisse affiner l’aperçu du design.", + "s1239": "Ouvrez l’application Strata locale pour utiliser les commandes de l’hôte.", + "s1240": "Ouvrez la page de la version pour mettre à jour cette installation", + "s1241": "Ouvrez le nombre de sous-agents ci-dessus pour examiner cette exécution d’exemple. Chaque ligne indique l’état, l’utilisation de tokens et le temps écoulé.", + "s1242": "Ouvrir {0}", + "s1243": "Ouvrir {0} dans le panneau latéral", + "s1244": "OpenAI Chat Completions", + "s1245": "OpenAI Responses", + "s1246": "Composition aérée", + "s1247": "Ouverture de la visionneuse PDF…", + "s1248": "Ouvre une copie locale de cet aperçu.", + "s1249": "Fichiers de modèle Strata optimisés", + "s1250": "Facultatif", + "s1251": "Options pour {0}", + "s1252": "Original", + "s1253": "Couverture Fieldnotes d’origine : Room to begin again, avec des formes botaniques.", + "s1254": "Idée d’origine conservée", + "s1255": "Original restauré", + "s1256": "Original restauré dans cet exemple.", + "s1257": "Original enregistré", + "s1258": "Autres applications", + "s1259": "D’autres modèles chargés ont réservé cette mémoire. Choisissez un autre GPU, réduisez le contexte ou déchargez un modèle.", + "s1260": "Les autres modèles chargés restent disponibles.", + "s1261": "Autres modèles locaux", + "s1262": "Autres modèles locaux…", + "s1263": "Sortie", + "s1264": "Tokens de sortie", + "s1265": "Vue d’ensemble", + "s1266": "PCIe", + "s1267": "Transfert PCIe", + "s1268": "PDF", + "s1269": "Commandes du PDF", + "s1270": "Page {0} du PDF", + "s1271": "Les requêtes parallèles multiplient la mémoire du cache KV — laissez 1 sur une mémoire unifiée.", + "s1272": "Groupe de paramètres", + "s1273": "Paramètres", + "s1274": "En réserve", + "s1275": "En réserve / restaurées", + "s1276": "Conversations en réserve", + "s1277": "Les conversations en réserve reprennent depuis leur état enregistré. La plus ancienne est retirée quand le cache est plein.", + "s1278": "Le placement partiel des couches sur le GPU nécessite un plan d’allocation vérifié. Choisissez Automatique, Toutes les couches ou CPU uniquement.", + "s1279": "Déchargement partiel : la répartition entre le GPU et la mémoire système n’est pas estimée.", + "s1280": "Collez uniquement le token qui suit --token", + "s1281": "Collez le token du tunnel fourni par Cloudflare, pas la commande d’installation complète.", + "s1282": "Mettre l’animation en pause", + "s1283": "En pause", + "s1284": "Heure de pointe", + "s1285": "Fenêtre de pénalité", + "s1286": "En attente", + "s1287": "Performances", + "s1288": "Choisir une planification", + "s1289": "Les images sont ouvertes dans l’aperçu. Choisissez un modèle local avec Lire les images activé pour les envoyer.", + "s1290": "Les images doivent être des fichiers PNG, JPEG ou WebP joints.", + "s1291": "Épingler", + "s1292": "Épinglé", + "s1293": "Plan", + "s1294": "Lancer l’animation", + "s1295": "Portfolio prêt à publier", + "s1296": "Portugais", + "s1297": "Puissance", + "s1298": "Traitement du prompt", + "s1299": "Traitement du prompt de la dernière requête", + "s1300": "Traiter le prompt maintenant", + "s1301": "Traiter le prompt de cette requête", + "s1302": "Préparer", + "s1303": "Préparez d’abord un modèle. Son installateur télécharge le moteur correspondant.", + "s1304": "Préparez un modèle dans Modèles pour configurer les paramètres de son moteur et ses outils MCP.", + "s1305": "Préparez d’abord l’environnement Python.", + "s1306": "Préparez le modèle avant d’optimiser.", + "s1307": "Préparez ce modèle avant de calibrer.", + "s1308": "Préparez les fichiers de vision de ce modèle avant d’activer la lecture d’images.", + "s1309": "Préparation des fichiers…", + "s1310": "Préparation de la capture d’écran…", + "s1311": "Préparation de votre connecteur", + "s1312": "Préparation de votre modèle", + "s1313": "Préparation de votre modèle…", + "s1314": "Préparation de votre capture d’écran…", + "s1315": "Préparation…", + "s1316": "Pénalité de présence", + "s1317": "Conservé avant toute révision.", + "s1318": "Appuyez sur les touches…", + "s1319": "Aperçu", + "s1320": "Version d’aperçu", + "s1321": "Actions sur le fichier d’aperçu", + "s1322": "Aperçu des statistiques des sous-agents", + "s1323": "Test d’aperçu · Exemple", + "s1324": "Largeur de l’aperçu : {0} pixels", + "s1325": "Moteur précédent disponible", + "s1326": "Page précédente", + "s1327": "Confidentialité", + "s1328": "La confidentialité d’abord", + "s1329": "Informations sur le processeur indisponibles", + "s1330": "Programme", + "s1331": "La progression s’affiche dans Modèles.", + "s1332": "Prompt", + "s1333": "Lot de prompts", + "s1334": "Lot de prompts ·", + "s1335": "Le contenu du prompt et la position passée dans la file ne sont pas conservés. Cette vue se met à jour pendant l’exécution de la requête.", + "s1336": "Lecture du prompt", + "s1337": "Protégez votre connexion", + "s1338": "Fournisseur", + "s1339": "Valeur par défaut du fournisseur", + "s1340": "Nom du fournisseur", + "s1341": "Quantification", + "s1342": "Longueur de la file", + "s1343": "En file d’attente", + "s1344": "Qwen · IQ2_M", + "s1345": "Qwen · IQ3_XXS", + "s1346": "Qwen · Q2_K", + "s1347": "RAM", + "s1348": "Marge de RAM", + "s1349": "Configuration brute", + "s1350": "Lecture", + "s1351": "Lire les experts depuis le disque", + "s1352": "Lire les images", + "s1353": "Lire les images quand ce modèle se charge", + "s1354": "Lire le prompt", + "s1355": "Lire un prompt d’exemple", + "s1356": "Débit de lecture", + "s1357": "Lecture", + "s1358": "Lecture et concentration", + "s1359": "Vitesses de lecture et de réponse. {0}.", + "s1360": "Lecture des fichiers…", + "s1361": "Lecture de la mémoire…", + "s1362": "Lecture du dossier des modèles…", + "s1363": "Lecture du prompt", + "s1364": "Lecture des réglages enregistrés…", + "s1365": "Taille de lecture", + "s1366": "Taille du texte de lecture", + "s1367": "Lecture en tok/s", + "s1368": "Lectures", + "s1369": "Prêt", + "s1370": "Prêt pour une requête.", + "s1371": "Prêt pour les requêtes.", + "s1372": "Prêt à se connecter", + "s1373": "Prêt à écouter", + "s1374": "Prêt pour l’aperçu", + "s1375": "Prêt à être restauré depuis les Réglages enregistrés.", + "s1376": "Prêt pour la revue", + "s1377": "Effort de raisonnement", + "s1378": "Niveau d’effort de raisonnement", + "s1379": "Effort de raisonnement : {0}", + "s1380": "Le raisonnement utilise les valeurs par défaut du fournisseur d’API.", + "s1381": "Conversations récentes", + "s1382": "Requêtes récentes", + "s1383": "Recommandé", + "s1384": "Valeurs par défaut recommandées", + "s1385": "Recommandé :", + "s1386": "Reconnecter le fichier", + "s1387": "Reconnecter le fichier local", + "s1388": "Durée enregistrée", + "s1389": "Tokens enregistrés en entrée / sortie", + "s1390": "Réduisez le contexte ou choisissez une version plus petite pour que ce modèle tienne.", + "s1391": "Réduit", + "s1392": "Réduire les animations désactive aussi le défilement fluide.", + "s1393": "Faites le point sur l’avancement et planifiez la semaine prochaine.", + "s1394": "Actualiser les compétences", + "s1395": "Révision de la couverture Fieldnotes rejetée : la mise en page raccourcie supprime le sous-titre utile.", + "s1396": "Recharger l’aperçu", + "s1397": "Recharger l’enregistré", + "s1398": "Recharge le modèle en mémoire", + "s1399": "Retirer", + "s1400": "Retirer la clé API ?", + "s1401": "Retirer le serveur MCP {0}", + "s1402": "Supprimer la connexion", + "s1403": "Échec du retrait", + "s1404": "Retirer de Strata ?", + "s1405": "Retirer de Strata…", + "s1406": "Retirer de la barre latérale", + "s1407": "Retirer la clé", + "s1408": "Retirer le modèle", + "s1409": "Retirer la clé API enregistrée", + "s1410": "Retire ce modèle de Strata. Vos fichiers GGUF d’origine restent dans leur dossier.", + "s1411": "Retirer l’espace de travail de la barre latérale ?", + "s1412": "Retirer {0}", + "s1413": "Supprime {0} Go de fichiers téléchargés. Vous pourrez télécharger à nouveau cette version.", + "s1414": "Retirer {0} du sélecteur de conversation", + "s1415": "Retirer {0} de la barre latérale", + "s1416": "Supprime {0} de fichiers téléchargés. Vous pourrez télécharger à nouveau cette version.", + "s1417": "Retirer {0} ?", + "s1418": "Retrait…", + "s1419": "Renommer", + "s1420": "Renommer la conversation", + "s1421": "Affichage de la page…", + "s1422": "Répéter", + "s1423": "Répéter automatiquement", + "s1424": "Pénalité de répétition", + "s1425": "Répéter la tâche", + "s1426": "Se répète chaque jour de la semaine", + "s1427": "Pénalité de répétition", + "s1428": "Remplacer ce brouillon par les réglages enregistrés en dernier dans le moteur.", + "s1429": "Rejouer", + "s1430": "Rejouer l’exemple", + "s1431": "Revoir cette astuce", + "s1432": "Signalé par le modèle", + "s1433": "Utilisation de tokens signalée par modèle au fil du temps. {0} tokens.", + "s1434": "Requête", + "s1435": "Corps de la requête trop volumineux", + "s1436": "Détails de la requête", + "s1437": "Échec de la requête ({0} {1})", + "s1438": "La taille de la requête est l’entrée plus la sortie à la fin. Ce n’est pas une lecture en direct du cache du modèle. Les anciens messages peuvent n’avoir aucune utilisation enregistrée.", + "s1439": "Filtre d’état des requêtes", + "s1440": "État de la requête indisponible. Reconnectez-vous avant de changer le modèle chargé.", + "s1441": "Délai d’attente de la requête", + "s1442": "Requêtes", + "s1443": "Les requêtes apparaissent ici quand un client ou la conversation Strata utilise l’API.", + "s1444": "Les requêtes, le contexte et la vitesse concernent ce modèle. Les mesures du GPU incluent tout le travail des périphériques sélectionnés.", + "s1445": "Requis ·", + "s1446": "Nécessite une installation de Strata plus récente.", + "s1447": "Recherche", + "s1448": "Réinitialiser", + "s1449": "Rétablir les valeurs par défaut", + "s1450": "La réinitialisation a perdu son état", + "s1451": "La réinitialisation est à revoir", + "s1452": "Revenir aux réglages recommandés", + "s1453": "La réinitialisation fonctionne", + "s1454": "Remettre {0} sur la valeur recommandée", + "s1455": "Redimensionner le panneau d’aperçu", + "s1456": "Aperçu de la préférence de ressources", + "s1457": "Ressources", + "s1458": "Réglages des réponses", + "s1459": "Sections des réglages des réponses", + "s1460": "Responses", + "s1461": "Responses nécessite un modèle natif en cours d’exécution et une version de Strata qui prend en charge cette API. Si besoin, mettez à jour l’installation native dans Paramètres → À propos.", + "s1462": "Les réponses sont des exemples simulés, pas celles d’un vrai modèle.", + "s1463": "Redémarrer le moteur", + "s1464": "Échec du redémarrage", + "s1465": "Le redémarrage n’est pas disponible avec le moteur d’exemple. Enregistrez les réglages pour le prochain chargement.", + "s1466": "Redémarrage indisponible avec le moteur d’exemple", + "s1467": "Restaurer", + "s1468": "Rétablir les valeurs par défaut", + "s1469": "Restaurer le résultat d’origine", + "s1470": "Restaurer le moteur précédent", + "s1471": "Restaurer l’enregistré", + "s1472": "Restaurer les réglages enregistrés", + "s1473": "Restaurer les réglages enregistrés ?", + "s1474": "Restaurer les réglages", + "s1475": "Restaurez d’abord cette tâche.", + "s1476": "Restauré", + "s1477": "Comparaison des résultats", + "s1478": "Résultat prêt · comparez les versions", + "s1479": "Version du résultat", + "s1480": "Reprendre le téléchargement", + "s1481": "Réessayer", + "s1482": "Réessayer le téléchargement", + "s1483": "Réessayer le chargement", + "s1484": "Réessayer l’installation", + "s1485": "Nouvelle tentative…", + "s1486": "Réutilisation non communiquée", + "s1487": "Réutilisé", + "s1488": "Réutilisé depuis le démarrage", + "s1489": "Rétablir", + "s1490": "Relire", + "s1491": "Revoir les réglages recommandés", + "s1492": "Revoir les résultats", + "s1493": "Revoyez les réglages en surbrillance avant de charger.", + "s1494": "Relisez les instructions, puis choisissez une planification.", + "s1495": "Examen des paramètres pris en charge", + "s1496": "Relit un fichier ou un diff : d’abord l’exactitude, puis le style, et signale ses constats avec les numéros de ligne.", + "s1497": "Révision du brouillon enregistré. Suivez le résultat dans la barre latérale. Cet exemple utilise des sorties factices et des vérifications simulées.", + "s1498": "Révision · suivre la progression", + "s1499": "Révision…", + "s1500": "Révision", + "s1501": "Révision rejetée · le meilleur point de départ est conservé.", + "s1502": "Revenir ici", + "s1503": "Ici même, sur votre ordinateur", + "s1504": "Base RoPE", + "s1505": "Mise à l’échelle RoPE", + "s1506": "Revenir à une version antérieure", + "s1507": "Revenir en arrière…", + "s1508": "Le retour en arrière nécessite un moteur précédent enregistré par une version de Strata qui le prend en charge.", + "s1509": "De la place pour les autres applications", + "s1510": "De la place pour votre travail au quotidien", + "s1511": "Place restante inconnue", + "s1512": "Lancez un prompt selon un horaire, ou quand vous en avez besoin.", + "s1513": "JSON de configuration d’exécution", + "s1514": "Lancer le modèle", + "s1515": "Exécuter plusieurs modèles", + "s1516": "Lancer maintenant", + "s1517": "Exécuter sur", + "s1518": "Exécuter selon un horaire", + "s1519": "Impossible de charger les profils d’exécution.", + "s1520": "Réglages d’exécution", + "s1521": "Lancer l’installation", + "s1522": "Lancer le test court", + "s1523": "Lancer le test de vitesse", + "s1524": "Lancez cette tâche pour voir ici son premier résultat.", + "s1525": "Lancer {0} maintenant", + "s1526": "En cours", + "s1527": "En cours…", + "s1528": "Exécute une commande", + "s1529": "S’exécute tant que l’hôte de Strata est ouvert. Exécute les instructions enregistrées avec le modèle chargé.", + "s1530": "Exécution", + "s1531": "Russe", + "s1532": "SSD", + "s1533": "Informations sur le débordement sur SSD", + "s1534": "Débordement sur SSD probable", + "s1535": "Débordement sur SSD probable. Une partie de ce modèle peut être lue depuis le stockage, les réponses peuvent donc être plus lentes.", + "s1536": "Débordement sur SSD · réponses plus lentes", + "s1537": "Mêmes vérifications, deux versions", + "s1538": "Même pool de mémoire que la RAM système", + "s1539": "L’exemple dépasse le contexte, 256 tokens de sortie compris. Choisissez un texte plus court ou augmentez le contexte.", + "s1540": "Image d’exemple · 1200 × 900", + "s1541": "Charge de travail d’exemple", + "s1542": "Échantillonnage", + "s1543": "L’échantillonnage doit être un objet.", + "s1544": "Enregistrer", + "s1545": "Enregistrer la capture d’écran du moniteur", + "s1546": "Enregistrez une configuration pour la réutiliser.", + "s1547": "Enregistrer et redémarrer", + "s1548": "Enregistrer sous un nouveau nom…", + "s1549": "Enregistrer les modifications", + "s1550": "Enregistrer les réglages actuels…", + "s1551": "Enregistrer les journaux", + "s1552": "Enregistrer le nom", + "s1553": "Enregistrer le rapport", + "s1554": "Enregistrer les réglages", + "s1555": "Enregistrer les réglages pour le prochain chargement.", + "s1556": "Enregistrer le brouillon et redémarrer", + "s1557": "Enregistrer l’original", + "s1558": "Enregistrer dans", + "s1559": "Brouillon enregistré", + "s1560": "Enregistré sur l’hôte Strata, jamais dans le stockage du navigateur.", + "s1561": "Impossible de lire les profils d’exécution enregistrés.", + "s1562": "Enregistré en lieu sûr", + "s1563": "Réglages enregistrés", + "s1564": "Réglages enregistrés{0}{1}", + "s1565": "Enregistré. Rechargez le modèle pour appliquer ces réglages. Une sauvegarde de la configuration précédente a été conservée.", + "s1566": "Enregistrement de l’original…", + "s1567": "Enregistrement du premier brouillon avant d’explorer une autre direction.", + "s1568": "Enregistrement…", + "s1569": "Dites bonjour, ou lancez-vous directement.", + "s1570": "Agrandir la navigation et les commandes.", + "s1571": "Planifier votre tâche", + "s1572": "Planifier {0}", + "s1573": "Tâches planifiées", + "s1574": "Planifiée · calcul de la prochaine exécution", + "s1575": "Impossible de préparer la capture d’écran.", + "s1576": "Impossible d’enregistrer la capture d’écran.", + "s1577": "Impossible de charger les icônes de la capture d’écran. Réessayez.", + "s1578": "Faire défiler les onglets d’aperçu vers la gauche", + "s1579": "Faire défiler les onglets d’aperçu vers la droite", + "s1580": "Rechercher dans toutes les conversations", + "s1581": "Rechercher dans les conversations", + "s1582": "Rechercher des conversations, des écrans ou des actions…", + "s1583": "Rechercher des conversations…", + "s1584": "Rechercher des commandes", + "s1585": "Rechercher des paramètres du moteur", + "s1586": "Rechercher un nom ou une clé technique…", + "s1587": "Rechercher des paramètres natifs", + "s1588": "Rechercher des paramètres", + "s1589": "Rechercher des paramètres…", + "s1590": "Rechercher des requêtes", + "s1591": "Rechercher des compétences", + "s1592": "Rechercher des compétences…", + "s1593": "Rechercher des tâches", + "s1594": "Rechercher des tâches…", + "s1595": "Graine", + "s1596": "Sélectionnez un fichier de modèle .gguf. Les dossiers, adaptateurs et projecteurs ne peuvent pas être chargés comme modèle de conversation.", + "s1597": "Sélectionnez un modèle pour voir son contexte et sa vitesse. Les mesures du GPU et de la RAM système sont des mesures partagées de l’hôte.", + "s1598": "Sélectionnez un modèle pour voir le contexte", + "s1599": "Sélectionnez le modèle à lancer.", + "s1600": "Sélectionnez le fichier .gguf du modèle, et non son dossier.", + "s1601": "Sélectionnez la valeur et copiez-la manuellement.", + "s1602": "Sélectionnez cette version pour voir le contexte, la mémoire et les performances.", + "s1603": "Sélectionné", + "s1604": "Sélectionné automatiquement pour ce modèle sur cet ordinateur.", + "s1605": "Envoyer", + "s1606": "Envoyer le message", + "s1607": "Séparez les expressions par des virgules.", + "s1608": "URL du serveur", + "s1609": "Accès au serveur", + "s1610": "L’accès au serveur se gère dans Serveur API", + "s1611": "Serveur API", + "s1612": "Filtre du modèle servi", + "s1613": "Statistiques de la session", + "s1614": "Sessions", + "s1615": "Définir", + "s1616": "Définissez une clé API avant de partager avec d’autres appareils.", + "s1617": "Définissez son URL de base sur", + "s1618": "Définir la clé", + "s1619": "Définissez les combinaisons de touches qui vous conviennent.", + "s1620": "Fixez le résultat voulu", + "s1621": "Configurer Strata", + "s1622": "Configurer une tâche récurrente", + "s1623": "Configurer manuellement", + "s1624": "Configurer votre domaine", + "s1625": "Configuration…", + "s1626": "Paramètres", + "s1627": "Les réglages sont prêts. Chargez le modèle quand vous voulez.", + "s1628": "Réglages de ce modèle. Les valeurs vides utilisent les valeurs par défaut de Strata.", + "s1629": "Nom des réglages", + "s1630": "Réglages enregistrés", + "s1631": "Sections des paramètres", + "s1632": "Contexte de conversation de l’installation", + "s1633": "Objectif de l’installation", + "s1634": "Modèle de l’installation", + "s1635": "Installation requise", + "s1636": "Progression de l’installation", + "s1637": "Partager", + "s1638": "Partager sur Reddit", + "s1639": "Partager sur X", + "s1640": "Partagé", + "s1641": "Mémoire GPU partagée", + "s1642": "RAM partagée après le chargement", + "s1643": "RAM partagée réservée", + "s1644": "Mémoire partagée · pas de liaison PCIe", + "s1645": "Partagé sur le réseau local", + "s1646": "Mémoire système partagée", + "s1647": "Mémoire unifiée partagée", + "s1648": "Partagé avec la RAM", + "s1649": "Le partage télécharge l’image et ouvre un brouillon. Joignez l’image à votre publication.", + "s1650": "Le partage est déjà en cours de démarrage.", + "s1651": "Maj + Entrée ajoute une ligne. Tapez / pour les commandes de conversation. Échap ferme les panneaux.", + "s1652": "Texte court", + "s1653": "Raccourcir le titre et aérer la composition en gardant le style botanique.", + "s1654": "Raccourci encore", + "s1655": "Titre raccourci", + "s1656": "Raccourcit la limite de sortie demandée quand le prompt laisse moins de place.", + "s1657": "Plus court et plus clair", + "s1658": "Plus court n’est pas toujours mieux.", + "s1659": "Afficher", + "s1660": "Afficher la clé API", + "s1661": "Tout afficher ({0})", + "s1662": "Afficher les descriptions", + "s1663": "Afficher moins", + "s1664": "Afficher dans l’explorateur de fichiers", + "s1665": "Afficher moins", + "s1666": "Afficher ou masquer la barre latérale", + "s1667": "Afficher la barre latérale", + "s1668": "Afficher les éléments non pris en charge", + "s1669": "Afficher {0} de plus", + "s1670": "Affichage des 1 000 premiers éléments. Saisissez un chemin pour ouvrir un fichier précis.", + "s1671": "Affichage des 1 000 premières lignes correspondantes.", + "s1672": "Vérifications de comparaison simulées", + "s1673": "Depuis", + "s1674": "Taille", + "s1675": "Sections de l’éditeur de compétences", + "s1676": "Compétence activée", + "s1677": "Portée de la compétence dans l’espace de travail", + "s1678": "Compétences", + "s1679": "Ignorer les demandes d’autorisation", + "s1680": "Commandes slash", + "s1681": "Plus lent · mémoire système", + "s1682": "Petits écrans", + "s1683": "Logiciel", + "s1684": "Logiciel à gérer", + "s1685": "Certains fichiers n’ont pas pu être lus. Essayez de les ajouter séparément.", + "s1686": "Des fichiers du modèle sont manquants. Utilisez Télécharger / réparer pour les restaurer.", + "s1687": "Quelque chose demande votre attention.", + "s1688": "Trier les tâches", + "s1689": "Source", + "s1690": "Espace", + "s1691": "Espace disponible", + "s1692": "Espace restant", + "s1693": "Espacement", + "s1694": "Espagnol", + "s1695": "Parler à nouveau", + "s1696": "Dicter dans la zone de message sans envoyer", + "s1697": "Parlez naturellement. Une pause de 3,5 secondes termine la dictée. Le texte apparaît dans votre zone de message sans être envoyé.", + "s1698": "Précis et ordonné", + "s1699": "La reconnaissance vocale n’est pas disponible dans ce navigateur. Essayez un navigateur compatible avec la dictée.", + "s1700": "La reconnaissance vocale n’est pas disponible dans ce navigateur. Utilisez la dictée intégrée à votre ordinateur.", + "s1701": "Dictée vocale", + "s1702": "Dictée vocale · {0}", + "s1703": "Vitesse", + "s1704": "Historique de vitesse", + "s1705": "Projection de vitesse", + "s1706": "La projection de vitesse doit être activée ou désactivée.", + "s1707": "Aperçu du test de vitesse", + "s1708": "Les vitesses proviennent de chaque instance du moteur. Les mesures manquantes affichent —.", + "s1709": "Les noms de fichiers GGUF fractionnés doivent contenir 00001-of-000NN et correspondre à leurs métadonnées.", + "s1710": "Répartir sur les GPU…", + "s1711": "Standard / système", + "s1712": "Démarrez une nouvelle conversation quand vous voulez.", + "s1713": "Recommencer", + "s1714": "Commencer à répondre", + "s1715": "Lancer la calibration", + "s1716": "Commencer à discuter", + "s1717": "Lancer l’aperçu", + "s1718": "Lancez-le avec `npm run host` puis rechargez la page.", + "s1719": "Démarrer ou arrêter la dictée", + "s1720": "Démarrer le partage", + "s1721": "Démarrez le connecteur pour le domaine que vous avez configuré.", + "s1722": "Partez d’une idée ci-dessous, ou créez la vôtre.", + "s1723": "Démarrer votre première conversation", + "s1724": "Démarrage · 0.5B Q4_K_M", + "s1725": "Démarrage du microphone…", + "s1726": "Démarrage…", + "s1727": "État", + "s1728": "À la pointe. Chez vous.", + "s1729": "Statut", + "s1730": "Statut indisponible", + "s1731": "Statut :", + "s1732": "Étape", + "s1733": "Tient toujours", + "s1734": "Arrêter", + "s1735": "Arrêter le test", + "s1736": "Arrêtez le partage local et Cloudflare avant de retirer la clé API.", + "s1737": "Arrêter le partage", + "s1738": "Arrêtez le test avant de décharger ce modèle.", + "s1739": "Arrêtez l’exécution en cours avant de modifier.", + "s1740": "Arrêtez le tunnel en cours avant d’en démarrer un autre.", + "s1741": "Arrêtez le serveur natif qui tourne hors de cette interface avant d’optimiser.", + "s1742": "Arrêtez le serveur natif qui tourne hors de cette interface avant de modifier les fichiers du moteur.", + "s1743": "Arrêtez le serveur natif qui tourne hors de cette interface avant de préparer les fichiers.", + "s1744": "Arrêtez cette tâche avant de la supprimer", + "s1745": "Arrêter l’optimisation", + "s1746": "Arrêter le tunnel", + "s1747": "Arrêter {0}", + "s1748": "Arrêté", + "s1749": "Arrêt du tunnel…", + "s1750": "Arrêt…", + "s1751": "Stockage", + "s1752": "Réglages du stockage", + "s1753": "Strata", + "s1754": "Strata peut maintenant lire les fichiers de {0}.", + "s1755": "Le contrôle de Strata s’est arrêté. Python 3.10 ou plus récent est requis.", + "s1756": "Strata n’a pas pu afficher cet écran", + "s1757": "Strata télécharge et configure le connecteur Cloudflare pour vous.", + "s1758": "Dossier Strata", + "s1759": "Police de Strata", + "s1760": "Dossier d’installation de Strata", + "s1761": "Strata n’est pas connecté à son moteur.", + "s1762": "Modèles optimisés par Strata", + "s1763": "Strata prépare tous les fragments, la couche de brouillon et les fichiers partagés. Les téléchargements terminés sont réutilisés.", + "s1764": "Strata n’envoie aucune télémétrie d’utilisation. Les conversations restent dans le stockage du navigateur. Quand vous choisissez un modèle API, cette conversation et les instructions des compétences activées sont envoyées à son fournisseur. Le journal des requêtes de l’interface garde en mémoire le client, les durées et les métadonnées de tokens. La surveillance de l’API native peut conserver le contenu des requêtes en mémoire lorsqu’elle est activée. Les outils connectés accèdent aux ressources que vous configurez.", + "s1765": "Strata utilise ces fichiers sur place. Vous pourrez charger le modèle après l’avoir ajouté.", + "s1766": "Strata — ouvrir la conversation", + "s1767": "Budget de Strata", + "s1768": "Échec du flux ({0})", + "s1769": "Version la plus solide conservée", + "s1770": "Structure en place", + "s1771": "Structure conservée", + "s1772": "Aperçu des sous-agents", + "s1773": "Sous-agents", + "s1774": "Les sous-agents lancés dans cette conversation apparaissent ici, avec leur progression, leur utilisation de tokens et leur durée. Les exécutions terminées restent visibles.", + "s1775": "Sous-agents — afficher la vue d’ensemble", + "s1776": "Vérification de réussite", + "s1777": "Suggérer une tâche", + "s1778": "Pris en charge", + "s1779": "Pris en charge, lecture du prompt plus lente", + "s1780": "Swift 1.5", + "s1781": "Basculer toutes les conversations sur {0} ({1}). Le chargement peut prendre quelques instants.", + "s1782": "Passer à", + "s1783": "Passez à un modèle local avec Lire les images activé, ou retirez les pièces jointes.", + "s1784": "Passer en mode sombre", + "s1785": "Passer au thème sombre", + "s1786": "Passer en mode clair", + "s1787": "Passer au thème clair", + "s1788": "Passer à {0} ?", + "s1789": "Changer de version", + "s1790": "Changer de version ?", + "s1791": "Système", + "s1792": "RAM système", + "s1793": "Budget système de {0} Go compté à part ; l’utilisation supplémentaire de l’hôte n’est pas estimée.", + "s1794": "Mémoire système", + "s1795": "Le budget de mémoire système réserve de la place pour le système d’exploitation.", + "s1796": "Jetez un œil pendant que nous préparons tout.", + "s1797": "On retient la direction la plus solide.", + "s1798": "Tâche supprimée", + "s1799": "Idées de tâches", + "s1800": "Tâche introuvable.", + "s1801": "Résultat de la tâche", + "s1802": "Étapes de configuration de la tâche", + "s1803": "Tâches", + "s1804": "Apprenez-moi une notion utile de statistiques. Ajoutez un exemple simple et une question pour vérifier ma compréhension.", + "s1805": "Température", + "s1806": "Adresse temporaire · désactivez le streaming dans votre client.", + "s1807": "Répartition des tenseurs", + "s1808": "Le texte est dans votre zone de message. Relisez-le avant de l’envoyer.", + "s1809": "Ce fichier n’existe plus.", + "s1810": "Ce fichier est en dehors de l’espace de travail.", + "s1811": "Ce dossier n’existe pas.", + "s1812": "Ce dossier ne contient pas de SKILL.md, le modèle n’a donc rien à lire. Un dossier de compétence contient un fichier SKILL.md avec ses instructions.", + "s1813": "Ce dossier est déjà dans vos espaces de travail.", + "s1814": "Cet ID de modèle n’est pas chargé. Choisissez-en un dans /v1/models.", + "s1815": "Ce nom de serveur est déjà utilisé.", + "s1816": "C’est un fichier, pas un dossier.", + "s1817": "C’est un dossier, pas un fichier.", + "s1818": "Le fichier GGUF est incomplet. Téléchargez tous ses poids avant de l’ajouter.", + "s1819": "L’en-tête GGUF est tronqué ou dépasse la taille de métadonnées prise en charge.", + "s1820": "L’environnement Python de Strata est introuvable. Utilisez d’abord Télécharger / réparer.", + "s1821": "Le service vocal du navigateur n’a pas pu se connecter. Vérifiez votre connexion ou essayez un autre navigateur.", + "s1822": "Le candidat ajoute du détail sans perdre l’idée d’origine.", + "s1823": "L’ordinateur sera occupé pendant environ 5 à 15 minutes. Déchargez d’abord les modèles.", + "s1824": "Le connecteur n’a pas pu être téléchargé. Vérifiez votre connexion et réessayez.", + "s1825": "Le connecteur n’a pas pu être préparé automatiquement.", + "s1826": "Le connecteur n’a pas pu être préparé automatiquement. Relancez la configuration du connecteur.", + "s1827": "Le téléchargement du connecteur n’a pas pu être vérifié. Relancez la configuration automatique.", + "s1828": "Le téléchargement du connecteur est anormalement volumineux.", + "s1829": "Le paquet du connecteur contenait un exécutable non valide.", + "s1830": "Le paquet du connecteur ne contenait pas l’exécutable attendu.", + "s1831": "Le cache de contexte et l’exécution doivent tenir dans la RAM ou la mémoire du GPU.", + "s1832": "Le modèle actuellement chargé peut différer de celui qui a répondu aux messages précédents.", + "s1833": "Le dossier de modèles par défaut est en conflit avec une autre bibliothèque. Choisissez un autre dossier.", + "s1834": "Le modèle d’image téléchargé n’a pas passé la vérification. Relancez le téléchargement.", + "s1835": "Le moteur ne s’est pas relancé.", + "s1836": "Le moteur ne tourne pas. Chargez un modèle avant d’appliquer les réglages.", + "s1837": "Le moteur a renvoyé une liste de modèles incomplète. Relancez l’opération.", + "s1838": "Le moteur indique toujours cette instance du modèle comme chargée.", + "s1839": "La mémoire estimée nécessaire dépasse celle de cet ordinateur.", + "s1840": "Le premier fragment est manquant ou non valide. Gardez tous les fragments du modèle dans le même dossier.", + "s1841": "Le premier espace de travail ne peut pas être retiré.", + "s1842": "Le parcours est prêt. Les vitesses restent non mesurées tant qu’aucun adaptateur de test local n’est connecté.", + "s1843": "L’hôte est en cours d’arrêt.", + "s1844": "Le fichier du modèle d’image est plus gros que prévu.", + "s1845": "La révision suivante supprime le sous-titre utile. Gardez la couverture complète.", + "s1846": "Le modèle chargé sera déchargé.", + "s1847": "La configuration du modèle est en dehors de l’installation de Strata.", + "s1848": "Le modèle n’a pas pu être chargé.", + "s1849": "Le modèle n’a pas fini de se charger.", + "s1850": "Le modèle ne s’est pas chargé.", + "s1851": "Le modèle n’a pas renvoyé de brouillon utilisable. Réessayez ou configurez manuellement.", + "s1852": "Les fichiers du modèle n’ont pas été supprimés.", + "s1853": "Le modèle n’a renvoyé aucune réponse.", + "s1854": "Les fragments du modèle ne forment pas un ensemble cohérent. Retéléchargez le fragment manquant ou différent.", + "s1855": "Le modèle sera retiré de Strata.", + "s1856": "Le modèle sera déchargé puis retiré de Strata.", + "s1857": "Le moteur natif n’a pas répondu à temps. Consultez les journaux du moteur.", + "s1858": "L’installation native doit utiliser le dépôt officiel de Strata pour se mettre à jour ici.", + "s1859": "L’installateur natif peut restaurer son moteur précédent. Les fichiers des modèles restent en place.", + "s1860": "L’installateur natif met à jour l’installation. Les fichiers des modèles et les réglages sont conservés. Déchargez les modèles natifs avant la mise à jour.", + "s1861": "La nouvelle révision est concise, mais perd un détail utile.", + "s1862": "L’opération n’a pas pu se terminer. Vérifiez la connexion au moteur et réessayez.", + "s1863": "Les fichiers GGUF d’origine sont conservés.", + "s1864": "L’original reste toujours disponible.", + "s1865": "L’original est enregistré. Le nouveau résultat apparaîtra ici quand il sera prêt à être comparé.", + "s1866": "L’original reste disponible.", + "s1867": "Le vrai moteur d’inférence est indisponible. Chargez un modèle et réessayez.", + "s1868": "Le service de versions a renvoyé une réponse non valide.", + "s1869": "Le résultat est prêt. Passez de l’original à la version mise à jour, ou comparez-les côte à côte. Cet exemple utilise des sorties factices et des vérifications simulées.", + "s1870": "Le modèle en cours d’exécution sera déchargé et ses fichiers supprimés.", + "s1871": "L’exemple ou le contexte n’est pas pris en charge par cette configuration.", + "s1872": "La boîte de dialogue d’enregistrement n’a pas pu s’ouvrir. Essayez d’enregistrer à nouveau la capture d’écran.", + "s1873": "La mise à jour enregistrée reste disponible.", + "s1874": "Le modèle sélectionné", + "s1875": "La révision plus courte casse la réinitialisation. Gardez les commandes fonctionnelles de B.", + "s1876": "La révision plus courte supprime une étape utile. Gardez la version complète de B.", + "s1877": "La version la plus solide est conservée.", + "s1878": "Le token sert uniquement à cette connexion et n’est pas enregistré.", + "s1879": "Le tunnel est en cours de mise à jour. Réessayez dans un instant.", + "s1880": "Le service de mise à jour a renvoyé un résultat incomplet.", + "s1881": "Le résultat mis à jour est prêt. Passez de l’original à la version mise à jour, ou comparez-les côte à côte. Cet exemple utilise des sorties factices et des vérifications simulées.", + "s1882": "Le résultat mis à jour reste disponible.", + "s1883": "La version n’a pas pu se charger. Réessayez quand le moteur sera prêt.", + "s1884": "Leur mémoire (RAM)", + "s1885": "Il n’y a pas assez de stockage libre pour ce modèle d’image.", + "s1886": "Il n’y a pas assez d’espace libre pour télécharger ce modèle.", + "s1887": "Ces fragments déclarent des architectures différentes.", + "s1888": "Réflexion", + "s1889": "Réflexion et rédaction", + "s1890": "Budget de tokens de réflexion", + "s1891": "Cette API n’a renvoyé aucun modèle. Ajoutez un ID de modèle ci-dessous.", + "s1892": "Ce GGUF n’inclut pas son tokenizer. Choisissez le modèle complet, pas un projecteur ni un adaptateur.", + "s1893": "Ce format de tenseur GGUF n’est pas encore pris en charge par l’importateur.", + "s1894": "Cette version de GGUF ou cet ordre des octets n’est pas pris en charge.", + "s1895": "Cette copie de Strata contient des modifications locales. Enregistrez-les ou validez-les avant de mettre à jour.", + "s1896": "Cette action est indisponible.", + "s1897": "Cet adaptateur ne peut pas appliquer les réglages de lot de prompts.", + "s1898": "Cet alias correspond à plusieurs instances. Choisissez l’ID exact du modèle.", + "s1899": "Ce navigateur n’offre pas de reconnaissance vocale. Utilisez la dictée intégrée à votre ordinateur dans la zone de message.", + "s1900": "Cette conversation sera supprimée définitivement.", + "s1901": "Cet ordinateur", + "s1902": "Cette configuration a besoin de plus de mémoire résidente. Revoyez le mappage mémoire ou choisissez une version plus petite.", + "s1903": "Cette conversation", + "s1904": "Ce moteur ne peut pas encore exécuter de modèles d’images. Choisissez Désactivé pour lancer le modèle de conversation.", + "s1905": "Ce fichier ne peut pas être ouvert.", + "s1906": "Ce fichier n’est pas un aperçu local.", + "s1907": "Ce fichier ou ce dossier est indisponible. Vérifiez son emplacement et ses autorisations.", + "s1908": "Ce type de fichier ne peut pas être ouvert depuis un aperçu.", + "s1909": "Ce dossier est indisponible ou protégé en écriture. Vérifiez le chemin et les autorisations du dossier.", + "s1910": "Cette installation ne calibre que les GPU NVIDIA. Utilisez le test court sur les autres appareils.", + "s1911": "Cette installation n’a pas de numéro de version comparable.", + "s1912": "C’est un adaptateur ou un fichier auxiliaire. Choisissez le GGUF du modèle complet.", + "s1913": "Ce n’est qu’un avertissement : le modèle risque d’être plus lent à cause du déchargement sur le SSD.", + "s1914": "Ce n’est pas un fichier de modèle GGUF.", + "s1915": "Cette API locale n’a pas de clé configurée.", + "s1916": "Ce média n’a pas pu se charger.", + "s1917": "Ce modèle ne tient pas dans la configuration choisie.", + "s1918": "Les métadonnées d’attention ou d’experts de ce modèle ne sont pas valides.", + "s1919": "Il manque des tenseurs ou des fragments à ce modèle.", + "s1920": "Ce modèle n’est plus chargé.", + "s1921": "Ce modèle n’est pas installé. Téléchargez-le et préparez-le d’abord.", + "s1922": "Ce modèle n’est pas prêt.", + "s1923": "Ce modèle a besoin d’un moteur plus récent.", + "s1924": "Ce modèle a besoin d’environ {0} Go.{1}", + "s1925": "Ce modèle prend en charge jusqu’à", + "s1926": "Cette version du modèle est indisponible.", + "s1927": "Ce modèle a été déchargé avant l’envoi.", + "s1928": "Cet hôte natif prend actuellement en charge un seul modèle avec placement automatique sur le GPU.", + "s1929": "Cet hôte natif prend en charge un seul modèle avec placement automatique sur le GPU.", + "s1930": "Cette opération n’est plus en cours.", + "s1931": "Cette image n’a pas pu être enregistrée.", + "s1932": "Ce port privé du moteur est déjà utilisé.", + "s1933": "Cet hôte ne peut pas annuler cette requête.", + "s1934": "Cette requête n’est plus conservée dans le journal de session.", + "s1935": "Cette requête n’est plus conservée.", + "s1936": "Cette configuration ne peut pas faire tenir son contexte et son exécution dans la mémoire disponible. Réduisez le contexte ou utilisez une version plus petite.", + "s1937": "Ce modèle fractionné a un nombre de fragments non pris en charge.", + "s1938": "Cela change la version du modèle pour toutes les conversations. Vos conversations restent enregistrées.", + "s1939": "Cela fait passer cette conversation en mode Ignorer les autorisations. Serveurs :", + "s1940": "Ce fichier texte est trop volumineux pour être prévisualisé.", + "s1941": "Cela prend en général quelques secondes. Vous pouvez fermer cette fenêtre pendant la connexion.", + "s1942": "Cette version n’est plus téléchargée.", + "s1943": "Cette version a besoin de plus de mémoire avec le contexte actuel. Choisissez une version plus petite ou réduisez le contexte dans Moteur.", + "s1944": "Ce site web n’a pas de fichier local", + "s1945": "Cet espace de travail", + "s1946": "Trois tâches qui avancent ensemble", + "s1947": "Juste — choisissez la plus petite variante", + "s1948": "Heure", + "s1949": "Time-skip", + "s1950": "Actions Time-skip", + "s1951": "Time-skip {0}", + "s1952": "Vers le GPU {0} Mo/s{1}", + "s1953": "Tok/s", + "s1954": "Utilisation des tokens", + "s1955": "Tokens en entrée / sortie", + "s1956": "Tokens de la requête en cours ou de la dernière requête de ce modèle.", + "s1957": "Demain est déjà planifié", + "s1958": "Trop gros", + "s1959": "Trop gros pour ce PC", + "s1960": "Trop général", + "s1961": "Activité des outils ·", + "s1962": "L’exécution des outils n’est pas connectée dans cette version. Les propositions et approbations enregistrées sont des exemples. La disponibilité n’accorde aucune autorisation.", + "s1963": "Temps des outils", + "s1964": "Délai d’attente des outils (secondes)", + "s1965": "Outils", + "s1966": "Outils et longs prompts", + "s1967": "Top-k", + "s1968": "Top-p", + "s1969": "Total sur les GPU sélectionnés", + "s1970": "Total dans cette conversation", + "s1971": "Mémoire totale", + "s1972": "Capacité physique totale de la RAM et de tous les GPU dédiés. Le placement du modèle détermine comment elle est utilisée.", + "s1973": "Total de tokens", + "s1974": "Transfert total vers les GPU sélectionnés", + "s1975": "Sujet de la visite", + "s1976": "Transfert vers le GPU indisponible", + "s1977": "Translucide", + "s1978": "Commandes translucides ou surfaces pleines. Le texte reste opaque.", + "s1979": "Transparence", + "s1980": "Phrases déclencheuses", + "s1981": "Essayez /time-skip, ou chargez un modèle pour discuter…", + "s1982": "Réessayer", + "s1983": "Essayez un autre filtre ou un autre nom de client.", + "s1984": "Essayez une autre recherche.", + "s1985": "Essayez ceci dans Strata", + "s1986": "Essayez deux versions et gardez la meilleure", + "s1987": "Essai d’une nouvelle direction", + "s1988": "Nouvel essai de révision. Votre progression est enregistrée.", + "s1989": "Optimiser et commencer à discuter", + "s1990": "Optimiser le modèle", + "s1991": "Optimisé pour votre ordinateur", + "s1992": "Optimisation arrêtée. Vos fichiers de modèle sont intacts.", + "s1993": "Optimisation…", + "s1994": "Token du tunnel", + "s1995": "Tournez le cadran · ou utilisez les flèches", + "s1996": "Transformez vos notes en plan de matinée ciblé.", + "s1997": "Tours / appels d’outils", + "s1998": "Transforme les commits fusionnés en notes de version destinées aux utilisateurs, regroupées par nouveauté, correctif et changement majeur.", + "s1999": "Deux passes. Une amélioration utile. L’original est toujours là.", + "s2000": "Deux directions possibles.", + "s2001": "Tapez /loop pour ouvrir les Tâches. Choisissez une tâche, fixez sa planification et laissez Strata la répéter, comme un point quotidien chaque jour de la semaine à 8 h.", + "s2002": "Tapez /time-skip et ce que vous voulez améliorer. Strata explore une révision, la compare à l’original et garde la meilleure version.", + "s2003": "Indisponible", + "s2004": "Comprend les photos et les captures d’écran. Les fichiers de vision sont déjà téléchargés.", + "s2005": "Comprend les photos, les captures d’écran et les graphiques. Les fichiers de vision se téléchargent automatiquement. Activez-les au chargement de ce modèle.", + "s2006": "Annuler", + "s2007": "Unifiée", + "s2008": "Mémoire unifiée", + "s2009": "Action de contrôle native inconnue.", + "s2010": "Action de tunnel inconnue.", + "s2011": "Décharger", + "s2012": "Déchargez un modèle avant d’en ajouter un autre. Cet aperçu prend en charge huit instances.", + "s2013": "Décharger après N secondes d’inactivité", + "s2014": "Déchargez une instance avant d’en ajouter une autre. Jusqu’à huit instances natives peuvent tourner ici.", + "s2015": "Décharger et changer de dossier", + "s2016": "Déchargez toutes les instances de ce modèle avant de supprimer ses fichiers.", + "s2017": "Échec du déchargement", + "s2018": "Décharger le modèle", + "s2019": "Déchargez les modèles et terminez les opérations avant de modifier l’installation.", + "s2020": "Déchargez les modèles natifs avant de modifier les fichiers du moteur.", + "s2021": "Déchargez les modèles natifs avant de changer le dossier des modèles.", + "s2022": "Déchargez les modèles actuels avant de changer de dossier.", + "s2023": "Déchargez ce modèle local avant de remplacer la référence de son fichier.", + "s2024": "Déchargez ce modèle avant de supprimer ses fichiers.", + "s2025": "Déchargez d’abord cette version", + "s2026": "Décharger {0} instances", + "s2027": "Déchargement…", + "s2028": "Détacher", + "s2029": "Non lu", + "s2030": "Mesures du moteur non reconnues", + "s2031": "Modifications non enregistrées", + "s2032": "Unsloth", + "s2033": "Non pris en charge", + "s2034": "Opération native non prise en charge.", + "s2035": "Dossier parent", + "s2036": "À jour", + "s2037": "Mettre à jour", + "s2038": "Mettre à jour Strata", + "s2039": "Mettre à jour Strata ?", + "s2040": "Mise à jour disponible", + "s2041": "Mettre à jour le moteur", + "s2042": "Mettre à jour le moteur ?", + "s2043": "La mise à jour a passé les vérifications d’exemple", + "s2044": "Mise à jour prête à être vérifiée", + "s2045": "Mettre à jour les réglages enregistrés", + "s2046": "Mettre à jour les réglages", + "s2047": "Mettez à jour l’installation native de Strata pour utiliser l’API Responses.", + "s2048": "Mettez à jour votre moteur ou importez un GGUF local pour ce modèle.", + "s2049": "Mis à jour", + "s2050": "Couverture Fieldnotes mise à jour : Make room for ideas, avec plus d’espace libre autour du titre.", + "s2051": "Résultat mis à jour conservé", + "s2052": "Mise à jour…", + "s2053": "Tableau de bord d’utilisation", + "s2054": "Période d’utilisation", + "s2055": "Source d’utilisation", + "s2056": "Utilisation indisponible", + "s2057": "Vue d’utilisation", + "s2058": "Utilisez Commande/Ctrl avec une lettre, un chiffre ou un signe de ponctuation.", + "s2059": "Utilisez Entrée ou Commande/Ctrl + Entrée. Maj + Entrée reste disponible pour une nouvelle ligne.", + "s2060": "Utilisez des variables d’environnement STRATA_ avec des valeurs de texte.", + "s2061": "Utilisez Strata en naviguant, en écrivant ou en travaillant.", + "s2062": "Utiliser une police de votre ordinateur", + "s2063": "Utiliser un GGUF local…", + "s2064": "Utiliser un modèle local", + "s2065": "Utiliser un modèle local…", + "s2066": "Utilisez un ID de modèle de /v1/models.", + "s2067": "Utilisez un nom de serveur simple : lettres, chiffres, tirets ou tirets bas.", + "s2068": "Utilisez un nom de tâche de 1 à 120 caractères.", + "s2069": "Utilisez un objet avec une entrée par serveur d’outils.", + "s2070": "Utiliser par défaut pour ce modèle", + "s2071": "Utiliser les outils MCP connectés", + "s2072": "Utilisez ici env, headers et cwd. Les identifiants existants sont masqués et conservés si vous gardez le masque.", + "s2073": "Utiliser les performances maximales", + "s2074": "Utiliser dans la conversation", + "s2075": "Utilisez des instructions de 1 à 12 000 caractères.", + "s2076": "Utilisez l’intelligence comme vous l’entendez.", + "s2077": "Utiliser l’ID du modèle", + "s2078": "Utiliser ma propre clé", + "s2079": "Utiliser un seul GPU quand le modèle y tient", + "s2080": "Utilisez l’adresse API du serveur. Pour un autre PC, saisissez son adresse réseau au lieu de localhost.", + "s2081": "Utilisez cette adresse et votre clé API Strata dans votre autre application.", + "s2082": "Utiliser ce dossier", + "s2083": "Utiliser ce dossier", + "s2084": "Utilisez ce nom d’hôte et votre clé API Strata dans votre client. Le streaming est pris en charge.", + "s2085": "Utiliser cette clé", + "s2086": "Utiliser ce modèle", + "s2087": "Utiliser cette version", + "s2088": "Utilisez jusqu’à 32 phrases déclencheuses, de 160 caractères maximum chacune.", + "s2089": "Utiliser la version", + "s2090": "Utilisez votre clé existante dans l’application que vous connectez.", + "s2091": "Utilisé au prochain chargement de ce modèle. Les valeurs d’échantillonnage par défaut s’appliquent à la prochaine requête.", + "s2092": "Sous-titre utile perdu", + "s2093": "Utilise le service vocal de votre navigateur.", + "s2094": "Utilise vos réglages enregistrés", + "s2095": "VRAM", + "s2096": "Taux de réussite en VRAM", + "s2097": "Valider le brouillon", + "s2098": "Version", + "s2099": "Actions sur la version", + "s2100": "Détails de la version", + "s2101": "Version indisponible", + "s2102": "Très élevé", + "s2103": "Vidéo", + "s2104": "Voir toutes les conversations", + "s2105": "Voir et changer de modèle", + "s2106": "Voir les journaux du moteur", + "s2107": "Voir le dernier résultat", + "s2108": "Voir le journal", + "s2109": "Voir les versions du modèle", + "s2110": "Voir le journal des requêtes", + "s2111": "Voir la requête {0}", + "s2112": "Voir les requêtes", + "s2113": "Voir la vue d’ensemble des sous-agents", + "s2114": "Voir la révision rejetée", + "s2115": "Les fichiers de l’encodeur de vision sont inclus. La lecture d’images ne se charge que si elle est activée.", + "s2116": "Style visuel", + "s2117": "Style visuel conservé", + "s2118": "Attendez la fin de la vérification du dossier des modèles.", + "s2119": "Attendez que ce modèle ait terminé avant de lancer un test.", + "s2120": "En attente de l’état de l’API…", + "s2121": "En attente d’une requête", + "s2122": "En attente de la télémétrie du moteur…", + "s2123": "Préchauffer", + "s2124": "Le préchauffage prend quelques secondes.", + "s2125": "Nous réservons de la mémoire GPU et limitons les workers d’experts CPU pour laisser de la marge aux autres applications. L’utilisation réelle varie selon votre modèle. Les besoins en RAM du modèle et les réserves de sécurité du système s’appliquent toujours.", + "s2126": "Adresse du site web", + "s2127": "Les sites web s’ouvrent dans votre navigateur par défaut.", + "s2128": "Jours de semaine", + "s2129": "Bilan hebdomadaire", + "s2130": "Bienvenue", + "s2131": "Nous appliquerons votre préférence et lancerons un court test de vitesse.", + "s2132": "Nous ouvrirons la conversation quand votre modèle sera prêt.", + "s2133": "Nous mesurons, appliquons votre préférence et préparons la conversation.", + "s2134": "Ce qui a changé", + "s2135": "Par quoi commençons-nous ?", + "s2136": "Que voulez-vous que Strata fasse ?", + "s2137": "Travaillez aux côtés de votre modèle", + "s2138": "Dérouler le plan", + "s2139": "Mise à jour en cours", + "s2140": "Travailler ensemble", + "s2141": "En cours…", + "s2142": "Espace de travail ajouté", + "s2143": "Espaces de travail", + "s2144": "Rédiger les récits du projet", + "s2145": "Écriture {0} Mo/s", + "s2146": "Écritures", + "s2147": "Rédige des messages de commit conventionnels à partir d’un diff, avec une ligne de portée et un paragraphe sur le pourquoi.", + "s2148": "Entraînement à l’écriture", + "s2149": "Vous pourrez toujours changer de modèles plus tard.", + "s2150": "Vous disposez de {0} Go libres.", + "s2151": "Il vous faut plus de stockage.", + "s2152": "Votre CPU", + "s2153": "Votre connecteur Cloudflare est installé et prêt.", + "s2154": "Votre route Cloudflare doit pointer vers {0}.", + "s2155": "Votre GPU", + "s2156": "Votre navigateur ne peut pas lister les polices installées. Saisissez le nom d’une police installée sur votre ordinateur.", + "s2157": "Le service vocal de votre navigateur ne prend pas en charge cette langue.", + "s2158": "Votre choix :", + "s2159": "Votre ordinateur", + "s2160": "Votre ordinateur peut sembler plus lent pendant le chargement des poids. Vous pouvez arrêter le téléchargement et le reprendre plus tard.", + "s2161": "Votre conversation et vos brouillons sont conservés pendant la reconnexion.", + "s2162": "Votre nom d’hôte", + "s2163": "Votre API d’inférence est accessible aux appareils de ce réseau.", + "s2164": "Votre installation locale de Strata gère les modèles optimisés, les fichiers complémentaires et les mises à jour du moteur.", + "s2165": "Votre modèle local reste disponible. Ajoutez une connexion API pour utiliser plus de modèles dans Strata.", + "s2166": "Votre modèle", + "s2167": "Votre dossier de modèles", + "s2168": "Vos modèles sont enregistrés ici. Utilisez un dossier existant pour réutiliser les téléchargements pris en charge.", + "s2169": "Votre nouvelle clé", + "s2170": "Votre ancienne clé cessera de fonctionner.", + "s2171": "Votre propre clé", + "s2172": "Vos conversations et vos réglages enregistrés sont toujours disponibles.", + "s2173": "Vous êtes connecté", + "s2174": "Zéro garde le modèle chargé.", + "s2175": "\\ -H 'Authorization: Bearer YOUR_API_KEY'", + "s2176": "accent", + "s2177": "actif", + "s2178": "actif ·", + "s2179": "réel", + "s2180": "avancé", + "s2181": "ai.example.com", + "s2182": "tout", + "s2183": "un autre espace de travail", + "s2184": "réponse", + "s2185": "vitesse de réponse", + "s2186": "api server endpoint openai anthropic port API serveur point d’accès port", + "s2187": "appearance colours apparence couleurs", + "s2188": "artifact-content", + "s2189": "croissant", + "s2190": "attribué", + "s2191": "à {0} tok/s", + "s2192": "auto", + "s2193": "auto ou 16,32", + "s2194": "auto, ou des points de répartition croissants comme 18 ou 16,32.", + "s2195": "débutant", + "s2196": "éclair", + "s2197": "branche", + "s2198": "brand brand--{0} {1}", + "s2199": "occupé", + "s2200": "button:not([disabled])", + "s2201": "cache ·", + "s2202": "calc(100dvh - {0}px)", + "s2203": "modification", + "s2204": "modifications", + "s2205": "chat", + "s2206": "chat, programmation", + "s2207": "chat:send", + "s2208": "chat:slot:", + "s2209": "vérification", + "s2210": "horloge", + "s2211": "code", + "s2212": "code-preview", + "s2213": "colonnes", + "s2214": "confortable", + "s2215": "commande", + "s2216": "compact", + "s2217": "terminé", + "s2218": "terminés ·", + "s2219": "ordinateur", + "s2220": "config-errors", + "s2221": "de contexte. Modifiez le contexte sur la page Modèle.", + "s2222": "réduire", + "s2223": "conversation prompt ask discussion prompt demander", + "s2224": "copier", + "s2225": "cœurs ·", + "s2226": "compteur", + "s2227": "CPU", + "s2228": "curl", + "s2229": "personnalisé", + "s2230": "valeurs personnalisées", + "s2231": "danger", + "s2232": "sombre", + "s2233": "décimal", + "s2234": "exemple", + "s2235": "refusé", + "s2236": "décroissant", + "s2237": "bureau", + "s2238": "détails", + "s2239": "dial-detent", + "s2240": "dial-detent dial-detent--recommended", + "s2241": "dialog", + "s2242": "dialog-surface", + "s2243": "dialog-surface dialog-surface--sheet", + "s2244": "dialog-surface--compact", + "s2245": "dialog-surface--wide", + "s2246": "dictation-feedback", + "s2247": "disque", + "s2248": "ne tient pas", + "s2249": "domaine", + "s2250": "terminé", + "s2251": "télécharger", + "s2252": "download weights gguf choose tune engine parameters context sampling télécharger poids gguf choisir optimiser moteur paramètres contexte échantillonnage", + "s2253": "eject stop vram éjecter arrêter vram", + "s2254": "fin", + "s2255": "moteur", + "s2256": "erreur du moteur", + "s2257": "erreur", + "s2258": "échap", + "s2259": "développer", + "s2260": "expert", + "s2261": "experts", + "s2262": "family-qwen", + "s2263": "rapide", + "s2264": "fichier", + "s2265": "fichiers ou recherche", + "s2266": "tient", + "s2267": "dossier", + "s2268": "pour les commandes,", + "s2269": "pour les conversations,", + "s2270": "pour les espaces de travail.", + "s2271": "libre", + "s2272": "depuis l’écran Modèles après le chargement", + "s2273": "complet", + "s2274": "génération", + "s2275": "génération · {0} tok/s", + "s2276": "go:models", + "s2277": "go:monitor", + "s2278": "go:tasks", + "s2279": "bon", + "s2280": "groupe", + "s2281": "matériel", + "s2282": "élevé", + "s2283": "inactif", + "s2284": "image", + "s2285": "image:select", + "s2286": "img", + "s2287": "dans chaque requête. Chaque modèle a sa propre file d’attente.", + "s2288": "dans cette bibliothèque d’exemple", + "s2289": "entrée ·", + "s2290": "info", + "s2291": "entrée · 256 en sortie ·", + "s2292": "input:not(:disabled),button:not(:disabled)", + "s2293": "input:not([disabled])", + "s2294": "instantané", + "s2295": "instructions", + "s2296": "instructions prompts abilities consignes prompts compétences", + "s2297": "est calibré. L’installateur enregistre les réglages mesurés à la fin.", + "s2298": "est une mémoire rapide. L’adéquation réelle", + "s2299": "est une mémoire rapide. L’adéquation réelle et le comportement de déchargement", + "s2300": "is-open", + "s2301": "à l’instant", + "s2302": "keys bindings help touches raccourcis aide", + "s2303": "dernier", + "s2304": "launch-plan", + "s2305": "couches", + "s2306": "quitter", + "s2307": "clair", + "s2308": "lien", + "s2309": "chargement", + "s2310": "markdown", + "s2311": "moyen", + "s2312": "un message est requis", + "s2313": "micro", + "s2314": "milieu", + "s2315": "mobile", + "s2316": "mode", + "s2317": "modèle", + "s2318": "fichiers du modèle ·", + "s2319": "version du modèle", + "s2320": "model-file", + "s2321": "modèles", + "s2322": "lune", + "s2323": "plusieurs", + "s2324": "non", + "s2325": "aucun modèle chargé", + "s2326": "aucun", + "s2327": "noopener,noreferrer", + "s2328": "normal", + "s2329": "maintenant", + "s2330": "npx, uvx ou python", + "s2331": "nombre", + "s2332": "numérique", + "s2333": "sur", + "s2334": "sur une limite de {0} W", + "s2335": "désactivé", + "s2336": "activé", + "s2337": "onboard-art onboard-art--{0}", + "s2338": "onboard-tour-preview preview-{0}", + "s2339": "original", + "s2340": "sortie", + "s2341": "vue d’ensemble", + "s2342": "page", + "s2343": "mot de passe", + "s2344": "PDF", + "s2345": "pdfjs-dist/build/pdf.worker.min.mjs?url", + "s2346": "crayon", + "s2347": "en attente", + "s2348": "plus", + "s2349": "preferences theme appearance text size préférences thème apparence taille du texte", + "s2350": "préparer", + "s2351": "préparation des résultats", + "s2352": "principal", + "s2353": "project-brief.md", + "s2354": "project-brief.pdf", + "s2355": "tokens du prompt", + "s2356": "lecture du prompt", + "s2357": "px", + "s2358": "en file d’attente", + "s2359": "en file d’attente ·", + "s2360": "rapide", + "s2361": "radio", + "s2362": "radiogroup", + "s2363": "lecture à {0} tok/s", + "s2364": "lecture", + "s2365": "lecture du prompt", + "s2366": "prêt", + "s2367": "reboot refresh redémarrer actualiser", + "s2368": "actualiser", + "s2369": "release-plan.csv", + "s2370": "requests reused prompt tokens requêtes tokens du prompt réutilisés", + "s2371": "requêtes ·", + "s2372": "relisez ceci, vérifiez mon code", + "s2373": "lignes ·", + "s2374": "lancer", + "s2375": "en cours ·", + "s2376": "s ont été", + "s2377": "échantillonnage", + "s2378": "save download markdown enregistrer télécharger markdown", + "s2379": "schedule recurring loop automation planifier récurrent boucle automatisation", + "s2380": "select:not([disabled])", + "s2381": "sélectionné", + "s2382": "serveurs connectés", + "s2383": "partagé", + "s2384": "bouclier", + "s2385": "unique", + "s2386": "plus lent", + "s2387": "fluide", + "s2388": "speech microphone voice transcribe parole microphone voix transcrire", + "s2389": "sr-only", + "s2390": "démarrer", + "s2391": "stats performance speed hardware statistiques performances vitesse matériel", + "s2392": "état indisponible", + "s2393": "étape", + "s2394": "arrêter", + "s2395": "strata:dictation", + "s2396": "strata:open-preview", + "s2397": "strata:open-website", + "s2398": "strata:tasks", + "s2399": "réussite", + "s2400": "soleil", + "s2401": "svg use", + "s2402": "syntax-code {0} {1}", + "s2403": "onglet", + "s2404": "tableau", + "s2405": "tablist", + "s2406": "tabpanel", + "s2407": "texte", + "s2408": "textarea:not([disabled])", + "s2409": "le modèle chargé", + "s2410": "réflexion", + "s2411": "threads", + "s2412": "juste", + "s2413": "time-skip-content", + "s2414": "pour rechercher, rédiger et relire mon plan de lancement.", + "s2415": "à faire", + "s2416": "basculer", + "s2417": "tok", + "s2418": "tok/s", + "s2419": "tokens", + "s2420": "tokens / seconde", + "s2421": "too-big", + "s2422": "too-large", + "s2423": "outil", + "s2424": "outils", + "s2425": "outils ·", + "s2426": "total", + "s2427": "true", + "s2428": "tours", + "s2429": "indisponible", + "s2430": "mémoire unifiée", + "s2431": "inconnu", + "s2432": "mis à jour", + "s2433": "mises à jour", + "s2434": "url", + "s2435": "version", + "s2436": "version-ladder--compact", + "s2437": "versions", + "s2438": "préchauffage", + "s2439": "avertissement", + "s2440": "était", + "s2441": "site web", + "s2442": "ne s’exécutera plus et sera retirée de vos tâches actives.", + "s2443": "wizard onboarding install resume assistant prise en main installation reprendre", + "s2444": "écrit", + "s2445": "ws__chev {0}", + "s2446": "oui", + "s2447": "your-next-idea.md", + "s2448": "{0} / {1} tokens · {2} %", + "s2449": "{0} Go de VRAM", + "s2450": "{0} Go en cache.", + "s2451": "{0} Go de capacité prévue restent disponibles.", + "s2452": "{0} Go au-dessus du budget", + "s2453": "{0} Go restants", + "s2454": "{0} GPU · utilisation moyenne", + "s2455": "{0} Vous pourrez le télécharger à nouveau dans Modèles.", + "s2456": "{0} Vos fichiers GGUF d’origine restent dans leur dossier.", + "s2457": "{0} actives · {1} en file d’attente", + "s2458": "{0} actives · {1} en file d’attente. Terminez ou annulez d’abord les requêtes.", + "s2459": "{0} cœurs ·", + "s2460": "{0} valeur exacte", + "s2461": "{0} experts en cache", + "s2462": "{0} fichiers trouvés", + "s2463": "{0} fichier(s) ignoré(s). Ajoutez jusqu’à 64 fichiers texte, avec 256 Ko de texte au total. Les photos et les PDF peuvent s’ouvrir séparément.", + "s2464": "{0} n’est plus dans le stockage du navigateur. Joignez-le à nouveau.", + "s2465": "{0} modèles chargés", + "s2466": "{0} modèles chargés", + "s2467": "{0} tokens du prompt sur {1} réutilisés", + "s2468": "{0} sur cet ordinateur. Choisissez une version pour supprimer ses fichiers.", + "s2469": "{0} processeurs · {1} cœurs · {2} threads", + "s2470": "{0} sous-agents en cours · Voir la vue d’ensemble", + "s2471": "{0} sous-agents en cours — afficher la vue d’ensemble", + "s2472": "{0} tokens · {1} tok/s", + "s2473": "Trouvé : {0} {1}{2}. Les prochains téléchargements utiliseront ce dossier.", + "s2474": "{0} · {1} · {2} · prompt hors cache", + "s2475": "{0} — afficher les détails", + "s2476": "{0} % du contexte", + "s2477": "{0} % de ce fichier", + "s2478": "{0}, 60 dernières secondes", + "s2479": "{0}, 60 dernières secondes. Utilisez les flèches pour examiner les échantillons.", + "s2480": "{0} : en dehors de la période sélectionnée", + "s2481": "{0} : utilisez une valeur texte, nombre ou vrai/faux.", + "s2482": "Le contexte de {0} K dépasse le budget disponible du modèle.", + "s2483": "{0}{1} tokens au total", + "s2484": "· Par défaut dans la conversation", + "s2485": "· Compatibilité vérifiée au chargement.", + "s2486": "· Exemple", + "s2487": "· Résultat d’exemple", + "s2488": "· Téléchargé", + "s2489": "· Image {0}", + "s2490": "· Local", + "s2491": "· Les exécutions manquées sont ignorées quand Strata est fermé.", + "s2492": "· Ouvrir dans le panneau latéral", + "s2493": "· Lit les images", + "s2494": "· environ", + "s2495": "· inactif Gen{0}", + "s2496": "· dernière réponse", + "s2497": "· nécessite plus de contexte", + "s2498": "· recommandé", + "s2499": "· {0} Go de marge en RAM dans l’estimation", + "s2500": "— modifications non enregistrées", + "s2501": "« {0} » est arrêtée. Restaurez-la depuis Tâches supprimées quand vous voulez.", + "s2502": " ». Essayez", + "s2503": "−1 choisit une graine aléatoire.", + "s2504": "-y\n@modelcontextprotocol/server-filesystem\n/your/folder", + "s2505": ". Copiez le token depuis la configuration de son connecteur.", + "s2506": ". L’accès au réseau dépend de l’adresse d’écoute de l’hôte et de votre pare-feu.", + "s2507": ". Les mesures conservées peuvent être périmées. Démarrez l’hôte du moteur configuré, puis réessayez.", + "s2508": "i-quant 2 bits, qualité un peu meilleure, vitesse proche", + "s2509": "2 bits, le plus rapide", + "s2510": "i-quant 3 bits, meilleure qualité, plus lent (plus de calcul CPU par token)", + "s2511": "i-quant 3,5 bits, la meilleure qualité (équivalente au modèle complet), le plus lent ; demande un PC de 64 Go avec peu d’autres programmes", + "s2512": "4 bits (Unsloth Dynamic), EXPÉRIMENTAL : la meilleure qualité, mais la plupart des experts viennent du SSD sur un PC de 64 Go (7 à 8,5 tokens/s mesurés)", + "s2513": "4 bits, téléchargement de 111 Go, la plupart des experts lus depuis le SSD : lent (7 à 8,5 tokens/s sur un PC de 64 Go)", + "s2514": "Une recommandation fondée sur le matériel détecté et les valeurs par défaut prises en charge. Enregistrez pour l’appliquer ; la vitesse n’a pas été mesurée.", + "s2515": "Choisissez le dossier de données Strata qui contient vos modèles téléchargés. Les fichiers correspondants sont réutilisés ; les fichiers manquants sont préparés automatiquement.", + "s2516": "Choisissez le fichier .gguf du modèle. Pour un modèle fractionné, choisissez n’importe quel fragment ; Strata trouve le premier et vérifie l’ensemble.", + "s2517": "Les fichiers terminés sont conservés. Le téléchargement, l’empaquetage et le chargement sont des étapes distinctes ; c’est le moteur qui confirme que tout est prêt.", + "s2518": "Experts déjà dans la mémoire du GPU ; la part PCIe est indiquée à part quand elle est communiquée.", + "s2519": "Nom de la famille de polices", + "s2520": "Des lots plus grands peuvent utiliser plus de mémoire ; ils ne sont pas toujours plus rapides.", + "s2521": "La mémoire est une approximation du catalogue, pas une mesure de mémoire libre. L’espace de travail des lots et le déchargement partiel ne sont pas prévus. Le temps de raisonnement et de planification n’est pas estimé ; ces durées ne sont pas le temps total de la tâche.", + "s2522": "Mode : {0}", + "s2523": "Aucun modèle de conversation n’est déclaré ; la mise en forme des réponses dépend du moteur.", + "s2524": "Rien ne correspond à « {0} ». Essayez > pour les commandes, # pour les conversations ou @ pour les espaces de travail.", + "s2525": "Seule l’API d’inférence est partagée. Les clients ont besoin de votre clé API. Utilisez un réseau local de confiance ; cette connexion utilise HTTP.", + "s2526": "Revoir le contexte", + "s2527": "Lancer l’installation guidée", + "s2528": "Les identifiants enregistrés sont masqués. Gardez le masque pour conserver une valeur existante ; saisissez une nouvelle valeur pour la remplacer.", + "s2529": "Ce modèle a besoin d’un moteur plus récent. Mettez à jour votre moteur ou importez un GGUF local pour ce modèle.", + "s2530": "Vos instructions et le dernier résultat sont conservés dans Tâches supprimées. Vous pouvez y restaurer la tâche ; sa planification restera en pause.", + "s2531": "la moitié des experts (code, outils, images conservés) : demande environ 32 Go de RAM, plus rapide ; moins bon hors programmation", + "s2532": "http://192.168.1.20:1234/v1", + "s2533": "https://example.com", + "s2534": "la seule taille de Coder : la moitié des experts, stockés comme IQ3_S (3,5 bits)", + "s2535": "le modèle d’origine", + "s2536": "réfléchit beaucoup plus court (−63 % de tokens de réflexion, des réponses 1,8 fois plus rapides d’après les chiffres de ses auteurs)", + "s2537": "Aperçu {0}", + "s2538": "Zoom {0}", + "s2539": "{0} · journal", + "s2540": "{0}. Utilisez les flèches pour examiner les échantillons.", + "s2541": "{0} : indisponible", + "s2542": "{0}{1} tok/s{2}", + "s2543": "Aperçu : {0}…", + "s2544": "Génération : {0} tok/s", + "s2545": "Lecture : {0} tok/s", + "s2546": "Réutilisés : {0} tokens", + "s2547": "Depuis {0} : {1} requêtes · {2} tokens de prompt · {3} tokens de sortie", + "s2548": "Strata va calibrer {0} et enregistrer les réglages les plus rapides mesurés.", + "s2549": "{0} requêtes sur {1} ont réutilisé des tokens du prompt", + "s2550": "{0} outils · {1} serveurs sur {2} connectés", + "s2551": "Un contexte plus court peut laisser de la place à une version plus petite.", + "s2552": "Vérifiez la connexion du client et réessayez la requête.", + "s2553": "Analysez cet ordinateur pour voir quelles versions conviennent.", + "s2554": "Vérifiez votre connexion internet, puis réessayez.", + "s2555": "Choisissez un fichier GGUF de modèle de texte complet.", + "s2556": "Corrigez le JSON avant d’enregistrer ou d’appliquer.", + "s2557": "Gérer votre bibliothèque de compétences", + "s2558": "Réessayez, ou désactivez la mesure plus longue ci-dessus.", + "s2559": "Essayez de relancer cette tâche.", + "s2560": "Essayez de renvoyer le message.", + "s2561": "Vos fichiers téléchargés sont conservés.", + "s2562": "Messages de commit", + "s2563": "Revue de code", + "s2564": "Notes de version", + "s2565": "Rapport matériel", + "s2566": "Impossible de charger les réglages du modèle.", + "s2567": "Vérifiez que le moteur est connecté et que ce modèle est installé, puis réessayez.", + "s2568": "Exécuté", + "s2569": "Non autorisé dans ce mode. Rien n’a été exécuté.", + "s2570": "Rejouer l’aperçu", + "s2571": "Environ {0} min restantes", + "s2572": "Environ {0} h {1} min restantes", + "s2573": "Environ {0} h restantes", + "s2574": "Le thème Système suit votre ordinateur par défaut.", + "s2575": "La lecture d’images n’est pas disponible pour ce modèle.", + "s2576": "Désactivez la lecture d’images et réessayez.", + "s2577": "Le modèle s’est arrêté au démarrage, très probablement parce que le PC manquait de mémoire.", + "s2578": "Fermez les autres programmes et réessayez, ou choisissez « Garder 20 % pour mon travail ». En mode expert, vous pouvez aussi activer l’option peu de RAM : une partie du modèle est alors lue depuis le SSD.", + "s2579": "Le chargement prend trop de temps.", + "s2580": "Le PC manque peut-être de mémoire. Fermez les autres programmes et réessayez.", + "s2581": "Le moteur de Strata pour cet ordinateur n’est pas encore installé.", + "s2582": "Il est ajouté quand vous téléchargez un modèle. Téléchargez à nouveau votre modèle pour l’ajouter.", + "s2583": "Le téléchargement n’a pas pu accéder à internet.", + "s2584": "Vérifiez votre connexion, puis appuyez sur Reprendre le téléchargement.", + "s2585": "Un fichier téléchargé n’a pas passé le contrôle de sécurité de Strata.", + "s2586": "Appuyez sur Reprendre le téléchargement et Strata le récupérera à nouveau.", + "s2587": "L’assistant de programmation n’est pas encore installé sur cet ordinateur.", + "s2588": "La conversation fonctionne sans lui.", + "s2589": "Strata n’a pas pu lire ses propres composants.", + "s2590": "Fermez puis rouvrez Strata. Si le problème persiste, réinstallez l’application.", + "s2591": "Un problème est survenu.", + "s2592": "Réessayez. Si le problème persiste, ouvrez Détails et partagez-les quand vous demandez de l’aide.", + "s2593": "Analyse de votre ordinateur…", + "s2594": "Préparation en cours…", + "s2595": "Téléchargement de votre modèle…", + "s2596": "Préparation de votre modèle pour Strata…", + "s2597": "Mettre à jour le composant", + "s2598": "Mettez à jour le moteur de cet ordinateur. Vos modèles et vos réglages sont conservés.", + "s2599": "Enregistré dans {0}", + "s2600": "Vous avez déjà un modèle pris en charge sur cet ordinateur ? Choisissez le dossier qui contient ses fichiers. Strata les vérifie, prépare le modèle et le charge. Rien n’est copié ni téléchargé.", + "s2601": "Dossier contenant les fichiers GGUF", + "s2602": "Chemin complet du dossier", + "s2603": "Vérifier les fichiers", + "s2604": "Modèle trouvé", + "s2605": "{0} fichiers · {1}", + "s2606": "Préparer et charger", + "s2607": "Certaines parties de ce modèle sont manquantes, ou le dossier contient plus d’un modèle.", + "s2608": "Mettez toutes les parties d’un seul modèle dans un seul dossier, puis vérifiez à nouveau.", + "s2609": "Strata ne peut pas encore exécuter ces fichiers.", + "s2610": "Strata exécute les modèles Qwen3.8-Flash-Next. Téléchargez-en un depuis Modèles, ou choisissez un dossier contenant ses fichiers.", + "s2611": "Ces fichiers n’ont pas pu être vérifiés.", + "s2612": "Vérifiez que le dossier contient des fichiers GGUF complets, puis réessayez.", + "s2613": "Budget de réflexion", + "s2614": "Sans limite", + "s2615": "Ce que cette tâche peut faire", + "s2616": "Regarder seulement, ne rien modifier", + "s2617": "M’arrêter et me prévenir avant toute modification", + "s2619": "Tâche terminée", + "s2620": "La tâche attend votre accord", + "s2621": "La tâche a échoué", + "s2622": "Écriture d’un fichier", + "s2623": "Fichier écrit", + "s2624": "Impossible d’écrire le fichier", + "s2625": "Modification d’un fichier", + "s2626": "Fichier modifié", + "s2627": "Impossible de modifier le fichier", + "s2628": "Lecture d’un fichier", + "s2629": "Fichier lu", + "s2630": "Impossible de lire le fichier", + "s2631": "Observation d’une image", + "s2632": "Image observée", + "s2633": "Impossible d’observer l’image", + "s2634": "Recherche de fichiers", + "s2635": "Fichiers recherchés", + "s2636": "Impossible de rechercher des fichiers", + "s2637": "Recherche dans les fichiers", + "s2638": "Recherche faite dans les fichiers", + "s2639": "Impossible de chercher dans les fichiers", + "s2640": "Exécution d’une commande", + "s2641": "Commande exécutée", + "s2642": "La commande a échoué", + "s2643": "Ouverture d’une page web", + "s2644": "Page web ouverte", + "s2645": "Impossible d’ouvrir la page web", + "s2646": "Recherche sur le web", + "s2647": "Recherche web effectuée", + "s2648": "Impossible de faire la recherche web", + "s2649": "Mise à jour de sa liste de tâches", + "s2650": "Liste de tâches mise à jour", + "s2651": "Impossible de mettre à jour sa liste de tâches", + "s2652": "Affichage d’un résultat", + "s2653": "Résultat affiché", + "s2654": "Impossible d’afficher le résultat", + "s2655": "Vérification du dossier", + "s2656": "Dossier vérifié", + "s2657": "Impossible de vérifier le dossier", + "s2658": "Vérification des tâches en arrière-plan", + "s2659": "Tâches en arrière-plan vérifiées", + "s2660": "Impossible de vérifier les tâches en arrière-plan", + "s2661": "Lecture d’une tâche en arrière-plan", + "s2662": "Tâche en arrière-plan lue", + "s2663": "Impossible de lire la tâche en arrière-plan", + "s2664": "Arrêt d’une tâche en arrière-plan", + "s2665": "Tâche en arrière-plan arrêtée", + "s2666": "Impossible d’arrêter la tâche en arrière-plan", + "s2667": "Utilisation d’un outil", + "s2668": "Outil utilisé", + "s2669": "L’outil a échoué", + "s2670": "Appliquer les réglages et charger", + "s2671": "Appliquer et charger", + "s2672": "Les fichiers du modèle sont déjà sur cet ordinateur. Rien ne sera téléchargé ; seuls les réglages que vous avez choisis sont appliqués.", + "s2673": "Les modèles natifs actuellement chargés seront d’abord déchargés.", + "s2674": "Strata ne peut pas ouvrir son fichier de réglages.", + "s2675": "Lancez Strata une fois avec votre propre compte (pas en administrateur) ou appuyez sur Réparer.", + "s2676": "Essayer une modification sur une copie, la vérifier, et ne la garder que si elle est meilleure", + "s2677": "Fixer un objectif et laisser l’assistant travailler jusqu’à ce qu’il soit atteint", + "s2678": "Répéter un message toutes les quelques minutes tant que cette conversation est ouverte", + "s2679": "Tapez /loop, la fréquence et ce qu’il faut faire — par exemple /loop 10m vérifiez la compilation. Strata l’envoie encore et encore tant que la conversation est ouverte. Pour un travail qui doit continuer Strata fermé, utilisez les Tâches.", + "s2680": "Indiquer la fréquence", + "s2681": "Indiquer quoi faire", + "s2682": "Arrêt à tout moment", + "s2683": "Garder la mise à jour", + "s2684": "Remettre l’original", + "s2685": "La mise à jour est dans vos fichiers. Vous pouvez remettre l’original.", + "s2686": "Vos fichiers sont inchangés. Gardez la mise à jour pour l’appliquer à votre dossier ; vous pourrez remettre l’original plus tard.", + "s2687": "Vérifications", + "s2688": "Résultat", + "s2689": "Aucune vérification n’est configurée pour ce dossier, rien n’a donc été jugé automatiquement. Regardez les deux versions et choisissez celle à garder.", + "s2690": "Conservé avant toute modification.", + "s2691": "Révision {0}", + "s2692": "Ce qui n’a pas fonctionné", + "s2693": "Arrêter Time-skip", + "s2694": "Mise à jour conservée · vos fichiers l’ont maintenant", + "s2695": "Original conservé · vos fichiers sont inchangés", + "s2696": "Prêt à comparer · vous choisissez ce qu’on garde", + "s2697": "Tapez /loop, la fréquence, puis ce qu’il faut faire. Par exemple : /loop 10m vérifiez si la compilation réussit. Utilisez /loop stop pour l’arrêter.", + "s2698": "Indiquez d’abord la fréquence, comme 10m (minutes) ou 2h (heures), puis ce qu’il faut faire.", + "s2699": "Le délai le plus court entre deux exécutions est de 1 minute, pour que le modèle ait le temps de terminer chacune.", + "s2700": "Le délai le plus long entre deux exécutions est de 24 heures. Pour des attentes plus longues, utilisez une tâche dans l’écran Tâches.", + "s2701": "toutes les minutes", + "s2702": "toutes les {0} minutes", + "s2703": "toutes les heures", + "s2704": "toutes les {0} heures", + "s2705": "Une boucle tourne dans cette conversation : elle envoie « {0} » {1}, tant que la conversation est ouverte. Tapez /loop stop pour l’arrêter.", + "s2706": "Boucle lancée : « {0} » {1}, tant que la conversation est ouverte. Tapez /loop stop pour l’arrêter. Pour un travail qui doit continuer Strata fermé, utilisez l’écran Tâches.", + "s2707": "Aucune boucle ne tourne dans cette conversation.", + "s2708": "La boucle est arrêtée.", + "s2709": "La boucle s’est arrêtée après {0} exécutions. Tapez /loop à nouveau pour la relancer.", + "s2710": "Cette conversation a déjà une boucle. Tapez d’abord /loop stop, puis lancez-en une nouvelle.", + "s2713": "Vos fichiers ont changé après le début de cet essai, rien n’a donc été écrasé. Relancez Time-skip.", + "s2714": "Chargez d’abord un modèle, puis relancez Time-skip.", + "s2715": "Impossible de joindre l’assistant. Réessayez.", + "s2716": "Time-skip s’est arrêté. {0} Vos fichiers n’ont pas été modifiés.", + "s2717": "Time-skip a été arrêté avant la fin. Vos fichiers n’ont pas été modifiés.", + "s2718": "L’assistant n’a rien modifié, il n’y a donc rien à comparer. Vos fichiers n’ont pas été modifiés.", + "s2719": "Time-skip n’a pas pu démarrer. {0}", + "s2720": "Time-skip a perdu le contact avec l’application et s’est arrêté. Vos fichiers n’ont pas été modifiés.", + "s2721": "La mise à jour est maintenant dans vos fichiers", + "s2722": "Vos fichiers d’origine sont revenus", + "s2724": "Vos fichiers n’ont pas été modifiés", + "s2725": "Chargement de la liste des outils…", + "s2726": "Choisissez ce que l’assistant peut utiliser dans vos conversations. Un changement s’applique dès votre prochain message. En mode Manuel, tout ce qui modifie votre ordinateur demande d’abord votre accord.", + "s2727": "Sur le web", + "s2728": "Pour les gros travaux", + "s2729": "Exécuter des commandes", + "s2730": "Permet à l’assistant d’exécuter des commandes, par exemple pour ouvrir un dossier ou lancer un programme.", + "s2731": "Lire et modifier des fichiers", + "s2732": "Permet à l’assistant de lire, créer et modifier des fichiers dans le dossier de votre conversation.", + "s2733": "Trouver des fichiers et du texte", + "s2734": "Permet à l’assistant de chercher des fichiers par nom et dans leur contenu. Il ne fait que lire.", + "s2735": "Tâches longues", + "s2736": "Permet à l’assistant de lancer une commande lente en arrière-plan et d’en vérifier l’avancement plus tard.", + "s2737": "Ouvrir des pages web", + "s2738": "Permet à l’assistant de lire une page web que vous lui indiquez.", + "s2739": "Rechercher sur le web", + "s2740": "Permet à l’assistant de chercher sur le web quand il a besoin d’informations récentes.", + "s2741": "Assistants auxiliaires", + "s2742": "Permet à l’assistant de lancer des auxiliaires qui travaillent en même temps sur des parties d’une tâche.", + "s2743": "Objectifs", + "s2744": "Permet de fixer un objectif avec /goal. L’assistant continue de travailler jusqu’à ce qu’il soit atteint.", + "s2745": "Liste de tâches", + "s2746": "Permet à l’assistant de tenir une liste de contrôle pendant une grande tâche.", + "s2747": "Permet à l’assistant d’utiliser vos compétences enregistrées quand elles conviennent à la tâche.", + "s2748": "Afficher les résultats", + "s2749": "Permet à l’assistant d’afficher une page ou un fichier dans l’aperçu à côté de la conversation.", + "s2750": "Recherche web", + "s2751": "D’où viennent les résultats", + "s2752": "Les recherches utilisent votre propre compte auprès de ce service.", + "s2753": "Les résultats viennent de DuckDuckGo. Vous n’avez besoin ni de compte ni de clé.", + "s2754": "DuckDuckGo (sans clé)", + "s2755": "Exa (votre propre clé)", + "s2756": "Perplexity (votre propre clé)", + "s2757": "DeepSeek (votre propre clé)", + "s2758": "Votre clé", + "s2759": "Une clé est enregistrée sur cet ordinateur. Saisissez-en une nouvelle pour la remplacer.", + "s2760": "Enregistrée sur cet ordinateur uniquement. Strata ne la réaffiche jamais.", + "s2761": "Collez votre clé", + "s2762": "Enregistrer la clé", + "s2763": "Clé enregistrée", + "s2764": "Navigateur web", + "s2765": "Utiliser un navigateur web", + "s2766": "L’assistant peut ouvrir des pages, cliquer et saisir du texte dans {0}. En mode Manuel, chaque action demande d’abord votre accord.", + "s2767": "votre navigateur", + "s2768": "Chrome ou Edge est introuvable sur cet ordinateur. Installez-en un, puis revenez l’activer.", + "s2769": "Vos propres outils", + "s2770": "Apprenez quelque chose de nouveau à l’assistant : donnez-lui des instructions à suivre, une commande à exécuter, ou connectez un serveur d’outils. Les commandes et les serveurs demandent d’abord votre accord en mode Manuel.", + "s2771": "Pas encore d’outils à vous", + "s2772": "Par exemple : « Rédigez les notes de version dans notre style maison », ou une commande qui vérifie que votre site est en ligne.", + "s2773": "Ajouter un outil", + "s2774": "Modifier l’outil", + "s2775": "Enregistrer l’outil", + "s2776": "Commande", + "s2777": "Serveur d’outils", + "s2778": "Suivre mes instructions", + "s2779": "Exécuter une commande", + "s2780": "Connecter un serveur d’outils (MCP)", + "s2781": "Par exemple : Notes de version", + "s2782": "Ce qu’il fait", + "s2783": "Une phrase. L’assistant la lit pour décider quand utiliser l’outil.", + "s2784": "Comment il fonctionne", + "s2785": "Écrivez ce que l’assistant doit faire quand il utilise cet outil.", + "s2786": "Commande à exécuter", + "s2787": "Par exemple : curl -I https://example.com", + "s2788": "L’assistant peut transmettre du texte à la commande. La commande le lit dans le réglage STRATA_INPUT. Ce qu’elle affiche est renvoyé à l’assistant.", + "s2789": "Adresse web ou programme", + "s2790": "https://… ou le programme qui démarre le serveur", + "s2791": "Réglages supplémentaires pour le programme", + "s2792": "(facultatif, un par ligne)", + "s2793": "Retirer cet outil ?", + "s2794": "Le garder", + "s2795": "« {0} » ne sera plus disponible pour l’assistant.", + "s2796": "Donnez à l’outil un nom court : lettres, chiffres, espaces ou tirets.", + "s2797": "Dites en une phrase ce que fait l’outil. L’assistant la lit pour décider quand l’utiliser.", + "s2798": "Écrivez les instructions que l’assistant doit suivre quand il utilise cet outil.", + "s2799": "Saisissez la commande à exécuter.", + "s2800": "Saisissez l’adresse web du serveur d’outils, ou le programme qui le démarre.", + "s2801": "La liste des outils n’a pas pu être chargée.", + "s2802": "La modification n’a pas pu être enregistrée.", + "s2803": "L’outil n’a pas pu être enregistré.", + "s2804": "L’outil n’a pas pu être retiré.", + "s2805": "L’outil de navigateur ne fait pas partie de cette installation.", + "s2806": "Travail sur une copie de vos fichiers. Suivez l’avancement dans la barre latérale.", + "s2807": "Le résultat est prêt. Passez de l’original à la version mise à jour, ou comparez-les côte à côte.", + "s2808": "Ouverture d’une page dans le navigateur", + "s2809": "Page ouverte dans le navigateur", + "s2810": "Impossible d’ouvrir la page", + "s2811": "Clic sur la page", + "s2812": "Clic effectué sur la page", + "s2813": "Impossible de cliquer sur la page", + "s2814": "Pointage sur la page", + "s2815": "Pointage effectué sur la page", + "s2816": "Impossible de pointer sur la page", + "s2817": "Saisie sur la page", + "s2818": "Saisie effectuée sur la page", + "s2819": "Impossible de saisir sur la page", + "s2820": "Observation de la page", + "s2821": "Page observée", + "s2822": "Impossible d’observer la page", + "s2823": "Utilisation du navigateur", + "s2824": "Navigateur utilisé", + "s2825": "L’étape du navigateur a échoué", + "s2826": "Lecture de vos instructions", + "s2827": "Instructions lues", + "s2828": "Impossible de lire vos instructions", + "s2829": "Exécution de votre outil", + "s2830": "Outil exécuté", + "s2831": "Votre outil a échoué", + "s2832": "Ce dossier est trop gros pour tester une modification sur une copie. Ouvrez un dossier plus petit pour cette conversation, puis réessayez.", + "s2833": "Time-skip travaille sur un dossier qui vous appartient. Choisissez un dossier de travail pour cette conversation, puis réessayez.", + "s2834": "Exécution d’un petit programme sur la page", + "s2835": "Petit programme exécuté sur la page", + "s2836": "Impossible d’exécuter le programme sur la page", + "s2837": "Attente de la page", + "s2838": "Page attendue", + "s2839": "Impossible d’attendre la page", + "s2840": "Retour à la page précédente", + "s2841": "Retour effectué à la page précédente", + "s2842": "Impossible de revenir en arrière", + "s2843": "Gestion des onglets du navigateur", + "s2844": "Onglets du navigateur gérés", + "s2845": "Impossible de gérer les onglets du navigateur", + "s2846": "Fermeture de la page du navigateur", + "s2847": "Page du navigateur fermée", + "s2848": "Impossible de fermer la page du navigateur", + "s2849": "Renommer {0}", + "s2850": "Renommer l’espace de travail", + "s2851": "Nom de l’espace de travail", + "s2852": "Seul le nom change. Le dossier reste où il est.", + "s2853": "Impossible de renommer cet espace de travail", + "s2854": "Modèles Swift", + "s2855": "Modèles GSQ-RCO", + "s2856": "Modèles NVFP4", + "s2857": "Modèles Gyro", + "s2858": "Modèles Unsloth", + "s2859": "Modèles Qwen3.6", + "s2860": "Utiliser votre propre GGUF…", + "s2861": "RAM + VRAM", + "s2862": "Utilise {0} Go de SSD", + "s2863": "le plus petit", + "s2864": "bon équilibre", + "s2865": "la meilleure qualité pour sa taille", + "s2866": "plus de qualité", + "s2867": "sur {0}", + "s2868": "{0} : environ {1} sur {2} utilisés par ce modèle", + "s2869": "{0} · {1} de mémoire graphique", + "s2870": "Aucune carte graphique prise en charge n’est signalée par cette installation.", + "s2871": "Mémoire graphique", + "s2872": " · {0} de RAM", + "s2873": "Environ {0} Go seront lus depuis le SSD, les réponses peuvent donc être un peu plus lentes.", + "s2874": "Tient entièrement en mémoire.", + "s2875": "Ouvrir votre dossier {0} dans l’Explorateur de fichiers ?", + "s2876": "Ouvrir le dossier {0} dans l’Explorateur de fichiers ?", + "s2877": "Ouvrir le fichier {0} ?", + "s2878": "Ouvrir l’Explorateur de fichiers ?", + "s2879": "Lancer un programme : {0} ?", + "s2880": "Exécuter le script {0} ?", + "s2881": "Exécuter {0} étapes sur votre ordinateur ?", + "s2882": "Exécuter une commande sur votre ordinateur ?", + "s2883": "Créer le fichier {0} ?", + "s2884": "Créer le dossier {0} ?", + "s2885": "Écrire dans le fichier {0} ?", + "s2886": "Modifier le fichier {0} ?", + "s2887": "Copier {0} ?", + "s2888": "Déplacer {0} ?", + "s2889": "Renommer {0} ?", + "s2890": "Exécuter git {0} ?", + "s2891": "Installer des paquets avec {0} ?", + "s2892": "Arrêter une tâche en arrière-plan ?", + "s2893": "Ouvrir la page web {0} ?", + "s2894": "Utiliser l’outil connecté {0} ?", + "s2895": "Utiliser l’outil {0} ?", + "s2896": "Une fenêtre va s’ouvrir. Rien n’est modifié.", + "s2897": "Peut modifier votre ordinateur.", + "s2898": "Est supprimé de votre ordinateur.", + "s2899": "Remplace le fichier s’il existe déjà.", + "s2900": "Modifie les fichiers ou l’historique du projet.", + "s2901": "Télécharge des logiciels et modifie votre ordinateur.", + "s2902": "Plusieurs choses se passent. Détails montre chaque étape.", + "s2903": "Détails montre exactement ce que cela fait.", + "s2904": "Peut agir sur le service que vous avez connecté.", + "s2905": "Mettre {0} en pause", + "s2906": "Reprendre {0}", + "s2907": "Résumé de la tâche", + "s2908": "Planification", + "s2909": "Ce qu’elle peut faire", + "s2910": "Dernière exécution échouée", + "s2911": "Pas encore exécutée", + "s2912": "Ce qu’elle fait", + "s2913": "Dernière réponse", + "s2914": "Suivante : {0}", + "s2915": "Calcul de la prochaine exécution…", + "s2916": "Analyse de votre PC", + "s2917": "Examen de votre carte graphique et de votre mémoire", + "s2918": "Mesure de la vitesse de base", + "s2919": "Chronométrage de vos réglages actuels", + "s2920": "Point de départ : {0} tokens par seconde", + "s2921": "Essai de réglages", + "s2922": "Essai d’autres réglages, un par un", + "s2923": "Confirmation du meilleur", + "s2924": "Le test est répété pour être sûr", + "s2925": "Enregistrement", + "s2926": "Conservé pour ce modèle ; vous pouvez l’annuler", + "s2927": "Étapes de l’optimisation", + "s2928": "En attente", + "s2929": "Vitesse actuelle", + "s2930": "tokens par seconde", + "s2931": "Vos réglages", + "s2932": "{0} à {1} tokens par seconde", + "s2933": "Avant", + "s2934": "Réflexion…", + "s2935": "Je réfléchis…", + "s2936": "Je mijote une réponse…", + "s2937": "Je rumine…", + "s2938": "Je relie les points…", + "s2939": "Je suis une idée…", + "s2940": "Je fais un brouillon…", + "s2941": "Je pèse le pour et le contre…", + "s2942": "Je lis entre les lignes…", + "s2943": "Je prépare une réponse…", + "s2944": "J’assemble le tout…", + "s2945": "Je suis une intuition…", + "s2946": "Lecture de votre message…", + "s2947": "Rédaction de la réponse…", + "s2948": "En attente de votre réponse…", + "s2949": "Les auxiliaires travaillent ({0})…", + "s2950": "Travail sur l’objectif, étape {0}", + "s2951": "{0} tokens", + "s2952": "A réfléchi pendant {0}", + "s2953": "Raisonnement", + "s2954": "Aller au dernier message", + "s2955": "A besoin de vous", + "s2956": "étape {0} sur {1}", + "s2957": "En cours de travail", + "s2958": "Reprendre l’objectif", + "s2959": "Mettre l’objectif en pause", + "s2960": "Modifier l’objectif", + "s2961": "Supprimer l’objectif", + "s2962": "L’objectif n’a pas été modifié", + "s2963": "Enregistrer l’objectif", + "s2964": "Vers quoi l’assistant doit-il continuer à travailler ?", + "s2965": "Supprimer cet objectif ?", + "s2966": "nouveau", + "s2967": "supprimé", + "s2968": "modifié", + "s2969": "Ce fichier est trop gros, ou n’est pas du texte : il est listé mais pas affiché.", + "s2970": "Absent auparavant.", + "s2971": "Supprimé.", + "s2972": "Voir l’aperçu", + "s2973": "Voir le code", + "s2974": "Page d’origine", + "s2975": "Page mise à jour", + "s2976": "{0} lignes inchangées", + "s2977": "Modifications", + "s2978": "Agrandir l’image {0}", + "s2979": "Cette image n’a pas pu être chargée.", + "s2980": "Original et version mise à jour, côte à côte", + "s2981": "Fichiers modifiés", + "s2982": "+{0} de plus", + "s2983": "Time-skip est au travail", + "s2984": "Révision en cours", + "s2985": "Lecture de vos fichiers…", + "s2986": "Essai d’une version améliorée…", + "s2987": "Vérification du résultat…", + "s2988": "Comparaison des deux versions…", + "s2989": "Après", + "s2990": "Enregistré sous {0}. Il est utilisé à chaque chargement de ce modèle.", + "s2991": "Optimisé et enregistré", + "s2992": "Définition de l’objectif", + "s2993": "Objectif défini", + "s2994": "Impossible de définir l’objectif", + "s2995": "Mise à jour de l’objectif", + "s2996": "Objectif mis à jour", + "s2997": "Impossible de mettre à jour l’objectif", + "s2998": "Vérification de l’objectif", + "s2999": "Objectif vérifié", + "s3000": "Impossible de vérifier l’objectif", + "s3001": "Lecture de votre message…", + "s3002": "Détermination de la prochaine étape…", + "s3003": "Réflexion… {0} tokens", + "s3004": "Rédaction de la réponse…", + "s3005": "En attente de votre réponse…", + "s3006": "Les auxiliaires travaillent ({0})…", + "s3007": "Travail sur l’objectif, étape {0}", + "s3008": "Écriture de {0}…", + "s3009": "Écriture d’un fichier…", + "s3010": "Écriture de {0}… ({1} Ko)", + "s3011": "Écriture d’un fichier… ({0} Ko)", + "s3012": "Modification de {0}…", + "s3013": "Modification d’un fichier…", + "s3014": "Modification de {0}… ({1} Ko)", + "s3015": "Modification d’un fichier… ({0} Ko)", + "s3016": "Lecture de {0}…", + "s3017": "Lecture d’un fichier…", + "s3018": "Observation d’une image…", + "s3019": "Exécution d’une commande…", + "s3020": "Recherche dans vos fichiers…", + "s3021": "Recherche sur le web…", + "s3022": "Ouverture de {0}…", + "s3023": "Ouverture d’une page web…", + "s3024": "Ouverture d’une page…", + "s3025": "Utilisation du navigateur…", + "s3026": "Définition de l’objectif…", + "s3027": "Mise à jour de l’objectif…", + "s3028": "Vérification de l’objectif…", + "s3029": "Mise à jour de sa liste de tâches…", + "s3030": "Utilisation d’une compétence enregistrée…", + "s3031": "Affichage d’un résultat…", + "s3032": "Exécution d’un plan en plusieurs étapes…", + "s3033": "Vérification des tâches en arrière-plan…", + "s3034": "Lecture de vos instructions…", + "s3035": "Exécution de votre outil…", + "s3036": "Utilisation d’un outil…", + "s3037": "Lecture de vos fichiers…", + "s3038": "Essai d’une version améliorée…", + "s3039": "Vérification du résultat…", + "s3040": "Comparaison des deux versions…", + "s3041": "Nouvelle compétence", + "s3042": "Voir les journaux", + "s3043": "Journaux du moteur", + "s3044": "Strata n’envoie aucune télémétrie d’utilisation.", + "s3045": "Les conversations restent dans le stockage du navigateur.", + "s3046": "Quand vous choisissez un modèle API, cette conversation et les instructions des compétences activées sont envoyées à son fournisseur.", + "s3047": "Le journal des requêtes de l’interface garde en mémoire le client, les durées et les métadonnées de tokens.", + "s3048": "La surveillance de l’API native peut conserver le contenu des requêtes en mémoire lorsqu’elle est activée.", + "s3049": "Les outils connectés accèdent aux ressources que vous configurez.", + "s3050": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s et la lecture du prompt de {2} tok/s, avec {3} tokens réutilisés.", + "s3051": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s et la lecture du prompt de {2} tok/s.", + "s3052": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s, avec {2} tokens réutilisés.", + "s3053": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s.", + "s3054": "{0} requêtes jusqu’ici.", + "s3055": "Tâche retirée", + "s3056": "Retirer cette tâche ?", + "s3057": "{0} % plus rapide", + "s3058": "Déjà le plus rapide", + "s3059": "Toujours aussi rapide qu’avant", + "s3060": "Plus lent qu’avant", + "s3061": "Mesure non fiable", + "s3062": "Impossible de savoir pour l’instant", + "s3063": "L’optimisation n’est pas terminée", + "s3064": "Vos réponses arrivent maintenant plus vite. La qualité reste la même.", + "s3065": "Rien de ce que nous avons essayé n’a fait mieux que vos réglages actuels, rien n’a donc été modifié.", + "s3066": "Votre optimisation enregistrée fonctionne toujours aussi bien qu’au moment de son enregistrement.", + "s3067": "Votre optimisation a été conservée. Refaites la vérification plus tard.", + "s3068": "Votre PC était trop occupé pour essayer d’autres réglages, rien n’a donc été modifié. Réessayez quand les autres programmes sont fermés.", + "s3069": "Votre PC était occupé pendant le test, nous n’avons donc pas pu mesurer de façon fiable. Rien n’a été modifié. Réessayez quand les autres programmes sont fermés.", + "s3070": "Il n’y avait pas assez de mémoire libre pour tester. Rien n’a été modifié. Fermez les autres programmes et réessayez.", + "s3071": "Le moteur n’a pas pu démarrer avec ces réglages. Rien n’a été modifié.", + "s3072": "Le moteur s’est arrêté pendant la mesure. Rien n’a été modifié.", + "s3074": "Enregistré sous", + "s3075": "Le plan n’a pas été modifié", + "s3076": "Modifier le plan", + "s3077": "Étape {0}", + "s3078": "Supprimer cette étape", + "s3079": "Ajouter une étape", + "s3080": "Enregistrer le plan", + "s3081": "{0} étapes", + "s3082": "{0} sur {1} terminées", + "s3083": "Rien ne s’exécute tant que vous n’avez pas approuvé.", + "s3084": "Rejeter", + "s3085": "Lancer comme objectif", + "s3086": "Il n’y a pas de plan dans cette conversation.", + "s3087": "En attente — part quand l’étape {0} se termine", + "s3088": "En attente — part quand l’assistant a terminé", + "s3089": "Annuler ce message", + "s3090": "Reprendre", + "s3091": "ignorée", + "s3092": "En pause · {0} sur {1} terminées", + "s3093": "Plan approuvé.", + "s3094": "Expérimental", + "s3095": "Autres façons d’ouvrir {0}", + "s3096": "Actions sur le fichier", + "s3097": "Afficher dans le dossier", + "s3098": "Copier le chemin", + "s3099": "Joindre comme contexte", + "s3100": "Chemin copié", + "s3101": "Joint à votre prochain message", + "s3102": "Le fichier n’a pas été ouvert", + "s3103": "Le fichier n’a pas d’aperçu", + "s3104": "Le dossier n’a pas été ouvert", + "s3105": "Le chemin n’a pas été copié", + "s3106": "Le fichier n’a pas été joint", + "s3107": "Sélectionner un dossier", + "s3108": "Choisissez le dossier dans lequel cette conversation travaille", + "s3109": "Dossier du projet : {0}. Le changer.", + "s3110": "Utiliser le dossier par défaut", + "s3111": "Le dossier n’a pas été modifié", + "s3112": "Le plan", + "s3113": "C’est ici que la vérification compte le plus", + "s3114": "choisie par défaut", + "s3115": "C’est un travail court, il n’y a donc qu’une version. Rien ne vaut la peine d’être divisé en branches.", + "s3116": "Étape {0} sur {1} : {2}", + "s3117": "Démarre quand A atteint l’étape {0}", + "s3118": "En attente de démarrage", + "s3119": "En attente du plan", + "s3120": "Progression de {0}", + "s3121": "Garder une version", + "s3122": "La version A est dans vos fichiers.", + "s3123": "La version B est dans vos fichiers.", + "s3124": "La lecture d’images demande quelques fichiers de plus qui ne sont pas encore sur cet ordinateur.", + "s3125": "Télécharger les fichiers de lecture d’images", + "s3126": "Deux versions à comparer", + "s3127": "A et B sont allées jusqu’au bout. Gardez celle que vous préférez.", + "s3128": "Time-skip travaille avec un modèle chargé. Choisissez-en un dans l’onglet Modèles, puis réessayez.", + "s3129": "Ceci est un essai d’exemple réalisé alors que l’application ne pouvait pas joindre son hôte.", + "s3130": "Démarrage en cours", + "s3131": "Time-skip a besoin que l’application finisse de démarrer. Réessayez dans un instant.", + "s3132": "Travail sur une copie de vos fichiers.", + "s3133": "Le moteur n’a pas pu démarrer car l’un de ses fichiers de programme est absent de cet ordinateur.", + "s3134": "Réinstallez Strata (l’installateur l’inclut) ou appuyez sur Réparer. Fermer d’autres programmes n’aidera pas.", + "s3135": "Le moteur n’a pas pu démarrer car l’un de ses fichiers de programme ne convient pas à cet ordinateur ou est endommagé.", + "s3136": "Réinstallez Strata ou appuyez sur Réparer. Si le problème persiste, mettez à jour votre pilote graphique.", + "s3137": "Le moteur a besoin d’une fonction de processeur plus récente que celle de cet ordinateur.", + "s3138": "Ouvrez Détails et partagez-les quand vous demandez de l’aide.", + "s3139": "Le moteur a planté au démarrage.", + "s3140": "Redémarrez le PC et réessayez. Si le problème persiste, mettez à jour votre pilote graphique et ouvrez Détails quand vous demandez de l’aide.", + "s3141": "Windows ou votre logiciel de sécurité a empêché le moteur de démarrer.", + "s3142": "Autorisez Strata dans votre logiciel de sécurité, puis réessayez.", + "s3143": "Strata n’a pas trouvé un fichier dont il a besoin pour démarrer le moteur.", + "s3144": "Réinstallez Strata ou appuyez sur Réparer.", + "s3145": "Le modèle s’est arrêté au démarrage.", + "s3146": "Aucun sélecteur de dossier n’a été trouvé. Installez zenity ou kdialog pour choisir un dossier, ou saisissez le chemin.", + "s3147": "Le sélecteur de dossier n’a pas pu s’ouvrir. Installez zenity ou kdialog pour choisir un dossier, ou saisissez le chemin.", + "s3148": "Saisissez le chemin du dossier", + "s3149": "Chemin du dossier", + "s3150": "/home/you/Documents", + "s3151": "Quitter Strata", + "s3152": "Quitter Strata ?", + "s3153": "Cela arrête le modèle et ferme Strata. Vos conversations et vos fichiers restent comme ils sont. Fermer seulement l’onglet du navigateur laisserait Strata en marche.", + "s3154": "Strata est arrêté", + "s3155": "Strata est arrêté. Vous pouvez fermer cet onglet. Pour le réutiliser, lancez Strata depuis son icône.", + "s3156": "Strata n’a pas pu être arrêté d’ici. Lancez l’application avec --quit dans un terminal, ou réessayez.", + "s3157": "Fermeture…", + "s3158": "Décompression du moteur fourni avec l’application. Cela prend environ une minute la première fois.", + "s3159": "Utilisation de {0}", + "s3160": "Installé · cloudflared {0}", + "s3161": "Le connecteur de Cloudflare tourne déjà sur cet ordinateur comme service système, Strata n’en a donc pas démarré un second. Arrêtez d’abord ce service (ou utilisez son tunnel tel quel), puis reconnectez-vous ici.", + "s3162": "Le connecteur de Cloudflare (cloudflared) tourne déjà sur cet ordinateur, Strata n’en a donc pas démarré un second. Fermez-le d’abord (ou utilisez son tunnel tel quel), puis reconnectez-vous ici.", + "s3163": "Strata n’a pas trouvé le connecteur de Cloudflare (cloudflared) sur cet ordinateur.", + "s3164": "Installez cloudflared (avec votre gestionnaire de paquets, ou depuis le site de Cloudflare), puis appuyez sur Réessayer l’installation. Strata le cherche dans votre PATH et aux emplacements habituels.", + "s3165": "Le connecteur Cloudflare de cet ordinateur est trop ancien.", + "s3166": "Mettez cloudflared à jour vers une version plus récente, puis appuyez sur Réessayer l’installation.", + "s3167": "Le fichier trouvé comme cloudflared ne s’est pas exécuté.", + "s3168": "Réinstallez cloudflared, puis appuyez sur Réessayer l’installation.", + "s3169": "Fichier de réglages", + "s3170": "Ouvrir le fichier de réglages", + "s3171": "Les modifications que vous faites dans le fichier s’appliquent au prochain démarrage du modèle.", + "s3172": "Ouvrez plutôt le fichier depuis son dossier, ou réessayez.", + "s3173": "Votre fichier de réglages contient une erreur, le modèle ne démarrera donc pas tant qu’elle n’est pas corrigée.", + "s3174": "Ouvrez le fichier de réglages, corrigez les lignes ci-dessous, puis rechargez le modèle.", + "s3175": "Le fichier de réglages n’est pas du JSON valide ; regardez près de la ligne {0}. Vérifiez s’il manque une virgule entre deux entrées, s’il y a une virgule après la dernière entrée ou s’il manque un guillemet.", + "s3176": "Le fichier de réglages n’est pas du JSON valide. Vérifiez s’il manque une virgule entre deux entrées, s’il y a une virgule après la dernière entrée ou s’il manque un guillemet.", + "s3177": "Le fichier de réglages doit contenir un seul objet, { … }, avec les réglages à l’intérieur.", + "s3178": "\"{0}\" n’est pas un réglage lu par Strata, il est donc ignoré. Vouliez-vous dire \"{1}\" ?", + "s3179": "\"{0}\" n’est pas un réglage lu par Strata, il est donc ignoré.", + "s3180": "\"args\" doit être une liste d’entrées de texte entre guillemets, par exemple [\"--ple-io\", \"mmap\"]. Les nombres doivent aussi être entre guillemets.", + "s3181": "Strata gère lui-même l’adresse réseau, le port et la clé API : --host, --port et --api-key dans \"args\" ne sont donc pas pris en compte.", + "s3182": "\"env\" doit être un objet de noms STRATA_ avec des valeurs de texte entre guillemets.", + "s3183": "L’entrée \"env\" {0} doit être un texte entre guillemets, par exemple \"1\".", + "s3184": "\"sampling\" doit être un objet tel que { \"temperature\": 0.7 }.", + "s3185": "\"{0}\" doit être true ou false, pas {1}.", + "s3186": "\"{0}\" doit être un nombre de {1} à {2}, pas {3}.", + "s3187": "\"{0}\" doit être un nombre entier de {1} à {2}, pas {3}.", + "s3188": "\"{0}\" doit être l’une des valeurs {1}, pas {2}.", + "s3189": "\"{0}\" doit être un texte court, ou une liste de noms courts.", + "s3190": "Les points de \"layer_split\" doivent augmenter de 1 à 47, par exemple \"16,32\", ou valoir \"auto\".", + "s3191": "\"gpu\" doit être un numéro de carte graphique comme 0, ou une liste comme [0, 1].", + "s3192": "Ligne {0} : {1}", + "s3193": "Votre fichier de réglages contient une erreur, le modèle n’a donc pas été démarré.", + "s3194": "Ouvrez le fichier de réglages sous Réglages experts, corrigez la ligne indiquée sous Détails, puis rechargez le modèle.", + "s3195": "Mettez le moteur à jour (Paramètres, Moteur, Mettre à jour le moteur), puis réessayez.", + "s3196": "Déjà utilisé par {0}", + "s3197": "Arrêtez ou terminez la conversation qui utilise encore ce modèle, puis réessayez.", + "s3198": "Un autre modèle sur la même carte graphique n’a pas laissé de place à celui-ci.", + "s3199": "Chargez-le sur un autre GPU, ou déchargez d’abord l’autre modèle.", + "s3200": "cloudflared tourne déjà pour un autre tunnel (PID {0}).", + "s3201": "cloudflared tourne déjà pour d’autres tunnels (PID {0}).", + "s3202": "Le tunnel de Strata pour cette adresse tourne déjà (PID {0}).", + "s3203": "Le tunnel de Strata pour cette adresse tourne déjà.", + "s3204": "Arrêtez-le d’abord, ou utilisez-le tel quel, puis reconnectez-vous ici.", + "s3205": "Les modèles qui restent chargés utilisent environ {0} Go de RAM et {1} Go de la mémoire de cette carte.", + "s3206": "Activé par défaut", + "s3207": "Comprend les photos, les captures d’écran et les graphiques. Les fichiers d’images se téléchargent automatiquement. Désactivez-le pour économiser de la mémoire.", + "s3208": "Lire les images avec ce modèle", + "s3209": "(son serveur indique qu’il ne le peut pas)", + "s3210": "(activé par défaut)", + "s3211": "Les images ne peuvent être envoyées qu’aux API de modèles qui utilisent le style de conversation OpenAI. Choisissez un autre modèle, ou retirez l’image.", + "s3212": "La lecture d’images est désactivée pour ce modèle. Ouvrez Paramètres, Modèles, modifiez la connexion et activez Lire les images avec ce modèle, ou choisissez un autre modèle.", + "s3213": "Chargez d’abord un modèle qui lit les images, puis ajoutez l’image.", + "s3214": "Ce modèle a été démarré sans lecture d’images. Ouvrez Modèles, activez Lire les images et rechargez-le.", + "s3215": "Ce modèle ne peut pas lire les images. Choisissez un modèle qui lit les images, ou retirez l’image.", + "s3216": "Elle est ouverte dans l’aperçu.", + "s3217": "1 compétence utilisée : {0}", + "s3218": "{0} compétences utilisées : {1}", + "s3219": "Continuer dans une nouvelle conversation", + "s3220": "Suite de la tâche « {0} »", + "s3221": "(a exécuté {0}, terminé).", + "s3222": "(a exécuté {0}, sans terminer).", + "s3223": "Ce qu’elle a trouvé", + "s3224": "Demande votre attention", + "s3225": "Ce qu’elle a fait", + "s3226": "Fichiers", + "s3227": "Aidez-moi à reprendre à partir de là, s’il vous plaît.", + "s3228": "…et {0} étapes de plus", + "s3229": "Saisissez un nombre.", + "s3230": "Saisissez un nombre entier de {0} à {1}.", + "s3231": "Ajouter une compétence ouvre une fenêtre de dossier sur l’ordinateur qui exécute Strata. Ouvrez Strata sur cet ordinateur pour en ajouter une.", + "s3232": "Capture d’écran enregistrée", + "s3233": "Elle est dans votre dossier Téléchargements.", + "s3234": "La capture d’écran n’a pas été enregistrée", + "s3235": "Réessayez, ou faites plutôt une capture d’écran de cette fenêtre.", + "s3236": "La fenêtre de dossier ne s’est pas ouverte. Saisissez plutôt le chemin du dossier.", + "s3237": "Le fichier n’a pas été ajouté", + "s3238": "Essayez de le déposer à nouveau.", + "s3260": "NVFP4 (version de Strata)", + "s3261": "NVFP4 (version de NVIDIA)", + "s3262": "NVFP4 (NVIDIA, entraîné pour le FP4)", + "s3263": "Conversion propre à Strata. La meilleure qualité des versions NVFP4.", + "s3264": "Le checkpoint NVFP4 de NVIDIA, converti pour Strata. Même taille et même vitesse.", + "s3265": "Le checkpoint FP4 de NVIDIA, entraîné pour le FP4. Un peu plus rapide sur les prompts courts.", + "s3266": "Toutes les autres versions", + "s3267": "Plus de versions", + "s3268": "Téléchargement des fichiers du modèle · partie {0} sur {1}", + "s3269": "Téléchargement du lecteur d’images…", + "s3270": "Téléchargement du moteur pour ce PC…", + "s3271": "Préparation de {0}", + "s3272": "Parties du téléchargement", + "s3273": "Lecteur d’images", + "s3274": "Fichiers partagés", + "s3275": "Utilisés par plus d’un modèle", + "s3276": "Ces fichiers sont dans votre propre dossier, ils y restent donc. Seule l’entrée dans Strata est retirée.", + "s3277": "Le modèle en cours d’exécution sera déchargé.", + "s3278": "Local", + "s3279": "Strata n’a pas reconnu de moteur pour cet ordinateur. Le modèle va se télécharger, mais il risque de ne pas fonctionner tant que le bon moteur n’est pas installé (Paramètres → Moteur).", + "s3280": "Strata n’a pas reconnu de moteur pour cet ordinateur. Le modèle est téléchargé, mais il ne peut pas fonctionner tant que le bon moteur n’est pas installé. Ouvrez Paramètres → Moteur.", + "s7332": "Un modèle est en cours de téléchargement", + "s7333": "Votre modèle est en cours de téléchargement ({0} %). Vous pourrez discuter quand il sera terminé.", + "s7334": "Votre modèle est en cours de téléchargement. Vous pourrez discuter quand il sera terminé.", + "s7335": "Le modèle se charge", + "s7336": "Votre modèle est encore en cours de chargement. Vous pourrez discuter dans un instant.", + "s7337": "Aucun modèle n’est chargé", + "s7338": "Aucun modèle n’est chargé. Chargez-en un d’abord dans Modèles.", + "s7339": "Démarrage de l’assistant…", + "s7340": "L’assistant n’a pas pu démarrer. Réessayez dans un instant.", + "s7341": "Travail sur l’objectif…", + "s8001": "le choix pour ce PC", + "s8002": "l’autre choix", + "s7400": "L’assistant veut chercher sur le web : {0}. Les mots recherchés sont envoyés à {1}.", + "s7401": "L’assistant veut ouvrir la page web {0}. Le site de la page voit la requête.", + "s7402": "Laisser l’assistant chercher sur le web sans demander", + "s7403": "En mode Manuel, l’assistant demande une fois par conversation avant de chercher sur le web ou d’ouvrir une page web. Activez ceci pour passer cette question.", + "s7404": "DuckDuckGo, ou Bing quand DuckDuckGo est saturé", + "s8201": "moins d'1 min", + "s8202": "{0} min", + "s8203": "{0} h", + "s8204": "{0} j", + "s8205": "il y a {0}", + "s8206": "aujourd’hui {0}", + "s8207": "hier", + "s8208": "démarrée {0}", + "s8209": "en attente depuis {0}", + "s8210": "prochaine dans {0}", + "s8211": "répond maintenant", + "s8212": "arrêtée {0}", + "s8213": "Elle ne s’est pas terminée.", + "s8214": "Cette exécution a été arrêtée avant la fin.", + "s8215": "Strata s’est fermé pendant cette exécution, elle ne s’est donc pas terminée.", + "s8216": "Terminée, mais elle voulait modifier quelque chose sans pouvoir demander. Rien n’a été modifié.", + "s8217": "Arrêtée : {0} exécutions de suite n’ont pas fonctionné.", + "s8218": "Tâche planifiée", + "s8219": "Boucle · {0}", + "s8220": "Chargez d’abord un modèle", + "s8221": "Autres actions pour {0}", + "s8222": "Les cartes bougent toutes seules selon ce qui se passe. Une carte de À traiter y reste jusqu’à ce que vous vous en occupiez ou la fermiez.", + "s8223": "{0} demandent votre attention", + "s8224": "Rien n’a besoin de vous pour l’instant.", + "s8225": "{0} cartes", + "s8226": "À venir", + "s8227": "Suite de la conversation « {0} »", + "s8228": "La boucle", + "s8229": "Ce que j’ai demandé", + "s8230": "La dernière réponse", + "s8231": "Tableau des tâches", + "s8232": "À traiter", + "s8233": "Vous attendent", + "s8234": "Arrêtée sur une question à laquelle vous seul pouvez répondre.", + "s8235": "A trouvé un problème. Reste ici jusqu’à ce que vous vous en occupiez.", + "s8236": "Terminée sans problème ces 7 derniers jours.", + "s8237": "Relancer", + "s8238": "Ouvrir la tâche", + "s8239": "Ouvrir la conversation", + "s8240": "Arrêter la conversation", + "s8241": "Arrêter la boucle", + "s8242": "Voir le résultat", + "s8243": "Terminée", + "s8244": "Arrêtée par vous", + "s8245": "Arrêtée à la fermeture de Strata", + "s8246": "Terminée d’elle-même", + "s8247": "réponse {0} sur {1}", + "s8248": "réponse {0}", + "s8249": "1 auxiliaire au travail", + "s8250": "{0} auxiliaires au travail", + "s8251": "Tableau", + "s8252": "Afficher", + "s8253": "Tout ce qui tourne, attend votre réponse ou mérite un coup d’œil.", + "s8254": "Ça n’a pas fonctionné", + "s8255": "Aucune carte correspondante.", + "s8256": "Rien ici pour l’instant.", + "s8257": "toutes les {0} min", + "s8258": "Ce moteur Strata n’a pas de code pour la carte graphique qu’il a essayé d’utiliser.", + "s8259": "Choisissez une autre carte sous Exécuter sur, ou ouvrez Détails pour voir quelles cartes ont été trouvées et pour quoi le moteur est conçu.", + "s8260": "Ce réglage ne fait rien dans l’application. Les pages web de n’importe quel site peuvent déjà appeler l’API indiquée sous Serveur API. Pour n’autoriser que certains sites, ou pour utiliser le serveur propre du moteur (port 8080), ajoutez \"cors_origins\": [\"https://your.site\"] au fichier de configuration du modèle.", + "s8301": "Créer une clé API (recommandé)", + "s8302": "Sans clé API, n’importe quel appareil de ce réseau peut utiliser votre modèle.", + "s8303": "Seule l’API d’inférence est partagée. Les clients ont besoin de votre clé API quand il y en a une. Utilisez un réseau local de confiance ; cette connexion utilise HTTP.", + "s8304": "Créez une clé pour protéger votre API. Vous reviendrez ici quand elle sera prête. Vous pouvez aussi continuer sans clé, mais toute personne qui trouve le lien pourra alors utiliser votre modèle.", + "s8305": "Vous avez déjà un modèle pris en charge sur cet ordinateur ? Choisissez le dossier qui contient ses fichiers, ou l’un de ses fichiers .gguf. Strata les vérifie, prépare le modèle et le charge. Rien n’est copié ni téléchargé.", + "s8306": "Dossier contenant les fichiers GGUF, ou un fichier .gguf", + "s8307": "Chemin complet du dossier ou du fichier", + "s8308": "Sans clé API, toute personne qui peut atteindre cette adresse peut utiliser votre modèle.", + "s8309": "Strata n’a pas pu utiliser {0} pour les modèles ({1}), ils sont donc placés dans {2}. Vous pouvez choisir un autre dossier dans les Paramètres.", + "s8310": "Le port {0} est déjà utilisé. Strata est peut-être déjà en cours d’exécution ; fermez-le ou fermez l’autre programme, ou lancez Strata avec un autre port (STRATA_PORT).", + "s8311": "Windows ou un pare-feu ne laisse pas Strata utiliser le port {0}. Hyper-V, WSL et Docker se réservent des plages de ports (voir \"netsh int ipv4 show excludedportrange protocol=tcp\"). Lancez Strata avec un autre port (STRATA_PORT), par exemple 8801.", + "s8312": "{0} n’est pas une adresse de cet ordinateur, Strata ne peut donc pas y écouter. Vérifiez STRATA_BIND.", + "s8313": "Strata ne peut pas écouter sur {0}:{1} ({2}).", + "s8339": "Dossier des modèles", + "s8340": "Strata enregistre ici les gros fichiers de modèles.", + "s8341": "Changer de dossier", + "s8342": "En attente du dossier…", + "s8343": "Espace disque utilisé", + "s8344": "{0} libres", + "s8345": "sur ce disque", + "s8346": "Vos modèles utilisent {0}", + "s8347": "Terminez ou arrêtez le téléchargement pour changer de dossier.", + "s8348": "Ce dossier n’existe pas", + "s8349": "Ce dossier ne peut pas être utilisé", + "s8350": "Strata ne peut pas enregistrer de fichiers dans {0}.", + "s8351": "Strata ne trouve pas {0}.", + "s8352": "Choisissez un dossier en dehors du dossier actuel.", + "s8353": "Choisissez un dossier qui vous appartient, par exemple dans Documents ou sur un autre disque.", + "s8354": "Vérifiez que le disque est branché, puis choisissez à nouveau le dossier. Vos modèles n’ont pas été touchés.", + "s8355": "Utiliser ce dossier pour vos modèles ?", + "s8356": "Nouveau dossier", + "s8357": "{0} libres sur ce disque", + "s8358": "Vous avez choisi tout le disque {0}. Strata garde ses fichiers dans un dossier à part, vos modèles iront donc dans {1}.", + "s8359": "Les trois choix viennent ensuite.", + "s8360": "Déplacer mes modèles", + "s8361": "Utiliser les deux dossiers", + "s8362": "Repartir de zéro", + "s8363": "Déplacement de vos modèles", + "s8364": "Arrêter le déplacement", + "s8365": "{0} sur {1} Go", + "s8366": "Moins d’une minute restante", + "s8367": "Environ une minute restante", + "s8368": "Environ {0} minutes restantes", + "s8369": "Environ {0} heures restantes", + "s8370": "Gardez Strata ouvert. Vous pouvez continuer à utiliser d’autres applications. Vos modèles ne peuvent pas être chargés tant que le déplacement n’est pas terminé.", + "s8371": "Copie en cours : {0}, fichier {1} sur {2}", + "s8372": "De {0} vers {1}", + "s8373": "Déplacer mes modèles là-bas", + "s8374": "Vous n’avez aucun modèle à déplacer.", + "s8375": "Strata déplace vos {0} de modèles vers le nouveau dossier. C’est le même disque, cela prend donc un instant.", + "s8376": "Strata copie vos {0} de modèles vers le nouveau dossier, les vérifie, puis supprime les anciennes copies.", + "s8377": "Ne demande aucun espace supplémentaire.", + "s8378": "Demande {0} libres dans le nouveau dossier. Vous avez {1}.", + "s8379": "Les garder où ils sont et utiliser aussi le nouveau dossier", + "s8380": "Rien n’est copié. Vos modèles actuels continuent de fonctionner, et les nouveaux téléchargements vont dans le nouveau dossier.", + "s8381": "Ne demande pas d’espace maintenant. Les nouveaux téléchargements doivent tenir dans {1}.", + "s8382": "Ne demande pas d’espace maintenant.", + "s8383": "Strata utilise désormais le nouveau dossier et n’affiche pas vos modèles actuels. Vos anciens fichiers ne sont pas supprimés.", + "s8384": "Ne demande pas d’espace maintenant. Chaque modèle que vous téléchargerez ensuite aura besoin de son propre espace.", + "s8385": "Vos modèles ont besoin de {0}, ce disque a {1} libres.", + "s8386": "Libérez environ {0} sur ce disque, choisissez un autre dossier, ou prenez l’une des deux autres options.", + "s8387": "Ce qui doit arriver à vos modèles", + "s8388": "Un modèle en cours d’exécution est d’abord arrêté ; rechargez-le quand le déplacement est terminé.", + "s8389": "{0} seraient déplacés.", + "s8390": "L’espace libre est mesuré sur le disque qui contient {0}.", + "s8391": "Ancien dossier : {0}", + "s8392": "Strata copie un fichier à la fois et vérifie sa taille avant de supprimer l’ancien.", + "s8393": "Vous pouvez arrêter à tout moment ; les fichiers déjà déplacés restent utilisables.", + "s8394": "Le disque n’a plus d’espace", + "s8395": "Le déplacement s’est arrêté", + "s8396": "{0} s’est rempli après {1}, le déplacement s’est donc arrêté.", + "s8397": "Les modèles n’ont pas pu être déplacés.", + "s8398": "Rien n’a été perdu. Les modèles déjà déplacés sont dans le nouveau dossier, les autres sont toujours dans {0}, et le fichier à moitié copié a été supprimé. Libérez de l’espace sur {1} ou choisissez un autre dossier, puis réessayez.", + "s8399": "Rien n’a été perdu. Tous vos modèles sont toujours dans {0}, et le fichier à moitié copié a été supprimé. Libérez de l’espace sur {1} ou choisissez un autre dossier, puis réessayez.", + "s8400": "Rien n’a été perdu. Vos modèles qui n’ont pas été déplacés sont toujours dans {0}. Choisissez un autre dossier pour réessayer.", + "s8401": "Déplacement arrêté", + "s8402": "Rien n’a été perdu.", + "s8403": "{0} est dans le nouveau dossier.", + "s8404": "{0} est toujours dans l’ancien dossier.", + "s8405": "Les deux fonctionnent.", + "s8406": "Les modèles des deux dossiers sont listés normalement. Vous pourrez terminer le déplacement plus tard avec Changer de dossier.", + "s8407": "Vos modèles sont déplacés", + "s8408": "{0} sont maintenant dans {1}", + "s8409": "Les anciennes copies ont été supprimées et {0} sont de nouveau libres sur {1}.", + "s8410": "Strata utilise désormais aussi {0}. Les nouveaux téléchargements y vont, et vos modèles actuels restent où ils sont.", + "s8411": "Strata utilise désormais {0}. Vos anciens fichiers de modèles sont toujours dans {1} ; Strata ne les supprime pas.", + "s8412": "Le changement du dossier des modèles fait partie de l’application Strata.", + "s8413": "Un modèle est en cours d’exécution. Arrêtez-le d’abord, puis changez de dossier.", + "s8414": "Choisissez un dossier de modèles.", + "s8415": "Choisissez ce qu’il faut faire de vos modèles.", + "s8416": "Ce choix n’est pas possible ici.", + "s8417": "Un déplacement a été interrompu. Terminez-le ou laissez-le.", + "s8418": "Strata déplaçait vos modèles de {0} vers {1} quand il s’est arrêté. Rien n’est perdu.", + "s8419": "Terminer le déplacement", + "s8420": "Le laisser", + "s8421": "Terminer place tous vos modèles dans {1}. Le laisser les garde dans {0} et supprime les copies partielles de {1}.", + "s8422": "Les copies partielles ont été supprimées. Vos modèles sont dans {0}.", + "s8601": "Cartes graphiques", + "s8602": "Principale", + "s8603": "Auxiliaire", + "s8604": "Votre choix.", + "s8605": "Recommandé.", + "s8606": "Vous avez changé les rôles. Strata utilisera exactement ceux-ci.", + "s8607": "Recommandé : {0}", + "s8608": "Rôle de {0}", + "s8609": "{0} Go de mémoire", + "s8610": "Utilise la mémoire de votre ordinateur (graphisme intégré)", + "s8611": "Fait le travail principal", + "s8612": "Contient une partie du modèle", + "s8613": "Inutilisée", + "s8614": "Utilisée par {0}", + "s8615": "La désactiver", + "s8616": "Définir {0} comme principale", + "s8617": "{0} ne peut pas exécuter Strata.", + "s8618": "{0} est un graphisme intégré ; elle est lente comme carte principale.", + "s8619": "Les performances sont dégradées avec le CPU seul.", + "s8620": "Ce moteur a besoin d’une carte graphique pour démarrer. Activez-en une.", + "s8621": "Pas assez de mémoire pour cette configuration : environ {0} Go sont lus depuis le disque.", + "s8622": "{0} est maintenant auxiliaire.", + "s8623": "{0} est maintenant principale.", + "s8624": "La seule carte activée doit être la principale.", + "s8625": "Aucune carte graphique utilisable par Strata n’a été trouvée.", + "s8626": "Strata utilisera votre {0}.", + "s8627": "{0} est principale : {1}.", + "s8628": "les cartes se valent", + "s8629": "elle a plus de mémoire", + "s8630": "elle est plus rapide", + "s8631": "c’est la seule carte", + "s8632": "{0} aident.", + "s8633": "{0} aide.", + "s8634": "{0} démarre désactivée : {1}", + "s8635": "Strata ne peut pas l’exécuter.", + "s8636": "graphisme intégré.", + "s8637": "{0} Go ou moins.", + "s8638": "La carte qui fait les dernières étapes de chaque réponse : elle écrit les mots suivants, exécute l’étape d’anticipation et la vérifie, et garde votre conversation. Choisissez votre carte la plus rapide avec beaucoup de mémoire. Il n’y en a jamais qu’une.", + "s8639": "Contient une part du modèle et de sa mémoire rapide, pour que davantage tienne sur les cartes graphiques au lieu d’être lu depuis votre disque. Les prompts sont lus environ 20 % plus vite.", + "s8640": "Strata ne touche pas à cette carte. Pratique pour une carte que vous utilisez pour autre chose, comme un jeu ou votre écran.", + "s8641": "Le modèle a besoin d’environ {0} Go. Ces cartes et votre mémoire en offrent environ {1}. Il tient.", + "s8642": "Le modèle a besoin d’environ {0} Go. Ces cartes et votre mémoire en offrent environ {1}, donc environ {2} Go seraient lus depuis votre disque.", + "s8643": "Seuls votre processeur et votre mémoire sont utilisés.", + "s8644": "Pour les experts : le moteur démarre sur les cartes {0} (la principale en dernier).", + "s8645": "Non enregistré tant que vous gardez la recommandation : Strata choisit à nouveau si vous ajoutez ou retirez une carte.", + "s8646": "Inutilisée : {0} (une autre marque de carte graphique que celle que ce moteur pilote).", + "s9001": "Ce message fait environ {0} tokens, et ce modèle peut en lire environ {1} à la fois. Il est trop gros pour être envoyé tel quel.", + "s9002": "Joignez-le comme fichier pour que l’assistant le lise par parties, ou envoyez un aperçu raccourci.", + "s9003": "Cette conversation ne tient plus dans la fenêtre du modèle, et le résumé des anciens messages n’a pas libéré assez de place.", + "s9004": "Résumez-la maintenant et continuez, ou ouvrez une nouvelle conversation.", + "s9005": "Résumé des messages précédents…", + "s9006": "Les anciens messages ont été résumés pour faire de la place. La conversation était pleine à {0} % et l’est maintenant à {1} %.", + "s9007": "Les anciens messages ont été résumés pour faire de la place. La conversation était pleine à {0} %.", + "s9008": "Les anciens messages ont été résumés pour faire de la place.", + "s9009": "Cette conversation est pleine à {0} %, mais il n’y a rien d’ancien à résumer : c’est le dernier message qui la remplit. Ouvrez une nouvelle conversation, ou envoyez un message plus court.", + "s9010": "Il n’y a encore rien d’ancien à résumer. Tout ce qui est dans cette conversation sert encore à l’assistant.", + "s9011": "Il n’y a encore rien à résumer. Cette conversation n’a pas encore commencé avec l’assistant.", + "s9012": "Les anciens messages n’ont pas pu être résumés pour le moment. Réessayez dans un instant, ou ouvrez une nouvelle conversation.", + "s9013": "Cette conversation est encore en cours de travail. Arrêtez-la ou attendez la fin, puis réessayez.", + "s9014": "Joindre comme fichier", + "s9015": "Envoyer un aperçu raccourci", + "s9016": "Résumer et continuer", + "s9017": "Ouvrir une nouvelle conversation", + "s9018": "Le message n’a pas pu être préparé. Essayez un message plus court.", + "s9019": "La dernière session de Strata est encore en cours de fermeture.", + "s9020": "Attendez un instant et réessayez. Si le problème persiste, redémarrez l’ordinateur.", + "s9021": "Anticipation", + "s9022": "Auto (recommandé)", + "s9023": "MTP", + "s9024": "DFlash2", + "s9025": "Anticipation : MTP (DFlash2 ne tenait pas)", + "s9026": "Anticipation : MTP (DFlash2 n’est pas disponible dans ce mode)", + "s9027": "Anticipation : MTP (DFlash2 est réservé à Qwen3.8-Flash-Next)", + "s9028": "Anticipation : MTP (le module d’anticipation DFlash2 n’est pas encore téléchargé)", + "s9029": "Choisir DFlash2 télécharge aussi son module d’anticipation : environ {0} Go, une seule fois. S’il ne tient pas dans la mémoire graphique, le modèle utilise MTP à la place.", + "s9030": "Téléchargement du module d’anticipation DFlash2…", + "s9031": "Préparation du module d’anticipation DFlash2 pour le moteur…", + "s9032": "Le module d’anticipation DFlash2 est prêt.", + "s9033": "Le module d’anticipation DFlash2 n’a pas pu être téléchargé, le modèle démarre donc avec MTP. Chargement du modèle…", + "s9034": "Chargement du modèle…", + "s9035": "Ces fichiers du modèle sont manquants : {0}.", + "s9036": "Appuyez à nouveau sur Télécharger et charger pour les récupérer. Les fichiers déjà présents sont conservés. Si les mêmes fichiers sont listés à nouveau, ouvrez Détails et partagez-les quand vous demandez de l’aide.", + "s9037": "Cette mise à jour a été interrompue au redémarrage de l’application. Une mise à jour plus récente s’est terminée, il n’y a donc rien à faire." +} diff --git a/apps/host/src/locales/tools-fr.json b/apps/host/src/locales/tools-fr.json new file mode 100644 index 00000000..5d12b6d9 --- /dev/null +++ b/apps/host/src/locales/tools-fr.json @@ -0,0 +1,6 @@ +{ + "tl01": "Utilisez un nom de serveur simple de 32 caractères maximum : lettres, chiffres, tirets ou tirets bas.", + "tl02": "Ces serveurs d’outils ont été laissés de côté car leurs noms ne sont pas autorisés : {0}. Un nom peut contenir jusqu’à 32 lettres, chiffres, tirets ou tirets bas.", + "tl03": "Ces serveurs d’outils ont été laissés de côté car ils n’ont ni programme ni adresse web : {0}.", + "tl04": "Ces serveurs d’outils ont été laissés de côté car un autre a presque le même nom : {0}." +} diff --git a/apps/host/src/locales/tune-fr.json b/apps/host/src/locales/tune-fr.json new file mode 100644 index 00000000..6f81ceb2 --- /dev/null +++ b/apps/host/src/locales/tune-fr.json @@ -0,0 +1,45 @@ +{ + "tune01": "Optimiser ce modèle", + "tune02": "Recherche des réglages les plus rapides pour votre PC…", + "tune03": "environ {0} min restantes", + "tune04": "Cela prend environ 20 minutes.", + "tune05": "Arrêté. Vos réglages n’ont pas été modifiés.", + "tune06": "L’optimisation n’est pas terminée. Vos réglages n’ont pas été modifiés.", + "tune07": "Toujours aussi rapide qu’à l’enregistrement.", + "tune08": "C’est plus lent qu’avant. Vous pouvez optimiser à nouveau.", + "tune09": "Impossible de savoir pour l’instant. Votre optimisation a été conservée.", + "tune10": "Réponses {0} % plus rapides, enregistré sous « {1} »", + "tune11": "Vos réglages actuels sont déjà les plus rapides que nous ayons trouvés.", + "tune12": "Rien n’a été modifié.", + "tune13": "Enregistré sous « {0} », il ne sera donc pas réoptimisé à la réouverture de l’application.", + "tune14": "Vitesse : {0} → {1} tok/s", + "tune15": "Les réponses sont identiques à la configuration standard.", + "tune16": "Les réponses peuvent différer légèrement de la configuration standard.", + "tune17": "Les réponses ne sont pas reproductibles d’une exécution à l’autre.", + "tune18": "Comprend un réglage de qualité qui modifie les chiffres.", + "tune19": "Optimisation enregistrée utilisée : {0}", + "tune20": "Réponses {0} % plus rapides", + "tune21": "Ce PC a changé depuis l’optimisation, ces réglages ne sont donc pas utilisés tant que vous n’optimisez pas à nouveau.", + "tune22": "Ce PC ou le moteur a changé depuis l’optimisation. Une vérification courte prend environ 2 minutes.", + "tune23": "Pas encore d’optimisation enregistrée pour ces choix.", + "tune24": "Strata essaie différents réglages sur ce PC et garde ceux qui accélèrent les réponses. Votre modèle est déchargé pendant ce temps, et l’ordinateur sera occupé.", + "tune25": "Terminez d’abord l’opération en cours.", + "tune26": "Durée à y consacrer", + "tune27": "Rapide (environ 20 minutes)", + "tune28": "Approfondie (jusqu’à 2 heures)", + "tune29": "Ce que vous faites surtout", + "tune30": "Programmation avec de longs prompts", + "tune31": "Autoriser les réglages qui changent très légèrement les réponses (même qualité)", + "tune32": "Optimisations enregistrées", + "tune33": "Utilisée", + "tune34": "Utiliser", + "tune35": "Optimiser à nouveau", + "tune36": "Lancer l’optimisation", + "tune37": "Optimisation de votre modèle", + "tune38": "Les réponses peuvent différer d’une exécution à l’autre sur ce PC même avec la configuration standard ; ce réglage n’y ajoute rien.", + "tune39": "Utilisation de votre optimisation « {0} »", + "tune40": "Désactiver", + "tune41": "Activer", + "tune42": "Votre optimisation est désactivée. Les réglages standard sont utilisés.", + "tune43": "Votre PC était occupé, les mesures n’étaient donc pas fiables. Rien n’a été modifié. Réessayez quand il est au calme." +} diff --git a/apps/host/tests/agent-events.test.mjs b/apps/host/tests/agent-events.test.mjs index bacba919..6564e4fd 100644 --- a/apps/host/tests/agent-events.test.mjs +++ b/apps/host/tests/agent-events.test.mjs @@ -138,7 +138,7 @@ test('a chat that existed before the agent carries a bounded summary into its fi test('the browser and the person\'s own tools have plain sentences, translated in every language', async () => { const { readFileSync } = await import('node:fs'); - const catalog = Object.fromEntries(['en', 'de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh'].map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))])); + const catalog = Object.fromEntries(['en', 'de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh'].map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))])); const idOf = text => Object.entries(catalog.en).find(([, v]) => v === text)?.[0]; const cases = [ ['mcp__browser__browser_navigate', 'Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"], @@ -157,7 +157,7 @@ test('the browser and the person\'s own tools have plain sentences, translated i ]; for (const [name, running, done, failed] of cases) { assert.equal(toolVerb(name, 'running'), running, name); assert.equal(toolVerb(name, 'done'), done, name); assert.equal(toolVerb(name, 'error'), failed, name); - for (const text of [running, done, failed]) { const id = idOf(text); assert.ok(id, `${text} is in the catalog`); for (const l of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) assert.ok(catalog[l][id]?.trim(), `${l}: ${text}`); } + for (const text of [running, done, failed]) { const id = idOf(text); assert.ok(id, `${text} is in the catalog`); for (const l of ['de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh']) assert.ok(catalog[l][id]?.trim(), `${l}: ${text}`); } } const nav = presentTool({ callId: 'c1', name: 'mcp__browser__browser_navigate', args: { url: 'https://example.com' } }); assert.equal(nav.target, 'https://example.com'); assert.equal(nav.verb, 'Opening a page in the browser'); diff --git a/apps/host/tests/agent-status.test.mjs b/apps/host/tests/agent-status.test.mjs index a25b9da8..c9d6d811 100644 --- a/apps/host/tests/agent-status.test.mjs +++ b/apps/host/tests/agent-status.test.mjs @@ -154,7 +154,7 @@ test('real Harness: a turn that writes a file says what it is doing, in order, a test('a sentence with a name or a number also carries its catalog template and values, and every status sentence is in the catalog in every language', async () => { const { readFileSync } = await import('node:fs'); - const catalog = Object.fromEntries(['en', 'de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh'].map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))])); + const catalog = Object.fromEntries(['en', 'de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh'].map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))])); const idOf = text => Object.entries(catalog.en).find(([, v]) => v === text)?.[0]; const p = new TurnProjector(); const seen = []; p.onStatus = u => seen.push(u); p.consume({ type: 'assistant-stream', frame: { type: 'chunk', attemptId: 'a', chunk: { type: 'tool-call-delta', index: 0, id: 'c', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"' + 'x'.repeat(4000) } } }); @@ -163,7 +163,7 @@ test('a sentence with a name or a number also carries its catalog template and v const keys = ['Starting the assistant…', 'Starting…', 'Reading your message…', 'Working out the next step…', 'Thinking… {0} tokens', 'Writing the answer…', 'Waiting for your answer…', 'Helpers are working ({0})…', 'Working on the goal…', 'Writing {0}…', 'Writing a file…', 'Writing {0}… ({1} KB)', 'Writing a file… ({0} KB)', 'Changing {0}…', 'Changing a file…', 'Reading {0}…', 'Reading a file…', 'Running a command…', 'Searching your files…', 'Searching the web…', 'Opening {0}…', 'Opening a web page…', 'Using the browser…', 'Setting the goal…', 'Updating the goal…', 'Checking the goal…', 'Using a tool…', 'Reading your files…', 'Trying an improved version…', 'Checking the result…', 'Comparing the two versions…']; - for (const key of keys) { const id = idOf(key); assert.ok(id, `${key} is in the catalog`); for (const l of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { assert.ok(catalog[l][id]?.trim(), `${l}: ${key}`); assert.deepEqual((catalog[l][id].match(/\{\d\}/g) ?? []).sort(), (key.match(/\{\d\}/g) ?? []).sort(), `${l} keeps the slots of ${key}`); } } + for (const key of keys) { const id = idOf(key); assert.ok(id, `${key} is in the catalog`); for (const l of ['de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh']) { assert.ok(catalog[l][id]?.trim(), `${l}: ${key}`); assert.deepEqual((catalog[l][id].match(/\{\d\}/g) ?? []).sort(), (key.match(/\{\d\}/g) ?? []).sort(), `${l} keeps the slots of ${key}`); } } }); test('a goal step is always sent, even right after another status (it used to be swallowed by the 300 ms gap, which made a test flaky)', () => { diff --git a/apps/host/tests/agent-turn-guard.test.mjs b/apps/host/tests/agent-turn-guard.test.mjs index 4f33f171..6ac287a3 100644 --- a/apps/host/tests/agent-turn-guard.test.mjs +++ b/apps/host/tests/agent-turn-guard.test.mjs @@ -74,8 +74,8 @@ test('a turn that ends with no words always gets a plain message: out of room, o assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700, stoppedByPerson: true }), null, 'Stop is the person\'s own'); }); -test('every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all eight languages', () => { - const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +test('every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all nine languages', () => { + const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))])); const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0]; for (const [reason, text] of Object.entries(GUARD_NOTES)) { diff --git a/apps/host/tests/card-labels.test.mjs b/apps/host/tests/card-labels.test.mjs index 9943fdbd..33e164e9 100644 --- a/apps/host/tests/card-labels.test.mjs +++ b/apps/host/tests/card-labels.test.mjs @@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; const root = resolve(import.meta.dirname, '..'); -const languages = ['en', 'de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']; +const languages = ['en', 'de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh']; const catalog = Object.fromEntries(languages.map(l => [l, JSON.parse(readFileSync(resolve(root, 'src/locales', `${l}.json`), 'utf8'))])); const idOf = text => Object.entries(catalog.en).find(([, v]) => v === text)?.[0]; diff --git a/apps/host/tests/context-ui.test.mjs b/apps/host/tests/context-ui.test.mjs index b9b8dfc4..b55f46c9 100644 --- a/apps/host/tests/context-ui.test.mjs +++ b/apps/host/tests/context-ui.test.mjs @@ -1,5 +1,5 @@ // The page side of the context fixes (2026-10-22 hands-on test): what the error card offers, what the context meter reads while a turn runs, -// and that every sentence the host or the page says about the context is in the catalog in all eight languages. +// and that every sentence the host or the page says about the context is in the catalog in all nine languages. import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; @@ -99,8 +99,8 @@ test('the context meter follows the turn that is running: a tool step does not r assert.equal(chatMetrics(session([earlier, done]), null, 65536).used, 43090, 'when the turn has ended its final figure stands'); }); -test('every sentence about the context is in the catalog in all eight languages, with the same slots', () => { - const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +test('every sentence about the context is in the catalog in all nine languages, with the same slots', () => { + const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(read(`../src/locales/${l}.json`))])); const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0]; const sentences = [...Object.values(FIT_TEXT), 'Attach as a file', 'Send a shortened preview', 'Summarize and continue', 'Start a new chat', diff --git a/apps/host/tests/cors-help.test.mjs b/apps/host/tests/cors-help.test.mjs index 12c178fe..431285df 100644 --- a/apps/host/tests/cors-help.test.mjs +++ b/apps/host/tests/cors-help.test.mjs @@ -4,9 +4,9 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { expertParams } from '../server/catalog.mjs'; -const languages = ['en', 'de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']; +const languages = ['en', 'de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh']; -test('the CORS setting explains itself and the explanation exists in all 8 languages', async () => { +test('the CORS setting explains itself and the explanation exists in all 9 languages', async () => { const cors = expertParams().find(p => p.id === 'server.cors'); assert.match(cors.effect, /does nothing in the app/); assert.match(cors.effect, /"cors_origins"/); diff --git a/apps/host/tests/deepseek-context.test.mjs b/apps/host/tests/deepseek-context.test.mjs index 6963fb65..40bdd7cb 100644 --- a/apps/host/tests/deepseek-context.test.mjs +++ b/apps/host/tests/deepseek-context.test.mjs @@ -87,12 +87,12 @@ test('the Models screen honours the choice (it no longer forces 8K), offers the assert.match(screen, /installed\?\.ready && context === installed\.context/, 'a load at the prepared context starts from the saved file; only a changed choice runs setup again'); }); -test('the note is in the catalog in all eight languages, translated', () => { +test('the note is in the catalog in all nine languages, translated', () => { const find = lang => Object.values(JSON.parse(read(`../src/locales/fix-${lang}.json`))); assert.ok(find('en').includes(UNTESTED_NOTE)); const en = JSON.parse(read('../src/locales/fix-en.json')); const id = Object.keys(en).find(k => en[k] === UNTESTED_NOTE); - for (const lang of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']) { + for (const lang of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { const text = JSON.parse(read(`../src/locales/fix-${lang}.json`))[id]; assert.ok(text && text !== UNTESTED_NOTE, `${lang} is translated`); } diff --git a/apps/host/tests/drafting.test.mjs b/apps/host/tests/drafting.test.mjs index 89987d95..fe7d398f 100644 --- a/apps/host/tests/drafting.test.mjs +++ b/apps/host/tests/drafting.test.mjs @@ -1,5 +1,5 @@ // The Drafting choice in the app (MTP / DFlash2 / Off / Auto): the Models screen row, the setting the host saves, what the host asks Control before -// a load, the download plan line, and the words in all eight languages. The table of which card gets which drafter lives in Python +// a load, the download plan line, and the words in all nine languages. The table of which card gets which drafter lives in Python // (strata_control/drafting.py, tests/terminal/test_drafting.py); the app never reads it. import test from 'node:test'; import assert from 'node:assert/strict'; @@ -77,8 +77,8 @@ test('a load fetches the drafter first, never stops for it, and says what ran', assert.match(source, /drafting:cfg\.drafting\?\?'auto'/, 'the installed model reports its saved choice'); }); -test('every sentence of the Drafting choice is in the catalog in all eight languages, with the same slots', () => { - const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +test('every sentence of the Drafting choice is in the catalog in all nine languages, with the same slots', () => { + const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(read(`../src/locales/${l}.json`))])); const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0]; const sentences = ['Drafting', 'Auto (recommended)', 'MTP', 'DFlash2', diff --git a/apps/host/tests/french-catalog.test.mjs b/apps/host/tests/french-catalog.test.mjs new file mode 100644 index 00000000..acd2451f --- /dev/null +++ b/apps/host/tests/french-catalog.test.mjs @@ -0,0 +1,60 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { build } from 'esbuild'; + +// French (#3970): the catalogs are complete (the generic language tests cover keys and placeholders); these tests cover +// what is specific to French: spacing before ? ! : ;, apostrophes, short labels staying short, and the picker entry. +const names = [['en', 'fr'], ['fix-en', 'fix-fr'], ['tune-en', 'tune-fr'], ['tools-en', 'tools-fr']]; +const read = async name => JSON.parse(await readFile(`src/locales/${name}.json`, 'utf8')); +const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); +const { tr, setTranslationLanguage, localeTag, currentLanguage, LANGUAGES, validLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +test('French is in the language picker under its own name', () => { + const entry = LANGUAGES.find(item => item.value === 'fr'); + assert.equal(entry?.label, 'Français'); + assert.ok(validLanguage('fr')); + assert.equal(LANGUAGES.length, 9); + setTranslationLanguage('fr'); + assert.equal(currentLanguage(), 'fr'); + assert.equal(localeTag(), 'fr'); + assert.equal(tr('Settings'), 'Paramètres'); + assert.equal(tr('Cancel'), 'Annuler'); + assert.equal(tr('Open {0}', ['Modèles']).includes('{'), false); + assert.equal(tr('unrecognized user content Ω'), 'unrecognized user content Ω'); + setTranslationLanguage('en'); +}); + +test('French text keeps the French typography: a no-break space before ? ! : ; and a typographic apostrophe', async () => { + const bad = []; + for (const [englishName, frenchName] of names) { + const english = await read(englishName), french = await read(frenchName); + for (const [id, text] of Object.entries(french)) { + if (text === english[id]) continue; // kept as is: names, file names, class names + if (/[A-Za-zÀ-ÿ\)\]\d%] [?!;:]/.test(text) && !/https?:|\d:\d/.test(text)) bad.push(`${id}: ordinary space before punctuation: ${text}`); + if (/[A-Za-zÀ-ÿ\)\]\d%][?!;]/.test(text)) bad.push(`${id}: no space before ? ! or ;: ${text}`); + if (/[A-Za-zÀ-ÿ]'[A-Za-zÀ-ÿ{]/.test(text)) bad.push(`${id}: straight apostrophe: ${text}`); + } + } + assert.deepEqual(bad, []); +}); + +test('short labels stay short in French (buttons, tabs, chips)', async () => { + const english = await read('en'), french = await read('fr'); + const long = []; + for (const [id, text] of Object.entries(english)) { + if (text.length > 10 || french[id] === text || /\{\d+\}/.test(text)) continue; + // a label of up to 10 letters may take up to 3 times the room, and never more than 36 characters + if (french[id].length > Math.max(18, text.length * 3.2) || french[id].length > 36) long.push(`${id}: ${text} -> ${french[id]} (${french[id].length})`); + } + assert.deepEqual(long, []); +}); + +test('no French string is still English by accident: at most 5% of the main catalog is left unchanged', async () => { + const english = await read('en'), french = await read('fr'); + const same = Object.keys(english).filter(id => english[id] === french[id]); + assert.ok(same.length < Object.keys(english).length * 0.05, `${same.length} unchanged`); + // every unchanged string has no real words in it, or is a name that is spelled the same in French + const words = same.filter(id => english[id].split(/\s+/).length >= 4 && /\s(the|your|you|is|are|this|that|with|from|and)\s/i.test(english[id]) && !/^[-/\\]/.test(english[id])); + assert.deepEqual(words.map(id => `${id}: ${english[id]}`), []); +}); diff --git a/apps/host/tests/languages-and-catalog.test.mjs b/apps/host/tests/languages-and-catalog.test.mjs index 1cd8a25f..c7e4372e 100644 --- a/apps/host/tests/languages-and-catalog.test.mjs +++ b/apps/host/tests/languages-and-catalog.test.mjs @@ -2,7 +2,7 @@ import {test} from 'node:test'; import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; import {build} from 'esbuild'; -const languages=['en','zh','ja','de','es','ru','pt','ko']; +const languages=['en','zh','ja','de','es','ru','pt','ko','fr']; const catalogs=Object.fromEntries(await Promise.all(languages.map(async language=>[language,JSON.parse(await readFile(`src/locales/${language}.json`,'utf8'))]))); const english=catalogs.en; const slots=text=>[...text.matchAll(/\{\d+\}/g)].map(match=>match[0]).sort(); diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs index 9e7c7ae7..aefa8982 100644 --- a/apps/host/tests/locale-gaps.test.mjs +++ b/apps/host/tests/locale-gaps.test.mjs @@ -5,7 +5,7 @@ import { readdir, readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { build } from 'esbuild'; -const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const read = async name => JSON.parse(await readFile(`src/locales/${name}.json`, 'utf8')); const built = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`); @@ -38,7 +38,7 @@ test('every tr("...") literal and every command hint has a key in the English ca assert.deepEqual(missing, []); }); -test('the fix catalogs have the same keys and placeholders in all eight languages', async () => { +test('the fix catalogs have the same keys and placeholders in all nine languages', async () => { const en = await read('fix-en'); for (const language of languages) { const catalog = await read(`fix-${language}`); diff --git a/apps/host/tests/mcp-rows.test.mjs b/apps/host/tests/mcp-rows.test.mjs index c44411ea..5d00fd8f 100644 --- a/apps/host/tests/mcp-rows.test.mjs +++ b/apps/host/tests/mcp-rows.test.mjs @@ -53,7 +53,7 @@ test('the notices name the servers, one sentence per reason, in the catalog word assert.notEqual(notices[0].code, notices[1].code); assert.deepEqual(mcpSkippedNotices([]), []); // every sentence is in the catalog of every language (src/locales/tools-<lang>.json) - for (const lang of ['en', 'de', 'es', 'pt', 'ru', 'ja', 'ko', 'zh']) { + for (const lang of ['en', 'de', 'es', 'pt', 'ru', 'ja', 'ko', 'fr', 'zh']) { const catalog = JSON.parse(await readFile(new URL(`../src/locales/tools-${lang}.json`, import.meta.url), 'utf8')); const english = JSON.parse(await readFile(new URL('../src/locales/tools-en.json', import.meta.url), 'utf8')); for (const text of ['These tool servers were left out because their names are not allowed: {0}. A name can have up to 32 letters, numbers, hyphens or underscores.', diff --git a/apps/host/tests/models-folder.test.mjs b/apps/host/tests/models-folder.test.mjs index 9f6f2cb8..63650a5f 100644 --- a/apps/host/tests/models-folder.test.mjs +++ b/apps/host/tests/models-folder.test.mjs @@ -202,12 +202,12 @@ test('the Control command lines for status, resume and leave', async () => { assert.deepEqual(seen[2], ['models', 'move', '--leave', '--from', '/o', '--install-dir', '/i', '--output', 'json']); }); -test('the models folder strings exist in all 8 languages with the same placeholders', () => { +test('the models folder strings exist in all 9 languages with the same placeholders', () => { const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8')); const en = read('en'); const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8339 && Number(k.slice(1)) <= 8422); assert.equal(ours.length, 84); - for (const lang of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { + for (const lang of ['de', 'es', 'fr', 'ja', 'ko', 'pt', 'ru', 'zh']) { const text = read(lang); for (const key of ours) { assert.ok(text[key], `${lang} ${key}`); diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjs index bb27d0e8..d96f4b9f 100644 --- a/apps/host/tests/plain-errors.test.mjs +++ b/apps/host/tests/plain-errors.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { build } from 'esbuild'; -const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/${l}.json`, 'utf8'))]))); const built = await build({ stdin: { contents: "export * from './src/lib/plain-errors'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); const { plainFailure, plainFailureText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`); @@ -57,7 +57,7 @@ test('an ordinary sentence is left as it is and gets no Details', () => { assert.equal(f.detail, undefined); }); -test('every plain message and next step is translated in all eight languages', () => { +test('every plain message and next step is translated in all nine languages', () => { const en = catalogs.en; const ids = Object.fromEntries(Object.entries(en).map(([id, text]) => [text, id])); for (const [raw] of cases) { diff --git a/apps/host/tests/qa1-downloads.test.mjs b/apps/host/tests/qa1-downloads.test.mjs index e0ef38d4..26a3c629 100644 --- a/apps/host/tests/qa1-downloads.test.mjs +++ b/apps/host/tests/qa1-downloads.test.mjs @@ -115,7 +115,7 @@ test('the three NVFP4 versions have clear names and one line that tells them apa assert.match(lines[2], /faster on short prompts/); assert.equal(lib.versionNote('IQ3_S'), ''); assert.equal(lib.nativeShortName('nvfp4-nvfp4-nvidia'), 'NVFP4 (NVIDIA’s version)'); - for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']) { + for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { lib.setTranslationLanguage(language); const local = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.nativeVersionLabel(m)); assert.equal(new Set(local).size, 3, `${language}: three different names`); diff --git a/apps/host/tests/reliability.test.mjs b/apps/host/tests/reliability.test.mjs index a8e922ec..ce0cb40e 100644 --- a/apps/host/tests/reliability.test.mjs +++ b/apps/host/tests/reliability.test.mjs @@ -25,7 +25,7 @@ test('Markdown renders every incomplete stream prefix without looping', { timeou const mod = { exports: {} }; new Function('require', 'module', 'exports', bundle.outputFiles[0].text)(createRequire(import.meta.url), mod, mod.exports); const { render, setLanguage } = mod.exports; - for(const language of ['zh','ja','de','es','ru','pt','ko']) { setLanguage(language); const markup=render('Ready\n\n**Settings**\n\n*Download*\n\n[Cancel](https://example.com)\n\n| Name | Value |\n| --- | --- |\n| Close | Language |'); for(const word of ['Ready','Settings','Download','Cancel','Name','Value','Close','Language'])assert(markup.includes(word),language+': user text changed: '+word); } + for(const language of ['zh','ja','de','es','ru','pt','ko','fr']) { setLanguage(language); const markup=render('Ready\n\n**Settings**\n\n*Download*\n\n[Cancel](https://example.com)\n\n| Name | Value |\n| --- | --- |\n| Close | Language |'); for(const word of ['Ready','Settings','Download','Cancel','Name','Value','Close','Language'])assert(markup.includes(word),language+': user text changed: '+word); } setLanguage('en'); for (const marker of ['- ', '* ', '+ ', '1. ', '2) ', ' - ', ' 12. ']) assert.ok(render(marker).includes(marker)); const text = '# Answer\n\n- First item\n- Second item\n\n1. First step\n2. Second step\n\n```js\nconsole.log("hello");\n```\n\n| Name | Value |\n| --- | --- |\n| One | Two |'; diff --git a/apps/host/tests/run-config-check.test.mjs b/apps/host/tests/run-config-check.test.mjs index 5cd00c80..5183b479 100644 --- a/apps/host/tests/run-config-check.test.mjs +++ b/apps/host/tests/run-config-check.test.mjs @@ -91,8 +91,8 @@ test('the text editor: Notepad on Windows, text mode on a Mac, the system text-f assert.deepEqual(seen, [['xdg-open', '/s/strata-q.json']], 'with no text editor known the file’s own program opens it'); }); -test('every issue sentence exists in all eight languages and keeps its slots', async () => { - const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +test('every issue sentence exists in all nine languages and keeps its slots', async () => { + const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const compiled = await build({ stdin: { contents: "export * from './src/lib/run-config-issues'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' }); const { issueText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); const samples = [ diff --git a/apps/host/tests/speed-switches.test.mjs b/apps/host/tests/speed-switches.test.mjs index 58b8c638..13145c53 100644 --- a/apps/host/tests/speed-switches.test.mjs +++ b/apps/host/tests/speed-switches.test.mjs @@ -186,13 +186,13 @@ test('through the host: a Qwen model on a PC the engine cannot speed up offers n } finally { await f.cleanup(); } }); -test('the Expert settings show the rows in the existing row layout with an On / Off choice (Off recommended for KVA), and the words are in all eight languages', () => { +test('the Expert settings show the rows in the existing row layout with an On / Off choice (Off recommended for KVA), and the words are in all nine languages', () => { const screen = read('../src/components/NativeSettings.tsx'); assert.match(screen, /<h3 className="h4">\{tr\("Speed"\)\}<\/h3>/); assert.match(screen, /<label className="native-setting-row" key=\{sw\.id\}><span><strong>\{tr\(sw\.label\)\}<\/strong><small>\{tr\(sw\.hint\)\}<\/small><\/span><Select /, 'the same row, the same Select'); assert.match(screen, /\[\{ value: 'on', label: 'On \(recommended\)' \}, \{ value: 'off', label: 'Off' \}\] : \[\{ value: 'off', label: 'Off \(recommended\)' \}, \{ value: 'on', label: 'On' \}\]/); assert.match(screen, /if \(write\) env\[name\] = value; else delete env\[name\];/, 'the default removes the entries'); - const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; + const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalog = lang => JSON.parse(read(`../src/locales/fix-${lang}.json`)); const words = [...SPEED_SWITCHES.flatMap(s => [s.label, s.hint]), 'On (recommended)', 'Off (recommended)']; const english = Object.values(catalog('en')); diff --git a/apps/host/tests/tools-locales.test.mjs b/apps/host/tests/tools-locales.test.mjs index 294ddb7a..fe11434e 100644 --- a/apps/host/tests/tools-locales.test.mjs +++ b/apps/host/tests/tools-locales.test.mjs @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { build } from 'esbuild'; -const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tools-${l}.json`, 'utf8'))]))); const main = JSON.parse(await readFile('src/locales/en.json', 'utf8')); const tune = JSON.parse(await readFile('src/locales/tune-en.json', 'utf8')); diff --git a/apps/host/tests/tune-locales.test.mjs b/apps/host/tests/tune-locales.test.mjs index ed52eccd..4f43a9c3 100644 --- a/apps/host/tests/tune-locales.test.mjs +++ b/apps/host/tests/tune-locales.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { build } from 'esbuild'; -const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tune-${l}.json`, 'utf8'))]))); const main = JSON.parse(await readFile('src/locales/en.json', 'utf8')); const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort(); diff --git a/apps/host/tests/web-ask.test.mjs b/apps/host/tests/web-ask.test.mjs index 287afdf8..d16c8abf 100644 --- a/apps/host/tests/web-ask.test.mjs +++ b/apps/host/tests/web-ask.test.mjs @@ -162,13 +162,13 @@ test('the profile names the search service in the gate\'s question, and carries // ---------------------------------------------------------------------------------------------- the words, in every language -test('the card text and the Settings switch exist in all eight languages', async () => { +test('the card text and the Settings switch exist in all nine languages', async () => { const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' }); const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); const search = manualDecision(SEARCH, { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy' }).reason; const open = manualDecision(FETCH).reason; const english = [search, open, 'Let the assistant search the web without asking']; - for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']) { + for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { setTranslationLanguage(language); for (const text of english) assert.notEqual(tr(text), text, `${language}: ${text}`); const translated = tr(search); diff --git a/tests/terminal/test_drafting.py b/tests/terminal/test_drafting.py index c9e851ba..f1fdb311 100644 --- a/tests/terminal/test_drafting.py +++ b/tests/terminal/test_drafting.py @@ -238,7 +238,7 @@ class WhatTheEngineSaid(unittest.TestCase): class WordsMatchTheApp(unittest.TestCase): def test_every_line_the_engine_start_can_say_is_in_the_apps_catalog_in_all_eight_languages(self): folder = ROOT / "apps" / "host" / "src" / "locales" - catalogs = {l: json.loads((folder / f"{l}.json").read_text(encoding="utf-8")) for l in ("en", "de", "es", "ja", "ko", "pt", "ru", "zh")} + catalogs = {l: json.loads((folder / f"{l}.json").read_text(encoding="utf-8")) for l in ("en", "de", "es", "fr", "ja", "ko", "pt", "ru", "zh")} ids = {v: k for k, v in catalogs["en"].items()} self.assertEqual(len(drafting.REASONS), 4) for reason in drafting.REASONS: From 2ce07f86313f05007dc96cc0e78f7c39ebf90613 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:57:57 +0100 Subject: [PATCH 152/177] Docs: Polish README (#3355) Ports the Polish translation from #3355 and the Polski entry in the language row of every README. The pull request translated the older long README, so README.pl.md is rewritten from the current README.md (logo, centred language row, DeepSeek speed tables including Strix Halo, Gyro, coffee button). README.md's own language row had garbled names (double-encoded text); it is written out correctly. Co-authored-by: Jakub Luwierski <91573380+j-luwierski@users.noreply.github.com> --- README.de.md | 2 +- README.es.md | 2 +- README.fr.md | 2 +- README.ja.md | 2 +- README.md | 2 +- README.pl.md | 192 +++++++++++++++++++++++ README.pt-BR.md | 2 +- README.zh-CN.md | 2 +- tests/terminal/test_tui2_023_versions.py | 2 +- 9 files changed, 200 insertions(+), 8 deletions(-) create mode 100644 README.pl.md diff --git a/README.de.md b/README.de.md index e9dd81b4..cf1f8186 100644 --- a/README.de.md +++ b/README.de.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Strata auf Buy Me a Coffee unterstützen"></a> </p> -<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <b>Deutsch</b> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p> +<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <b>Deutsch</b> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a> · <a href="README.pl.md">Polski</a></sub></p> **Kostenlos, Open Source und ganz in deiner Hand.** Nutze Strata auf dem Desktop oder mit deinen liebsten Coding-Tools. Kein Konto nötig. diff --git a/README.es.md b/README.es.md index 52b9f30d..63e96151 100644 --- a/README.es.md +++ b/README.es.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Apoya Strata en Buy Me a Coffee"></a> </p> -<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <b>Español</b> · <a href="README.pt-BR.md">Português</a></sub></p> +<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <b>Español</b> · <a href="README.pt-BR.md">Português</a> · <a href="README.pl.md">Polski</a></sub></p> **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. diff --git a/README.fr.md b/README.fr.md index 0d2e04f1..a3f7fd4d 100644 --- a/README.fr.md +++ b/README.fr.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Soutenir Strata sur Buy Me a Coffee"></a> </p> -<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <b>Français</b> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p> +<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <b>Français</b> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a> · <a href="README.pl.md">Polski</a></sub></p> **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. diff --git a/README.ja.md b/README.ja.md index 47f8baa4..d57eab8c 100644 --- a/README.ja.md +++ b/README.ja.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Buy Me a Coffee で Strata を支援する"></a> </p> -<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <b>日本語</b> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p> +<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <b>日本語</b> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a> · <a href="README.pl.md">Polski</a></sub></p> **無料でオープンソース。自分の環境で動かせます。** デスクトップで、またはお好みのコーディングツールと一緒に Strata を使えます。アカウントは不要です。 diff --git a/README.md b/README.md index a5baabec..af82584d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Support Strata on Buy Me a Coffee"></a> </p> -<p align="center"><sub><b>English</b> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">PortuguĂŞs</a></sub></p> +<p align="center"><sub><b>English</b> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a> · <a href="README.pl.md">Polski</a></sub></p> **Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed. diff --git a/README.pl.md b/README.pl.md new file mode 100644 index 00000000..5c779ef2 --- /dev/null +++ b/README.pl.md @@ -0,0 +1,192 @@ +<p align="center"> + <picture> + <source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg"> + <img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340"> + </picture> +</p> + +<h3 align="center">Uruchom potężną sztuczną inteligencję na własnym komputerze.</h3> +<p align="center">Rozmawiaj, programuj i pracuj z obrazami — lokalnie.</p> + +<p align="center"> + <a href="#modele">Modele</a> · <a href="#instalacja"><b>Instalacja</b></a> · + <a href="#sprzęt">Sprzęt</a> · <a href="#narzędzia">Narzędzia</a> · + <a href="#pomoc">Pomoc</a> · <a href="#wesprzyj-stratę">Wsparcie</a> +</p> + +<p align="center"> + <a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Pobierz Stratę"></a> + <a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="Licencja MIT"></a> + <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Wesprzyj Stratę na Buy Me a Coffee"></a> +</p> + +<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a> · <b>Polski</b></sub></p> + +**Bezpłatna, z otwartym kodem źródłowym i do uruchomienia u siebie.** Używaj Straty na swoim komputerze albo razem z ulubionymi narzędziami do programowania. Konto nie jest potrzebne. + +## Modele + +Najpierw polecamy **ISTA-DASLab**, potem **Unsloth** i innych dostawców — o ile zgodny model mieści się w pamięci. + +<details> +<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle">  <b>Qwen3.8-Flash-Next</b></summary> + +| Dostawca | Do wyboru | +| --- | --- | +| **ISTA-DASLab · polecany** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) do programowania. | +| **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). Zużywa mniej pamięci, ale działa wolniej. | +| **Inne opcje** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Porównaj rozmiary, wymagania pamięciowe i zgodność](docs/MODELS.md). + +</details> + +<details> +<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle">  <b>Qwen3.6-35B-A3B</b></summary> + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. To obecnie udokumentowane pakiety dla tego modelu. + +[Przewodnik po modelu i zgodność](docs/QWEN36.md). + +</details> + +<details> +<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle">  <b>DeepSeekV4.1-Flash-1017</b></summary> + +W **aplikacji na komputer** i w **Terminalu**. To, co nie mieści się w pamięci, jest czytane z dysku SSD, więc potrzebujesz +dużo wolnego miejsca na dysku. + +| Zestaw (IST-DAS) | Do pobrania | Potrzebne wolne miejsce | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | około 245 GB | +| 2.00 bpw | 257 GB | około 265 GB | +| 2.25 bpw | 274 GB | około 280 GB | + +Działa na kartach NVIDIA RTX serii 30, 40 i 50 (Windows i Linux), AMD Radeon AI PRO R9700 (Linux) oraz AMD Ryzen AI Max — Strix Halo +(Windows). Instalacja pobiera pliki i silnik DeepSeek, a potem uruchamia model. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Zmierzone na zestawie 2.00 bpw w Strata 0.2.5 (Strix Halo: 0.2.7). „Wyjście” to szybkość odpowiedzi, „prompt” — jak szybko Strata czyta twój tekst. + +| Sprzęt | Wyjście | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB RAM | 4–6 tokenów/s | około 110 tokenów/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9–11 tokenów/s | około 155 tokenów/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21–25 tokenów/s | 320–360 tokenów/s (8K) | +| 4x Radeon AI PRO R9700 | 74–77 tokenów/s | 400–450 tokenów/s (8K) | +| Ryzen AI Max+ 395 (Strix Halo), 128 GB pamięci współdzielonej | 19–21 tokenów/s (kod), 11 (czat) | 87 tokenów/s (4K), 125 tokenów/s (8K) | + +[Pamięć, dysk i szczegóły](docs/DEEPSEEK41.md) · [Informacje o wydaniach](https://github.com/Niko1221/Strata/releases) + +</details> + +<a id="the-other-sizes"></a> + +Nie wiesz, co się zmieści? [Wybierz model do swojego komputera](docs/MODELS.md#pick-by-memory). + +## Instalacja + +<a id="option-a-the-strata-app"></a> + +### Aplikacja na komputer + +**[Pobierz Stratę dla Windows, Linuxa lub Maca →](https://github.com/Niko1221/Strata/releases/latest)** + +Zainstaluj aplikację, wybierz model i zacznij rozmawiać. Dla każdego systemu jest jeden instalator. Przy pierwszym +uruchomieniu aplikacja pobiera silnik dla twojej karty graficznej. [Pomoc z instalatorem](docs/INSTALL.md#the-app). + +<sub>Pliki: `Strata-0.2.6-windows-x64-setup.exe` · `Strata-0.2.6-linux-x86_64.AppImage` · `Strata-0.2.6-macos-arm64.dmg`</sub> + +<p align="center"> + <img src="docs/media/app-chat.png" width="900" alt="Aplikacja Strata na komputer: czat i podgląd kodu na żywo obok siebie"> + <br><sub>Czat, pliki i podgląd na żywo w jednym oknie.</sub> +</p> + +<a id="option-b-the-terminal-one-line"></a> + +### Aplikacja Terminal + +Wolisz terminal? Zainstaluj Stratę, a potem uruchom **`strata launch`**. + +<details open> +<summary><b>Polecenia instalacji</b></summary> + +**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 +``` + +W Windows otwórz potem nowe okno terminala. Następnie: + +```sh +strata launch +``` + +Postępuj zgodnie z podpowiedziami, aby pobrać i uruchomić model. [Przewodnik po Terminalu](docs/TERMINAL_LAUNCH.md). + +</details> + +<p align="center"> + <img src="docs/media/terminal-monitor.png" width="900" alt="Aplikacja Terminal Straty pokazująca aktywność modelu, szybkość, pamięć i ostatnie zapytania"> + <br><sub>Obserwuj model i sprzęt w trakcie pracy.</sub> +</p> + +<a id="build-from-source"></a> + +[Budowanie ze źródeł](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Pełny przewodnik instalacji](docs/INSTALL.md) + +<a id="what-you-need"></a> + +## Sprzęt + +| Obsługiwany sprzęt | Przewodnik | +| --- | --- | +| **NVIDIA GeForce RTX serii 20 / 30 / 40 / 50** | [Konfiguracja NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Konfiguracja AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · eksperymentalnie** | [Konfiguracja RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Konfiguracja Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 lub nowszy** | [Konfiguracja Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Konfiguracja Strix Halo](docs/STRIX_HALO.md) | + +<a id="using-it"></a> + +## Narzędzia + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw** i inne — przez API zgodne z OpenAI i Anthropic. + +Uruchom **`strata connect`**, aby zobaczyć instrukcję konfiguracji dla swojego narzędzia. [Przewodnik po połączeniach](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + +<a id="guides"></a> +<a id="how-fast-is-it"></a> +<a id="how-does-it-work"></a> +<a id="something-went-wrong"></a> + +## Pomoc + +[Wszystkie przewodniki](docs) · [Rozwiązywanie problemów](docs/TROUBLESHOOTING.md) · [Zgłoś błąd](https://github.com/Niko1221/Strata/issues/new/choose) · +[Testy wydajności](docs/COMMUNITY_BENCHMARKS.md) · [Jak to działa](docs/HOW_IT_WORKS.md) · [Współtworzenie](CONTRIBUTING.md) + +## Wesprzyj Stratę + +**Pomóż zachować lokalną sztuczną inteligencję otwartą dla wszystkich.** Kawa pomaga finansować rozwój i testy na większej liczbie sprzętu. + +<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: wesprzyj Stratę" height="48"></a> + +[Licencja MIT](LICENSE) · [Podziękowania i licencje modeli](docs/HOW_IT_WORKS.md#credits) · [Prywatność](docs/SAFETY.md) + +<a id="option-c-let-your-ai-set-it-up"></a> + +<sub>Dla narzędzi AI i automatycznych czytników: <a href="AGENTS.md">dokumentacja techniczna</a> · <a href="docs/AI_SETUP.md">instrukcja instalacji</a>.</sub> + +**Sponsoring, partnerstwa sprzętowe i współpraca:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.pt-BR.md b/README.pt-BR.md index bcc2796e..68556d00 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Apoie o Strata no Buy Me a Coffee"></a> </p> -<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <b>Português</b></sub></p> +<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <b>Português</b> · <a href="README.pl.md">Polski</a></sub></p> **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. diff --git a/README.zh-CN.md b/README.zh-CN.md index 4c716fe7..b21e8e80 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -20,7 +20,7 @@ <a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="在 Buy Me a Coffee 上支持 Strata"></a> </p> -<p align="center"><sub><a href="README.md">English</a> · <b>简体中文</b> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p> +<p align="center"><sub><a href="README.md">English</a> · <b>简体中文</b> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a> · <a href="README.pl.md">Polski</a></sub></p> **免费、开源,由你自己运行。** 在桌面上使用 Strata,或搭配你喜欢的编程工具。无需账号。 diff --git a/tests/terminal/test_tui2_023_versions.py b/tests/terminal/test_tui2_023_versions.py index 0c792fcb..6d73bfdf 100644 --- a/tests/terminal/test_tui2_023_versions.py +++ b/tests/terminal/test_tui2_023_versions.py @@ -39,7 +39,7 @@ class VersionBump(unittest.TestCase): def test_the_documents_that_state_the_current_version_agree(self): self.assertIn("Version 0.2.6, engine 0.1.51.", (ROOT / "AGENTS.md").read_text(encoding="utf-8")) - for name in ("README.md", "README.de.md", "README.es.md", "README.fr.md", "README.ja.md", "README.pt-BR.md", "README.zh-CN.md"): + for name in ("README.md", "README.de.md", "README.es.md", "README.fr.md", "README.ja.md", "README.pl.md", "README.pt-BR.md", "README.zh-CN.md"): text = (ROOT / name).read_text(encoding="utf-8") self.assertRegex(text, r"Strata-0[.]2[.][0-9]+-", name) # (the restyled READMEs state the app version through the download buttons; their owner moves them to the release) self.assertNotIn("Strata-0.2.2-", text, name) From 2b9869eddf0ed50262098584446dbf734582ad15 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:59:54 +0100 Subject: [PATCH 153/177] Web chat page: French (#3970) serve/web/locales/fr.json (247 keys, plurals one/other, same terms as the app catalog) and the French line in serve/web/i18n.js. tools/web_i18n.py and serve/test_web_i18n.py (node and python) pass. --- serve/web/i18n.js | 2 +- serve/web/locales/fr.json | 264 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 265 insertions(+), 1 deletion(-) create mode 100644 serve/web/locales/fr.json diff --git a/serve/web/i18n.js b/serve/web/i18n.js index 81defdbb..bdcebd7f 100644 --- a/serve/web/i18n.js +++ b/serve/web/i18n.js @@ -12,7 +12,7 @@ "use strict"; (function (root) { // [code, the language's own name]. A new language is a locales/<code>.json file plus one line here. - const LANGUAGES = [["en", "English"], ["de", "Deutsch"], ["es", "Español"], ["ja", "日本語"], ["ko", "한국어"], + const LANGUAGES = [["en", "English"], ["de", "Deutsch"], ["fr", "Français"], ["es", "Español"], ["ja", "日本語"], ["ko", "한국어"], ["pt", "Português"], ["ru", "Русский"], ["zh", "中文"]]; let lang = "en", catalog = null, rules = null; diff --git a/serve/web/locales/fr.json b/serve/web/locales/fr.json new file mode 100644 index 00000000..7bbb7616 --- /dev/null +++ b/serve/web/locales/fr.json @@ -0,0 +1,264 @@ +{ + "branch.back": "Y retourner", + "branch.from": "Créée à partir de « {title} »", + "branch.open": "Ouvrir l’originale", + "branch.started": "Branche créée", + "branch.startedText": "La conversation où vous étiez reste inchangée, dans la liste à gauche.", + "branch.title": "Branche de {title}", + "busy.stillWriting": "Écriture en cours", + "busy.stopFirst": "Arrêtez d’abord la réponse.", + "cancel": "Annuler", + "chat.clearedToast": "La dernière a été effacée.", + "chat.copy": "Copier", + "chat.copyAnswer": "Copier la réponse", + "chat.deleted": "Conversation supprimée", + "chat.empty": "Posez n’importe quelle question", + "chat.emptyModel": "{model} tourne sur ce PC. Rien n’en sort.", + "chat.image": "image", + "chat.interrupted": "Interrompue", + "chat.interruptedLower": "interrompue", + "chat.new": "Nouvelle conversation", + "chat.newToast": "Nouvelle conversation", + "chat.newToastText": "Celle où vous étiez est dans la liste à gauche.", + "chat.projectionOff": "projection désactivée", + "chat.projectionOn": "projection activée", + "chat.stopped": "Arrêtée", + "chat.stoppedLower": "arrêtée", + "chat.tokens": "{n} tokens", + "chat.toolCalls": { + "one": "{n} appel d’outil", + "other": "{n} appels d’outils" + }, + "chat.toolLimit": "arrêtée à la limite de {n} tours d’outils (mcp.max_rounds)", + "chat.untitled": "Nouvelle conversation", + "chat.you": "Vous", + "close": "Fermer", + "code.copy": "Copier le code", + "code.label": "code", + "composer.attach": "Joindre un fichier texte (ou le déposer ici)", + "composer.attachLabel": "Joindre un fichier", + "composer.attachPictures": "Joindre un fichier texte ou une image (ou la déposer ici)", + "composer.finishOpen": "Enregistrez ou annulez ce qui est ouvert au-dessus pour continuer", + "composer.hintInterject": "Entrée arrête la réponse ici et envoie tout de suite", + "composer.hintQueue": "Entrée envoie quand la réponse est terminée", + "composer.message": "Message", + "composer.newline": "Maj+Entrée : nouvelle ligne", + "composer.placeholder": "Posez une question…", + "composer.save": "Enregistrer cette conversation en Markdown", + "composer.saveLabel": "Enregistrer cette conversation", + "composer.send": "Envoyer", + "composer.stop": "Arrêter", + "drawer.apply": "Appliquer", + "drawer.busy": "Quand vous envoyez pendant qu’il répond", + "drawer.busyInterject": "Interrompre", + "drawer.busyInterjectNote": "La réponse s’arrête là où elle est (ce qui est écrit reste) et votre message part tout de suite. Un outil en cours se termine d’abord.", + "drawer.busyQueue": "Envoyer après", + "drawer.busyQueueNote": "Votre message attend et part dès que la réponse est terminée.", + "drawer.busyWait": "Attendre", + "drawer.busyWaitNote": "Envoyer est désactivé jusqu’à la fin de la réponse, comme avant.", + "drawer.chats": "Conversations", + "drawer.edit": "Modifier et revenir en arrière dans les messages", + "drawer.editNote": "modifier une réponse, en demander une nouvelle, ou revenir à un message précédent (avec Annuler)", + "drawer.greedy": "0 · glouton", + "drawer.high": "Élevé", + "drawer.list": "Liste des conversations enregistrées", + "drawer.listNote": "garde chaque conversation dans une liste à gauche, dans ce navigateur seulement. Désactivé : une seule conversation, comme avant", + "drawer.low": "Faible", + "drawer.math": "Afficher les maths", + "drawer.mathNote": "dessiner les équations des réponses sous forme de formules (fonctionne hors ligne)", + "drawer.maxTokens": "Tokens max.", + "drawer.maxTokensNote": "vide = jusqu’à la fin", + "drawer.mcp": "Utiliser les outils des serveurs MCP", + "drawer.medium": "Moyen", + "drawer.off": "Désactivé", + "drawer.random": "Aléatoire", + "drawer.reset": "Réinitialiser", + "drawer.saved": "Réglages de la conversation enregistrés", + "drawer.savedGreedy": "Glouton : la même question donne la même réponse.", + "drawer.savedHere": "Enregistré ici, mais pas pour les autres applications", + "drawer.savedOwn": "Les autres applications réutilisent leurs propres réglages.", + "drawer.savedShared": "Les autres applications (omp, clients API) utilisent ces réglages dès leur prochaine requête.", + "drawer.seed": "Graine", + "drawer.seedNote": "vide = aléatoire", + "drawer.share": "Utiliser aussi pour les autres applications", + "drawer.shareNote": "omp et les autres clients API reçoivent ces réglages pour tout ce qu’ils ne définissent pas eux-mêmes", + "drawer.short": "Réglages", + "drawer.showThinking": "Afficher la réflexion", + "drawer.showThinkingNote": "déployée pendant la diffusion", + "drawer.temperature": "Température", + "drawer.temperatureNote": "0 = toujours le mot le plus probable (exact, reproductible)", + "drawer.thinkHigh": "approfondie (par défaut)", + "drawer.thinkLow": "courte", + "drawer.thinkMedium": "moyenne", + "drawer.thinkNone": "répond tout de suite", + "drawer.thinking": "Réflexion", + "drawer.title": "Réglages de la conversation", + "drawer.untilDone": "Jusqu’à la fin", + "export.nothing": "Rien à enregistrer pour l’instant", + "file.big": "Fichier trop volumineux", + "file.bigText": "{name} dépasse 512 Ko.", + "file.binaryText": "{name} ressemble à un fichier binaire.", + "file.notText": "Ce n’est pas un fichier texte", + "file.notTextOnly": "{name} : joignez des fichiers texte (code, notes, journaux, données).", + "file.notTextPictures": "{name} : joignez des fichiers texte (code, notes, journaux, données) ou des images.", + "file.pasted": "image collée", + "file.pictureBig": "Image trop volumineuse", + "file.pictureBigText": "{name} dépasse 20 Mo.", + "file.picturesOff": "Les images sont désactivées", + "file.picturesOffText": "Ce modèle a été configuré pour le texte seul.", + "file.remove": "Retirer", + "group.month": "30 derniers jours", + "group.older": "Plus anciennes", + "group.today": "Aujourd’hui", + "group.week": "7 derniers jours", + "group.yesterday": "Hier", + "hist.editAnswer": "Modifier la réponse", + "hist.editAnswerTitle": "Corrigez le texte de la réponse. Aucune requête n’est envoyée.", + "hist.editLabel": "Modifier la réponse", + "hist.editNote": "L’ancienne réflexion et les anciens appels d’outils de la réponse sont retirés. Aucune requête n’est envoyée.", + "hist.editRemoves": { + "one": "Enregistrer masque le message qui la suit. ", + "other": "Enregistrer masque les {n} messages qui la suivent. " + }, + "hist.edited": "Modifiée", + "hist.editedHidden": { + "one": "Réponse modifiée, {n} message masqué", + "other": "Réponse modifiée, {n} messages masqués" + }, + "hist.editedOnly": "Réponse modifiée", + "hist.empty": "La réponse est vide", + "hist.emptyText": "Écrivez quelque chose avant d’enregistrer.", + "hist.finishFirst": "Terminez d’abord ce qui est ouvert", + "hist.finishFirstText": "Enregistrez-le ou appuyez sur Annuler.", + "hist.hidden": { + "one": "{n} message masqué", + "other": "{n} messages masqués" + }, + "hist.lostText": "Ce navigateur a gardé leurs noms, pas leur contenu. Ouvrez une nouvelle conversation et joignez-les à nouveau.", + "hist.lostText2": "Ce navigateur a gardé leurs noms, pas leur contenu. Joignez-les à nouveau.", + "hist.lostTitle": "Les pièces jointes doivent être ajoutées à nouveau", + "hist.nothingHidden": "De retour à ce message", + "hist.pendingFirst": "Un message attend", + "hist.pendingFirstText": "Envoyez-le ou reprenez-le d’abord.", + "hist.regenerate": "Régénérer", + "hist.regenerateTitle": "Demander une nouvelle réponse à cette question. Les outils peuvent se relancer.", + "hist.replaced": "La réponse a été remplacée", + "hist.rewind": "Revenir ici", + "hist.rewindTitle": "Revenir à ce point de la conversation", + "hist.save": "Enregistrer", + "math.source": "Source mathématique ({reason})", + "model.alreadyUnloaded": "Déjà déchargé", + "model.busy": "Le modèle est occupé", + "model.confirmUnload": "Décharger le modèle et libérer le GPU ? Charger, ou le prochain message, le ramène.", + "model.fewMinutes": "Cela peut prendre quelques minutes.", + "model.gpuFree": "Le GPU est libre. Charger, ou le prochain message, le ramène.", + "model.gpuInUse": "Le GPU est utilisé.", + "model.imageBusy": "Une image est en cours de génération. Elle se termine toute seule.", + "model.imageLoading": "Une image charge déjà le modèle", + "model.imageLoadingDot": "Une image charge déjà le modèle.", + "model.load": "Charger", + "model.loadFailed": "Échec du chargement", + "model.loadTitle": "Charger le modèle maintenant. Un message le charge aussi.", + "model.loaded": "Modèle chargé", + "model.loading": "Chargement…", + "model.loadingTitle": "Le modèle se charge", + "model.loadingToast": "Chargement du modèle", + "model.noAnswer": "Le serveur n’a pas répondu.", + "model.replyLoading": "Une réponse charge déjà le modèle", + "model.replyLoadingDot": "Une réponse charge déjà le modèle.", + "model.stopFirst": "Arrêtez la réponse, puis déchargez", + "model.stopFirstDot": "Arrêtez la réponse, puis déchargez.", + "model.unload": "Décharger", + "model.unloadFailed": "Échec du déchargement", + "model.unloadTitle": "Décharger le modèle et libérer le GPU", + "model.unloaded": "Modèle déchargé", + "model.unloading": "Déchargement…", + "model.unloadingTitle": "Le modèle se décharge", + "model.unsupported": "Le déchargement n’est pas disponible", + "model.waiting": "En attente du serveur", + "pending.afterTool": "Attente de la fin de l’outil, puis envoi : « {text} »", + "pending.cutting": "Arrêt de la réponse, puis envoi : « {text} »", + "pending.one": "Un message attend déjà", + "pending.oneText": "Reprenez-le ou attendez qu’il soit envoyé.", + "pending.queued": "Part quand cette réponse est terminée : « {text} »", + "pending.ready": "Pas encore envoyé : « {text} »", + "pending.send": "Envoyer", + "pending.sendNow": "Envoyer maintenant", + "pending.takeBack": "Reprendre", + "pill.connecting": "Connexion…", + "pill.generating": "Génération · {rate} tok/s", + "pill.idle": "Inactif", + "pill.image": "Génération de l’image…", + "pill.keyNeeded": "Clé API requise", + "pill.queued": "{n} en attente", + "pill.reading": "Lecture du prompt", + "pill.readingPct": "Lecture du prompt · {pct} %", + "pill.unloaded": "Déchargé", + "pill.unreachable": "Serveur injoignable", + "preview.confirm": "Exécuter ce code avec ses scripts ?\n\nIl s’exécute dans votre navigateur, coupé de cette conversation et du réseau, mais il peut quand même bloquer l’onglet, et c’est du code écrit par le modèle.\n\nSeulement ce bloc, et seulement jusqu’à la fermeture de l’aperçu.", + "preview.runScripts": "Exécuter les scripts", + "preview.showCode": "Afficher le code", + "preview.showPage": "Afficher un aperçu de la page", + "preview.showSvg": "Afficher un aperçu de l’image", + "preview.stopScripts": "Arrêter les scripts", + "preview.titlePage": "Aperçu de la page", + "preview.titleSvg": "Aperçu de l’image", + "rewind.branch": "Créer une branche ici", + "rewind.branchAnswerText": "Ouvre une nouvelle conversation avec les messages jusqu’à cette réponse. Cette conversation reste telle quelle.", + "rewind.branchUserText": "Ouvre une nouvelle conversation avec les messages avant celui-ci, et place votre message dans sa zone de saisie. Cette conversation reste telle quelle.", + "rewind.hereAnswer": "Continuer à partir d’ici", + "rewind.hereAnswerText": "Masque les messages après cette réponse. Annuler les ramène.", + "rewind.hereUser": "Modifier et renvoyer ici", + "rewind.hereUserText": "Masque ce message et ceux qui le suivent, et place votre message dans la zone ci-dessous. Annuler les ramène.", + "rewind.noList": "Pour plutôt ouvrir une nouvelle conversation à partir d’ici, activez Conversations enregistrées dans les réglages de la conversation.", + "rewind.title": "Revenir ici", + "settings.language": "Langue", + "settings.languageNote": "La conversation, ses réglages et les boutons ci-dessus sont traduits. Les vues Moniteur, Images et À propos sont encore en anglais.", + "sidebar.collapse": "Réduire la liste des conversations", + "sidebar.delete": "Supprimer cette conversation", + "sidebar.deleteShort": "Supprimer", + "sidebar.expand": "Ouvrir la liste des conversations", + "sidebar.foot": { + "one": "{n} conversation · gardée dans ce navigateur", + "other": "{n} conversations · gardées dans ce navigateur" + }, + "sidebar.nameFor": "Nom de cette conversation", + "sidebar.noMatch": "Aucune conversation ne correspond", + "sidebar.none": "Aucune conversation pour l’instant", + "sidebar.rename": "Renommer cette conversation", + "sidebar.renameShort": "Renommer", + "sidebar.search": "Rechercher dans les conversations", + "sidebar.title": "Conversations", + "store.failed": "La liste des conversations n’a pas pu être enregistrée. Les conversations à l’écran y sont toujours.", + "store.memory": "Ce navigateur ne gardera pas la liste des conversations. Elle reste en mémoire jusqu’à la fermeture de la page.", + "store.quota": "Ce navigateur ne peut pas en garder plus. Les conversations à l’écran y sont toujours.", + "store.title": "Liste des conversations non enregistrée", + "tab.about": "À propos", + "tab.chat": "Chat", + "tab.images": "Images", + "tab.monitor": "Moniteur", + "tab.views": "Vues", + "theme.label": "Basculer entre clair et sombre", + "theme.title": "Clair / sombre", + "think.done": "Réflexion", + "think.for": "A réfléchi pendant {s} s", + "think.now": "Réflexion…", + "toast.copied": "Copié dans le presse-papiers", + "toast.engineError": "le moteur a signalé une erreur", + "toast.httpAnswer": "Le serveur a répondu HTTP {code}.", + "toast.keyAbout": "Ce serveur a besoin d’une clé : ajoutez-la dans À propos > Paramètres.", + "toast.keyAbout2": "Clé API requise : ajoutez-la dans À propos > Paramètres.", + "toast.keyNeeded": "Ce serveur a besoin d’une clé API : ajoutez-la dans À propos > Paramètres.", + "toast.requestFailed": "La requête a échoué", + "tool.arguments": "Arguments", + "tool.beingWritten": "(en cours d’écriture)", + "tool.chars": "{n} caractères", + "tool.cut": ", coupé pour le modèle", + "tool.done": "Terminé", + "tool.error": "Erreur", + "tool.result": "Résultat", + "tool.running": "En cours", + "tool.skipped": "Non exécuté", + "tool.writing": "Écriture", + "undo": "Annuler" +} From 663ec80abf9e6fd20dfff1a0a5d27f326a43af3a Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:11:03 +0100 Subject: [PATCH 154/177] mmvq_il: the sm_89 (Ada) decode tables are on by default on compute capability 8.9 only, STRATA_MMVQ_IL_89=0 and STRATA_DEFAULTS=026 turn them off (#3453) Owner decision for 0.2.7: the tables of PR #3453 (the cells where an RTX 4070 and an RTX 4080 community run gave the same rows count, and the one-column Q3_K row) ship on for sm_89 cards, untested on Ada by us. The output is bitwise the same with them off (a table only changes how many rows a warp takes); no end-to-end gain was seen on a 4090 or 4080 in the report, so the reporter tests 0.2.7 and reports. The rule is a pure function in sm120_series.hpp: mmvq_il_89_default(hip, cc, v026) is true for cc 89 only, false in HIP builds and under STRATA_DEFAULTS=026 (defaults_026.hpp, as 38c9080db did for the other defaults); mmvq_il_89_resolve() adds the variable: "1" and "0" win, unset or other text is the rule. native_mmvq.cu reads it once. arch_defaults_test checks cc 89 on, every other cc off, HIP off, 026 off, "0" off, "1" wins over 026, the empty text. mmvq_il_parity expects the on-tables by default and the old ones with =0 or 026. Docs: MMVQ_IL_TABLE.md, DETAILS.md and the 0.2.7 release notes (a line that says it is not measured on an RTX 40 card, with the off switch). --- docs/DETAILS.md | 2 ++ docs/MMVQ_IL_TABLE.md | 2 +- docs/release-notes-0.2.7.md | 6 +++++- include/strata/core/sm120_series.hpp | 13 +++++++++++++ src/core/arch_defaults_test.cpp | 14 ++++++++++++++ src/kernels/cuda/native_mmvq.cu | 14 ++++++++++---- src/kernels/mmvq_il_parity.cpp | 9 ++++++--- 7 files changed, 51 insertions(+), 9 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index cb863f48..082ad0e6 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1186,6 +1186,8 @@ On 12.0 cards (sm_120) these also apply: - The interleaved small-batch matvec (`native_mmvq_il`, [MMVQ_IL_TABLE.md](MMVQ_IL_TABLE.md)) runs 5 to 8 tokens, with a 12.0 table and, on cards with 80 or more SMs, its own 2-4 token table. `STRATA_MMVQ_IL_WIDE=0` and `STRATA_MMVQ_IL_120=0` turn them off. + RTX 40 cards (compute capability 8.9) have their own 2-4 token tables and a one-token Q3_K row, on by default in 0.2.7 and not yet measured + on an RTX 40 card by us (same output bit for bit): `STRATA_MMVQ_IL_89=0` or `STRATA_DEFAULTS=026` turns them off. - With 80 or more SMs the native packs' prompt experts run on the fused int8 kernels (`STRATA_PF_FUSED`) for IQ2_S, IQ3_XXS, IQ3_S and IQ4_XS gate/up. IQ2_XXS and IQ2_XS keep MMQ. Smaller 12.0 cards (an RTX 5070 with 48 SMs) keep MMQ because the fused kernels were 4.7% slower on 20K prompts there. `STRATA_PF_FUSED=0` keeps MMQ. diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index 8974c3be..26c637b1 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -15,7 +15,7 @@ Which table a card gets: |---|---| | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | -| sm_89 (Ada) | the shared table (`kIlRowsShared`) unless `STRATA_MMVQ_IL_89=1`, which switches on `kIlRows_89`: the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. It is opt-in because no sm_89 card has run `mmvq_il_parity` on this code, and the issue saw no end-to-end decode change on a 4090 or a 4080 (issue 3453), so the gain is a microbenchmark one. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card. To flip the default, run `mmvq_il_parity` on an Ada card (it must end with `OK`) and an interleaved decode A/B with the switch on and off. | +| sm_89 (Ada) | `kIlRows_89`, ON by default on compute capability 8.9 cards only (0.2.7): the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. `STRATA_MMVQ_IL_89=0` or `STRATA_DEFAULTS=026` gives the shared table (`kIlRowsShared`) again, as in 0.2.6; an explicit `STRATA_MMVQ_IL_89=1` wins over the master switch. The output is bitwise the same either way (a table only changes how many rows a warp takes). Not measured on an Ada card by us: no sm_89 card has run `mmvq_il_parity` on this code, and the issue saw no end-to-end decode change on a 4090 or a 4080 (issue 3453), so the gain may be a microbenchmark one. The reporter tests 0.2.7 and reports back. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card. To check a card: run `mmvq_il_parity` on it (it must end with `OK`) and an interleaved decode A/B with the variable at 1 and 0. | | every other sm_80+ card | `kIlRowsShared` | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 6e806ade..6a741600 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -23,6 +23,10 @@ - The hyper-connection read split over two kernels (a discrete RTX 50 / RTX PRO Blackwell card with more than 13 GiB): **+1.2% decode on the RTX PRO 5000 with identical tokens**, about +1.5% together with the switch above. On 2x RTX A4000 and the RTX 3060 it was slower, so those cards keep the old read. Off switch: `STRATA_GR_V3=0`. + - RTX 40 cards (Ada, compute capability 8.9): new decode row tables for the interleaved matrix kernels, on by default. The output is the + same bit for bit; only how many rows a warp takes changes. **We have not measured them on an RTX 40 card**: the tables come from two + community runs (an RTX 4070 and an RTX 4080), and the report with the 4090 saw no change in decode speed. If you have an RTX 40 + card, please try 0.2.7 and post your decode numbers on issue 3453. Off switch: `STRATA_MMVQ_IL_89=0`. ## Going back to 0.2.6 @@ -34,7 +38,7 @@ Two switches bring back every default that 0.2.7 changed, in one step, for a tes the RAM store's spare slots and put and its settle after a prompt, the dense dequantizer, the F16 gate/up operand, the drafter's markov head and the head's column count, and the RDNA3 dense GEMM all go back to what 0.2.6 did. - **`STRATA_DEFAULTS=026`** (Qwen): the residency-biased routing, the wide and the stream-split hyper-connection reads, the int8 - prompt attention, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). + prompt attention, the RTX 40 (sm_89) decode tables, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). Long prompts on the approximate read (`STRATA_KVA`) are off by default and stay as `STRATA_KVA` says. A variable or flag you set yourself (`DS4_ATTN_SLAB=N`, `STRATA_ROUTE_PRIOR=2`, `--experts 5`, `--prefill-chunk N`, `--pcie-frac`, diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index 8a6932a6..2674b28c 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -67,6 +67,19 @@ inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, doubl /// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt. inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc >= 80; } +/// STRATA_MMVQ_IL_89 (#3453: the decode kernel row tables of an Ada card, the cells where an RTX 4070 and an RTX 4080 agreed; bitwise the same +/// output, only the rows-a-warp split differs) when the user set nothing: ON for compute capability 8.9 only (owner decision, 26 October: not yet +/// measured on an Ada card by us), off under STRATA_DEFAULTS=026 and in HIP builds. `cc` = 10 * major + minor as the engine resolves it. +inline bool mmvq_il_89_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc == 89; } + +/// The answer for STRATA_MMVQ_IL_89 given the variable's text (nullptr = unset): "1" on and "0" off win over everything, anything else (unset, +/// empty, other text) is the rule above. +inline bool mmvq_il_89_resolve(const char* env, bool hip, int cc, bool v026 = false) { + if (env != nullptr && env[0] == '1') return true; + if (env != nullptr && env[0] == '0') return false; + return mmvq_il_89_default(hip, cc, v026); +} + /// STRATA_GR_UP_WIDE (the hyper-connection up projection, one warp a row; bitwise the old kernel) when the user set nothing: ON for a compute /// capability 12.0 card (STRATA_SM120_PERF=0 turns the set off), CUDA builds only. inline bool gr_up_wide_default(bool hip, int major, int minor, bool v026 = false) { return !v026 && !hip && sm120_default(major, minor); } diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index db193a7f..3195bbba 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -243,6 +243,20 @@ int main() { CHECK(!gr_up_wide_default(true, 12, 0)); CHECK(!gr_up_wide_default(false, 8, 6)); CHECK(!gr_up_wide_default(false, 12, 1)); + // #3453: the sm_89 MMVQ-IL tables: on by default for compute capability 8.9 only, off under 026 and in HIP; "1" and "0" win + CHECK(mmvq_il_89_default(false, 89)); + CHECK(!mmvq_il_89_default(false, 86) && !mmvq_il_89_default(false, 80) && !mmvq_il_89_default(false, 90) && + !mmvq_il_89_default(false, 120) && !mmvq_il_89_default(false, 75) && !mmvq_il_89_default(false, 70) && + !mmvq_il_89_default(false, 60) && !mmvq_il_89_default(false, 0)); + CHECK(!mmvq_il_89_default(true, 89)); + CHECK(!mmvq_il_89_default(false, 89, true)); // STRATA_DEFAULTS=026 + CHECK(mmvq_il_89_resolve(nullptr, false, 89, false)); // unset: the rule + CHECK(!mmvq_il_89_resolve(nullptr, false, 89, true)); // unset + 026: off + CHECK(!mmvq_il_89_resolve(nullptr, false, 86, false)); // another card: off + CHECK(!mmvq_il_89_resolve("0", false, 89, false)); // STRATA_MMVQ_IL_89=0 turns it off + CHECK(mmvq_il_89_resolve("1", false, 89, true)); // an explicit =1 wins over the master switch + CHECK(mmvq_il_89_resolve("1", false, 86, false)); // (the tables are only looked up for cc 89 anyway) + CHECK(mmvq_il_89_resolve("", false, 89, false) && !mmvq_il_89_resolve("", false, 89, true)); // empty text: the rule // GR_V3 and IMMA CHECK(gr_v3_default(false, 12, 0, false, 72.0 * GiB, false)); CHECK(!gr_v3_default(false, 12, 0, false, 72.0 * GiB, true)); diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index f0c3913e..ef675882 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -29,6 +29,8 @@ #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/core/sm75_series.hpp" +#include "strata/core/sm120_series.hpp" +#include "strata/core/defaults_026.hpp" #include "s26_tsum.cuh" #if !defined(__HIPCC__) #include "q8_1_il.cuh" @@ -3158,10 +3160,14 @@ bool il_env_on(const char* name) { } bool il_t1_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_T1"); return on; } bool il_q3k_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_Q3K"); return on; } -// #3453: sm_89's own tables (kIlRows_89 / kIl1Rows_89) are opt-in with STRATA_MMVQ_IL_89=1 until an sm_89 card has run -// mmvq_il_parity and an end-to-end A/B (docs/MMVQ_IL_TABLE.md). Unset, an Ada card answers what it answered before: the -// shared table, no one-column row. Cached once; the lookup runs on the host once a launch. -bool il_89_opt_in() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL_89"); return v != nullptr && v[0] == '1'; }(); return on; } +// #3453: sm_89's own tables (kIlRows_89 / kIl1Rows_89) are ON by default on compute capability 8.9 only (owner decision, 0.2.7; no sm_89 card +// has run mmvq_il_parity or an end-to-end A/B for us, the reporter tests and reports back). STRATA_MMVQ_IL_89=0 gives an Ada card what it +// answered before (the shared table, no one-column row) and so does STRATA_DEFAULTS=026; STRATA_MMVQ_IL_89=1 wins over that master switch +// (sm120_series.hpp mmvq_il_89_resolve). Cached once; the lookup runs on the host once a launch. +bool il_89_opt_in() { + static const bool on = strata::mmvq_il_89_resolve(std::getenv("STRATA_MMVQ_IL_89"), false, 89, strata::qwen_defaults_026()); + return on; +} struct IlArch { int cc; const IlRows* t; size_t n; }; constexpr IlArch kIlArch[] = { {60, kIlRows_60, sizeof(kIlRows_60) / sizeof(IlRows)}, // Pascal GP100: measured on a Tesla P100 diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 9e9cd165..00ad704b 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -10,6 +10,8 @@ // the block scales rewritten as normal fp16 values, so every output is finite (a NaN would compare equal whatever // produced it). The bench cycles through enough copies of the weights to miss the L2 cache, as a layer's call does. #include "strata/kernels/iq_kernels.hpp" +#include "strata/core/defaults_026.hpp" +#include "strata/core/sm120_series.hpp" #include "strata/kernels/native_mmvq.hpp" #include <cuda_runtime.h> @@ -273,7 +275,8 @@ const int kAda4080[5][3][5] = { int check_tables() { int bad = 0; const char* e89 = std::getenv("STRATA_MMVQ_IL_89"); - const bool opt89 = e89 != nullptr && e89[0] == '1'; // sm_89's own tables are opt-in (#3453) + // sm_89's own tables are ON by default (#3453, 0.2.7) unless STRATA_MMVQ_IL_89=0 or STRATA_DEFAULTS=026 + const bool opt89 = strata::mmvq_il_89_resolve(e89, false, 89, strata::qwen_defaults_026()); for (int type : {23, 12, 13, 14, 11}) for (int nc = 2; nc <= 4; ++nc) for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) { @@ -283,7 +286,7 @@ int check_tables() { const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; const int ti = type == 23 ? 0 : type == 12 ? 1 : type == 13 ? 2 : type == 14 ? 3 : 4; const int b = native_mmvq_il_rows_for(89, type, nc, n_out); - // STRATA_MMVQ_IL_89=1: the agreement; unset: what sm_89 answered before #3453 (the shared table, which is + // tables on (the default): the agreement; off (=0 or STRATA_DEFAULTS=026): what sm_89 answered before #3453 (the shared table, which is // sm_86's except Q3_K, a type the shared table has no row for) const int want = opt89 ? (kAda4070[ti][nc - 2][cls] == kAda4080[ti][nc - 2][cls] ? kAda4070[ti][nc - 2][cls] : 0) : (type == 11 ? 0 : a); @@ -303,7 +306,7 @@ int check_tables() { ++bad; std::printf("FAIL table: the sm_60 table is not the P100's\n"); } - // sm_89 one column: only Q3_K with STRATA_MMVQ_IL_89=1 (the 4070 and the 4080 agree), else none; wider than 4: the plain kernels + // sm_89 one column: only Q3_K with the tables on (the 4070 and the 4080 agree), else none; wider than 4: the plain kernels if (native_mmvq_il_rows_for(89, 11, 1, 2560) != 0 || native_mmvq_il_rows_for(89, 11, 1, 6144) != (opt89 ? 1 : 0) || native_mmvq_il_rows_for(89, 12, 1, 6144) != 0) { ++bad; From dc390c38647a24cf26de65019e32a48733adce20 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:44:28 +0100 Subject: [PATCH 155/177] Prefill: opt-in STRATA_DEQUANT_SIDE=1 dequantizes the dense weights on a side stream into a double-buffered scratch (#3779, #3712) Problem: Gemm::native dequantizes each dense weight to FP16 in front of its GEMM on the compute stream, so the dequant never overlaps the kernels queued ahead of it. Change, opt-in (CUDA only, always off on HIP): with STRATA_DEQUANT_SIDE=1 the prompt path takes a second GEMM scratch (64 MiB more of its region, counted in bytes_needed and carried through relayout) and Gemm::set_dequant_side hands it to the Gemm. native() then dequantizes the next weight on a non-blocking side stream into the scratch the compute stream read last but one. Four events order every write and read of each scratch (free -> dequant -> ready -> GEMM -> free), so each product sees the same bytes as in the serial form. The row-sliced path (a weight larger than the scratch) stays serial. Metal answers false and keeps the serial form. Differs from the PR as submitted: if the side stream, its events or the setup fail, the PR failed the prompt-path init. Here one line is printed and the dense weights are dequantized in front of their GEMMs as before. Unset, nothing changes (gemm_dequant_side() is one cached flag; the scratch, stream and events are not created). Test: new gemm_dequant_side_parity (ctest, GPU, synthetic, 77 without a device): eight Q4_K / Q5_K / Q6_K weights of the engine's shapes (one larger than the scratch, so it takes the sliced path) run three rounds through Gemm::native serially and with the side stream, with and without a spin kernel queued ahead of each GEMM; every output must be identical bit for bit. Not covered: dense weights read by the side stream are the resident ones; a weight that arrived by an upload on another stream would need its own event (the prompt path has none that do). Reporter's numbers (linxuhao, CMP 170HX): measured with STRATA_PLE_COPY_STREAM and STRATA_EMBED_VRAM, the four PLE / embedding / dequant switches together give +2.2..+2.6 % prompts. Theirs, not measured here. Original change by linxuhao (PR #3779, commit 741fc6ab). --- CMakeLists.txt | 6 ++ include/strata/prefill/gemm.hpp | 20 ++++ metal/src/engine/stubs_0145.cpp | 3 + src/prefill/gemm.cu | 64 +++++++++++++ src/prefill/gemm_dequant_side_parity.cu | 121 ++++++++++++++++++++++++ src/prefill/prefill.cpp | 6 ++ 6 files changed, 220 insertions(+) create mode 100644 src/prefill/gemm_dequant_side_parity.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index 69a3fa7c..a7183b2e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1184,6 +1184,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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) + # STRATA_DEQUANT_SIDE: Gemm::native with the dense dequant on a side stream (two scratches) against the serial form, + # bitwise (GPU, synthetic, no model; 77 without a device) + add_executable(gemm_dequant_side_parity src/prefill/gemm_dequant_side_parity.cu) + target_link_libraries(gemm_dequant_side_parity PRIVATE strata_prefill ) + add_test(NAME gemm_dequant_side_parity COMMAND gemm_dequant_side_parity) + set_tests_properties(gemm_dequant_side_parity PROPERTIES SKIP_RETURN_CODE 77) # 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. diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 596b3e4b..80f625ee 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -66,6 +66,13 @@ public: /// Caller-owned buffers only: the scratch and workspace moved (the prompt path laid its buffers out again). void rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes); + /// STRATA_DEQUANT_SIDE=1 (gemm_dequant_side): a second dequant scratch of scratch_elems() elements, caller-owned + /// like the first. native() then dequantizes on a side stream into the two in turn, so a weight's dequant runs + /// while the kernels queued ahead of its GEMM do; events order every write and read of each scratch, so the + /// products are the serial form's, bit for bit. nullptr: the serial form. Called after init_external and + /// after every rebind (the "scratch free" events are re-armed on the compute stream). CUDA only. + bool set_dequant_side(uint16_t* scratch2, std::string& err); + uint16_t* scratch() const { return scratch_; } int64_t scratch_elems() const { return scratch_elems_; } void* stream() const { return stream_; } @@ -77,6 +84,14 @@ private: int64_t scratch_elems_ = 0; void* workspace_ = nullptr; bool external_ = false; + // STRATA_DEQUANT_SIDE (set_dequant_side): the second scratch, the side stream and, per scratch, "the dequant + // landed" (recorded on the side stream) and "the GEMM read it" (recorded on the compute stream); side_cur_ is + // the scratch the next native() dequantizes into (0: scratch_, 1: side_scratch_) + uint16_t* side_scratch_ = nullptr; + void* side_stream_ = nullptr; + void* side_ready_[2] = {}; + void* side_free_[2] = {}; + int side_cur_ = 0; void* hipblaslt_state_ = nullptr; void* rocblas_state_ = nullptr; // HIP: the rocBLAS solution table of f16_inplace (STRATA_ROCBLAS_TUNING) bool f16_io_ = false; @@ -122,6 +137,11 @@ void gemm_set_dense_f32(int mode); /// set_act_f16). Cached per device (a layer split can mix cards). STRATA_HIP_PROMPT_F16=0/1 overrides. bool prompt_f16(); +/// STRATA_DEQUANT_SIDE=1: the prompt path's dense-weight dequant on a side stream with a second GEMM scratch +/// (Gemm::set_dequant_side; the prompt path takes the scratch from its borrowed region when this is on). Off by +/// default; always off on HIP (its padded / MMQ paths use the scratch on the compute stream without the events). +bool gemm_dequant_side(); + } // namespace strata::prefill diff --git a/metal/src/engine/stubs_0145.cpp b/metal/src/engine/stubs_0145.cpp index 791d1df4..da99868c 100644 --- a/metal/src/engine/stubs_0145.cpp +++ b/metal/src/engine/stubs_0145.cpp @@ -151,3 +151,6 @@ namespace strata::kernels { void native_q8_0_sm60_release(void const* p0) { } } namespace strata::prefill { void swiglu_split_f16(float const* p0, unsigned short* p1, long long p2, int p3, bool p4, void* p5) { } } // STRATA_PLE_COMPACT (opt-in, CUDA / HIP prompt path): prefill.cpp references it; the Metal prompt runs through its window and never reaches it. namespace strata::kernels { void ple_iq4nl_dequant(const uint8_t* p0, int64_t p1, float* p2, void* p3) { strata::metal_engine::missing("strata::kernels::ple_iq4nl_dequant"); } } +// STRATA_DEQUANT_SIDE (opt-in, CUDA only): off on Metal; the prompt path takes no second scratch and set_dequant_side(nullptr) keeps the serial form. +namespace strata::prefill { bool gemm_dequant_side() { return false; } } +auto strata::prefill::Gemm::set_dequant_side(uint16_t* p0, std::string& p1) -> bool { if (p0 == nullptr) return true; strata::metal_engine::missing("strata::prefill::Gemm::set_dequant_side"); return false; } diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index a52af750..6d7816c9 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -627,7 +627,21 @@ const uint16_t* Gemm::unpad_x(const uint16_t* X, int64_t T, int64_t K, int64_t l return unpadded_x_; } +bool gemm_dequant_side() { +#if defined(__HIPCC__) + return false; +#else + static const bool on = [] { const char* v = std::getenv("STRATA_DEQUANT_SIDE"); return v && v[0] == '1'; }(); + return on; +#endif +} + Gemm::~Gemm() { + for (void* e : side_ready_) + if (e) (void) cudaEventDestroy((cudaEvent_t) e); + for (void* e : side_free_) + if (e) (void) cudaEventDestroy((cudaEvent_t) e); + if (side_stream_) (void) cudaStreamDestroy((cudaStream_t) side_stream_); #if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__) delete static_cast<strata::prefill::mmq::Context*>(mmq_ctx_); if (mmq_buf_) cudaFree(mmq_buf_); @@ -687,6 +701,38 @@ void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, siz #endif } +bool Gemm::set_dequant_side(uint16_t* scratch2, std::string& err) { + side_scratch_ = scratch2; + side_cur_ = 0; + if (scratch2 == nullptr) return true; + if (side_stream_ == nullptr) { // once: the stream and the four events outlive every rebind + cudaStream_t s = nullptr; + if (const cudaError_t e = cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking); e != cudaSuccess) { + err = std::string("prefill gemm: dequant side stream: ") + cudaGetErrorString(e); + side_scratch_ = nullptr; + return false; + } + side_stream_ = s; + for (int i = 0; i < 2; ++i) { + cudaEvent_t r = nullptr, f = nullptr; + const bool made = cudaEventCreateWithFlags(&r, cudaEventDisableTiming) == cudaSuccess && + cudaEventCreateWithFlags(&f, cudaEventDisableTiming) == cudaSuccess; + side_ready_[i] = r; // kept even on a failure: the destructor frees what was made + side_free_[i] = f; + if (!made) { + err = "prefill gemm: dequant side events"; + side_scratch_ = nullptr; + return false; + } + } + } + // both scratches are free once what the compute stream holds now is done (a rebind follows a stream sync, so + // this is belt and braces; a wait on an event never recorded would pass anyway) + for (int i = 0; i < 2; ++i) + (void) cudaEventRecord((cudaEvent_t) side_free_[i], (cudaStream_t) stream_); + return true; +} + bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) { // #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install cublasHandle_t h = nullptr; @@ -1356,6 +1402,24 @@ void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_); f16(X, scratch_, Y + r0, T, n, K, ldy, beta); } + // the side stream's next dequant into scratch_ waits for these slices' reads and writes of it + if (side_scratch_) (void) cudaEventRecord((cudaEvent_t) side_free_[0], (cudaStream_t) stream_); + return; + } + if (side_scratch_) { + // STRATA_DEQUANT_SIDE: the dequant on the side stream, into the scratch the compute stream read last but one. + // free[cur] -> dequant -> ready[cur] -> GEMM -> free[cur] orders the dequant after the GEMM that last read + // this scratch and the GEMM after the dequant that filled it, so every read and write of a scratch is where + // the serial form had it - the same kernels, the same bits - and the dequant runs while the kernels queued + // ahead of this GEMM do. + uint16_t* const s = side_cur_ == 0 ? scratch_ : side_scratch_; + (void) cudaStreamWaitEvent((cudaStream_t) side_stream_, (cudaEvent_t) side_free_[side_cur_], 0); + strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, s, side_stream_); + (void) cudaEventRecord((cudaEvent_t) side_ready_[side_cur_], (cudaStream_t) side_stream_); + (void) cudaStreamWaitEvent((cudaStream_t) stream_, (cudaEvent_t) side_ready_[side_cur_], 0); + f16(X, s, Y, T, N, K, ldy, beta); + (void) cudaEventRecord((cudaEvent_t) side_free_[side_cur_], (cudaStream_t) stream_); + side_cur_ ^= 1; return; } strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, scratch_, stream_); diff --git a/src/prefill/gemm_dequant_side_parity.cu b/src/prefill/gemm_dequant_side_parity.cu new file mode 100644 index 00000000..2ad906ae --- /dev/null +++ b/src/prefill/gemm_dequant_side_parity.cu @@ -0,0 +1,121 @@ +// src/prefill/gemm_dequant_side_parity.cu - STRATA_DEQUANT_SIDE: Gemm::native with the dense-weight dequant on a side +// stream into two scratches (Gemm::set_dequant_side) against the serial form, bitwise (GPU, synthetic, no model). +// +// A run of dense projections (Q4_K and Q6_K weights of the engine's shapes, one of them larger than the scratch so it takes +// the sliced path, which keeps the serial form) is executed twice from the same inputs: once serially, once with the side +// stream. Every output must be identical bit for bit. Also a run with a long queue of compute work ahead of each GEMM, so +// the side dequant really overlaps it. Exit 77 without a CUDA device. +#include "strata/prefill/gemm.hpp" + +#include <cuda_fp16.h> +#include <cuda_runtime.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <random> +#include <string> +#include <vector> + +namespace { +__global__ void fill_f16(__half* p, int64_t n, unsigned seed, float scale) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + unsigned x = (unsigned) i * 2654435761u + seed; + x ^= x >> 16; x *= 2246822519u; x ^= x >> 13; x *= 3266489917u; x ^= x >> 16; + p[i] = __float2half(((float) (x & 0xffff) / 32768.0f - 1.0f) * scale); +} +// busy work on the compute stream ahead of a GEMM +__global__ void spin(float* p, int64_t n, int iters) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float v = p[i]; + for (int k = 0; k < iters; ++k) v = v * 1.0000001f + 1e-7f; + p[i] = v; +} +bool ok(cudaError_t e, const char* what) { + if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e)); + return e == cudaSuccess; +} +uint16_t sane_half(std::mt19937& rng) { + const uint32_t r = rng(); + return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); +} +struct Weight { int type, bytes_per_block; int at[2]; int64_t N, K; void* dev = nullptr; }; +} // namespace + +int main() { + setvbuf(stdout, nullptr, _IONBF, 0); + int n_dev = 0; + if (cudaGetDeviceCount(&n_dev) != cudaSuccess || n_dev < 1) { std::printf("no CUDA device (skipped)\n"); return 77; } + cudaStream_t st = nullptr; + if (!ok(cudaStreamCreate(&st), "stream")) return 1; + const int64_t T = 512; + const int64_t scratch_elems = 2560LL * 4096; // 6144 x 2560 does not fit: the sliced path + strata::prefill::Gemm gemm; + std::string err; + if (!gemm.init(st, scratch_elems, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; } + uint16_t* scratch2 = nullptr; + if (!ok(cudaMalloc((void**) &scratch2, (size_t) scratch_elems * 2), "scratch2")) return 1; + + std::vector<Weight> ws = { + {12, 144, {0, 2}, 10240, 2560}, {14, 210, {208, -1}, 2560, 6144}, {12, 144, {0, 2}, 6144, 2560}, + {14, 210, {208, -1}, 3072, 2560}, {12, 144, {0, 2}, 2560, 4096}, {13, 176, {0, 2}, 2560, 2560}, + {12, 144, {0, 2}, 512, 2560}, {14, 210, {208, -1}, 12288, 2560}, + }; + std::mt19937 rng(20261026u); + for (Weight& w : ws) { + const size_t blocks = (size_t) (w.N * w.K / 256), bytes = blocks * (size_t) w.bytes_per_block; + std::vector<uint8_t> h(bytes); + for (auto& b : h) b = (uint8_t) (rng() & 0xff); + for (size_t k = 0; k < blocks; ++k) + for (int at : w.at) + if (at >= 0) { const uint16_t v = sane_half(rng); std::memcpy(&h[k * (size_t) w.bytes_per_block + (size_t) at], &v, 2); } + if (!ok(cudaMalloc(&w.dev, bytes), "W") || !ok(cudaMemcpy(w.dev, h.data(), bytes, cudaMemcpyHostToDevice), "W copy")) return 1; + } + int64_t max_k = 0, max_n = 0; + for (const Weight& w : ws) { max_k = std::max(max_k, w.K); max_n = std::max(max_n, w.N); } + uint16_t* X = nullptr; + float *busy = nullptr, *Y[2] = {nullptr, nullptr}; + const int64_t busy_n = 1 << 22; + if (!ok(cudaMalloc((void**) &X, (size_t) T * max_k * 2), "X") || !ok(cudaMalloc((void**) &busy, (size_t) busy_n * 4), "busy") || + !ok(cudaMalloc((void**) &Y[0], (size_t) T * max_n * 4 * ws.size()), "Y0") || + !ok(cudaMalloc((void**) &Y[1], (size_t) T * max_n * 4 * ws.size()), "Y1")) + return 1; + fill_f16<<<(unsigned) ((T * max_k + 255) / 256), 256, 0, st>>>((__half*) X, T * max_k, 17u, 2.0f); + cudaMemset(busy, 0, (size_t) busy_n * 4); + if (!ok(cudaStreamSynchronize(st), "fill")) return 1; + + int bad = 0; + for (int busy_iters : {0, 20000}) { + for (int side = 0; side < 2; ++side) { + std::string e2; + if (!gemm.set_dequant_side(side ? scratch2 : nullptr, e2)) { std::printf("FAIL: set_dequant_side: %s\n", e2.c_str()); return 1; } + cudaMemset(Y[side], 0xff, (size_t) T * max_n * 4 * ws.size()); + for (int round = 0; round < 3; ++round) // the scratch parity of the second round differs from the first + for (size_t i = 0; i < ws.size(); ++i) { + if (busy_iters) spin<<<(unsigned) ((busy_n + 255) / 256), 256, 0, st>>>(busy, busy_n, busy_iters); + gemm.native(X, ws[i].type, ws[i].dev, Y[side] + (size_t) i * T * max_n, T, ws[i].N, ws[i].K, max_n, 0.0f); + } + if (!ok(cudaStreamSynchronize(st), "run") || !ok(cudaDeviceSynchronize(), "device")) return 1; + } + std::vector<uint8_t> a((size_t) T * max_n * 4 * ws.size()), b(a.size()); + cudaMemcpy(a.data(), Y[0], a.size(), cudaMemcpyDeviceToHost); + cudaMemcpy(b.data(), Y[1], b.size(), cudaMemcpyDeviceToHost); + for (size_t i = 0; i < ws.size(); ++i) { + // the written part of the output: T rows of N floats at stride max_n + long long diff = 0; + for (int64_t r = 0; r < T; ++r) + if (std::memcmp(&a[((size_t) i * T * max_n + (size_t) r * max_n) * 4], &b[((size_t) i * T * max_n + (size_t) r * max_n) * 4], + (size_t) ws[i].N * 4) != 0) + ++diff; + const bool sliced = ws[i].N * ws[i].K > scratch_elems; + std::printf(" busy %-6d type %2d N %5lld K %4lld%s: %s\n", busy_iters, ws[i].type, (long long) ws[i].N, (long long) ws[i].K, + sliced ? " (sliced)" : "", diff ? "*** DIFFERS ***" : "bitwise equal"); + if (diff) ++bad; + } + } + gemm.set_dequant_side(nullptr, err); + std::printf("gemm_dequant_side_parity: %s\n", bad ? "FAILED" : "OK"); + return bad ? 1 : 0; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 21f65e6a..d8aa780b 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1582,8 +1582,11 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co { uint16_t* gs = o.take<uint16_t>((size_t) GEMM_SCRATCH, ok); void* ws = o.take<uint8_t>(GEMM_WS, ok); + // STRATA_DEQUANT_SIDE: the second dequant scratch (counted by bytes_needed_impl, retaken by relayout) + uint16_t* gs2 = gemm_dequant_side() ? o.take<uint16_t>((size_t) GEMM_SCRATCH, ok) : nullptr; if (!ok) { err = "prefill: GEMM scratch does not fit"; return false; } if (!m.gemm.init_external(stream, gs, GEMM_SCRATCH, ws, GEMM_WS, err)) return false; + { std::string side_err; if (!m.gemm.set_dequant_side(gs2, side_err)) std::fprintf(stderr, "prefill: STRATA_DEQUANT_SIDE=1 not taken (%s): the dense weights are dequantized in front of their GEMMs\n", side_err.c_str()); } // this stage's device decides, once, here (init runs on the stage's own device): its gr_* kernels write the // image its GEMMs read, and set_act_f16 writes that device's symbol const core::OnDevice on_stage(m.device); @@ -1739,7 +1742,9 @@ bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std:: o.owned = &m.owned; uint16_t* gs = o.take<uint16_t>((size_t) GEMM_SCRATCH, ok); void* ws = o.take<uint8_t>(GEMM_WS, ok); + uint16_t* gs2 = gemm_dequant_side() ? o.take<uint16_t>((size_t) GEMM_SCRATCH, ok) : nullptr; // STRATA_DEQUANT_SIDE if (ok) m.gemm.rebind(gs, GEMM_SCRATCH, ws, GEMM_WS); + if (ok) { std::string side_err; if (!m.gemm.set_dequant_side(gs2, side_err)) std::fprintf(stderr, "prefill: STRATA_DEQUANT_SIDE=1 not taken (%s): the dense weights are dequantized in front of their GEMMs\n", side_err.c_str()); } if (!ok || !carve((size_t) chunk, &o)) { size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); @@ -2388,6 +2393,7 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se if (owned_pages) o.granule = 2ull << 20; o.take<uint16_t>((size_t) GEMM_SCRATCH, ok); o.take<uint8_t>(GEMM_WS, ok); + if (gemm_dequant_side()) o.take<uint16_t>((size_t) GEMM_SCRATCH, ok); // STRATA_DEQUANT_SIDE: the second scratch auto f = [&](size_t n) { o.take<float>(n, ok); }; // `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h, // bo aliases emb. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted From 59b4be2a5493a03c990d8ba8bb61801d657308d1 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:19:31 +0100 Subject: [PATCH 156/177] App: French for the four new DeepSeek card and 12 GB NVIDIA strings (fx80-fx83) --- apps/host/src/locales/fix-fr.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/host/src/locales/fix-fr.json b/apps/host/src/locales/fix-fr.json index 0b0ab157..052851ed 100644 --- a/apps/host/src/locales/fix-fr.json +++ b/apps/host/src/locales/fix-fr.json @@ -77,5 +77,9 @@ "fx76": "Activé (recommandé)", "fx77": "C’est un très gros modèle. Le téléchargement fait {0} Go et il faut à peu près autant d’espace disque libre. Il tourne sur les cartes NVIDIA RTX 30, 40 et 50, sur une Radeon AI PRO R9700 (Linux) ou sur un PC Ryzen AI Max / Strix Halo (Windows) ; sa vitesse dépend de la mémoire et de la carte (la ligne ci-dessous indique à quoi s’attendre sur cet ordinateur). Ce qui ne tient pas en mémoire est lu depuis votre SSD, un disque NVMe compte donc beaucoup.", "fx78": "Pas encore testé. Un contexte aussi long prend de la mémoire graphique au modèle et lit lentement les longs prompts.", - "fx79": "Désactivé (recommandé)" + "fx79": "Désactivé (recommandé)", + "fx80": "Il faut environ {0} Go d’espace disque libre. Ce qui ne tient pas en mémoire est lu depuis votre SSD.", + "fx81": "{0} de RAM + VRAM, plus environ {1} Go de disque", + "fx82": "Réponses plus rapides sur les cartes NVIDIA de 12 Go", + "fx83": "Privilégie les parties du modèle déjà présentes sur la carte graphique, ce qui accélère nettement les réponses sur les cartes de 12 Go. Désactivez-le si les réponses semblent moins bonnes qu’avant." } From 902dc814d6d05161227ead6d6f8f69f37f97216b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:31:47 +0100 Subject: [PATCH 157/177] Desktop shell: a pinned app port with a warning when it is busy (#3402); minimise to tray with Tauri's own tray icon and a native desktop notification through the loopback bridge (#3477) --- apps/desktop/src-tauri/Cargo.lock | 154 ++++++++++ apps/desktop/src-tauri/Cargo.toml | 4 +- .../src-tauri/gen/schemas/acl-manifests.json | 2 +- .../src-tauri/gen/schemas/desktop-schema.json | 264 ++++++++++++++++++ apps/desktop/src-tauri/src/main.rs | 36 ++- apps/desktop/src-tauri/src/shell.rs | 238 ++++++++++++++++ apps/desktop/src-tauri/src/updater.rs | 10 + 7 files changed, 703 insertions(+), 5 deletions(-) create mode 100644 apps/desktop/src-tauri/src/shell.rs diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 368763dc..09b71357 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -349,6 +349,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -1755,6 +1761,19 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2097,6 +2116,20 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2", + "objc2-foundation", + "time", + "uuid", +] + [[package]] name = "markup5ever" version = "0.39.0" @@ -2166,6 +2199,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "muda" version = "0.20.0" @@ -2229,6 +2272,20 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "notify-rust" +version = "4.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4587364a9a0074333429b3df75a30a205340c56a536ca3eb6ca0e59b87bbf8af" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2757,6 +2814,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "precomputed-hash" version = "0.1.1" @@ -2825,6 +2891,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + [[package]] name = "quick-xml" version = "0.42.0" @@ -2855,6 +2927,35 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -3531,6 +3632,7 @@ dependencies = [ "serde_json", "tauri", "tauri-build", + "tauri-plugin-notification", "tauri-plugin-shell", "tauri-plugin-single-instance", "tauri-plugin-updater", @@ -3755,6 +3857,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http", + "image", "jni 0.21.1", "libc", "log", @@ -3869,6 +3972,26 @@ dependencies = [ "walkdir", ] +[[package]] +name = "tauri-plugin-notification" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b939d7b19c8af1381a72ef8474b3aba2b56c1ddac2c23f0c8e96abbcf86b198b" +dependencies = [ + "log", + "notify-rust", + "rand", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "time", + "url", + "zbus", +] + [[package]] name = "tauri-plugin-shell" version = "2.5.0" @@ -4042,6 +4165,17 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "tauri-winrt-notification" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-version", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -5332,6 +5466,26 @@ dependencies = [ "serde", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 324f8963..90c1cf12 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -15,8 +15,10 @@ webkit2gtk = "2.0" tauri-build = { version = "2", features = [] } [dependencies] -tauri = { version = "2", features = [] } +tauri = { version = "2", features = ["tray-icon", "image-png"] } tauri-plugin-shell = "2" +# Desktop notifications for an approval that waits (#3477); the tray icon above is Tauri's own. +tauri-plugin-notification = "2" tauri-plugin-updater = "2" tauri-plugin-single-instance = "2" serde = { version = "1", features = ["derive"] } diff --git a/apps/desktop/src-tauri/gen/schemas/acl-manifests.json b/apps/desktop/src-tauri/gen/schemas/acl-manifests.json index ee63464d..9bccc08a 100644 --- a/apps/desktop/src-tauri/gen/schemas/acl-manifests.json +++ b/apps/desktop/src-tauri/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"shell":{"default_permission":{"identifier":"default","description":"This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n","permissions":["allow-open"]},"permissions":{"allow-execute":{"identifier":"allow-execute","description":"Enables the execute command without any pre-configured scope.","commands":{"allow":["execute"],"deny":[]}},"allow-kill":{"identifier":"allow-kill","description":"Enables the kill command without any pre-configured scope.","commands":{"allow":["kill"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-spawn":{"identifier":"allow-spawn","description":"Enables the spawn command without any pre-configured scope.","commands":{"allow":["spawn"],"deny":[]}},"allow-stdin-write":{"identifier":"allow-stdin-write","description":"Enables the stdin_write command without any pre-configured scope.","commands":{"allow":["stdin_write"],"deny":[]}},"deny-execute":{"identifier":"deny-execute","description":"Denies the execute command without any pre-configured scope.","commands":{"allow":[],"deny":["execute"]}},"deny-kill":{"identifier":"deny-kill","description":"Denies the kill command without any pre-configured scope.","commands":{"allow":[],"deny":["kill"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-spawn":{"identifier":"deny-spawn","description":"Denies the spawn command without any pre-configured scope.","commands":{"allow":[],"deny":["spawn"]}},"deny-stdin-write":{"identifier":"deny-stdin-write","description":"Denies the stdin_write command without any pre-configured scope.","commands":{"allow":[],"deny":["stdin_write"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"cmd":{"description":"The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"}},"required":["cmd","name"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"},"sidecar":{"description":"If this command is a sidecar command.","type":"boolean"}},"required":["name","sidecar"],"type":"object"}],"definitions":{"ShellScopeEntryAllowedArg":{"anyOf":[{"description":"A non-configurable argument that is passed to the command in the order it was specified.","type":"string"},{"additionalProperties":false,"description":"A variable that is set while calling the command from the webview API.","properties":{"raw":{"default":false,"description":"Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.","type":"boolean"},"validator":{"description":"[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: <https://docs.rs/regex/latest/regex/#syntax>","type":"string"}},"required":["validator"],"type":"object"}],"description":"A command argument allowed to be executed by the webview API."},"ShellScopeEntryAllowedArgs":{"anyOf":[{"description":"Use a simple boolean to allow all or disable all arguments to this command configuration.","type":"boolean"},{"description":"A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.","items":{"$ref":"#/definitions/ShellScopeEntryAllowedArg"},"type":"array"}],"description":"A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration."}},"description":"Shell scope entry.","title":"ShellScopeEntry"}},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file +{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"shell":{"default_permission":{"identifier":"default","description":"This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n","permissions":["allow-open"]},"permissions":{"allow-execute":{"identifier":"allow-execute","description":"Enables the execute command without any pre-configured scope.","commands":{"allow":["execute"],"deny":[]}},"allow-kill":{"identifier":"allow-kill","description":"Enables the kill command without any pre-configured scope.","commands":{"allow":["kill"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-spawn":{"identifier":"allow-spawn","description":"Enables the spawn command without any pre-configured scope.","commands":{"allow":["spawn"],"deny":[]}},"allow-stdin-write":{"identifier":"allow-stdin-write","description":"Enables the stdin_write command without any pre-configured scope.","commands":{"allow":["stdin_write"],"deny":[]}},"deny-execute":{"identifier":"deny-execute","description":"Denies the execute command without any pre-configured scope.","commands":{"allow":[],"deny":["execute"]}},"deny-kill":{"identifier":"deny-kill","description":"Denies the kill command without any pre-configured scope.","commands":{"allow":[],"deny":["kill"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-spawn":{"identifier":"deny-spawn","description":"Denies the spawn command without any pre-configured scope.","commands":{"allow":[],"deny":["spawn"]}},"deny-stdin-write":{"identifier":"deny-stdin-write","description":"Denies the stdin_write command without any pre-configured scope.","commands":{"allow":[],"deny":["stdin_write"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"cmd":{"description":"The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"}},"required":["cmd","name"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"},"sidecar":{"description":"If this command is a sidecar command.","type":"boolean"}},"required":["name","sidecar"],"type":"object"}],"definitions":{"ShellScopeEntryAllowedArg":{"anyOf":[{"description":"A non-configurable argument that is passed to the command in the order it was specified.","type":"string"},{"additionalProperties":false,"description":"A variable that is set while calling the command from the webview API.","properties":{"raw":{"default":false,"description":"Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.","type":"boolean"},"validator":{"description":"[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: <https://docs.rs/regex/latest/regex/#syntax>","type":"string"}},"required":["validator"],"type":"object"}],"description":"A command argument allowed to be executed by the webview API."},"ShellScopeEntryAllowedArgs":{"anyOf":[{"description":"Use a simple boolean to allow all or disable all arguments to this command configuration.","type":"boolean"},{"description":"A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.","items":{"$ref":"#/definitions/ShellScopeEntryAllowedArg"},"type":"array"}],"description":"A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration."}},"description":"Shell scope entry.","title":"ShellScopeEntry"}},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file diff --git a/apps/desktop/src-tauri/gen/schemas/desktop-schema.json b/apps/desktop/src-tauri/gen/schemas/desktop-schema.json index 5625606d..ba712940 100644 --- a/apps/desktop/src-tauri/gen/schemas/desktop-schema.json +++ b/apps/desktop/src-tauri/gen/schemas/desktop-schema.json @@ -2426,6 +2426,216 @@ "const": "core:window:deny-unminimize", "markdownDescription": "Denies the unminimize command without any pre-configured scope." }, + { + "description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`", + "type": "string", + "const": "notification:default", + "markdownDescription": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`" + }, + { + "description": "Enables the batch command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-batch", + "markdownDescription": "Enables the batch command without any pre-configured scope." + }, + { + "description": "Enables the cancel command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-cancel", + "markdownDescription": "Enables the cancel command without any pre-configured scope." + }, + { + "description": "Enables the check_permissions command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-check-permissions", + "markdownDescription": "Enables the check_permissions command without any pre-configured scope." + }, + { + "description": "Enables the create_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-create-channel", + "markdownDescription": "Enables the create_channel command without any pre-configured scope." + }, + { + "description": "Enables the delete_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-delete-channel", + "markdownDescription": "Enables the delete_channel command without any pre-configured scope." + }, + { + "description": "Enables the get_active command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-get-active", + "markdownDescription": "Enables the get_active command without any pre-configured scope." + }, + { + "description": "Enables the get_pending command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-get-pending", + "markdownDescription": "Enables the get_pending command without any pre-configured scope." + }, + { + "description": "Enables the is_permission_granted command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-is-permission-granted", + "markdownDescription": "Enables the is_permission_granted command without any pre-configured scope." + }, + { + "description": "Enables the list_channels command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-list-channels", + "markdownDescription": "Enables the list_channels command without any pre-configured scope." + }, + { + "description": "Enables the notify command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-notify", + "markdownDescription": "Enables the notify command without any pre-configured scope." + }, + { + "description": "Enables the permission_state command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-permission-state", + "markdownDescription": "Enables the permission_state command without any pre-configured scope." + }, + { + "description": "Enables the register_action_types command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-register-action-types", + "markdownDescription": "Enables the register_action_types command without any pre-configured scope." + }, + { + "description": "Enables the register_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-register-listener", + "markdownDescription": "Enables the register_listener command without any pre-configured scope." + }, + { + "description": "Enables the remove_active command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-remove-active", + "markdownDescription": "Enables the remove_active command without any pre-configured scope." + }, + { + "description": "Enables the remove_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-remove-listener", + "markdownDescription": "Enables the remove_listener command without any pre-configured scope." + }, + { + "description": "Enables the request_permission command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-request-permission", + "markdownDescription": "Enables the request_permission command without any pre-configured scope." + }, + { + "description": "Enables the show command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-show", + "markdownDescription": "Enables the show command without any pre-configured scope." + }, + { + "description": "Denies the batch command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-batch", + "markdownDescription": "Denies the batch command without any pre-configured scope." + }, + { + "description": "Denies the cancel command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-cancel", + "markdownDescription": "Denies the cancel command without any pre-configured scope." + }, + { + "description": "Denies the check_permissions command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-check-permissions", + "markdownDescription": "Denies the check_permissions command without any pre-configured scope." + }, + { + "description": "Denies the create_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-create-channel", + "markdownDescription": "Denies the create_channel command without any pre-configured scope." + }, + { + "description": "Denies the delete_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-delete-channel", + "markdownDescription": "Denies the delete_channel command without any pre-configured scope." + }, + { + "description": "Denies the get_active command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-get-active", + "markdownDescription": "Denies the get_active command without any pre-configured scope." + }, + { + "description": "Denies the get_pending command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-get-pending", + "markdownDescription": "Denies the get_pending command without any pre-configured scope." + }, + { + "description": "Denies the is_permission_granted command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-is-permission-granted", + "markdownDescription": "Denies the is_permission_granted command without any pre-configured scope." + }, + { + "description": "Denies the list_channels command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-list-channels", + "markdownDescription": "Denies the list_channels command without any pre-configured scope." + }, + { + "description": "Denies the notify command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-notify", + "markdownDescription": "Denies the notify command without any pre-configured scope." + }, + { + "description": "Denies the permission_state command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-permission-state", + "markdownDescription": "Denies the permission_state command without any pre-configured scope." + }, + { + "description": "Denies the register_action_types command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-register-action-types", + "markdownDescription": "Denies the register_action_types command without any pre-configured scope." + }, + { + "description": "Denies the register_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-register-listener", + "markdownDescription": "Denies the register_listener command without any pre-configured scope." + }, + { + "description": "Denies the remove_active command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-remove-active", + "markdownDescription": "Denies the remove_active command without any pre-configured scope." + }, + { + "description": "Denies the remove_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-remove-listener", + "markdownDescription": "Denies the remove_listener command without any pre-configured scope." + }, + { + "description": "Denies the request_permission command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-request-permission", + "markdownDescription": "Denies the request_permission command without any pre-configured scope." + }, + { + "description": "Denies the show command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-show", + "markdownDescription": "Denies the show command without any pre-configured scope." + }, { "description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`", "type": "string", @@ -2491,6 +2701,60 @@ "type": "string", "const": "shell:deny-stdin-write", "markdownDescription": "Denies the stdin_write command without any pre-configured scope." + }, + { + "description": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`", + "type": "string", + "const": "updater:default", + "markdownDescription": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`" + }, + { + "description": "Enables the check command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-check", + "markdownDescription": "Enables the check command without any pre-configured scope." + }, + { + "description": "Enables the download command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-download", + "markdownDescription": "Enables the download command without any pre-configured scope." + }, + { + "description": "Enables the download_and_install command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-download-and-install", + "markdownDescription": "Enables the download_and_install command without any pre-configured scope." + }, + { + "description": "Enables the install command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-install", + "markdownDescription": "Enables the install command without any pre-configured scope." + }, + { + "description": "Denies the check command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-check", + "markdownDescription": "Denies the check command without any pre-configured scope." + }, + { + "description": "Denies the download command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-download", + "markdownDescription": "Denies the download command without any pre-configured scope." + }, + { + "description": "Denies the download_and_install command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-download-and-install", + "markdownDescription": "Denies the download_and_install command without any pre-configured scope." + }, + { + "description": "Denies the install command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-install", + "markdownDescription": "Denies the install command without any pre-configured scope." } ] }, diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 8f38a00e..83eff268 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -39,6 +39,7 @@ use tauri::{Manager, WebviewUrl, WebviewWindowBuilder}; mod updater; mod desktoplog; +mod shell; #[cfg(target_os = "linux")] mod supervisor; @@ -252,13 +253,24 @@ fn pick_port() -> Result<u16, String> { /// launch starts with empty storage, as before). const PREFERRED_PORT: u16 = 47831; +/// Set when the port the person (or the app) wanted was busy: "busy:<wanted>:<used>". The host gets it as STRATA_PORT_NOTICE and tells the +/// person (the chats and settings saved on the page belong to the port, so a different port starts empty) (#3402). +static PORT_NOTICE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None); + fn pick_stable_port() -> Result<u16, String> { - match TcpListener::bind(("127.0.0.1", PREFERRED_PORT)) { + // The person may have chosen a port in Settings (shell-prefs.json); otherwise the app's usual one. + let wanted = shell::wanted_port(&shell::read_prefs(), PREFERRED_PORT); + *PORT_NOTICE.lock().unwrap() = None; + match TcpListener::bind(("127.0.0.1", wanted)) { Ok(listener) => { drop(listener); - Ok(PREFERRED_PORT) + Ok(wanted) + } + Err(_) => { + let used = pick_port()?; + *PORT_NOTICE.lock().unwrap() = Some(shell::busy_notice(wanted, used)); + Ok(used) } - Err(_) => pick_port(), } } @@ -469,6 +481,9 @@ fn host_command(res: &Path, port: u16, shutdown_token: &str) -> Result<Command, .stderr(Stdio::inherit()); apply_runtime_policy(&mut cmd, res); hide_console(&mut cmd); + if let Some(notice) = PORT_NOTICE.lock().unwrap().clone() { + cmd.env("STRATA_PORT_NOTICE", notice); + } // A user with the Strata API worker on a different port sets this; unset means the worker's // documented loopback default. if let Ok(url) = std::env::var("STRATA_SERVER_URL") { @@ -875,6 +890,7 @@ fn run_embedded() { })) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_updater::Builder::new().build()) + .plugin(tauri_plugin_notification::init()) .manage(HostProcess(Mutex::new(None))) .manage(HostPort(Mutex::new(None))) .manage(ShutdownToken(Mutex::new(None))) @@ -901,6 +917,20 @@ fn run_embedded() { Ok(()) }) .on_window_event(|window, event| { + // "Minimise to tray" (Settings, off by default): closing the main window hides it and keeps Strata running in the tray; Quit in the + // tray menu ends it (#3477). If no tray could be made the window closes as before. + if let tauri::WindowEvent::CloseRequested { api, .. } = event { + if window.label() == "main" { + let prefs = shell::read_prefs(); + if prefs.tray { + api.prevent_close(); + shell::hide_to_tray(&window.app_handle().clone(), &prefs.language); + if !shell::tray_exists(&window.app_handle().clone()) { + let _ = window.destroy(); + } + } + } + } if let tauri::WindowEvent::Destroyed = event { stop_host(&window.app_handle().clone()); } diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs new file mode 100644 index 00000000..3b20d0be --- /dev/null +++ b/apps/desktop/src-tauri/src/shell.rs @@ -0,0 +1,238 @@ +//! The shell's own choices and the two things the host asks of it besides updates (#3402, #3477). +//! +//! `<Strata data folder>/shell-prefs.json` is written by the App Host when the person changes a setting +//! (`apps/host/server/shell-prefs.mjs`) and read here when Strata starts, before any page exists: +//! +//! { "port": 0 | 1024..65535, "tray": false, "language": "en" } +//! +//! * `port`: the port the window's origin uses. 0 is the default, 47831. When the port is busy the shell takes a free one and tells the +//! host (`STRATA_PORT_NOTICE=busy:<wanted>:<used>`), which shows the person a warning: the chats and settings of the page are kept per +//! port, so a different port starts empty. +//! * `tray`: closing the window hides it and keeps Strata running in the tray (Windows, macOS). The tray menu follows `language`. +//! * `/shell/notify` on the loopback bridge shows a desktop notification (an approval is waiting) whether the window is open or hidden. + +use std::path::PathBuf; + +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Prefs { + pub port: u16, + pub tray: bool, + pub language: String, +} + +impl Default for Prefs { + fn default() -> Self { + Prefs { port: 0, tray: false, language: "en".into() } + } +} + +pub const LANGUAGES: [&str; 8] = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko"]; + +pub fn prefs_path() -> PathBuf { + crate::desktoplog::data_dir().join("shell-prefs.json") +} + +/// The file's text as choices; anything missing or out of range is the default. +pub fn parse_prefs(text: &str) -> Prefs { + let value: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).unwrap_or(Value::Null); + let port = value.get("port").and_then(Value::as_u64).filter(|p| (1024..=65535).contains(p)).unwrap_or(0) as u16; + let tray = value.get("tray").and_then(Value::as_bool).unwrap_or(false); + let language = value + .get("language") + .and_then(Value::as_str) + .filter(|l| LANGUAGES.contains(l)) + .unwrap_or("en") + .to_string(); + Prefs { port, tray, language } +} + +pub fn read_prefs() -> Prefs { + std::fs::read_to_string(prefs_path()).map(|t| parse_prefs(&t)).unwrap_or_default() +} + +/// The port to ask for: the person's choice, else the app's usual one. +pub fn wanted_port(prefs: &Prefs, usual: u16) -> u16 { + if prefs.port != 0 { prefs.port } else { usual } +} + +/// The notice the host shows when the wanted port was taken. +pub fn busy_notice(wanted: u16, used: u16) -> String { + format!("busy:{wanted}:{used}") +} + +/// `%41%20b` -> "A b" (a query value from the host). Bad escapes are kept as typed. +pub fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { + out.push(v); + i += 3; + continue; + } + } + out.push(if bytes[i] == b'+' { b' ' } else { bytes[i] }); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The value of `key` in the query of a request path (`/shell/notify?title=..&body=..`). +pub fn query_value(path: &str, key: &str) -> Option<String> { + let query = path.split_once('?')?.1; + query.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + (k == key).then(|| percent_decode(v)) + }) +} + +/// A short single-line text for a notification: no control characters, bounded. +pub fn clean_text(text: &str, max: usize) -> String { + text.chars().filter(|c| !c.is_control()).take(max).collect::<String>().trim().to_string() +} + +/// The tray menu: (open, quit, tooltip), in the app's language. +pub fn tray_labels(language: &str) -> (&'static str, &'static str, &'static str) { + match language { + "zh" => ("打开 Strata", "退出 Strata", "Strata"), + "ja" => ("Strata を開く", "Strata を終了", "Strata"), + "de" => ("Strata öffnen", "Strata beenden", "Strata"), + "es" => ("Abrir Strata", "Salir de Strata", "Strata"), + "ru" => ("Открыть Strata", "Выйти из Strata", "Strata"), + "pt" => ("Abrir o Strata", "Sair do Strata", "Strata"), + "ko" => ("Strata 열기", "Strata 종료", "Strata"), + _ => ("Open Strata", "Quit Strata", "Strata"), + } +} + +#[cfg(not(target_os = "linux"))] +mod native { + use tauri::menu::{Menu, MenuItem}; + use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; + use tauri::{AppHandle, Manager}; + use tauri_plugin_notification::NotificationExt; + + const TRAY_ID: &str = "strata-tray"; + + fn show_main(app: &AppHandle) { + if let Some(window) = app.get_webview_window("main") { + let _ = window.unminimize(); + let _ = window.show(); + let _ = window.set_focus(); + } + } + + /// Hide the window and keep Strata running in the tray (made on the first need, with the menu in the app's language). + pub fn hide_to_tray(app: &AppHandle, language: &str) { + if app.tray_by_id(TRAY_ID).is_none() { + let (open, quit, tip) = super::tray_labels(language); + let built = (|| -> tauri::Result<()> { + let open_item = MenuItem::with_id(app, "open", open, true, None::<&str>)?; + let quit_item = MenuItem::with_id(app, "quit", quit, true, None::<&str>)?; + let menu = Menu::with_items(app, &[&open_item, &quit_item])?; + let mut builder = TrayIconBuilder::with_id(TRAY_ID) + .tooltip(tip) + .menu(&menu) + .show_menu_on_left_click(false) + .on_menu_event(|app, event| match event.id().as_ref() { + "open" => show_main(app), + "quit" => app.exit(0), + _ => {} + }) + .on_tray_icon_event(|tray, event| { + if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { + show_main(tray.app_handle()); + } + }); + if let Some(icon) = app.default_window_icon() { + builder = builder.icon(icon.clone()); + } + builder.build(app)?; + Ok(()) + })(); + if built.is_err() { + // No tray could be made (a desktop without one): do not hide a window nobody could bring back. + return; + } + } + if let Some(window) = app.get_webview_window("main") { + let _ = window.hide(); + } + } + + pub fn tray_exists(app: &AppHandle) -> bool { + app.tray_by_id(TRAY_ID).is_some() + } + + /// Show a desktop notification; a hidden or minimised window also asks for attention (the taskbar button flashes). + pub fn notify(app: &AppHandle, title: &str, body: &str) -> bool { + if title.is_empty() { + return false; + } + if let Some(window) = app.get_webview_window("main") { + let hidden = !window.is_visible().unwrap_or(true) || window.is_minimized().unwrap_or(false); + if hidden { + let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational)); + } + } + app.notification().builder().title(title).body(body).show().is_ok() + } +} + +#[cfg(not(target_os = "linux"))] +pub use native::{hide_to_tray, notify, tray_exists}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_file_gives_choices_and_anything_wrong_is_the_default() { + assert_eq!(parse_prefs(""), Prefs::default()); + assert_eq!(parse_prefs("{ not json"), Prefs::default()); + let p = parse_prefs(r#"{"port":47900,"tray":true,"language":"de"}"#); + assert_eq!((p.port, p.tray, p.language.as_str()), (47900, true, "de")); + assert_eq!(parse_prefs("\u{feff}{\"port\":47900}").port, 47900); + assert_eq!(parse_prefs(r#"{"port":80}"#).port, 0, "a port below 1024 is not used"); + assert_eq!(parse_prefs(r#"{"port":70000}"#).port, 0); + assert_eq!(parse_prefs(r#"{"port":"47831"}"#).port, 0, "a text is not a number"); + assert_eq!(parse_prefs(r#"{"tray":"yes","language":"xx"}"#), Prefs::default()); + } + + #[test] + fn the_wanted_port_is_the_choice_or_the_usual_one() { + assert_eq!(wanted_port(&Prefs::default(), 47831), 47831); + assert_eq!(wanted_port(&Prefs { port: 47900, ..Prefs::default() }, 47831), 47900); + assert_eq!(busy_notice(47831, 51234), "busy:47831:51234"); + } + + #[test] + fn query_values_are_decoded_and_bounded() { + let path = "/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F+ok"; + assert_eq!(query_value(path, "title").as_deref(), Some("Strata needs your answer")); + assert_eq!(query_value(path, "body").as_deref(), Some("a & b? ok")); + assert_eq!(query_value(path, "missing"), None); + assert_eq!(query_value("/shell/notify", "title"), None); + assert_eq!(percent_decode("100%"), "100%"); + assert_eq!(percent_decode("%zz%41"), "%zzA"); + assert_eq!(percent_decode("%C3%A4"), "ä"); + assert_eq!(clean_text("a\nb\u{7}c", 10), "abc"); + assert_eq!(clean_text("abcdef", 3), "abc"); + } + + #[test] + fn every_language_has_tray_labels() { + for language in LANGUAGES { + let (open, quit, tip) = tray_labels(language); + assert!(!open.is_empty() && !quit.is_empty() && !tip.is_empty(), "{language}"); + if language != "en" { + assert_ne!(open, tray_labels("en").0, "{language}"); + } + } + assert_eq!(tray_labels("xx"), tray_labels("en")); + } +} diff --git a/apps/desktop/src-tauri/src/updater.rs b/apps/desktop/src-tauri/src/updater.rs index dd0a1ced..889e7109 100644 --- a/apps/desktop/src-tauri/src/updater.rs +++ b/apps/desktop/src-tauri/src/updater.rs @@ -210,6 +210,16 @@ fn handle(mut stream: TcpStream, app: &AppHandle, token: &str, progress: &Arc<Mu respond(&mut stream, "202 Accepted", &progress.lock().unwrap().json()); } ("GET", "/app-update/status") => respond(&mut stream, "200 OK", &progress.lock().unwrap().json()), + // The host asks for a desktop notification (an approval is waiting): title and body are in the query, bounded and cleaned here. + ("POST", p) if p.starts_with("/shell/notify") => { + let title = crate::shell::clean_text(&crate::shell::query_value(p, "title").unwrap_or_default(), 120); + let body = crate::shell::clean_text(&crate::shell::query_value(p, "body").unwrap_or_default(), 300); + #[cfg(not(target_os = "linux"))] + let shown = crate::shell::notify(app, &title, &body); + #[cfg(target_os = "linux")] + let shown = false; + respond(&mut stream, "200 OK", &serde_json::json!({ "shown": shown })) + } _ => respond(&mut stream, "404 Not Found", &serde_json::json!({ "error": "unknown route" })), } } From c17a6f4ce1cd1ad911508c6d87512c5169af6d0b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:31:51 +0100 Subject: [PATCH 158/177] App: the Monitor's readings strip (energy since start, cost in the person's own currency, GPU fan and clock, CPU and SSD temperature) with the Electricity price setting (#3628, PR #3628 by hash13 as the starting idea); a sound when work finishes (#3586); desktop notification and tray, pinned port and interface size settings with their host routes (#3477, #3402, #3970); the gh-<lang> catalog in nine languages --- apps/host/public/strata-done-sound.wav | Bin 0 -> 83834 bytes apps/host/scripts/make-gh-locales.py | 365 ++++++++++++++++++ apps/host/server/device-probes.mjs | 14 +- apps/host/server/energy-meter.mjs | 14 + apps/host/server/index.mjs | 28 ++ apps/host/server/monitor.mjs | 15 +- apps/host/server/region.mjs | 66 ++++ apps/host/server/shell-prefs.mjs | 77 ++++ apps/host/server/temperature-telemetry.mjs | 124 ++++++ apps/host/src/components/ElectricityPrice.tsx | 29 ++ apps/host/src/components/ShellSettings.tsx | 74 ++++ apps/host/src/lib/attention.ts | 85 ++++ apps/host/src/lib/currency.ts | 114 ++++++ apps/host/src/lib/i18n.ts | 13 +- apps/host/src/lib/money.ts | 28 ++ apps/host/src/lib/native-monitor.ts | 4 +- apps/host/src/lib/store.ts | 83 +++- apps/host/src/lib/types.ts | 6 +- apps/host/src/locales/gh-de.json | 36 ++ apps/host/src/locales/gh-en.json | 36 ++ apps/host/src/locales/gh-es.json | 36 ++ apps/host/src/locales/gh-fr.json | 36 ++ apps/host/src/locales/gh-ja.json | 36 ++ apps/host/src/locales/gh-ko.json | 36 ++ apps/host/src/locales/gh-pt.json | 36 ++ apps/host/src/locales/gh-ru.json | 36 ++ apps/host/src/locales/gh-zh.json | 36 ++ apps/host/src/screens/Monitor.tsx | 13 + apps/host/src/screens/Settings.tsx | 10 +- apps/host/src/styles/monitor.css | 9 + apps/host/tests/currency.test.mjs | 105 +++++ apps/host/tests/gh-app-features.test.mjs | 230 +++++++++++ apps/host/tests/locale-gaps.test.mjs | 2 +- 33 files changed, 1810 insertions(+), 22 deletions(-) create mode 100644 apps/host/public/strata-done-sound.wav create mode 100644 apps/host/scripts/make-gh-locales.py create mode 100644 apps/host/server/energy-meter.mjs create mode 100644 apps/host/server/region.mjs create mode 100644 apps/host/server/shell-prefs.mjs create mode 100644 apps/host/server/temperature-telemetry.mjs create mode 100644 apps/host/src/components/ElectricityPrice.tsx create mode 100644 apps/host/src/components/ShellSettings.tsx create mode 100644 apps/host/src/lib/attention.ts create mode 100644 apps/host/src/lib/currency.ts create mode 100644 apps/host/src/lib/money.ts create mode 100644 apps/host/src/locales/gh-de.json create mode 100644 apps/host/src/locales/gh-en.json create mode 100644 apps/host/src/locales/gh-es.json create mode 100644 apps/host/src/locales/gh-fr.json create mode 100644 apps/host/src/locales/gh-ja.json create mode 100644 apps/host/src/locales/gh-ko.json create mode 100644 apps/host/src/locales/gh-pt.json create mode 100644 apps/host/src/locales/gh-ru.json create mode 100644 apps/host/src/locales/gh-zh.json create mode 100644 apps/host/tests/currency.test.mjs create mode 100644 apps/host/tests/gh-app-features.test.mjs diff --git a/apps/host/public/strata-done-sound.wav b/apps/host/public/strata-done-sound.wav new file mode 100644 index 0000000000000000000000000000000000000000..ec3173e3ac6c6e461740a6f5e8146d2cf59b0517 GIT binary patch literal 83834 zcmWJsWt0<H7mRe;JFa86`v)wt_~Nj*ySqCq?y$JKySuwPEIKgQNG6`Nr#l__-kEde z7w1gT@4mWKb?@ucs(JHCE!3*+jk`4)Hg-x;qe`VxgP*3SRI24Y)GCe2s2VbG%D{Hu z->6iO%AzW-YN;Bd+N8Rp@~RB#8tN|Uaq30tjp|+M1L}k7{p#K7t?ISvrRsmwW7U1t zE!9=jCUsDCU$suvLzSWWp4yh`lp<1(l5>-Fl0xEqVr-&J;#Yh_yiweztX3*2FJdEO zWbC>;Rc<C%mFvjE<ePHs*ss`G<zW13q99pZHBx;}6V%#urC>Ai6`79u(HdActSeR% zi=*e!o~Vp$Myeri;qkB$zM$)*3qkW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al 0 HcmV?d00001 diff --git a/apps/host/scripts/make-gh-locales.py b/apps/host/scripts/make-gh-locales.py new file mode 100644 index 00000000..41898d25 --- /dev/null +++ b/apps/host/scripts/make-gh-locales.py @@ -0,0 +1,365 @@ +"""Writes src/locales/gh-<lang>.json: the interface strings of the 0.2.7 GitHub items done in f-027-gh-app (the Monitor's Power card #3628, +approval notifications and the tray #3477, the finished-task sound #3586, the pinned port #3402, the interface size #3970). +Run from apps/host: python scripts/make-gh-locales.py +The keys are gh01.. in this order; gh-en.json is the English source. Placeholders ({0}, {1}) must be kept in every language. +A separate file keeps this work from colliding with the other catalogs (the same reason tune-, tools- and fix- exist).""" +import json +import re +from pathlib import Path + +EN = [ + "Energy since start", + "Cost since start", + "GPU fan", + "GPU clock", + "CPU temperature", + "SSD temperature", + "Electricity price", + "Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.", + "Price per kWh", + "Sound when work finishes", + "Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.", + "Play sound", + "Notify me when Strata needs an answer", + "In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.", + "Strata needs your answer", + "The assistant wants to use {0}. Open Strata to approve or deny.", + "a tool", + "Minimise to tray", + "Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.", + "App port", + "The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.", + "Port (empty = automatic)", + "Using port {0} now.", + "Strata could not use its port", + "Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.", + "Choose a port between 1024 and 65535, or leave it empty.", + "Makes all text, buttons and menus in Strata larger or smaller.", + "Energy and temperature readings", + "per kWh, in {0}", + "per kWh", + "Change currency", + "Automatic ({0})", + "Currency", + "less than {0}", +] + +T = { +"zh": [ + "启动以来的能耗", + "启动以来的费用", + "GPU 风扇", + "GPU 频率", + "CPU 温度", + "SSD 温度", + "电价", + "每千瓦时的价格。监控页会据此显示 Strata 启动以来显卡用电的费用。留空则不显示费用。", + "每千瓦时价格", + "工作完成时的提示音", + "回答或耗时较长的任务完成时,或 Strata 在后台时,播放一段简短的提示音。", + "播放提示音", + "Strata 需要您答复时通知我", + "在手动模式下,当助手等待您批准而 Strata 在后台时,显示桌面通知。", + "Strata 需要您的答复", + "助手想使用 {0}。打开 Strata 以批准或拒绝。", + "一个工具", + "最小化到托盘", + "关闭窗口后,Strata 会继续在托盘(时钟旁边)运行。要停止它,请在托盘菜单中选择“退出”。下次启动 Strata 时生效。", + "应用端口", + "Strata 窗口和本地地址使用的端口。留空则由 Strata 自行选择(空闲时为 47831)。下次启动 Strata 时生效。", + "端口(留空 = 自动)", + "当前使用端口 {0}。", + "Strata 无法使用它的端口", + "端口 {0} 已被其他程序占用,因此 Strata 改用端口 {1} 启动。在端口 {0} 上保存的聊天和设置在 Strata 能再次使用该端口之前不会显示。请关闭其他程序并重新启动 Strata。", + "请选择 1024 到 65535 之间的端口,或留空。", + "让 Strata 中的所有文字、按钮和菜单变大或变小。", + "能耗和温度读数", + "每千瓦时,币种 {0}", + "每千瓦时", + "更改货币", + "自动({0})", + "货币", + "不足 {0}", +], +"ja": [ + "起動後の消費電力量", + "起動後の電気代", + "GPU ファン", + "GPU クロック", + "CPU 温度", + "SSD 温度", + "電気料金", + "1キロワット時あたりの料金です。モニターに、Strata の起動後にグラフィックスカードが使った電気代が表示されます。空欄のままなら電気代は表示されません。", + "1 kWh あたりの料金", + "作業完了時の音", + "回答や時間のかかった作業が終わったとき、または Strata がバックグラウンドにあるときに、短い音を鳴らします。", + "音を鳴らす", + "Strata の返答が必要なときに通知する", + "手動モードで、アシスタントが承認を待っていて Strata がバックグラウンドにあるときに、デスクトップ通知を表示します。", + "Strata があなたの返答を待っています", + "アシスタントが {0} を使おうとしています。Strata を開いて承認または拒否してください。", + "ツール", + "トレイに最小化", + "ウィンドウを閉じても、Strata は時計の横のトレイで動き続けます。止めるには、トレイのメニューで「終了」を選びます。次に Strata を起動したときから有効になります。", + "アプリのポート", + "Strata のウィンドウとローカルアドレスが使うポートです。空欄なら Strata が選びます(空いていれば 47831)。次に Strata を起動したときから有効になります。", + "ポート(空欄 = 自動)", + "現在のポートは {0} です。", + "Strata は指定のポートを使えませんでした", + "ポート {0} は別のプログラムが使っているため、Strata はポート {1} で起動しました。ポート {0} に保存されたチャットと設定は、Strata が再びそのポートを使えるようになるまで表示されません。他のプログラムを閉じて Strata を再起動してください。", + "1024 から 65535 の間のポートを選ぶか、空欄にしてください。", + "Strata のすべての文字、ボタン、メニューを大きくしたり小さくしたりします。", + "消費電力量と温度の値", + "1 kWh あたり、通貨は {0}", + "1 kWh あたり", + "通貨を変更", + "自動({0})", + "通貨", + "{0} 未満", +], +"de": [ + "Energie seit dem Start", + "Kosten seit dem Start", + "GPU-Lüfter", + "GPU-Takt", + "CPU-Temperatur", + "SSD-Temperatur", + "Strompreis", + "Preis einer Kilowattstunde. Der Monitor zeigt dann, was Ihre Grafikkarte seit dem Start von Strata gekostet hat. Leer lassen, um die Kosten auszublenden.", + "Preis pro kWh", + "Ton, wenn Arbeit fertig ist", + "Spielt einen kurzen Ton, wenn eine Antwort oder Aufgabe, die länger gedauert hat, fertig ist oder wenn Strata im Hintergrund läuft.", + "Ton abspielen", + "Benachrichtigen, wenn Strata eine Antwort braucht", + "Zeigt im manuellen Modus eine Desktop-Benachrichtigung, wenn der Assistent auf Ihre Freigabe wartet und Strata im Hintergrund läuft.", + "Strata braucht Ihre Antwort", + "Der Assistent möchte {0} verwenden. Öffnen Sie Strata, um zu erlauben oder abzulehnen.", + "ein Werkzeug", + "In den Infobereich minimieren", + "Beim Schließen des Fensters läuft Strata im Infobereich neben der Uhr weiter. Wählen Sie im Menü des Symbols „Beenden“, um es zu stoppen. Gilt ab dem nächsten Start von Strata.", + "App-Port", + "Der Port, den das Fenster und die lokale Adresse von Strata verwenden. Leer lassen, damit Strata ihn wählt (47831, wenn frei). Gilt ab dem nächsten Start von Strata.", + "Port (leer = automatisch)", + "Aktuell wird Port {0} verwendet.", + "Strata konnte seinen Port nicht verwenden", + "Port {0} wird von einem anderen Programm verwendet, daher wurde Strata auf Port {1} gestartet. Unter Port {0} gespeicherte Chats und Einstellungen werden nicht angezeigt, bis Strata ihn wieder verwenden kann. Schließen Sie das andere Programm und starten Sie Strata neu.", + "Wählen Sie einen Port zwischen 1024 und 65535 oder lassen Sie das Feld leer.", + "Macht alle Texte, Schaltflächen und Menüs in Strata größer oder kleiner.", + "Energie- und Temperaturwerte", + "pro kWh, in {0}", + "pro kWh", + "Währung ändern", + "Automatisch ({0})", + "Währung", + "weniger als {0}", +], +"es": [ + "Energía desde el inicio", + "Coste desde el inicio", + "Ventilador de la GPU", + "Reloj de la GPU", + "Temperatura de la CPU", + "Temperatura del SSD", + "Precio de la electricidad", + "Precio de un kilovatio hora. El Monitor mostrará entonces lo que ha costado tu tarjeta gráfica desde que se inició Strata. Déjalo vacío para ocultar el coste.", + "Precio por kWh", + "Sonido al terminar el trabajo", + "Reproduce un sonido breve cuando termina una respuesta o tarea que tardó un rato, o cuando Strata está en segundo plano.", + "Reproducir sonido", + "Avisarme cuando Strata necesite una respuesta", + "En el modo manual, muestra una notificación de escritorio cuando el asistente espera tu aprobación y Strata está en segundo plano.", + "Strata necesita tu respuesta", + "El asistente quiere usar {0}. Abre Strata para aprobar o denegar.", + "una herramienta", + "Minimizar a la bandeja", + "Al cerrar la ventana, Strata sigue funcionando en la bandeja, junto al reloj. Elige Salir en el menú de la bandeja para detenerlo. Se aplica la próxima vez que se inicie Strata.", + "Puerto de la aplicación", + "El puerto que usan la ventana y la dirección local de Strata. Déjalo vacío para que Strata elija (47831 si está libre). Se aplica la próxima vez que se inicie Strata.", + "Puerto (vacío = automático)", + "Ahora se usa el puerto {0}.", + "Strata no pudo usar su puerto", + "El puerto {0} lo usa otro programa, así que Strata se inició en el puerto {1}. Los chats y ajustes guardados en el puerto {0} no se muestran hasta que Strata pueda volver a usarlo. Cierra el otro programa y reinicia Strata.", + "Elige un puerto entre 1024 y 65535, o déjalo vacío.", + "Hace más grandes o más pequeños todos los textos, botones y menús de Strata.", + "Lecturas de energía y temperatura", + "por kWh, en {0}", + "por kWh", + "Cambiar moneda", + "Automática ({0})", + "Moneda", + "menos de {0}", +], +"ru": [ + "Энергия с запуска", + "Стоимость с запуска", + "Вентилятор GPU", + "Частота GPU", + "Температура CPU", + "Температура SSD", + "Цена электричества", + "Цена одного киловатт-часа. Тогда монитор покажет, во сколько видеокарта обошлась с запуска Strata. Оставьте поле пустым, чтобы скрыть стоимость.", + "Цена за кВт·ч", + "Звук по окончании работы", + "Проигрывает короткий звук, когда закончился долгий ответ или задача, а также когда Strata работает в фоне.", + "Проиграть звук", + "Уведомлять, когда Strata нужен ответ", + "В ручном режиме показывает уведомление на рабочем столе, когда помощник ждёт вашего подтверждения, а Strata работает в фоне.", + "Strata нужен ваш ответ", + "Помощник хочет использовать {0}. Откройте Strata, чтобы разрешить или отклонить.", + "инструмент", + "Сворачивать в трей", + "При закрытии окна Strata продолжает работать в трее рядом с часами. Чтобы остановить её, выберите «Выход» в меню значка. Действует со следующего запуска Strata.", + "Порт приложения", + "Порт, который используют окно и локальный адрес Strata. Оставьте поле пустым, чтобы Strata выбрала сама (47831, если свободен). Действует со следующего запуска Strata.", + "Порт (пусто = автоматически)", + "Сейчас используется порт {0}.", + "Strata не смогла использовать свой порт", + "Порт {0} занят другой программой, поэтому Strata запустилась на порту {1}. Чаты и настройки, сохранённые на порту {0}, не показываются, пока Strata не сможет снова его использовать. Закройте другую программу и перезапустите Strata.", + "Выберите порт от 1024 до 65535 или оставьте поле пустым.", + "Увеличивает или уменьшает весь текст, кнопки и меню в Strata.", + "Показания энергии и температуры", + "за кВт·ч, в валюте {0}", + "за кВт·ч", + "Сменить валюту", + "Автоматически ({0})", + "Валюта", + "меньше {0}", +], +"pt": [ + "Energia desde o início", + "Custo desde o início", + "Ventoinha da GPU", + "Clock da GPU", + "Temperatura da CPU", + "Temperatura do SSD", + "Preço da eletricidade", + "Preço de um quilowatt-hora. O Monitor passa a mostrar quanto a sua placa de vídeo custou desde que o Strata iniciou. Deixe vazio para ocultar o custo.", + "Preço por kWh", + "Som ao terminar o trabalho", + "Toca um som curto quando uma resposta ou tarefa que demorou termina, ou quando o Strata está em segundo plano.", + "Tocar som", + "Avisar quando o Strata precisar de uma resposta", + "No modo manual, mostra uma notificação na área de trabalho quando o assistente espera sua aprovação e o Strata está em segundo plano.", + "O Strata precisa da sua resposta", + "O assistente quer usar {0}. Abra o Strata para aprovar ou negar.", + "uma ferramenta", + "Minimizar para a bandeja", + "Ao fechar a janela, o Strata continua em execução na bandeja, ao lado do relógio. Escolha Sair no menu da bandeja para encerrá-lo. Vale a partir da próxima vez que o Strata iniciar.", + "Porta do aplicativo", + "A porta usada pela janela e pelo endereço local do Strata. Deixe vazio para o Strata escolher (47831 quando estiver livre). Vale a partir da próxima vez que o Strata iniciar.", + "Porta (vazio = automático)", + "Usando a porta {0} agora.", + "O Strata não conseguiu usar a sua porta", + "A porta {0} está em uso por outro programa, então o Strata iniciou na porta {1}. Os chats e as configurações salvos na porta {0} não aparecem até o Strata poder usá-la de novo. Feche o outro programa e reinicie o Strata.", + "Escolha uma porta entre 1024 e 65535, ou deixe vazio.", + "Deixa todos os textos, botões e menus do Strata maiores ou menores.", + "Leituras de energia e temperatura", + "por kWh, em {0}", + "por kWh", + "Alterar moeda", + "Automática ({0})", + "Moeda", + "menos de {0}", +], +"ko": [ + "시작 이후 에너지", + "시작 이후 비용", + "GPU 팬", + "GPU 클럭", + "CPU 온도", + "SSD 온도", + "전기 요금", + "1킬로와트시의 요금입니다. 모니터에 Strata를 시작한 뒤 그래픽 카드에 든 전기 요금이 표시됩니다. 비워 두면 비용을 표시하지 않습니다.", + "kWh당 요금", + "작업이 끝났을 때 소리", + "답변이나 오래 걸린 작업이 끝났을 때, 또는 Strata가 백그라운드에 있을 때 짧은 소리를 재생합니다.", + "소리 재생", + "Strata가 답을 필요로 할 때 알림", + "수동 모드에서 어시스턴트가 승인을 기다리고 Strata가 백그라운드에 있을 때 데스크톱 알림을 표시합니다.", + "Strata가 답을 기다리고 있습니다", + "어시스턴트가 {0}을(를) 사용하려고 합니다. Strata를 열어 승인하거나 거부하세요.", + "도구", + "트레이로 최소화", + "창을 닫아도 Strata는 시계 옆 트레이에서 계속 실행됩니다. 끝내려면 트레이 메뉴에서 '종료'를 선택하세요. 다음에 Strata를 시작할 때부터 적용됩니다.", + "앱 포트", + "Strata의 창과 로컬 주소가 사용하는 포트입니다. 비워 두면 Strata가 고릅니다(비어 있으면 47831). 다음에 Strata를 시작할 때부터 적용됩니다.", + "포트(비움 = 자동)", + "지금은 포트 {0}을(를) 사용 중입니다.", + "Strata가 지정한 포트를 사용할 수 없었습니다", + "포트 {0}을(를) 다른 프로그램이 사용 중이어서 Strata는 포트 {1}에서 시작했습니다. 포트 {0}에 저장된 채팅과 설정은 Strata가 다시 그 포트를 쓸 수 있을 때까지 표시되지 않습니다. 다른 프로그램을 닫고 Strata를 다시 시작하세요.", + "1024에서 65535 사이의 포트를 고르거나 비워 두세요.", + "Strata의 모든 글자, 버튼, 메뉴를 더 크게 또는 더 작게 만듭니다.", + "에너지 및 온도 측정값", + "kWh당, 통화 {0}", + "kWh당", + "통화 변경", + "자동({0})", + "통화", + "{0} 미만", +], +"fr": [ + "Énergie depuis le démarrage", + "Coût depuis le démarrage", + "Ventilateur du GPU", + "Fréquence du GPU", + "Température du CPU", + "Température du SSD", + "Prix de l'électricité", + "Prix d'un kilowattheure. Le Moniteur affiche alors ce que votre carte graphique a coûté depuis le démarrage de Strata. Laissez vide pour masquer le coût.", + "Prix par kWh", + "Son à la fin du travail", + "Joue un court son quand une réponse ou une tâche qui a pris du temps est terminée, ou quand Strata est en arrière-plan.", + "Jouer le son", + "Me prévenir quand Strata a besoin d'une réponse", + "En mode manuel, affiche une notification sur le bureau quand l'assistant attend votre accord et que Strata est en arrière-plan.", + "Strata a besoin de votre réponse", + "L'assistant veut utiliser {0}. Ouvrez Strata pour accepter ou refuser.", + "un outil", + "Réduire dans la zone de notification", + "Fermer la fenêtre garde Strata actif dans la zone de notification, près de l'horloge. Choisissez Quitter dans le menu de l'icône pour l'arrêter. S'applique au prochain démarrage de Strata.", + "Port de l'application", + "Le port que la fenêtre et l'adresse locale de Strata utilisent. Laissez vide pour que Strata choisisse (47831 s'il est libre). S'applique au prochain démarrage de Strata.", + "Port (vide = automatique)", + "Port {0} utilisé en ce moment.", + "Strata n'a pas pu utiliser son port", + "Le port {0} est utilisé par un autre programme, donc Strata a démarré sur le port {1}. Les conversations et réglages enregistrés sur le port {0} ne s'affichent pas tant que Strata ne peut pas le réutiliser. Fermez l'autre programme et relancez Strata.", + "Choisissez un port entre 1024 et 65535, ou laissez vide.", + "Agrandit ou réduit tous les textes, boutons et menus de Strata.", + "Relevés d'énergie et de température", + "par kWh, en {0}", + "par kWh", + "Changer de devise", + "Automatique ({0})", + "Devise", + "moins de {0}", +], +} + +here = Path(__file__).resolve().parent.parent / "src" / "locales" + + +NBSP = "\u00a0" + + +def french(text): + """The same French spacing as scripts/fr_sync.py: a typographic apostrophe, a no-break space before : ; ? ! % and inside the guillemets.""" + text = re.sub(r"(?<=[A-Za-z\u00c0-\u017f])'(?=[A-Za-z\u00c0-\u017f{])", "\u2019", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + return text + + +def write(lang, values): + assert len(values) == len(EN), (lang, len(values), len(EN)) + for source, text in zip(EN, values): + assert sorted(re.findall(r"\{\d+\}", source)) == sorted(re.findall(r"\{\d+\}", text)), (lang, source, text) + if lang == "fr": + values = [french(v) for v in values] + data = {f"gh{i + 1:02d}": text for i, text in enumerate(values)} + (here / f"gh-{lang}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + + +write("en", EN) +for lang, values in T.items(): + write(lang, values) +print("written", len(EN), "strings in", len(T) + 1, "languages") diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs index cee55a4b..80a68d8c 100644 --- a/apps/host/server/device-probes.mjs +++ b/apps/host/server/device-probes.mjs @@ -40,13 +40,15 @@ export function parseNvidiaDevices(raw) { return [{id:uuid,index:Number(index),sensorIndex:Number(index),busId:bus?.toLowerCase(),vendor:'nvidia',name,vramGb:round((number(memory)??0)/1024,1),unified:false,backend:'cuda',driver}]; }); } +/** A percentage reading; "[N/A]" and out-of-range values are no reading. */ +const percentOf = v => { const n=number(v); return n!==null&&n>=0&&n<=100?n:null; }; export function parseNvidiaReadings(raw) { return raw.split('\n').flatMap(line=>{ - const [id,temp,load,memory,power,limit,gen,maxGen,width]=line.split(',').map(s=>s.trim()); + const [id,temp,load,memory,power,limit,gen,maxGen,width,fan,clock]=line.split(',').map(s=>s.trim()); if (!id?.startsWith('GPU-')) return []; const t=number(temp),u=number(load),m=number(memory); const positive = v => { const n=number(v); return n!==null&&n>=0?n:null; }; - return [{id,temperatureC:t!==null&&t>=0&&t<=150?t:null,utilizationPct:u!==null&&u>=0&&u<=100?u:null,memoryUsedGb:m!==null&&m>=0?round(m/1024,2):null,powerW:positive(power),powerLimitW:positive(limit),pcieGen:positive(gen),pcieGenMax:positive(maxGen),pcieWidth:positive(width),pcieRxMbs:null}]; + return [{id,temperatureC:t!==null&&t>=0&&t<=150?t:null,utilizationPct:u!==null&&u>=0&&u<=100?u:null,memoryUsedGb:m!==null&&m>=0?round(m/1024,2):null,powerW:positive(power),powerLimitW:positive(limit),pcieGen:positive(gen),pcieGenMax:positive(maxGen),pcieWidth:positive(width),pcieRxMbs:null,fanPct:percentOf(fan),clockMhz:positive(clock)}]; }); } export function parsePcieThroughput(raw) { @@ -77,7 +79,7 @@ export async function detectDrmGpus() { export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, run = probe } = {}) { const now=new Date().toISOString(); const hasNvidia=gpus.some(g=>g.vendor==='nvidia'); - let raw=hasNvidia?await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current','--format=csv,noheader,nounits'],2000):''; + let raw=hasNvidia?await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,fan.speed,clocks.current.graphics','--format=csv,noheader,nounits'],2000):''; // Older drivers can reject a field; retain their basic sensors in that case. if(hasNvidia&&!raw)raw=await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used','--format=csv,noheader,nounits'],2000); const nvidia=new Map(parseNvidiaReadings(raw).map(r=>[r.id,r])); @@ -90,11 +92,13 @@ export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, ru if(counters)reading={...reading,utilizationPct:counters.utilizationPct,memoryUsedGb:round(counters.memoryUsedGb,2)}; } if(gpu.sensorPath&&!nvidia.has(gpu.id)) { - let temperature=null,power=null,powerLimit=null; + let temperature=null,power=null,powerLimit=null,fanPwm=null,clockHz=null; for(const hwmon of await list(`${gpu.sensorPath}/hwmon`)) { const folder=`${gpu.sensorPath}/hwmon/${hwmon}`,inputs=(await list(folder)).filter(n=>/^temp\d+_input$/.test(n)); power ??= number(await read(`${folder}/power1_average`)) ?? number(await read(`${folder}/power1_input`)); powerLimit ??= number(await read(`${folder}/power1_cap`)); + fanPwm ??= number(await read(`${folder}/pwm1`)); // 0-255, the fan's duty as the amdgpu driver reports it + clockHz ??= number(await read(`${folder}/freq1_input`)); // the graphics clock in Hz for(const input of inputs) { const label=await read(`${folder}/${input.replace('_input','_label')}`); if(label&&!/edge|gpu/i.test(label))continue; @@ -106,7 +110,7 @@ export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, ru const utilization=number(await read(`${gpu.sensorPath}/gpu_busy_percent`)),bytes=number(await read(`${gpu.sensorPath}/mem_info_vram_used`)); const gen=path=>read(path).then(raw=>({2.5:1,5:2,8:3,16:4,32:5,64:6}[Number.parseFloat(raw)]??null)); const [pcieGen,pcieGenMax,width]=await Promise.all([gen(`${gpu.sensorPath}/current_link_speed`),gen(`${gpu.sensorPath}/max_link_speed`),read(`${gpu.sensorPath}/current_link_width`)]); - reading={...reading,temperatureC:temperature,utilizationPct:utilization!==null&&utilization>=0&&utilization<=100?utilization:null,memoryUsedGb:bytes!==null&&bytes>=0?round(bytes/1024**3,2):null,powerW:power!==null&&power>=0?power/1e6:null,powerLimitW:powerLimit!==null&&powerLimit>=0?powerLimit/1e6:null,pcieGen,pcieGenMax,pcieWidth:number(width)}; + reading={...reading,fanPct:fanPwm!==null&&fanPwm>=0&&fanPwm<=255?Math.round(fanPwm/255*100):null,clockMhz:clockHz!==null&&clockHz>0?Math.round(clockHz/1e6):null,temperatureC:temperature,utilizationPct:utilization!==null&&utilization>=0&&utilization<=100?utilization:null,memoryUsedGb:bytes!==null&&bytes>=0?round(bytes/1024**3,2):null,powerW:power!==null&&power>=0?power/1e6:null,powerLimitW:powerLimit!==null&&powerLimit>=0?powerLimit/1e6:null,pcieGen,pcieGenMax,pcieWidth:number(width)}; } return {...reading,sampledAt:now,source:Object.entries(reading).some(([key,value])=>key!=='id'&&typeof value==='number')?'sensor':'none'}; })); diff --git a/apps/host/server/energy-meter.mjs b/apps/host/server/energy-meter.mjs new file mode 100644 index 00000000..9bed3eef --- /dev/null +++ b/apps/host/server/energy-meter.mjs @@ -0,0 +1,14 @@ +/** + * GPU energy since the host started, in Wh (#3628): the power reading held for the time since the last tick, added up. + * A long gap (the PC slept, the host was paused) counts for at most 5 s, so a sleep never adds a made-up hour of use. + */ +const meter = { wh: 0, at: 0 }; + +export function addEnergy(powerW, at) { + const dt = meter.at ? Math.min((at - meter.at) / 1000, 5) : 0; + meter.at = at; + if (typeof powerW === 'number' && Number.isFinite(powerW) && powerW >= 0 && dt > 0) meter.wh += powerW * dt / 3600; + return meter.wh; +} + +export const energyWh = () => meter.wh; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index d28418c8..e059a657 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -71,6 +71,8 @@ import { createRuntimeModels } from './runtime-models.mjs'; import { createNativeControl } from './native-control.mjs'; import { nativeUnloadPlan } from './storage-check.mjs'; import { installBundledEngine, cleanupAfterInstall } from './bundled-engine.mjs'; +import { systemLocale } from './region.mjs'; +import { createShellNotifier, DEFAULT_PORT, parsePortNotice, readShellPrefs, writeShellPrefs } from './shell-prefs.mjs'; import { findControl, createControl, componentsDirectory } from './control-runtime.mjs'; import { forbidden as acquisitionForbidden } from './acquisition.mjs'; import { randomBytes, timingSafeEqual } from 'node:crypto'; @@ -127,6 +129,19 @@ const appUi = createAppUi({ shutdown: () => shutdown() }); /* The app's version has one source: the desktop shell passes it (STRATA_APP_VERSION, from apps/desktop/src-tauri/Cargo.toml). Outside the app it is read from the same file in a checkout, else 'dev'. */ function appVersion() { return appVersionFrom({ env: process.env, here: HERE }); } const appUpdater = appUi.updater; +const shellNotifier = createShellNotifier(); +/** What the page needs for the desktop settings: whether this is the desktop app, the port in use, the saved choices and a busy-port notice. */ +function shellState() { + const saved = readShellPrefs(); + const desktop = !!shellNotifier; + return { + desktop, + tray: desktop && process.platform !== 'linux', + port: PORT, defaultPort: DEFAULT_PORT, + pinnedPort: saved.port || null, minimizeToTray: saved.tray, + portNotice: parsePortNotice(process.env.STRATA_PORT_NOTICE), + }; +} /* The engine that ships inside the installer is put in the components folder when this PC has none (or an older one); no network, hashes checked. The model list waits for it. */ const bundledEngine = control && !process.env.STRATA_NO_BUNDLED_ENGINE ? installBundledEngine({ bundleDir: process.env.STRATA_ENGINE_BUNDLE_DIR || resolve(HERE, '..', '..', 'engine-bundle'), components: componentsDirectory(), log: line => console.log(line) }) @@ -1932,6 +1947,19 @@ async function api(req, res, path, method, url) { try { return json(res, 200, await agent.approve({ chatId: b.sessionId, callId: b.toolId, decision: b.decision })); } catch (e) { return error(res, e.code === 'approval-gone' ? 409 : 400, e.message); } } + /* The desktop shell's own choices (#3402, #3477): the port it asks for, the tray, and a desktop notification through the shell. */ + if (path === '/api/locale' && method === 'GET') return json(res, 200, systemLocale()); + if (path === '/api/shell' && method === 'GET') return json(res, 200, shellState()); + if (path === '/api/shell/prefs' && method === 'POST') { + const b = await readBody(req); + try { writeShellPrefs(b); } catch (e) { return error(res, 400, e.message); } + return json(res, 200, shellState()); + } + if (path === '/api/shell/notify' && method === 'POST') { + const b = await readBody(req); + if (!shellNotifier || typeof b.title !== 'string') return json(res, 200, { shown: false }); + try { return json(res, 200, await shellNotifier.notify({ title: b.title, body: String(b.body ?? '') })); } catch { return json(res, 200, { shown: false }); } + } /* The person changed the chat's mode while a turn runs: it applies to the next tool call, goal and helpers included. */ if (path === '/api/chat/mode' && method === 'POST') { const b = await readBody(req); diff --git a/apps/host/server/monitor.mjs b/apps/host/server/monitor.mjs index e07e291f..c861d9b9 100644 --- a/apps/host/server/monitor.mjs +++ b/apps/host/server/monitor.mjs @@ -4,6 +4,8 @@ import { detect, cachedHardware } from './hardware.mjs'; import { readGpuTelemetry, gpuMemoryTotals } from './device-probes.mjs'; import { createSystemSampler } from './system-telemetry.mjs'; import { sensorPace, WATCH_MS } from './sensor-pace.mjs'; +import { readTemperatures } from './temperature-telemetry.mjs'; +import { addEnergy, energyWh } from './energy-meter.mjs'; import { state as servingState } from './serving.mjs'; import { originalDashboard } from './monitor-dashboard.mjs'; import { get as getStore } from './store.mjs'; @@ -68,6 +70,8 @@ export function watch() { } export function setLiveProbe(probe) { liveProbe = typeof probe === 'function' ? probe : () => false; } let systemReading=null; +/* CPU and SSD temperatures (null where this PC cannot give one) and the GPU energy used since the host started (#3628). */ +let temperatures={cpuTempC:null,ssdTempC:null}; const sampleSystem=createSystemSampler(); const finite = value => typeof value==='number'&&Number.isFinite(value); function aggregate(readings,key,mode='sum') { @@ -80,7 +84,7 @@ function hardwareSnapshot() { const demo=process.env.STRATA_REAL_ENGINE!=='1',hw=state.hardware; const devices=cachedHardware()?.gpus??hwCache?.gpus??[]; const memoryPools=Math.max(1,devices.filter(g=>!g.unified).length+Number(devices.some(g=>g.unified))); - const readings=demo?devices.map((gpu,i)=>({id:gpu.id??`${gpu.vendor}:${gpu.index}`,source:'demo',sampledAt:new Date().toISOString(),utilizationPct:Math.round(clamp(hw.gpuLoad+i*2,0,100)),temperatureC:Math.round(hw.gpuTempC+i),memoryUsedGb:round(Math.min(gpu.vramGb,hw.vramUsedGb/memoryPools),2),powerW:gpu.unified?null:round(35+hw.gpuLoad*2,0),powerLimitW:gpu.unified?null:300,pcieGen:gpu.unified?null:4,pcieGenMax:gpu.unified?null:4,pcieWidth:gpu.unified?null:16,pcieRxMbs:gpu.unified?null:round(hw.gpuLoad*1.2,1)})):hw.gpus.map(g=>({...g})); + const readings=demo?devices.map((gpu,i)=>({id:gpu.id??`${gpu.vendor}:${gpu.index}`,source:'demo',sampledAt:new Date().toISOString(),utilizationPct:Math.round(clamp(hw.gpuLoad+i*2,0,100)),temperatureC:Math.round(hw.gpuTempC+i),memoryUsedGb:round(Math.min(gpu.vramGb,hw.vramUsedGb/memoryPools),2),powerW:gpu.unified?null:round(35+hw.gpuLoad*2,0),powerLimitW:gpu.unified?null:300,pcieGen:gpu.unified?null:4,pcieGenMax:gpu.unified?null:4,pcieWidth:gpu.unified?null:16,pcieRxMbs:gpu.unified?null:round(hw.gpuLoad*1.2,1),fanPct:gpu.unified?null:Math.round(30+hw.gpuLoad*0.5),clockMhz:gpu.unified?null:Math.round(1400+hw.gpuLoad*14)})):hw.gpus.map(g=>({...g})); const memory = gpuMemoryTotals(devices,readings); return { gpus:readings,cpus:systemReading?.cpus??[],cpuLoad:systemReading?.cpuLoad??null, @@ -90,7 +94,9 @@ function hardwareSnapshot() { ramUsedGb:systemReading?.ramUsedGb??null,ramTotalGb:systemReading?.ramTotalGb??hw.ramTotalGb, gpuTempC:aggregate(readings,'temperatureC','max'),tempLimitC:hw.tempLimitC, powerW:aggregate(readings,'powerW'),powerLimitW:aggregate(readings,'powerLimitW'), - pcieRxMbs:aggregate(readings,'pcieRxMbs'),diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null, + pcieRxMbs:aggregate(readings,'pcieRxMbs'), + cpuTempC:demo?54:temperatures.cpuTempC,ssdTempC:demo?41:temperatures.ssdTempC,energyWh:round(energyWh(),3), + diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null, }; } @@ -121,11 +127,12 @@ function tick() { if(!sensorsPending&&Date.now()-sensorsAt>=pace.intervalMs){ sensorsPending=true;sensorsAt=Date.now(); const hardware=cachedHardware()??hwCache; - void Promise.all([readGpuTelemetry(hardware?.gpus??[],{transfer:pace.transfer}),sampleSystem(hardware?.processors??[])]) - .then(([readings,system])=>{state.hardware.gpus=readings;systemReading=system;}) + void Promise.all([readGpuTelemetry(hardware?.gpus??[],{transfer:pace.transfer}),sampleSystem(hardware?.processors??[]),(process.env.STRATA_REAL_ENGINE==='1'?readTemperatures():Promise.resolve(temperatures)).catch(()=>({cpuTempC:null,ssdTempC:null}))]) + .then(([readings,system,temps])=>{state.hardware.gpus=readings;systemReading=system;temperatures=temps;}) .catch(()=>{state.hardware.gpus=[];systemReading=null;}) .finally(()=>{sensorsPending=false;}); } + addEnergy(hardwareSnapshot().powerW,Date.now()); const hw = state.hardware; const busy = state.phase === 'generating' || state.phase === 'reading' || state.phase === 'thinking'; diff --git a/apps/host/server/region.mjs b/apps/host/server/region.mjs new file mode 100644 index 00000000..312b122c --- /dev/null +++ b/apps/host/server/region.mjs @@ -0,0 +1,66 @@ +/** + * The computer's regional format, for the Monitor's cost line (#3628): which region and, where the system names it, which currency the + * person uses. Read once, without PowerShell: + * Windows the regional format (Settings > Time & language > Region > Regional format) from the registry: LocaleName ("en-US"); when it + * names no region, the country or region setting (Geo\Name). + * macOS `defaults read -g AppleLocale` ("en_US", or "de_DE@currency=CHF" when the person set another currency). + * Linux LC_ALL, LC_MONETARY or LANG ("de_DE.UTF-8"), and the locale's own currency when `locale -k int_curr_symbol` answers. + * Nothing here is a guess: no region means no answer, and the page then falls back to its own language list. + */ +import { execFileSync } from 'node:child_process'; + +const NONE = Object.freeze({ locale: null, region: null, currency: null, source: null }); + +/** "en_US.UTF-8" / "de_DE@euro" / "zh-Hans-CN" -> { locale: "en-US", region: "US" } (null parts when the tag has none). */ +export function parseLocaleTag(text) { + const tag = String(text ?? '').trim().replace(/[.@].*$/, '').replace(/_/g, '-'); + if (!tag || /^(c|posix)$/i.test(tag)) return { locale: null, region: null }; + const parts = tag.split('-'); + const region = parts.slice(1).find(p => /^[A-Za-z]{2}$/.test(p)) ?? null; + const language = /^[A-Za-z]{2,3}$/.test(parts[0]) ? parts[0].toLowerCase() : null; + if (!language) return { locale: null, region: null }; + return { locale: region ? `${language}-${region.toUpperCase()}` : language, region: region ? region.toUpperCase() : null }; +} + +export function parseRegValue(out, name) { + const m = new RegExp(`^\\s*${name}\\s+REG_SZ\\s+(.*?)\\s*$`, 'mi').exec(String(out ?? '')); + return m ? m[1] : null; +} + +const currencyCode = value => (/^[A-Z]{3}$/.test(String(value ?? '').trim().toUpperCase()) ? String(value).trim().toUpperCase() : null); + +export function detectRegion({ platform = process.platform, env = process.env, run = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', timeout: 4000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }) } = {}) { + try { + if (platform === 'win32') { + const intl = 'HKCU\\Control Panel\\International'; + const named = parseLocaleTag(parseRegValue(run('reg', ['query', intl, '/v', 'LocaleName']), 'LocaleName')); + if (named.region) return { ...named, currency: null, source: 'windows' }; + let geo = null; + try { geo = parseRegValue(run('reg', ['query', `${intl}\\Geo`, '/v', 'Name']), 'Name'); } catch { /* no country setting */ } + const region = /^[A-Za-z]{2}$/.test(geo ?? '') ? geo.toUpperCase() : null; + return region ? { locale: named.locale ? `${named.locale}-${region}` : null, region, currency: null, source: 'windows' } : { ...NONE }; + } + if (platform === 'darwin') { + const raw = String(run('defaults', ['read', '-g', 'AppleLocale'])).trim(); + const named = parseLocaleTag(raw); + const currency = currencyCode(/@currency=([A-Za-z]{3})/.exec(raw)?.[1]); + return named.region || currency ? { ...named, currency, source: 'macos' } : { ...NONE }; + } + const named = parseLocaleTag(env.LC_ALL || env.LC_MONETARY || env.LANG); + let currency = null; + try { currency = currencyCode(/int_curr_symbol="?([A-Za-z]{3})/.exec(run('locale', ['-k', 'int_curr_symbol']))?.[1]); } catch { /* no locale command */ } + return named.region || currency ? { ...named, currency, source: 'linux' } : { ...NONE }; + } catch { + return { ...NONE }; + } +} + +let cached = null; +/** The answer is cached: the regional format does not change while the host runs. */ +export function systemLocale(options) { + if (options) return detectRegion(options); + // A test or a demo can name the regional format (the screenshots of the Monitor); a packaged app never reads it. + if (process.env.STRATA_TEST_LOCALE && process.env.STRATA_PACKAGED !== '1') { const named = parseLocaleTag(process.env.STRATA_TEST_LOCALE); return { ...named, currency: null, source: 'test' }; } + cached ??= detectRegion(); + return cached; +} diff --git a/apps/host/server/shell-prefs.mjs b/apps/host/server/shell-prefs.mjs new file mode 100644 index 00000000..a81237f8 --- /dev/null +++ b/apps/host/server/shell-prefs.mjs @@ -0,0 +1,77 @@ +/** + * The desktop shell's own choices, kept in <Strata data folder>/shell-prefs.json (#3402, #3477): the shell reads the file when it starts + * (the port it asks for, whether closing the window keeps Strata in the tray, the language of the tray menu), before any page exists. + * The page changes them through the host (POST /api/shell/prefs); a change of the port or the tray applies the next time Strata starts. + * + * { "port": 0 | 1024..65535, "tray": false, "language": "en" } + * + * Port 0 is the default: the shell asks for 47831 and takes a free port when that one is busy. + */ +import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { componentsDirectory } from './control-runtime.mjs'; + +export const DEFAULT_PORT = 47831; +export const LANGUAGES = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +export const DEFAULTS = Object.freeze({ port: 0, tray: false, language: 'en' }); + +export const validPort = value => Number.isInteger(value) && value >= 1024 && value <= 65535; + +export function shellPrefsFile({ env = process.env } = {}) { + return join(dirname(componentsDirectory({ env })), 'shell-prefs.json'); +} + +/** The file's content with every field checked; anything missing or wrong is the default. */ +export function cleanPrefs(raw) { + const value = raw && typeof raw === 'object' ? raw : {}; + return { + port: validPort(value.port) ? value.port : 0, + tray: value.tray === true, + language: LANGUAGES.includes(value.language) ? value.language : 'en', + }; +} + +export function readShellPrefs(file = shellPrefsFile()) { + try { return cleanPrefs(JSON.parse(readFileSync(file, 'utf8').replace(/^/, ''))); } catch { return { ...DEFAULTS }; } +} + +/** Merge a change into the file. Throws a plain sentence for a port that cannot be used. */ +export function writeShellPrefs(patch, file = shellPrefsFile()) { + const next = readShellPrefs(file); + if (patch && 'port' in patch) { + const wanted = patch.port === null || patch.port === '' || patch.port === 0 ? 0 : Number(patch.port); + if (wanted !== 0 && !validPort(wanted)) throw new Error('Choose a port between 1024 and 65535, or leave it empty to let Strata choose.'); + next.port = wanted; + } + if (patch && 'tray' in patch) next.tray = patch.tray === true; + if (patch && 'language' in patch && LANGUAGES.includes(patch.language)) next.language = patch.language; + mkdirSync(dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n'); + renameSync(temporary, file); + return next; +} + +/** + * What the shell tells the host about this start: STRATA_PORT_NOTICE is "busy:<wanted>:<used>" when the port it wanted was taken + * (set by the shell, never by the person). The page turns it into a sentence in the person's language. + */ +export function parsePortNotice(value) { + const m = /^busy:(\d{1,5}):(\d{1,5})$/.exec(String(value ?? '')); + return m ? { wanted: Number(m[1]), used: Number(m[2]) } : null; +} + +/** The notification route of the shell's bridge (loopback, token). Null outside the desktop app. */ +export function createShellNotifier({ env = process.env, fetcher = fetch } = {}) { + const base = env.STRATA_SHELL_BRIDGE, token = env.STRATA_SHELL_TOKEN; + if (!base || !token || !/^http:\/\/127\.0\.0\.1:\d+$/.test(base)) return null; + return { + async notify({ title, body }) { + const query = `title=${encodeURIComponent(String(title ?? '').slice(0, 120))}&body=${encodeURIComponent(String(body ?? '').slice(0, 300))}`; + const response = await fetcher(`${base}/shell/notify?${query}`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(5000) }); + let reply = null; + try { reply = await response.json(); } catch { /* no body */ } + return { shown: response.ok && reply?.shown === true }; + }, + }; +} diff --git a/apps/host/server/temperature-telemetry.mjs b/apps/host/server/temperature-telemetry.mjs new file mode 100644 index 00000000..0417dc04 --- /dev/null +++ b/apps/host/server/temperature-telemetry.mjs @@ -0,0 +1,124 @@ +/** + * CPU and SSD temperatures for the Monitor's Power card (#3628). A value that this PC cannot give stays null and its line is left out, + * so the card never shows a made-up number. + * + * Linux: the kernel's hwmon sensors (coretemp, k10temp, zenpower for the processor; nvme and drivetemp for the drives). + * Windows: the drive reports its own temperature to a query that needs no administrator (IOCTL_STORAGE_QUERY_PROPERTY with the device + * temperature property). Get-StorageReliabilityCounter is tried first because it is the documented route; on a normal account it is + * refused, then the query is used. One long-lived PowerShell asks every 30 s (windows-poll.mjs). + * There is no unprivileged, trustworthy processor temperature on Windows, so none is shown there. + * macOS: none. + */ +import { readFile, readdir } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { createPowerShellLoop, endWithHost } from './windows-poll.mjs'; + +const CPU_SENSORS = new Set(['coretemp', 'k10temp', 'zenpower', 'cpu_thermal', 'cpu-thermal']); +const DISK_SENSORS = new Set(['nvme', 'drivetemp']); +const plausible = c => Number.isFinite(c) && c > 0 && c < 150; + +/** hwmon entries [{name, temps: [milli-degrees…]}] -> the hottest processor and drive sensor. */ +export function pickTemperatures(entries) { + let cpu = null, ssd = null; + for (const { name, temps } of entries) { + const hottest = Math.max(...temps.map(t => t / 1000).filter(plausible), -Infinity); + if (!Number.isFinite(hottest)) continue; + if (CPU_SENSORS.has(name)) cpu = Math.max(cpu ?? -Infinity, hottest); + else if (DISK_SENSORS.has(name)) ssd = Math.max(ssd ?? -Infinity, hottest); + } + return { cpuTempC: cpu === null ? null : Math.round(cpu), ssdTempC: ssd === null ? null : Math.round(ssd) }; +} + +export async function readLinuxTemperatures({ base = '/sys/class/hwmon', read = readFile, list = readdir } = {}) { + const entries = []; + let folders = []; + try { folders = await list(base); } catch { return { cpuTempC: null, ssdTempC: null }; } + for (const folder of folders) { + try { + const name = String(await read(`${base}/${folder}/name`, 'utf8')).trim(); + if (!CPU_SENSORS.has(name) && !DISK_SENSORS.has(name)) continue; + const files = (await list(`${base}/${folder}`)).filter(f => /^temp\d+_input$/.test(f)); + const temps = []; + for (const file of files) temps.push(Number(String(await read(`${base}/${folder}/${file}`, 'utf8')).trim())); + entries.push({ name, temps }); + } catch { /* a sensor that disappears is skipped */ } + } + return pickTemperatures(entries); +} + +/** One line of the Windows loop: "ssd 53" or "ssd -". */ +export function parseSsdLine(line) { + const m = /^\s*ssd\s+(-?\d+|-)\s*$/.exec(String(line)); + if (!m) return undefined; + const value = m[1] === '-' ? NaN : Number(m[1]); + return plausible(value) ? value : null; +} + +const WINDOWS_SCRIPT = String.raw` +$ErrorActionPreference='SilentlyContinue' +$cs=@' +using System; +using System.Runtime.InteropServices; +public static class StrataDiskTemp { + [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateFile(string n, uint a, uint s, IntPtr p, uint d, uint f, IntPtr t); + [DllImport("kernel32.dll", SetLastError=true)] static extern bool DeviceIoControl(IntPtr h, uint c, byte[] i, uint il, byte[] o, uint ol, out uint r, IntPtr ov); + [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); + public static int Read(int n) { + IntPtr h = CreateFile("\\\\.\\PhysicalDrive" + n, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero); + if (h == (IntPtr)(-1)) return -1; + try { + byte[] q = new byte[12]; q[0] = 0x34; byte[] o = new byte[512]; uint r; + if (!DeviceIoControl(h, 0x002D1400, q, 12, o, 512, out r, IntPtr.Zero)) return -1; + if (BitConverter.ToUInt16(o, 12) < 1) return -1; + return BitConverter.ToInt16(o, 26); + } finally { CloseHandle(h); } + } +} +'@ +$compiled=$false +while($true){ + $max=-1 + $c=@(Get-PhysicalDisk | Get-StorageReliabilityCounter | Where-Object { $_.Temperature -gt 0 }) + if($c.Count -gt 0){ $max=($c | Measure-Object Temperature -Maximum).Maximum } + else { + if(-not $compiled){ Add-Type -TypeDefinition $cs; $compiled=$true } + foreach($n in 0..15){ $v=[StrataDiskTemp]::Read($n); if($v -gt $max){ $max=$v } } + } + if($max -gt 0){ [Console]::Out.WriteLine('ssd '+$max) } else { [Console]::Out.WriteLine('ssd -') } + [Console]::Out.Flush() + Start-Sleep -Seconds 30 +}`; + +export function createWindowsSsdReader({ spawnFn = spawn, maxStarts = 2, now = Date.now, intervalSec = 30 } = {}) { + let latest = null; + const loop = createPowerShellLoop({ + script: WINDOWS_SCRIPT, spawnFn, maxStarts, + onLine: line => { + const parsed = parseSsdLine(line); + if (parsed === undefined) return false; + latest = { value: parsed, at: now() }; + return true; + }, + }); + return { + read() { loop.start(); return latest && now() - latest.at < 4 * intervalSec * 1000 ? latest.value : null; }, + stop() { loop.stop(); }, + get starts() { return loop.starts; }, + }; +} + +let windowsReader = null; +let linuxCache = { at: 0, value: { cpuTempC: null, ssdTempC: null } }; + +/** The temperatures this PC can give now: { cpuTempC, ssdTempC } (null where unreadable). Cheap to call every few seconds. */ +export async function readTemperatures({ platform = process.platform, now = Date.now } = {}) { + if (platform === 'linux') { + if (now() - linuxCache.at > 10_000) linuxCache = { at: now(), value: await readLinuxTemperatures() }; + return linuxCache.value; + } + if (platform === 'win32') { + windowsReader ??= endWithHost(createWindowsSsdReader()); + return { cpuTempC: null, ssdTempC: windowsReader.read() }; + } + return { cpuTempC: null, ssdTempC: null }; +} diff --git a/apps/host/src/components/ElectricityPrice.tsx b/apps/host/src/components/ElectricityPrice.tsx new file mode 100644 index 00000000..16851877 --- /dev/null +++ b/apps/host/src/components/ElectricityPrice.tsx @@ -0,0 +1,29 @@ +import { useEffect, useMemo, useState } from 'react'; +import { currencyChoices, currencyLabel } from '../lib/currency'; +import { tr } from '../lib/i18n'; +import { useMoney } from '../lib/money'; +import { setElectricity, useStore } from '../lib/store'; +import { Btn, Select } from './ui'; + +/** + * The price of one kWh for the Monitor's cost line (#3628). The person types only the number: the currency is the one of the computer's + * region, shown beside it. "Change currency" is a way to pick another one, never a step that has to be taken. + */ +export function ElectricityPrice() { + const price = useStore(s => s.electricityPrice), override = useStore(s => s.electricityCurrency); + const money = useMoney(); + const [text, setText] = useState(price > 0 ? String(price) : ''), [picking, setPicking] = useState(false); + useEffect(() => { setText(price > 0 ? String(price) : ''); }, [price]); + const commit = () => setElectricity(Number(text.replace(',', '.')), override); + const choices = useMemo(() => currencyChoices(money.locale), [money.locale]); + return <span className="stack"> + <span className="row"> + <input className="st-input" inputMode="decimal" size={7} aria-label={tr("Price per kWh")} placeholder="0.30" value={text} onChange={e => setText(e.target.value)} onBlur={commit} onKeyDown={e => { if (e.key === 'Enter') commit(); }}/> + <span className="small muted">{money.currency ? tr("per kWh, in {0}", [currencyLabel(money.currency, money.locale)]) : tr("per kWh")}</span> + <Btn size="sm" onClick={() => setPicking(v => !v)}>{tr("Change currency")}</Btn> + </span> + {picking ? <Select ariaLabel={tr("Currency")} translateLabels={false} value={override} + options={[{ value: '', label: tr("Automatic ({0})", [money.detected ?? '—']) }, ...choices]} + onChange={value => { setElectricity(price, String(value)); setPicking(false); }}/> : null} + </span>; +} diff --git a/apps/host/src/components/ShellSettings.tsx b/apps/host/src/components/ShellSettings.tsx new file mode 100644 index 00000000..32cf0839 --- /dev/null +++ b/apps/host/src/components/ShellSettings.tsx @@ -0,0 +1,74 @@ +import { useEffect, useState } from 'react'; +import { api } from '../lib/client'; +import { tr } from '../lib/i18n'; +import { askNotificationPermission, playDoneSound } from '../lib/attention'; +import { setApprovalNotify, setDoneSound, useStore } from '../lib/store'; +import { Btn } from './ui'; + +/** What the host says about the desktop shell (GET /api/shell): null in a browser or while it loads. */ +export interface ShellState { + desktop: boolean; + tray: boolean; + port: number; + defaultPort: number; + pinnedPort: number | null; + minimizeToTray: boolean; + portNotice: { wanted: number; used: number } | null; +} + +export function useShellState(): [ShellState | null, (patch: { port?: number | null; tray?: boolean }) => Promise<string | null>] { + const [shell, setShell] = useState<ShellState | null>(null); + useEffect(() => { + let alive = true; + api.get<ShellState>('/api/shell').then(s => { if (alive) setShell(s); }).catch(() => undefined); + return () => { alive = false; }; + }, []); + const save = async (patch: { port?: number | null; tray?: boolean }) => { + try { setShell(await api.post<ShellState>('/api/shell/prefs', patch)); return null; } + catch (error) { return error instanceof Error ? error.message : 'The choice was not saved.'; } + }; + return [shell, save]; +} + +/** The sound for finished work (#3586): off until switched on, with a button to hear it. */ +export function DoneSoundSetting() { + const on = useStore(s => s.doneSound); + return <span className="row"> + <Btn size="sm" onClick={() => playDoneSound()}>{tr("Play sound")}</Btn> + <button className="st-toggle" role="switch" aria-checked={on} aria-label={tr("Sound when work finishes")} onClick={() => setDoneSound(!on)}/> + </span>; +} + +/** A desktop notification when Manual mode waits for an approval (#3477). */ +export function ApprovalNotifySetting() { + const on = useStore(s => s.approvalNotify); + return <button className="st-toggle" role="switch" aria-checked={on} aria-label={tr("Notify me when Strata needs an answer")} + onClick={() => { if (!on) void askNotificationPermission(); setApprovalNotify(!on); }}/>; +} + +/** Keep the app running in the tray when its window is closed (#3477). Desktop app on Windows and macOS only. */ +export function TraySetting({ shell, save }: { shell: ShellState; save: (patch: { tray: boolean }) => Promise<string | null> }) { + return <button className="st-toggle" role="switch" aria-checked={shell.minimizeToTray} aria-label={tr("Minimise to tray")} onClick={() => void save({ tray: !shell.minimizeToTray })}/>; +} + +/** The port the app's window and local address use (#3402). Empty lets Strata choose; the choice applies the next time Strata starts. */ +export function PortSetting({ shell, save }: { shell: ShellState; save: (patch: { port: number | null }) => Promise<string | null> }) { + const [text, setText] = useState(shell.pinnedPort ? String(shell.pinnedPort) : ''), [problem, setProblem] = useState(''); + useEffect(() => { setText(shell.pinnedPort ? String(shell.pinnedPort) : ''); }, [shell.pinnedPort]); + const commit = async () => { + const trimmed = text.trim(); + if (trimmed === (shell.pinnedPort ? String(shell.pinnedPort) : '')) { setProblem(''); return; } + if (trimmed === '') { setProblem((await save({ port: null })) ?? ''); return; } + const value = Number(trimmed); + if (!Number.isInteger(value) || value < 1024 || value > 65535) { setProblem(tr("Choose a port between 1024 and 65535, or leave it empty.")); return; } + setProblem((await save({ port: value })) ?? ''); + }; + return <span className="stack"> + <span className="row"> + <input className="st-input" inputMode="numeric" size={7} aria-label={tr("Port (empty = automatic)")} placeholder={String(shell.defaultPort)} value={text} + onChange={e => setText(e.target.value.replace(/[^0-9]/g, '').slice(0, 5))} onBlur={() => void commit()} onKeyDown={e => { if (e.key === 'Enter') void commit(); }}/> + </span> + <span className="xs muted">{tr("Using port {0} now.", [shell.port])}</span> + {problem ? <span className="xs" role="alert">{problem}</span> : null} + </span>; +} diff --git a/apps/host/src/lib/attention.ts b/apps/host/src/lib/attention.ts new file mode 100644 index 00000000..46d19c5f --- /dev/null +++ b/apps/host/src/lib/attention.ts @@ -0,0 +1,85 @@ +/** + * Telling the person that Strata needs them or has finished (#3586, #3477). Both are opt-in and off by default. + * + * - A short sound when an answer or task that took a while is finished, or when Strata is in the background (public/strata-done-sound.wav, + * made for Strata from sine waves, no sample). + * - A desktop notification when Manual mode waits for an approval and Strata is in the background. The desktop app shows it through its own + * shell (the host passes it on, so it also works while the window is hidden in the tray); a browser uses the page's notifications. + */ +import { api } from './client'; +import { tr } from './i18n'; + +/** An answer that came back faster than this does not chime while the person is looking at the window. */ +export const QUICK_MS = 8000; +const SOUND_URL = '/strata-done-sound.wav'; +const MIN_GAP_MS = 2000; +let lastPlayed = 0; + +export interface DoneContext { enabled: boolean; durationMs: number; focused: boolean; now?: number } + +/** Whether the finished-work sound should play now: only when asked for, only for work that took a while or when the window is not in front. */ +export function shouldPlayDone({ enabled, durationMs, focused, now = Date.now() }: DoneContext): boolean { + if (!enabled) return false; + if (now - lastPlayed < MIN_GAP_MS) return false; + return !focused || durationMs >= QUICK_MS; +} + +export const windowInFront = (): boolean => typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus(); + +export function playDoneSound(make: (url: string) => { volume: number; play(): Promise<void> | void } = url => new Audio(url)): boolean { + try { + const audio = make(SOUND_URL); + audio.volume = 0.6; + lastPlayed = Date.now(); + const started = audio.play(); + if (started && typeof (started as Promise<void>).catch === 'function') (started as Promise<void>).catch(() => { /* the browser asked for a click first: no sound this time */ }); + return true; + } catch { + return false; + } +} + +/** Called when an answer or a task is finished. */ +export function workFinished(enabled: boolean, durationMs: number): void { + if (shouldPlayDone({ enabled, durationMs, focused: windowInFront() })) playDoneSound(); +} + +export interface Notice { title: string; body: string } + +/** The sentence of the approval notification, in the person's language. */ +export function approvalNotice(tool: string): Notice { + return { title: tr('Strata needs your answer'), body: tr('The assistant wants to use {0}. Open Strata to approve or deny.', [tool || tr('a tool')]) }; +} + +/** Shows a notification through the desktop shell when there is one, else through the page. Returns whether something was shown. */ +export async function showNotice(notice: Notice, deps: { post?: (body: Notice) => Promise<{ shown?: boolean }>; page?: (notice: Notice) => boolean } = {}): Promise<boolean> { + const post = deps.post ?? (body => api.post<{ shown?: boolean }>('/api/shell/notify', body)); + try { + const result = await post(notice); + if (result?.shown) return true; + } catch { /* no shell here: the page's own notification below */ } + return (deps.page ?? pageNotification)(notice); +} + +function pageNotification(notice: Notice): boolean { + try { + if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false; + new Notification(notice.title, { body: notice.body, tag: 'strata-approval' }); + return true; + } catch { + return false; + } +} + +/** Manual mode waits for an approval. Only a window that is not in front needs the notification. */ +export function approvalNeeded(enabled: boolean, tool: string, focused = windowInFront()): Promise<boolean> { + if (!enabled || focused) return Promise.resolve(false); + return showNotice(approvalNotice(tool)); +} + +/** Turning approval notifications on in a browser asks the page's permission once; the desktop shell needs none. */ +export async function askNotificationPermission(): Promise<void> { + try { + if (typeof Notification !== 'undefined' && Notification.permission === 'default') await Notification.requestPermission(); + } catch { /* some web views have none */ } +} diff --git a/apps/host/src/lib/currency.ts b/apps/host/src/lib/currency.ts new file mode 100644 index 00000000..3a7a7a51 --- /dev/null +++ b/apps/host/src/lib/currency.ts @@ -0,0 +1,114 @@ +/** + * The currency of the Monitor's cost line (#3628): the person's own, found from the computer's region, never typed and never a guess. + * + * Order: the system (the host reads the regional format of Windows, macOS or Linux: its region, or its currency when the system names one), + * then the browser's language list, then the region of the app's language, and then no currency at all: the number is shown without a + * symbol rather than in a currency the person does not use. A currency picked in Settings overrides all of this. + */ + +/** ISO 3166 region -> ISO 4217 currency. */ +const PAIRS = `AD:EUR AE:AED AF:AFN AG:XCD AI:XCD AL:ALL AM:AMD AO:AOA AR:ARS AS:USD AT:EUR AU:AUD AW:AWG AX:EUR AZ:AZN +BA:BAM BB:BBD BD:BDT BE:EUR BF:XOF BG:EUR BH:BHD BI:BIF BJ:XOF BL:EUR BM:BMD BN:BND BO:BOB BQ:USD BR:BRL BS:BSD BT:BTN BV:NOK BW:BWP BY:BYN BZ:BZD +CA:CAD CC:AUD CD:CDF CF:XAF CG:XAF CH:CHF CI:XOF CK:NZD CL:CLP CM:XAF CN:CNY CO:COP CR:CRC CU:CUP CV:CVE CW:XCG CX:AUD CY:EUR CZ:CZK +DE:EUR DJ:DJF DK:DKK DM:XCD DO:DOP DZ:DZD EC:USD EE:EUR EG:EGP EH:MAD ER:ERN ES:EUR ET:ETB FI:EUR FJ:FJD FK:FKP FM:USD FO:DKK FR:EUR +GA:XAF GB:GBP GD:XCD GE:GEL GF:EUR GG:GBP GH:GHS GI:GIP GL:DKK GM:GMD GN:GNF GP:EUR GQ:XAF GR:EUR GS:GBP GT:GTQ GU:USD GW:XOF GY:GYD +HK:HKD HM:AUD HN:HNL HR:EUR HT:HTG HU:HUF ID:IDR IE:EUR IL:ILS IM:GBP IN:INR IO:USD IQ:IQD IR:IRR IS:ISK IT:EUR +JE:GBP JM:JMD JO:JOD JP:JPY KE:KES KG:KGS KH:KHR KI:AUD KM:KMF KN:XCD KP:KPW KR:KRW KW:KWD KY:KYD KZ:KZT +LA:LAK LB:LBP LC:XCD LI:CHF LK:LKR LR:LRD LS:LSL LT:EUR LU:EUR LV:EUR LY:LYD +MA:MAD MC:EUR MD:MDL ME:EUR MF:EUR MG:MGA MH:USD MK:MKD ML:XOF MM:MMK MN:MNT MO:MOP MP:USD MQ:EUR MR:MRU MS:XCD MT:EUR MU:MUR MV:MVR MW:MWK MX:MXN MY:MYR MZ:MZN +NA:NAD NC:XPF NE:XOF NF:AUD NG:NGN NI:NIO NL:EUR NO:NOK NP:NPR NR:AUD NU:NZD NZ:NZD OM:OMR +PA:PAB PE:PEN PF:XPF PG:PGK PH:PHP PK:PKR PL:PLN PM:EUR PR:USD PS:ILS PT:EUR PW:USD PY:PYG QA:QAR RE:EUR RO:RON RS:RSD RU:RUB RW:RWF +SA:SAR SB:SBD SC:SCR SD:SDG SE:SEK SG:SGD SH:SHP SI:EUR SJ:NOK SK:EUR SL:SLE SM:EUR SN:XOF SO:SOS SR:SRD SS:SSP ST:STN SV:USD SX:XCG SY:SYP SZ:SZL +TC:USD TD:XAF TF:EUR TG:XOF TH:THB TJ:TJS TK:NZD TL:USD TM:TMT TN:TND TO:TOP TR:TRY TT:TTD TV:AUD TW:TWD TZ:TZS +UA:UAH UG:UGX UM:USD US:USD UY:UYU UZ:UZS VA:EUR VC:XCD VE:VES VG:USD VI:USD VN:VND VU:VUV WF:XPF WS:WST XK:EUR YE:YER YT:EUR ZA:ZAR ZM:ZMW ZW:ZWG`; + +export const REGION_CURRENCY: Readonly<Record<string, string>> = Object.freeze(Object.fromEntries(PAIRS.split(/\s+/).map(pair => pair.split(':') as [string, string]))); + +/** The region of each app language that has one region of its own; English and Spanish-speaking countries are many, so only the first is a guess. */ +export const LANGUAGE_REGION: Readonly<Record<string, string>> = Object.freeze({ zh: 'CN', ja: 'JP', de: 'DE', es: 'ES', ru: 'RU', pt: 'BR', ko: 'KR' }); + +export const currencyForRegion = (region: string | null | undefined): string | null => (region ? REGION_CURRENCY[region.toUpperCase()] ?? null : null); + +/** The region in a language tag ("en-US", "de_DE.UTF-8", "zh-Hans-CN"), or null when the tag names none. */ +export function regionOfLocale(tag: string | null | undefined): string | null { + if (!tag) return null; + const clean = String(tag).replace(/[.@].*$/, '').replace(/_/g, '-'); + try { + const region = new Intl.Locale(clean).region; + return region ?? null; + } catch { + const found = /-([A-Za-z]{2})(?:-|$)/.exec(clean); + return found ? found[1].toUpperCase() : null; + } +} + +/** What the host read from the system (GET /api/locale). */ +export interface SystemLocale { locale: string | null; region: string | null; currency: string | null; source: string | null } + +export interface ResolvedCurrency { currency: string | null; locale: string; source: 'system' | 'browser' | 'language' | 'none' } + +/** + * The currency to show money in, and the locale to write the number in. + * `override` is the currency the person chose in Settings (empty: automatic). + */ +export function resolveCurrency({ system, browserLanguages = [], language, override = '' }: { system?: SystemLocale | null; browserLanguages?: readonly string[]; language: string; override?: string }): ResolvedCurrency { + const appTag = language === 'zh' ? 'zh-CN' : language; + const locale = system?.locale ?? browserLanguages.find(tag => regionOfLocale(tag)) ?? browserLanguages[0] ?? appTag; + if (/^[A-Za-z]{3}$/.test(override)) return { currency: override.toUpperCase(), locale, source: 'system' }; + const fromSystem = system?.currency ?? currencyForRegion(system?.region); + if (fromSystem) return { currency: fromSystem, locale, source: 'system' }; + for (const tag of browserLanguages) { + const found = currencyForRegion(regionOfLocale(tag)); + if (found) return { currency: found, locale, source: 'browser' }; + } + const fromLanguage = currencyForRegion(LANGUAGE_REGION[language]); + if (fromLanguage) return { currency: fromLanguage, locale, source: 'language' }; + return { currency: null, locale, source: 'none' }; +} + +/** How many decimals this currency normally has (2 for dollars and euros, 0 for yen); 2 when there is no currency. */ +export function minorDigits(currency: string | null, locale: string): number { + if (!currency) return 2; + try { return new Intl.NumberFormat(locale, { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2; } catch { return 2; } +} + +/** + * An amount of money, written for the person's locale with the currency's usual digits ("$0.12", "$1.23", "1,23 €", "¥3"). + * An amount below the smallest normal unit (one cent; one yen) is not shown as 0.00 or as a long run of decimals but as + * "less than $0.01" (`lessThan` writes the sentence in the person's language). With no currency the number is shown alone, + * and never in a currency that was only guessed. + */ +export function formatMoney(amount: number, { currency, locale, lessThan = shown => `less than ${shown}` }: { currency: string | null; locale: string; lessThan?: (shown: string) => string }): string { + if (!Number.isFinite(amount) || amount < 0) return '—'; + const digits = minorDigits(currency, locale), unit = 10 ** -digits; + const write = (value: number): string => { + try { + if (currency) return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value); + } catch { /* an unknown currency code or locale: the number alone */ } + try { + return new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value); + } catch { + return value.toFixed(digits); + } + }; + return amount > 0 && amount < unit ? lessThan(write(unit)) : write(amount); +} + +/** "USD ($)": the code and its symbol in the person's locale, for the Settings line. */ +export function currencyLabel(currency: string, locale: string): string { + try { + const symbol = new Intl.NumberFormat(locale, { style: 'currency', currency, currencyDisplay: 'narrowSymbol' }).formatToParts(0).find(part => part.type === 'currency')?.value; + return symbol && symbol !== currency ? `${currency} (${symbol})` : currency; + } catch { + return currency; + } +} + +/** Every currency this web view knows, by name, for the override list. */ +export function currencyChoices(locale: string): { value: string; label: string }[] { + let codes: string[] = []; + try { codes = (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.('currency') ?? []; } catch { /* an older web view */ } + let names: Intl.DisplayNames | null = null; + try { names = new Intl.DisplayNames([locale], { type: 'currency' }); } catch { /* no names */ } + return codes.map(code => ({ value: code, label: `${code} – ${names?.of(code) ?? code}` })); +} diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 952e3ca2..628f1f37 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -23,6 +23,15 @@ import fix_es from '../locales/fix-es.json'; import fix_ru from '../locales/fix-ru.json'; import fix_pt from '../locales/fix-pt.json'; import fix_ko from '../locales/fix-ko.json'; +/* The strings of the 0.2.7 GitHub items (gh-<lang>.json, scripts/make-gh-locales.py). */ +import gh_en from '../locales/gh-en.json'; +import gh_zh from '../locales/gh-zh.json'; +import gh_ja from '../locales/gh-ja.json'; +import gh_de from '../locales/gh-de.json'; +import gh_es from '../locales/gh-es.json'; +import gh_ru from '../locales/gh-ru.json'; +import gh_pt from '../locales/gh-pt.json'; +import gh_ko from '../locales/gh-ko.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -36,8 +45,8 @@ export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */ -const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en}; -const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja},{...base_de,...tune_de,...tools_de,...fix_de},{...base_es,...tune_es,...tools_es,...fix_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko}] as Record<string,string>[]; +const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en}; +const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko}] as Record<string,string>[]; const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,es,ru,pt,ko}; const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/lib/money.ts b/apps/host/src/lib/money.ts new file mode 100644 index 00000000..9da6d759 --- /dev/null +++ b/apps/host/src/lib/money.ts @@ -0,0 +1,28 @@ +import { useEffect, useState } from 'react'; +import { tr } from './i18n'; +import { api } from './client'; +import { formatMoney, resolveCurrency, type ResolvedCurrency, type SystemLocale } from './currency'; +import { useStore } from './store'; + +let asked: Promise<SystemLocale | null> | null = null; + +/** The computer's regional format, read once from the host (null in a browser build that has none, or while it loads). */ +export function useSystemLocale(): SystemLocale | null { + const [value, setValue] = useState<SystemLocale | null>(null); + useEffect(() => { + let alive = true; + asked ??= api.get<SystemLocale>('/api/locale').catch(() => null); + void asked.then(v => { if (alive) setValue(v); }); + return () => { alive = false; }; + }, []); + return value; +} + +/** The person's currency and locale for money (#3628) and a function that writes an amount in them. */ +export function useMoney(): ResolvedCurrency & { format: (amount: number) => string; detected: string | null } { + const system = useSystemLocale(), language = useStore(s => s.language), override = useStore(s => s.electricityCurrency); + const browserLanguages = typeof navigator === 'undefined' ? [] : [...(navigator.languages ?? [navigator.language])].filter(Boolean); + const resolved = resolveCurrency({ system, browserLanguages, language, override }); + const detected = override ? resolveCurrency({ system, browserLanguages, language }).currency : resolved.currency; + return { ...resolved, detected, format: amount => formatMoney(amount, { ...resolved, lessThan: shown => tr('less than {0}', [shown]) }) }; +} diff --git a/apps/host/src/lib/native-monitor.ts b/apps/host/src/lib/native-monitor.ts index f2c4bf5b..16846852 100644 --- a/apps/host/src/lib/native-monitor.ts +++ b/apps/host/src/lib/native-monitor.ts @@ -54,7 +54,9 @@ export function withHostSensors(live:MonitorState,host:MonitorState|null):Monito const empty=(g:GpuReading)=>![g.utilizationPct,g.temperatureC,g.memoryUsedGb,g.powerW].some(hasReading); const pick=<T,>(a:T,b:T)=>hasReading(a as unknown)?a:b; return {...live,hardware:{...h, - gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);return sensor&&empty(g)?{...g,...sensor}:g;}), + // The fan and the clock are the host's own readings; the engine's metrics do not carry them (#3628). + gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);const own=sensor&&empty(g)?{...g,...sensor}:g;return sensor?{...own,fanPct:own.fanPct??sensor.fanPct,clockMhz:own.clockMhz??sensor.clockMhz}:own;}), + cpuTempC:s.cpuTempC,ssdTempC:s.ssdTempC,energyWh:s.energyWh, gpuLoad:pick(h.gpuLoad,s.gpuLoad),vramUsedGb:pick(h.vramUsedGb,s.vramUsedGb),vramTotalGb:pick(h.vramTotalGb,s.vramTotalGb),gpuTempC:pick(h.gpuTempC,s.gpuTempC), powerW:pick(h.powerW,s.powerW),powerLimitW:pick(h.powerLimitW,s.powerLimitW),pcieRxMbs:pick(h.pcieRxMbs,s.pcieRxMbs)}}; } diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 3449089a..76f06e3d 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -5,6 +5,7 @@ import { updateAgent } from './agents'; import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop'; import { LoopScheduler } from './loop-runner'; import { applyStatusFrame, clearStatus } from './live-status'; +import { approvalNeeded, workFinished } from './attention'; import { applyGoalFrame } from './goal'; import { tidyAnswer } from './answer-text'; import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables'; @@ -82,6 +83,13 @@ export interface AppState { transparency: 'translucent' | 'opaque'; /** Chrome scale, independent of the conversation's reading size. */ uiScale: number; + /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ + electricityPrice: number; + electricityCurrency: string; + /** Opt-in: a short sound when a task finishes (#3586). */ + doneSound: boolean; + /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ + approvalNotify: boolean; /** Governs anonymous usage reporting. Nothing is sent in this build; the * choice is recorded so a version that does offer it starts from it. */ shareTelemetry: boolean; @@ -143,6 +151,10 @@ export interface Prefs { motion: 'system' | 'full' | 'reduced'; transparency: 'translucent' | 'opaque'; uiScale: number; + electricityPrice: number; + electricityCurrency: string; + doneSound: boolean; + approvalNotify: boolean; /** Governs anonymous usage reporting. Nothing is sent in this build; the * choice is recorded so a version that does offer it starts from it. */ shareTelemetry: boolean; @@ -160,6 +172,10 @@ const PREFS_DEFAULTS: Prefs = { motion: 'system', transparency: 'translucent', uiScale: 1, + electricityPrice: 0, + electricityCurrency: '', + doneSound: false, + approvalNotify: false, shareTelemetry: false, }; @@ -203,6 +219,11 @@ function loadPrefs(): Prefs { language: validLanguage(parsed.language) ? parsed.language : 'en', fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 14)), + uiScale: [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2].includes(Number(parsed.uiScale)) ? Number(parsed.uiScale) : 1, + electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, + electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', + doneSound: parsed.doneSound === true, + approvalNotify: parsed.approvalNotify === true, }; } catch { /* fall through to the next key */ @@ -215,6 +236,9 @@ const prefs = loadPrefs(); // Use the saved language for the very first render, before host bootstrap. setTranslationLanguage(prefs.language); +/** The last approval question a notification was shown for, so one question is announced once. */ +let lastApprovalNotice = ''; + let state: AppState = { language: prefs.language, fontFamily: prefs.fontFamily, @@ -232,6 +256,10 @@ let state: AppState = { motion: prefs.motion, transparency: prefs.transparency, uiScale: prefs.uiScale, + electricityPrice: prefs.electricityPrice, + electricityCurrency: prefs.electricityCurrency, + doneSound: prefs.doneSound, + approvalNotify: prefs.approvalNotify, paletteOpen: false, shortcutsOpen: false, settingsSection: 'Appearance', @@ -422,9 +450,11 @@ function applyPrefs() { root.dataset.contrast = state.contrast; root.dataset.density = state.density; root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`); - // The chrome scale. The reading size is deliberately separate: someone who - // needs larger prose does not necessarily want larger buttons. - root.style.setProperty('--st-ui-scale', String(state.uiScale)); + // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were + // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs + // larger prose does not necessarily want larger buttons. + root.style.setProperty('--st-ui-scale', '1'); + root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale)); // "system" means the OS decides, so the attribute is absent rather than set // to a third value the stylesheet would have to special-case. @@ -452,6 +482,10 @@ function savePrefs() { motion: state.motion, transparency: state.transparency, uiScale: state.uiScale, + electricityPrice: state.electricityPrice, + electricityCurrency: state.electricityCurrency, + doneSound: state.doneSound, + approvalNotify: state.approvalNotify, shareTelemetry: state.shareTelemetry, }; try { @@ -471,7 +505,17 @@ export function toggleRail() { set({ rail: !state.rail }); savePrefs(); } -export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();} +export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);} +let shellAnnounced = false; +/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ +function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);} +/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ +async function announcePortNotice(){ + try{ + const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell'); + if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used])); + }catch{/* a browser or an older host has no shell */} +} export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();} export function setFocus(focus: boolean) { @@ -544,7 +588,24 @@ export function setTransparency(transparency: 'translucent' | 'opaque') { savePrefs(); } -export const UI_SCALES = [0.9, 1, 1.1, 1.25] as const; +/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ +export function setElectricity(price: number, currency: string) { + const ok = Number.isFinite(price) && price > 0 && price < 1000; + set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' }); + savePrefs(); +} + +export function setDoneSound(doneSound: boolean) { + set({ doneSound }); + savePrefs(); +} + +export function setApprovalNotify(approvalNotify: boolean) { + set({ approvalNotify }); + savePrefs(); +} + +export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; export function setUiScale(uiScale: number) { set({ uiScale }); @@ -680,8 +741,8 @@ function applyEvent(e: StreamEvent) { // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null }; if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? '')); - else if (t.attention) pushToast('warn', 'Task needs your yes', String(t.title ?? '')); - else if (t.status === 'done') pushToast('success', 'Task finished', String(t.title ?? '')); + else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); } + else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); } break; } case 'agent': @@ -726,6 +787,7 @@ export async function bootstrap() { connection: 'live', }); applyProviders(providers); + if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); } closeEvents?.(); let reconnect = false; closeEvents = onEvent(applyEvent, (status) => { @@ -1746,6 +1808,12 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] })); } else if (type === 'status') { applyStatusFrame(sessionId, frame as Record<string, unknown>); + // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. + if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) { + lastApprovalNotice = `${sessionId}:${String(frame.seq)}`; + const tool = (frame.args as { tool?: unknown } | undefined)?.tool; + void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : ''); + } } else if (type === 'goal') { applyGoalFrame(sessionId, frame.goal); } else if (type === 'plan') { @@ -1820,6 +1888,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g patchAssistant((m) => ({ ...m, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); } else if (type === 'done') { clearStatus(sessionId); + workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); patchSession(sessionId, (sess) => ({ ...sess, tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0), diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 28e044bd..1e477540 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -23,7 +23,7 @@ export interface HardwareCheck { export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] } export interface CpuReading { id:string; utilizationPct:number|null } -export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null } +export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null } export interface GpuInfo { id?: string; @@ -285,6 +285,10 @@ export interface MonitorState { powerW?: number | null; powerLimitW?: number | null; pcieRxMbs?: number | null; + /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */ + cpuTempC?: number | null; + ssdTempC?: number | null; + energyWh?: number | null; diskReadGbs?: number | null; diskWriteMbs?: number | null; gpuLoad: number | null; diff --git a/apps/host/src/locales/gh-de.json b/apps/host/src/locales/gh-de.json new file mode 100644 index 00000000..d6a54a5a --- /dev/null +++ b/apps/host/src/locales/gh-de.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energie seit dem Start", + "gh02": "Kosten seit dem Start", + "gh03": "GPU-Lüfter", + "gh04": "GPU-Takt", + "gh05": "CPU-Temperatur", + "gh06": "SSD-Temperatur", + "gh07": "Strompreis", + "gh08": "Preis einer Kilowattstunde. Der Monitor zeigt dann, was Ihre Grafikkarte seit dem Start von Strata gekostet hat. Leer lassen, um die Kosten auszublenden.", + "gh09": "Preis pro kWh", + "gh10": "Ton, wenn Arbeit fertig ist", + "gh11": "Spielt einen kurzen Ton, wenn eine Antwort oder Aufgabe, die länger gedauert hat, fertig ist oder wenn Strata im Hintergrund läuft.", + "gh12": "Ton abspielen", + "gh13": "Benachrichtigen, wenn Strata eine Antwort braucht", + "gh14": "Zeigt im manuellen Modus eine Desktop-Benachrichtigung, wenn der Assistent auf Ihre Freigabe wartet und Strata im Hintergrund läuft.", + "gh15": "Strata braucht Ihre Antwort", + "gh16": "Der Assistent möchte {0} verwenden. Öffnen Sie Strata, um zu erlauben oder abzulehnen.", + "gh17": "ein Werkzeug", + "gh18": "In den Infobereich minimieren", + "gh19": "Beim Schließen des Fensters läuft Strata im Infobereich neben der Uhr weiter. Wählen Sie im Menü des Symbols „Beenden“, um es zu stoppen. Gilt ab dem nächsten Start von Strata.", + "gh20": "App-Port", + "gh21": "Der Port, den das Fenster und die lokale Adresse von Strata verwenden. Leer lassen, damit Strata ihn wählt (47831, wenn frei). Gilt ab dem nächsten Start von Strata.", + "gh22": "Port (leer = automatisch)", + "gh23": "Aktuell wird Port {0} verwendet.", + "gh24": "Strata konnte seinen Port nicht verwenden", + "gh25": "Port {0} wird von einem anderen Programm verwendet, daher wurde Strata auf Port {1} gestartet. Unter Port {0} gespeicherte Chats und Einstellungen werden nicht angezeigt, bis Strata ihn wieder verwenden kann. Schließen Sie das andere Programm und starten Sie Strata neu.", + "gh26": "Wählen Sie einen Port zwischen 1024 und 65535 oder lassen Sie das Feld leer.", + "gh27": "Macht alle Texte, Schaltflächen und Menüs in Strata größer oder kleiner.", + "gh28": "Energie- und Temperaturwerte", + "gh29": "pro kWh, in {0}", + "gh30": "pro kWh", + "gh31": "Währung ändern", + "gh32": "Automatisch ({0})", + "gh33": "Währung", + "gh34": "weniger als {0}" +} diff --git a/apps/host/src/locales/gh-en.json b/apps/host/src/locales/gh-en.json new file mode 100644 index 00000000..e1f12476 --- /dev/null +++ b/apps/host/src/locales/gh-en.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energy since start", + "gh02": "Cost since start", + "gh03": "GPU fan", + "gh04": "GPU clock", + "gh05": "CPU temperature", + "gh06": "SSD temperature", + "gh07": "Electricity price", + "gh08": "Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.", + "gh09": "Price per kWh", + "gh10": "Sound when work finishes", + "gh11": "Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.", + "gh12": "Play sound", + "gh13": "Notify me when Strata needs an answer", + "gh14": "In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.", + "gh15": "Strata needs your answer", + "gh16": "The assistant wants to use {0}. Open Strata to approve or deny.", + "gh17": "a tool", + "gh18": "Minimise to tray", + "gh19": "Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.", + "gh20": "App port", + "gh21": "The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.", + "gh22": "Port (empty = automatic)", + "gh23": "Using port {0} now.", + "gh24": "Strata could not use its port", + "gh25": "Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.", + "gh26": "Choose a port between 1024 and 65535, or leave it empty.", + "gh27": "Makes all text, buttons and menus in Strata larger or smaller.", + "gh28": "Energy and temperature readings", + "gh29": "per kWh, in {0}", + "gh30": "per kWh", + "gh31": "Change currency", + "gh32": "Automatic ({0})", + "gh33": "Currency", + "gh34": "less than {0}" +} diff --git a/apps/host/src/locales/gh-es.json b/apps/host/src/locales/gh-es.json new file mode 100644 index 00000000..82538fef --- /dev/null +++ b/apps/host/src/locales/gh-es.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energía desde el inicio", + "gh02": "Coste desde el inicio", + "gh03": "Ventilador de la GPU", + "gh04": "Reloj de la GPU", + "gh05": "Temperatura de la CPU", + "gh06": "Temperatura del SSD", + "gh07": "Precio de la electricidad", + "gh08": "Precio de un kilovatio hora. El Monitor mostrará entonces lo que ha costado tu tarjeta gráfica desde que se inició Strata. Déjalo vacío para ocultar el coste.", + "gh09": "Precio por kWh", + "gh10": "Sonido al terminar el trabajo", + "gh11": "Reproduce un sonido breve cuando termina una respuesta o tarea que tardó un rato, o cuando Strata está en segundo plano.", + "gh12": "Reproducir sonido", + "gh13": "Avisarme cuando Strata necesite una respuesta", + "gh14": "En el modo manual, muestra una notificación de escritorio cuando el asistente espera tu aprobación y Strata está en segundo plano.", + "gh15": "Strata necesita tu respuesta", + "gh16": "El asistente quiere usar {0}. Abre Strata para aprobar o denegar.", + "gh17": "una herramienta", + "gh18": "Minimizar a la bandeja", + "gh19": "Al cerrar la ventana, Strata sigue funcionando en la bandeja, junto al reloj. Elige Salir en el menú de la bandeja para detenerlo. Se aplica la próxima vez que se inicie Strata.", + "gh20": "Puerto de la aplicación", + "gh21": "El puerto que usan la ventana y la dirección local de Strata. Déjalo vacío para que Strata elija (47831 si está libre). Se aplica la próxima vez que se inicie Strata.", + "gh22": "Puerto (vacío = automático)", + "gh23": "Ahora se usa el puerto {0}.", + "gh24": "Strata no pudo usar su puerto", + "gh25": "El puerto {0} lo usa otro programa, así que Strata se inició en el puerto {1}. Los chats y ajustes guardados en el puerto {0} no se muestran hasta que Strata pueda volver a usarlo. Cierra el otro programa y reinicia Strata.", + "gh26": "Elige un puerto entre 1024 y 65535, o déjalo vacío.", + "gh27": "Hace más grandes o más pequeños todos los textos, botones y menús de Strata.", + "gh28": "Lecturas de energía y temperatura", + "gh29": "por kWh, en {0}", + "gh30": "por kWh", + "gh31": "Cambiar moneda", + "gh32": "Automática ({0})", + "gh33": "Moneda", + "gh34": "menos de {0}" +} diff --git a/apps/host/src/locales/gh-fr.json b/apps/host/src/locales/gh-fr.json new file mode 100644 index 00000000..9d556360 --- /dev/null +++ b/apps/host/src/locales/gh-fr.json @@ -0,0 +1,36 @@ +{ + "gh01": "Énergie depuis le démarrage", + "gh02": "Coût depuis le démarrage", + "gh03": "Ventilateur du GPU", + "gh04": "Fréquence du GPU", + "gh05": "Température du CPU", + "gh06": "Température du SSD", + "gh07": "Prix de l’électricité", + "gh08": "Prix d’un kilowattheure. Le Moniteur affiche alors ce que votre carte graphique a coûté depuis le démarrage de Strata. Laissez vide pour masquer le coût.", + "gh09": "Prix par kWh", + "gh10": "Son à la fin du travail", + "gh11": "Joue un court son quand une réponse ou une tâche qui a pris du temps est terminée, ou quand Strata est en arrière-plan.", + "gh12": "Jouer le son", + "gh13": "Me prévenir quand Strata a besoin d’une réponse", + "gh14": "En mode manuel, affiche une notification sur le bureau quand l’assistant attend votre accord et que Strata est en arrière-plan.", + "gh15": "Strata a besoin de votre réponse", + "gh16": "L’assistant veut utiliser {0}. Ouvrez Strata pour accepter ou refuser.", + "gh17": "un outil", + "gh18": "Réduire dans la zone de notification", + "gh19": "Fermer la fenêtre garde Strata actif dans la zone de notification, près de l’horloge. Choisissez Quitter dans le menu de l’icône pour l’arrêter. S’applique au prochain démarrage de Strata.", + "gh20": "Port de l’application", + "gh21": "Le port que la fenêtre et l’adresse locale de Strata utilisent. Laissez vide pour que Strata choisisse (47831 s’il est libre). S’applique au prochain démarrage de Strata.", + "gh22": "Port (vide = automatique)", + "gh23": "Port {0} utilisé en ce moment.", + "gh24": "Strata n’a pas pu utiliser son port", + "gh25": "Le port {0} est utilisé par un autre programme, donc Strata a démarré sur le port {1}. Les conversations et réglages enregistrés sur le port {0} ne s’affichent pas tant que Strata ne peut pas le réutiliser. Fermez l’autre programme et relancez Strata.", + "gh26": "Choisissez un port entre 1024 et 65535, ou laissez vide.", + "gh27": "Agrandit ou réduit tous les textes, boutons et menus de Strata.", + "gh28": "Relevés d’énergie et de température", + "gh29": "par kWh, en {0}", + "gh30": "par kWh", + "gh31": "Changer de devise", + "gh32": "Automatique ({0})", + "gh33": "Devise", + "gh34": "moins de {0}" +} diff --git a/apps/host/src/locales/gh-ja.json b/apps/host/src/locales/gh-ja.json new file mode 100644 index 00000000..55229a69 --- /dev/null +++ b/apps/host/src/locales/gh-ja.json @@ -0,0 +1,36 @@ +{ + "gh01": "起動後の消費電力量", + "gh02": "起動後の電気代", + "gh03": "GPU ファン", + "gh04": "GPU クロック", + "gh05": "CPU 温度", + "gh06": "SSD 温度", + "gh07": "電気料金", + "gh08": "1キロワット時あたりの料金です。モニターに、Strata の起動後にグラフィックスカードが使った電気代が表示されます。空欄のままなら電気代は表示されません。", + "gh09": "1 kWh あたりの料金", + "gh10": "作業完了時の音", + "gh11": "回答や時間のかかった作業が終わったとき、または Strata がバックグラウンドにあるときに、短い音を鳴らします。", + "gh12": "音を鳴らす", + "gh13": "Strata の返答が必要なときに通知する", + "gh14": "手動モードで、アシスタントが承認を待っていて Strata がバックグラウンドにあるときに、デスクトップ通知を表示します。", + "gh15": "Strata があなたの返答を待っています", + "gh16": "アシスタントが {0} を使おうとしています。Strata を開いて承認または拒否してください。", + "gh17": "ツール", + "gh18": "トレイに最小化", + "gh19": "ウィンドウを閉じても、Strata は時計の横のトレイで動き続けます。止めるには、トレイのメニューで「終了」を選びます。次に Strata を起動したときから有効になります。", + "gh20": "アプリのポート", + "gh21": "Strata のウィンドウとローカルアドレスが使うポートです。空欄なら Strata が選びます(空いていれば 47831)。次に Strata を起動したときから有効になります。", + "gh22": "ポート(空欄 = 自動)", + "gh23": "現在のポートは {0} です。", + "gh24": "Strata は指定のポートを使えませんでした", + "gh25": "ポート {0} は別のプログラムが使っているため、Strata はポート {1} で起動しました。ポート {0} に保存されたチャットと設定は、Strata が再びそのポートを使えるようになるまで表示されません。他のプログラムを閉じて Strata を再起動してください。", + "gh26": "1024 から 65535 の間のポートを選ぶか、空欄にしてください。", + "gh27": "Strata のすべての文字、ボタン、メニューを大きくしたり小さくしたりします。", + "gh28": "消費電力量と温度の値", + "gh29": "1 kWh あたり、通貨は {0}", + "gh30": "1 kWh あたり", + "gh31": "通貨を変更", + "gh32": "自動({0})", + "gh33": "通貨", + "gh34": "{0} 未満" +} diff --git a/apps/host/src/locales/gh-ko.json b/apps/host/src/locales/gh-ko.json new file mode 100644 index 00000000..24decc86 --- /dev/null +++ b/apps/host/src/locales/gh-ko.json @@ -0,0 +1,36 @@ +{ + "gh01": "시작 이후 에너지", + "gh02": "시작 이후 비용", + "gh03": "GPU 팬", + "gh04": "GPU 클럭", + "gh05": "CPU 온도", + "gh06": "SSD 온도", + "gh07": "전기 요금", + "gh08": "1킬로와트시의 요금입니다. 모니터에 Strata를 시작한 뒤 그래픽 카드에 든 전기 요금이 표시됩니다. 비워 두면 비용을 표시하지 않습니다.", + "gh09": "kWh당 요금", + "gh10": "작업이 끝났을 때 소리", + "gh11": "답변이나 오래 걸린 작업이 끝났을 때, 또는 Strata가 백그라운드에 있을 때 짧은 소리를 재생합니다.", + "gh12": "소리 재생", + "gh13": "Strata가 답을 필요로 할 때 알림", + "gh14": "수동 모드에서 어시스턴트가 승인을 기다리고 Strata가 백그라운드에 있을 때 데스크톱 알림을 표시합니다.", + "gh15": "Strata가 답을 기다리고 있습니다", + "gh16": "어시스턴트가 {0}을(를) 사용하려고 합니다. Strata를 열어 승인하거나 거부하세요.", + "gh17": "도구", + "gh18": "트레이로 최소화", + "gh19": "창을 닫아도 Strata는 시계 옆 트레이에서 계속 실행됩니다. 끝내려면 트레이 메뉴에서 '종료'를 선택하세요. 다음에 Strata를 시작할 때부터 적용됩니다.", + "gh20": "앱 포트", + "gh21": "Strata의 창과 로컬 주소가 사용하는 포트입니다. 비워 두면 Strata가 고릅니다(비어 있으면 47831). 다음에 Strata를 시작할 때부터 적용됩니다.", + "gh22": "포트(비움 = 자동)", + "gh23": "지금은 포트 {0}을(를) 사용 중입니다.", + "gh24": "Strata가 지정한 포트를 사용할 수 없었습니다", + "gh25": "포트 {0}을(를) 다른 프로그램이 사용 중이어서 Strata는 포트 {1}에서 시작했습니다. 포트 {0}에 저장된 채팅과 설정은 Strata가 다시 그 포트를 쓸 수 있을 때까지 표시되지 않습니다. 다른 프로그램을 닫고 Strata를 다시 시작하세요.", + "gh26": "1024에서 65535 사이의 포트를 고르거나 비워 두세요.", + "gh27": "Strata의 모든 글자, 버튼, 메뉴를 더 크게 또는 더 작게 만듭니다.", + "gh28": "에너지 및 온도 측정값", + "gh29": "kWh당, 통화 {0}", + "gh30": "kWh당", + "gh31": "통화 변경", + "gh32": "자동({0})", + "gh33": "통화", + "gh34": "{0} 미만" +} diff --git a/apps/host/src/locales/gh-pt.json b/apps/host/src/locales/gh-pt.json new file mode 100644 index 00000000..ad331c49 --- /dev/null +++ b/apps/host/src/locales/gh-pt.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energia desde o início", + "gh02": "Custo desde o início", + "gh03": "Ventoinha da GPU", + "gh04": "Clock da GPU", + "gh05": "Temperatura da CPU", + "gh06": "Temperatura do SSD", + "gh07": "Preço da eletricidade", + "gh08": "Preço de um quilowatt-hora. O Monitor passa a mostrar quanto a sua placa de vídeo custou desde que o Strata iniciou. Deixe vazio para ocultar o custo.", + "gh09": "Preço por kWh", + "gh10": "Som ao terminar o trabalho", + "gh11": "Toca um som curto quando uma resposta ou tarefa que demorou termina, ou quando o Strata está em segundo plano.", + "gh12": "Tocar som", + "gh13": "Avisar quando o Strata precisar de uma resposta", + "gh14": "No modo manual, mostra uma notificação na área de trabalho quando o assistente espera sua aprovação e o Strata está em segundo plano.", + "gh15": "O Strata precisa da sua resposta", + "gh16": "O assistente quer usar {0}. Abra o Strata para aprovar ou negar.", + "gh17": "uma ferramenta", + "gh18": "Minimizar para a bandeja", + "gh19": "Ao fechar a janela, o Strata continua em execução na bandeja, ao lado do relógio. Escolha Sair no menu da bandeja para encerrá-lo. Vale a partir da próxima vez que o Strata iniciar.", + "gh20": "Porta do aplicativo", + "gh21": "A porta usada pela janela e pelo endereço local do Strata. Deixe vazio para o Strata escolher (47831 quando estiver livre). Vale a partir da próxima vez que o Strata iniciar.", + "gh22": "Porta (vazio = automático)", + "gh23": "Usando a porta {0} agora.", + "gh24": "O Strata não conseguiu usar a sua porta", + "gh25": "A porta {0} está em uso por outro programa, então o Strata iniciou na porta {1}. Os chats e as configurações salvos na porta {0} não aparecem até o Strata poder usá-la de novo. Feche o outro programa e reinicie o Strata.", + "gh26": "Escolha uma porta entre 1024 e 65535, ou deixe vazio.", + "gh27": "Deixa todos os textos, botões e menus do Strata maiores ou menores.", + "gh28": "Leituras de energia e temperatura", + "gh29": "por kWh, em {0}", + "gh30": "por kWh", + "gh31": "Alterar moeda", + "gh32": "Automática ({0})", + "gh33": "Moeda", + "gh34": "menos de {0}" +} diff --git a/apps/host/src/locales/gh-ru.json b/apps/host/src/locales/gh-ru.json new file mode 100644 index 00000000..51e56bf8 --- /dev/null +++ b/apps/host/src/locales/gh-ru.json @@ -0,0 +1,36 @@ +{ + "gh01": "Энергия с запуска", + "gh02": "Стоимость с запуска", + "gh03": "Вентилятор GPU", + "gh04": "Частота GPU", + "gh05": "Температура CPU", + "gh06": "Температура SSD", + "gh07": "Цена электричества", + "gh08": "Цена одного киловатт-часа. Тогда монитор покажет, во сколько видеокарта обошлась с запуска Strata. Оставьте поле пустым, чтобы скрыть стоимость.", + "gh09": "Цена за кВт·ч", + "gh10": "Звук по окончании работы", + "gh11": "Проигрывает короткий звук, когда закончился долгий ответ или задача, а также когда Strata работает в фоне.", + "gh12": "Проиграть звук", + "gh13": "Уведомлять, когда Strata нужен ответ", + "gh14": "В ручном режиме показывает уведомление на рабочем столе, когда помощник ждёт вашего подтверждения, а Strata работает в фоне.", + "gh15": "Strata нужен ваш ответ", + "gh16": "Помощник хочет использовать {0}. Откройте Strata, чтобы разрешить или отклонить.", + "gh17": "инструмент", + "gh18": "Сворачивать в трей", + "gh19": "При закрытии окна Strata продолжает работать в трее рядом с часами. Чтобы остановить её, выберите «Выход» в меню значка. Действует со следующего запуска Strata.", + "gh20": "Порт приложения", + "gh21": "Порт, который используют окно и локальный адрес Strata. Оставьте поле пустым, чтобы Strata выбрала сама (47831, если свободен). Действует со следующего запуска Strata.", + "gh22": "Порт (пусто = автоматически)", + "gh23": "Сейчас используется порт {0}.", + "gh24": "Strata не смогла использовать свой порт", + "gh25": "Порт {0} занят другой программой, поэтому Strata запустилась на порту {1}. Чаты и настройки, сохранённые на порту {0}, не показываются, пока Strata не сможет снова его использовать. Закройте другую программу и перезапустите Strata.", + "gh26": "Выберите порт от 1024 до 65535 или оставьте поле пустым.", + "gh27": "Увеличивает или уменьшает весь текст, кнопки и меню в Strata.", + "gh28": "Показания энергии и температуры", + "gh29": "за кВт·ч, в валюте {0}", + "gh30": "за кВт·ч", + "gh31": "Сменить валюту", + "gh32": "Автоматически ({0})", + "gh33": "Валюта", + "gh34": "меньше {0}" +} diff --git a/apps/host/src/locales/gh-zh.json b/apps/host/src/locales/gh-zh.json new file mode 100644 index 00000000..eaa5e8fc --- /dev/null +++ b/apps/host/src/locales/gh-zh.json @@ -0,0 +1,36 @@ +{ + "gh01": "启动以来的能耗", + "gh02": "启动以来的费用", + "gh03": "GPU 风扇", + "gh04": "GPU 频率", + "gh05": "CPU 温度", + "gh06": "SSD 温度", + "gh07": "电价", + "gh08": "每千瓦时的价格。监控页会据此显示 Strata 启动以来显卡用电的费用。留空则不显示费用。", + "gh09": "每千瓦时价格", + "gh10": "工作完成时的提示音", + "gh11": "回答或耗时较长的任务完成时,或 Strata 在后台时,播放一段简短的提示音。", + "gh12": "播放提示音", + "gh13": "Strata 需要您答复时通知我", + "gh14": "在手动模式下,当助手等待您批准而 Strata 在后台时,显示桌面通知。", + "gh15": "Strata 需要您的答复", + "gh16": "助手想使用 {0}。打开 Strata 以批准或拒绝。", + "gh17": "一个工具", + "gh18": "最小化到托盘", + "gh19": "关闭窗口后,Strata 会继续在托盘(时钟旁边)运行。要停止它,请在托盘菜单中选择“退出”。下次启动 Strata 时生效。", + "gh20": "应用端口", + "gh21": "Strata 窗口和本地地址使用的端口。留空则由 Strata 自行选择(空闲时为 47831)。下次启动 Strata 时生效。", + "gh22": "端口(留空 = 自动)", + "gh23": "当前使用端口 {0}。", + "gh24": "Strata 无法使用它的端口", + "gh25": "端口 {0} 已被其他程序占用,因此 Strata 改用端口 {1} 启动。在端口 {0} 上保存的聊天和设置在 Strata 能再次使用该端口之前不会显示。请关闭其他程序并重新启动 Strata。", + "gh26": "请选择 1024 到 65535 之间的端口,或留空。", + "gh27": "让 Strata 中的所有文字、按钮和菜单变大或变小。", + "gh28": "能耗和温度读数", + "gh29": "每千瓦时,币种 {0}", + "gh30": "每千瓦时", + "gh31": "更改货币", + "gh32": "自动({0})", + "gh33": "货币", + "gh34": "不足 {0}" +} diff --git a/apps/host/src/screens/Monitor.tsx b/apps/host/src/screens/Monitor.tsx index 451ea29d..d75db79a 100644 --- a/apps/host/src/screens/Monitor.tsx +++ b/apps/host/src/screens/Monitor.tsx @@ -15,6 +15,7 @@ import { contextLabel, duration, tokens, tps } from '../lib/format'; import { defaultGpuSet, gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware'; import { useStore } from '../lib/store'; import { api } from '../lib/client'; +import { useMoney } from '../lib/money'; import { useKept } from '../lib/kept-state'; import type { Hardware, MonitorState, ServeRequest } from '../lib/types'; import { useNative, nativeRouting, type NativeState } from '../lib/native'; @@ -72,6 +73,7 @@ function LegacyMonitorScreen({ native }: { native: NativeState | null; }) { const storedLive = useStore(s => s.monitor), inventory = useStore(s => s.hardware); + const electricityPrice = useStore(s => s.electricityPrice), money = useMoney(); const storedRuntime = useStore(s => s.runtime), serving = useStore(s => s.serving); const [instanceSelection, setInstanceSelection] = useState('all'); const routing = native ? nativeRouting(native, inventory) : null; @@ -146,6 +148,16 @@ function LegacyMonitorScreen({ native }: { const cacheMemory = cacheKnown ? data.expertCache.memoryGb : null; const cachePercent = hasReading(cacheMemory) ? percent(cacheMemory, gpuCapacity(defaultDevices)) : cacheKnown ? percent(data.expertCache.used, data.expertCache.total) : null; const ramPct = percent(data.hardware.ramUsedGb, data.hardware.ramTotalGb); + // The readings strip under the cards: what the GPU used and cost since Strata started, the fan and clock, and the temperatures this PC can give. + const energyWh = data.hardware.energyWh, fan = gpuValue('fanPct', 'max'), clock = gpuValue('clockMhz', 'max'); + const readingsStrip = [ + hasReading(energyWh) ? { label: 'Energy since start', value: energyWh >= 1000 ? `${number(energyWh / 1000, 2)} kWh` : `${number(energyWh, 1)} Wh` } : null, + hasReading(energyWh) && electricityPrice > 0 ? { label: 'Cost since start', value: money.format(energyWh / 1000 * electricityPrice) } : null, + hasReading(fan) ? { label: 'GPU fan', value: `${number(fan)} %` } : null, + hasReading(clock) ? { label: 'GPU clock', value: `${number(clock)} MHz` } : null, + hasReading(data.hardware.cpuTempC) ? { label: 'CPU temperature', value: `${number(data.hardware.cpuTempC)} °C` } : null, + hasReading(data.hardware.ssdTempC) ? { label: 'SSD temperature', value: `${number(data.hardware.ssdTempC)} °C` } : null, + ].filter((line): line is { label: string; value: string } => line !== null); const history = data.history, timestamps = history.map(s => s.t); const historyGpu = (key: Parameters<typeof gpuMetric>[2], fallback: 'gpuLoad' | 'vramUsedGb' | 'gpuTempC' | 'powerW' | 'pcieRxMbs', mode: Parameters<typeof gpuMetric>[3] = 'sum') => history.map(sample => sample.gpus ? gpuMetric(selectedGpus, sample.gpus, key, mode) : (sample.gpuIds ? selectedGpus.length === sample.gpuIds.length && selectedGpus.every(gpu => sample.gpuIds!.includes(gpuId(gpu))) : gpuChoice === 'all') ? sample[fallback] : null); const historyCpu = history.map(sample => cpuChoice === 'all' ? sample.cpuLoad : sample.cpus?.find(p => p.id === cpuChoice)?.utilizationPct); @@ -184,6 +196,7 @@ function LegacyMonitorScreen({ native }: { <MonitorMetric label={tr("CPU")} icon="cpu" value={number(cpu)} unit={hasReading(cpu) ? '%' : ''} source={hasReading(cpu) ? 'Measured' : 'Unavailable'} sub={cpuName} chart={chart('CPU utilization', historyCpu, '%', 100)}/> <MonitorMetric label={tr("Disk read")} icon="disk" value={number(hasReading(data.hardware.diskReadGbs) ? data.hardware.diskReadGbs >= 1 ? data.hardware.diskReadGbs : data.hardware.diskReadGbs * 1024 : null, 1)} unit={hasReading(data.hardware.diskReadGbs) ? data.hardware.diskReadGbs >= 1 ? 'GB/s' : 'MB/s' : ''} source={hasReading(data.hardware.diskReadGbs) ? 'Measured' : 'Unavailable'} sub={hasReading(data.hardware.diskWriteMbs) ? `Write ${number(data.hardware.diskWriteMbs, 1)} MB/s` : 'Read throughput'} chart={chart('Disk read', history.map(s => hasReading(s.diskReadGbs) ? s.diskReadGbs * 1024 : null), 'MB/s', undefined, 'var(--st-info)')}/> </div> + {tr(readingsStrip.length ? <section className="st-card monitor-readings" aria-label={tr("Energy and temperature readings")}><dl>{readingsStrip.map(item => <div key={item.label}><dt>{tr(item.label)}</dt><dd className="num">{item.value}</dd></div>)}</dl></section> : null)} <div className="monitor-context-requests"> <section className="st-card monitor-context"><h2 className="h4">{tr("Context fill")}</h2><div className="monitor-context__gauge"><Gauge value={contextPct ?? 0} label={tr(hasReading(contextPct) ? `${Math.round(contextPct)}%` : '—')} sub={contextKnown ? `${tokens(contextUsed)} / ${contextLabel(data.context.maxTokens)}` : selection === 'all' && (runtime?.instances.length ?? 0) > 1 ? 'Select a model to see context' : 'No recorded request usage'}/></div> <div className="monitor-bar-reading"><span>{tr("Experts in VRAM")}</span><span className="muted num">{tr(cacheKnown ? `${number(data.expertCache.used)}${hasReading(cacheMemory) ? ` · ${number(cacheMemory, 1)} GB` : ''}` : '—')}</span></div><ReadingBar label={tr("Experts in VRAM")} value={cachePercent}/> diff --git a/apps/host/src/screens/Settings.tsx b/apps/host/src/screens/Settings.tsx index a14854f2..0361d712 100644 --- a/apps/host/src/screens/Settings.tsx +++ b/apps/host/src/screens/Settings.tsx @@ -10,12 +10,15 @@ import { PrivacyNotes } from '../components/PrivacyNotes'; import { AboutVersions, SettingsUpdates } from '../components/SettingsUpdates'; import { NativeOperations } from '../components/NativeOperations'; import { FontChoice } from '../components/FontChoice'; +import { ElectricityPrice } from '../components/ElectricityPrice'; +import { ApprovalNotifySetting, DoneSoundSetting, PortSetting, TraySetting, useShellState } from '../components/ShellSettings'; import { LANGUAGES } from '../lib/i18n'; import { setLanguage } from '../lib/store'; import { CONTENT_FONT_RANGE, setContentFontSize, setDensity, setFocus, setMotion, setShortcuts, setTheme, setTransparency, setUiScale, UI_SCALES, useStore, setSettingsSection } from '../lib/store'; const PANELS = [{ name: 'Appearance', icon: 'sun', sections: ['General', 'Reading & focus'] }, { name: 'Models', icon: 'models', sections: [] }, { name: 'Tools', icon: 'tool', sections: [] }, { name: 'Storage', icon: 'disk', sections: ['Storage'] }, { name: 'Engine', icon: 'engine', sections: [] }, { name: 'About', icon: 'info', sections: ['About', 'Update', 'Privacy'] }] as const; export function SettingsScreen() { const prefs = useStore(s => s); + const [shell, saveShell] = useShellState(); const active = prefs.settingsSection; const scrollRef = useRef<HTMLDivElement>(null); const fields: { @@ -26,11 +29,16 @@ export function SettingsScreen() { control: ReactNode; }[] = [ { section: 'General', label: 'Language', hint: 'Choose the language used throughout Strata.', control: <Select translateLabels={false} ariaLabel={tr("Language")} value={prefs.language} options={[...LANGUAGES]} onChange={value => setLanguage(value as typeof prefs.language)}/> }, + { section: 'General', label: 'Sound when work finishes', hint: 'Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.', aliases: 'audio chime done complete notification', control: <DoneSoundSetting /> }, + { section: 'General', label: 'Notify me when Strata needs an answer', hint: 'In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.', aliases: 'approval permission alert notification manual', control: <ApprovalNotifySetting /> }, + ...(shell?.tray ? [{ section: 'General', label: 'Minimise to tray', hint: 'Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.', aliases: 'tray background close notification area', control: <TraySetting shell={shell} save={saveShell} /> }] : []), + ...(shell?.desktop ? [{ section: 'General', label: 'App port', hint: 'The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.', aliases: 'network address 47831 localhost api', control: <PortSetting shell={shell} save={saveShell} /> }] : []), + { section: 'General', label: 'Electricity price', hint: 'Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.', aliases: 'cost power energy kwh currency money', control: <ElectricityPrice /> }, { section: 'Reading & focus', label: 'Font', hint: 'Choose an installed font for the interface and conversations.', control: <FontChoice /> }, { section: 'General', label: 'Keyboard shortcuts', hint: 'Set the key combinations that feel natural to you.', aliases: 'command keys hotkeys', control: <Btn size="sm" onClick={() => setShortcuts(true)}>{tr("Edit shortcuts")}</Btn> }, { section: 'Reading & focus', label: 'Appearance', hint: 'System follows your computer by default.', aliases: 'theme light dark system automatic', control: <Select value={prefs.theme} ariaLabel={tr("Appearance")} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }, { value: 'system', label: 'System' }]} onChange={setTheme}/> }, { section: 'Reading & focus', label: 'Reading size', hint: 'Conversation text size. Interface controls stay separate.', aliases: 'font text zoom', control: <label className="row"><input aria-label={tr("Reading text size")} type="range" className="st-slider" min={CONTENT_FONT_RANGE.min} max={CONTENT_FONT_RANGE.max} value={prefs.contentFontSize} onChange={e => setContentFontSize(Number(e.target.value))}/><output>{tr(prefs.contentFontSize)}{tr(" px")}</output></label> }, - { section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: <Select value={String(prefs.uiScale)} ariaLabel={tr("Interface size")} options={UI_SCALES.map(v => ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> }, + { section: 'Reading & focus', label: 'Interface size', hint: 'Makes all text, buttons and menus in Strata larger or smaller.', aliases: 'zoom scale font text size bigger smaller 4k 90% 100% 110% 125% 150% 175% 200%', control: <Select value={String(prefs.uiScale)} ariaLabel={tr("Interface size")} options={UI_SCALES.map(v => ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> }, { section: 'Reading & focus', label: 'Spacing', hint: 'Comfortable spacing by default.', aliases: 'density comfortable compact', control: <Select value={prefs.density} ariaLabel={tr("Interface spacing")} options={[{ value: 'comfortable', label: 'Comfortable' }, { value: 'compact', label: 'Compact' }]} onChange={setDensity}/> }, { section: 'Reading & focus', label: 'Motion', hint: 'Reduced motion also disables smooth scrolling.', aliases: 'animation system full reduced', control: <Select value={prefs.motion} ariaLabel={tr("Motion")} options={[{ value: 'system', label: 'Follow system' }, { value: 'full', label: 'Full' }, { value: 'reduced', label: 'Reduced' }]} onChange={setMotion}/> }, { section: 'Reading & focus', label: 'Transparency', hint: 'Translucent controls or solid surfaces. Text stays opaque.', aliases: 'blur glass liquid opaque translucent', control: <Select value={prefs.transparency} ariaLabel={tr("Transparency")} options={[{ value: 'translucent', label: 'Translucent' }, { value: 'opaque', label: 'Opaque' }]} onChange={setTransparency}/> }, diff --git a/apps/host/src/styles/monitor.css b/apps/host/src/styles/monitor.css index ba54c9c9..621c3a69 100644 --- a/apps/host/src/styles/monitor.css +++ b/apps/host/src/styles/monitor.css @@ -89,3 +89,12 @@ .monitor-spark .spark__readout { right: auto; left: 0; max-width: 230px; } .monitor-metric:nth-child(even) .monitor-spark .spark__readout { right: 0; left: auto; } } + +/* The energy and temperature readings (#3628): one thin row under the cards, a label and a value each, wrapping to 3 and 2 columns on narrow windows. */ +.monitor-readings { padding: 12px 20px; } +.monitor-readings dl { margin: 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px 24px; } +.monitor-readings dl > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.monitor-readings dt { color: var(--st-ink-muted); font-size: 12px; } +.monitor-readings dd { margin: 0; font-size: 15px; font-weight: 600; overflow-wrap: anywhere; } +@media (max-width: 1100px) { .monitor-readings dl { grid-template-columns: repeat(3, minmax(0, 1fr)); } } +@media (max-width: 640px) { .monitor-readings { padding: 12px 16px; } .monitor-readings dl { grid-template-columns: repeat(2, minmax(0, 1fr)); } } diff --git a/apps/host/tests/currency.test.mjs b/apps/host/tests/currency.test.mjs new file mode 100644 index 00000000..fa33c0a0 --- /dev/null +++ b/apps/host/tests/currency.test.mjs @@ -0,0 +1,105 @@ +// The currency of the Monitor's cost line (#3628): found from the computer's region, formatted for the person's locale, never guessed. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; +import { parseLocaleTag, parseRegValue, detectRegion } from '../server/region.mjs'; + +const compiled = await build({ stdin: { contents: "export * from './src/lib/currency';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node' }); +const norm = text => text.replace(/\s/g, ' '); // a no-break space becomes a space +const C = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +test('a region maps to its currency, an unknown one to nothing', () => { + for (const [region, code] of [['DE', 'EUR'], ['SI', 'EUR'], ['BG', 'EUR'], ['US', 'USD'], ['GB', 'GBP'], ['JP', 'JPY'], ['CH', 'CHF'], ['BR', 'BRL'], ['KR', 'KRW'], ['CN', 'CNY'], ['IN', 'INR'], ['de', 'EUR']]) + assert.equal(C.currencyForRegion(region), code, region); + assert.equal(C.currencyForRegion('ZZ'), null); + assert.equal(C.currencyForRegion(null), null); + assert.equal(C.currencyForRegion(''), null); + for (const code of Object.values(C.REGION_CURRENCY)) assert.match(code, /^[A-Z]{3}$/); + const known = new Set(Intl.supportedValuesOf('currency')); + const unknown = [...new Set(Object.values(C.REGION_CURRENCY))].filter(code => !known.has(code)); + assert.ok(unknown.length <= 3, `currencies this runtime does not know: ${unknown}`); +}); + +test('the region comes out of a language tag, or the tag has none', () => { + assert.equal(C.regionOfLocale('en-US'), 'US'); + assert.equal(C.regionOfLocale('de_DE.UTF-8'), 'DE'); + assert.equal(C.regionOfLocale('zh-Hans-CN'), 'CN'); + assert.equal(C.regionOfLocale('en'), null); + assert.equal(C.regionOfLocale(''), null); + assert.equal(C.regionOfLocale(undefined), null); +}); + +test('the currency: the override, then the system, then the browser, then the app language, then none', () => { + const windows = { locale: 'en-US', region: 'US', currency: null, source: 'windows' }; + assert.deepEqual(C.resolveCurrency({ system: windows, language: 'en' }), { currency: 'USD', locale: 'en-US', source: 'system' }); + assert.equal(C.resolveCurrency({ system: { locale: 'de-CH', region: 'CH', currency: 'EUR', source: 'linux' }, language: 'en' }).currency, 'EUR', 'a currency the system names wins over its region'); + assert.equal(C.resolveCurrency({ system: windows, language: 'en', override: 'chf' }).currency, 'CHF', 'the picker overrides'); + assert.equal(C.resolveCurrency({ system: windows, language: 'en', override: 'x' }).currency, 'USD', 'a bad override is ignored'); + assert.deepEqual(C.resolveCurrency({ system: null, browserLanguages: ['en', 'sl-SI'], language: 'en' }), { currency: 'EUR', locale: 'sl-SI', source: 'browser' }); + assert.deepEqual(C.resolveCurrency({ system: null, browserLanguages: [], language: 'ja' }), { currency: 'JPY', locale: 'ja', source: 'language' }); + assert.equal(C.resolveCurrency({ system: null, browserLanguages: [], language: 'zh' }).currency, 'CNY'); + assert.equal(C.resolveCurrency({ system: null, browserLanguages: [], language: 'pt' }).currency, 'BRL'); + assert.deepEqual(C.resolveCurrency({ system: null, browserLanguages: ['en'], language: 'en' }), { currency: null, locale: 'en', source: 'none' }, 'English names no region: no currency, never EUR'); + assert.equal(C.resolveCurrency({ system: { locale: null, region: null, currency: null, source: null }, language: 'en' }).currency, null); +}); + +test('money is written for the locale with the usual digits of the currency, and a tiny amount is "less than" one unit', () => { + const us = { currency: 'USD', locale: 'en-US' }, de = { currency: 'EUR', locale: 'de-DE' }, jp = { currency: 'JPY', locale: 'ja-JP' }; + assert.equal(C.formatMoney(1.2345, us), '$1.23'); + assert.equal(C.formatMoney(0.123456, us), '$0.12'); + assert.equal(C.formatMoney(0.01, us), '$0.01'); + assert.equal(C.formatMoney(12.5, us), '$12.50'); + assert.equal(C.formatMoney(0, us), '$0.00'); + assert.equal(C.formatMoney(0.0000339, us), 'less than $0.01', 'not 0.00 and not a run of decimals'); + assert.equal(C.formatMoney(0.0099, us), 'less than $0.01'); + assert.equal(norm(C.formatMoney(1.234, de)), norm('1,23 €')); + assert.equal(norm(C.formatMoney(0.004, de)), norm('less than 0,01 €')); + assert.match(C.formatMoney(3.2, jp), /^[¥¥]3$/); + assert.match(C.formatMoney(0.4, jp), /^less than [¥¥]1$/, 'a currency with no minor unit: below one yen'); + assert.equal(norm(C.formatMoney(0.001, de)), norm('less than 0,01 €')); +}); + +test('the sentence for a tiny amount comes from the caller, so it can be translated', () => { + assert.equal(norm(C.formatMoney(0.001, { currency: 'EUR', locale: 'fr-FR', lessThan: shown => `moins de ${shown}` })), norm('moins de 0,01 €')); + assert.equal(C.minorDigits('USD', 'en-US'), 2); + assert.equal(C.minorDigits('JPY', 'en-US'), 0); + assert.equal(C.minorDigits(null, 'en-US'), 2); +}); + +test('with no currency the number is shown alone, and a broken code or locale never throws', () => { + assert.equal(C.formatMoney(1.2345, { currency: null, locale: 'en-US' }), '1.23'); + assert.equal(C.formatMoney(0.0123456, { currency: null, locale: 'en-US' }), '0.01'); + assert.equal(C.formatMoney(0.001, { currency: null, locale: 'en-US' }), 'less than 0.01'); + assert.equal(C.formatMoney(0, { currency: null, locale: 'en-US' }), '0.00'); + assert.equal(C.formatMoney(1.5, { currency: 'XXXX', locale: 'en-US' }), '1.50'); + assert.equal(C.formatMoney(1.5, { currency: 'USD', locale: 'not a locale!' }), '1.50'); + assert.equal(C.formatMoney(NaN, { currency: 'USD', locale: 'en-US' }), '—'); +}); + +test('the Settings line names the currency with its symbol, and the picker lists every currency', () => { + assert.equal(C.currencyLabel('USD', 'en-US'), 'USD ($)'); + assert.equal(C.currencyLabel('EUR', 'de-DE'), 'EUR (€)'); + assert.equal(C.currencyLabel('ZZZ', 'en-US'), 'ZZZ'); + const choices = C.currencyChoices('en-US'); + assert.ok(choices.length > 100); + assert.ok(choices.some(c => c.value === 'JPY' && /Japanese Yen/.test(c.label))); +}); + +test('the host reads the regional format: Windows, macOS and Linux, and says nothing when there is none', () => { + assert.deepEqual(parseLocaleTag('en_US.UTF-8'), { locale: 'en-US', region: 'US' }); + assert.deepEqual(parseLocaleTag('de_DE@euro'), { locale: 'de-DE', region: 'DE' }); + assert.deepEqual(parseLocaleTag('zh-Hans-CN'), { locale: 'zh-CN', region: 'CN' }); + assert.deepEqual(parseLocaleTag('fr'), { locale: 'fr', region: null }); + assert.deepEqual(parseLocaleTag('C'), { locale: null, region: null }); + assert.deepEqual(parseLocaleTag(undefined), { locale: null, region: null }); + assert.equal(parseRegValue(' LocaleName REG_SZ en-US\r\n', 'LocaleName'), 'en-US'); + const win = values => (cmd, args) => { const key = args.join(' '); for (const [needle, out] of Object.entries(values)) if (key.includes(needle)) return out; throw new Error('not found'); }; + assert.deepEqual(detectRegion({ platform: 'win32', run: win({ LocaleName: ' LocaleName REG_SZ de-DE\r\n' }) }), { locale: 'de-DE', region: 'DE', currency: null, source: 'windows' }); + assert.deepEqual(detectRegion({ platform: 'win32', run: win({ 'Geo /v Name': ' Name REG_SZ SI\r\n', LocaleName: ' LocaleName REG_SZ en\r\n' }) }), { locale: 'en-SI', region: 'SI', currency: null, source: 'windows' }, 'a regional format with no region uses the country setting'); + assert.deepEqual(detectRegion({ platform: 'win32', run: () => { throw new Error('no registry'); } }), { locale: null, region: null, currency: null, source: null }); + assert.deepEqual(detectRegion({ platform: 'darwin', run: () => 'de_CH@currency=EUR\n' }), { locale: 'de-CH', region: 'CH', currency: 'EUR', source: 'macos' }); + assert.deepEqual(detectRegion({ platform: 'darwin', run: () => 'en_GB\n' }), { locale: 'en-GB', region: 'GB', currency: null, source: 'macos' }); + assert.deepEqual(detectRegion({ platform: 'linux', env: { LANG: 'sl_SI.UTF-8' }, run: () => 'int_curr_symbol="EUR "\n' }), { locale: 'sl-SI', region: 'SI', currency: 'EUR', source: 'linux' }); + assert.deepEqual(detectRegion({ platform: 'linux', env: { LC_ALL: 'C' }, run: () => { throw new Error('no locale command'); } }), { locale: null, region: null, currency: null, source: null }); + assert.equal(detectRegion({ platform: 'linux', env: { LC_MONETARY: 'ja_JP.UTF-8', LANG: 'en_US.UTF-8' }, run: () => { throw new Error('x'); } }).region, 'JP', 'the monetary locale comes first'); +}); diff --git a/apps/host/tests/gh-app-features.test.mjs b/apps/host/tests/gh-app-features.test.mjs new file mode 100644 index 00000000..7c12c2bc --- /dev/null +++ b/apps/host/tests/gh-app-features.test.mjs @@ -0,0 +1,230 @@ +// The 0.2.7 GitHub items done in f-027-gh-app: the Power card's readings (#3628), the finished-work sound (#3586), approval +// notifications and the tray choice (#3477), the pinned port (#3402). Hermetic: scratch folders and fake fetch/spawn only. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { EventEmitter } from 'node:events'; +import { build } from 'esbuild'; +import { pickTemperatures, readLinuxTemperatures, parseSsdLine, createWindowsSsdReader } from '../server/temperature-telemetry.mjs'; +import { addEnergy, energyWh } from '../server/energy-meter.mjs'; +import { cleanPrefs, readShellPrefs, writeShellPrefs, parsePortNotice, createShellNotifier, validPort, DEFAULTS } from '../server/shell-prefs.mjs'; +import { parseNvidiaReadings } from '../server/device-probes.mjs'; + +const compiled = await build({ stdin: { contents: "export * from './src/lib/attention'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); +const A = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +test('temperatures: the hottest processor and drive sensor, nothing invented', () => { + assert.deepEqual(pickTemperatures([{ name: 'coretemp', temps: [51000, 56000] }, { name: 'nvme', temps: [41850] }, { name: 'amdgpu', temps: [70000] }]), { cpuTempC: 56, ssdTempC: 42 }); + assert.deepEqual(pickTemperatures([{ name: 'nvme', temps: [-1, 0, 200000] }]), { cpuTempC: null, ssdTempC: null }); + assert.deepEqual(pickTemperatures([]), { cpuTempC: null, ssdTempC: null }); +}); + +test('Linux hwmon folders are read through the injected file functions', async () => { + const files = { '/h/hwmon0/name': 'k10temp\n', '/h/hwmon0/temp1_input': '48500\n', '/h/hwmon1/name': 'nvme\n', '/h/hwmon1/temp1_input': '39000\n', '/h/hwmon2/name': 'acpitz\n' }; + const dirs = { '/h': ['hwmon0', 'hwmon1', 'hwmon2'], '/h/hwmon0': ['name', 'temp1_input'], '/h/hwmon1': ['name', 'temp1_input'], '/h/hwmon2': ['name'] }; + const read = async path => { if (!(path in files)) throw new Error('ENOENT'); return files[path]; }; + const list = async path => { if (!(path in dirs)) throw new Error('ENOENT'); return dirs[path]; }; + assert.deepEqual(await readLinuxTemperatures({ base: '/h', read, list }), { cpuTempC: 49, ssdTempC: 39 }); + assert.deepEqual(await readLinuxTemperatures({ base: '/missing', read, list }), { cpuTempC: null, ssdTempC: null }); +}); + +test('the Windows SSD loop gives a value only for a plausible line and goes stale', () => { + assert.equal(parseSsdLine('ssd 53'), 53); + assert.equal(parseSsdLine('ssd -'), null); + assert.equal(parseSsdLine('ssd 400'), null); + assert.equal(parseSsdLine('something else'), undefined); + let clock = 1000; + const child = Object.assign(new EventEmitter(), { stdout: Object.assign(new EventEmitter(), { unref() {} }), unref() {}, kill() {} }); + const reader = createWindowsSsdReader({ spawnFn: () => child, now: () => clock }); + assert.equal(reader.read(), null, 'no line yet'); + child.stdout.emit('data', 'ssd 47\r\n'); + assert.equal(reader.read(), 47); + clock += 10 * 60 * 1000; + assert.equal(reader.read(), null, 'an old value is not shown'); +}); + +test('GPU energy adds up the held power over the time between ticks, at most 5 s of a gap', () => { + const before = energyWh(); + addEnergy(360, 10_000); // first tick: nothing to add yet + assert.equal(energyWh(), before); + addEnergy(360, 11_000); // 360 W for 1 s = 0.1 Wh + assert.ok(Math.abs(energyWh() - before - 0.1) < 1e-9); + addEnergy(360, 3_600_000); // a sleep of an hour counts as 5 s only + assert.ok(Math.abs(energyWh() - before - 0.6) < 1e-9); + addEnergy(null, 3_601_000); // no reading: nothing added + assert.ok(Math.abs(energyWh() - before - 0.6) < 1e-9); +}); + +test('nvidia-smi fan and clock are read, an unsupported field is no reading', () => { + const [a] = parseNvidiaReadings('GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16, 35, 1800'); + assert.equal(a.fanPct, 35); assert.equal(a.clockMhz, 1800); + const [b] = parseNvidiaReadings('GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16, [N/A], [N/A]'); + assert.equal(b.fanPct, null); assert.equal(b.clockMhz, null); + const [c] = parseNvidiaReadings('GPU-1, 41, 5, 1024'); + assert.equal(c.fanPct, null); +}); + +test('the readings strip lists only what this PC can read and the Settings has the price', () => { + const monitor = readFileSync(new URL('../src/screens/Monitor.tsx', import.meta.url), 'utf8'); + for (const label of ['Energy since start', 'Cost since start', 'GPU fan', 'GPU clock', 'CPU temperature', 'SSD temperature']) assert.ok(monitor.includes(`'${label}'`), label); + assert.match(monitor, /\.filter\(\(line\): line is/); + assert.match(monitor, /readingsStrip\.length \? <section className="st-card monitor-readings"/, 'the whole strip is left out when no reading is available'); + assert.doesNotMatch(monitor, /lines=\{/, 'the Power card keeps its old height'); + const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8'); + assert.match(settings, /label: 'Electricity price'/); +}); + +test('shell prefs: defaults, a valid port, automatic, a refused port, the tray, the language', () => { + const dir = mkdtempSync(join(tmpdir(), 'strata-shell-prefs-')); + try { + const file = join(dir, 'sub', 'shell-prefs.json'); + assert.deepEqual(readShellPrefs(file), DEFAULTS); + assert.deepEqual(writeShellPrefs({ port: 47900 }, file), { port: 47900, tray: false, language: 'en' }); + assert.deepEqual(writeShellPrefs({ tray: true, language: 'de' }, file), { port: 47900, tray: true, language: 'de' }); + assert.throws(() => writeShellPrefs({ port: 80 }, file), /between 1024 and 65535/); + assert.throws(() => writeShellPrefs({ port: 70000 }, file), /between 1024 and 65535/); + assert.equal(readShellPrefs(file).port, 47900, 'a refused port changes nothing'); + assert.equal(writeShellPrefs({ port: null }, file).port, 0); + assert.equal(writeShellPrefs({ language: 'xx' }, file).language, 'de', 'an unknown language is ignored'); + writeFileSync(file, '{ not json'); + assert.deepEqual(readShellPrefs(file), DEFAULTS); + assert.deepEqual(cleanPrefs({ port: '47831', tray: 'yes', language: 'ko' }), { port: 0, tray: false, language: 'ko' }); + assert.ok(validPort(1024) && validPort(65535) && !validPort(1023) && !validPort(65536) && !validPort(47.5)); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('the busy-port notice and the shell notifier come only from the shell', async () => { + assert.deepEqual(parsePortNotice('busy:47831:51234'), { wanted: 47831, used: 51234 }); + assert.equal(parsePortNotice('busy:x:1'), null); + assert.equal(parsePortNotice(undefined), null); + assert.equal(createShellNotifier({ env: {} }), null, 'a browser or a source checkout has no shell'); + assert.equal(createShellNotifier({ env: { STRATA_SHELL_BRIDGE: 'http://example.com:1', STRATA_SHELL_TOKEN: 't' } }), null, 'only a loopback bridge'); + const seen = []; + const notifier = createShellNotifier({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:5555', STRATA_SHELL_TOKEN: 'secret' }, fetcher: async (url, init) => { seen.push([url, init]); return { ok: true, json: async () => ({ shown: true }) }; } }); + assert.deepEqual(await notifier.notify({ title: 'Strata needs your answer', body: 'a & b?' }), { shown: true }); + assert.equal(seen[0][0], 'http://127.0.0.1:5555/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F'); + assert.equal(seen[0][1].headers.authorization, 'Bearer secret'); + assert.equal(seen[0][1].method, 'POST'); +}); + +test('the finished-work sound is opt-in, quiet for quick answers in front, and never twice in a row', async () => { + const base = { enabled: true, durationMs: 20_000, focused: true, now: 1_000_000 }; + assert.equal(A.shouldPlayDone({ ...base, enabled: false }), false); + assert.equal(A.shouldPlayDone({ ...base, durationMs: 1000 }), false, 'a quick answer with the window in front'); + assert.equal(A.shouldPlayDone({ ...base, durationMs: 1000, focused: false }), true, 'the window is in the background'); + assert.equal(A.shouldPlayDone(base), true, 'work that took a while'); + const played = []; + assert.equal(A.playDoneSound(url => ({ volume: 0, play() { played.push(url); return Promise.resolve(); } })), true); + assert.deepEqual(played, ['/strata-done-sound.wav']); + assert.equal(A.shouldPlayDone({ ...base, now: Date.now() + 100 }), false, 'a second chime within two seconds is skipped'); + assert.equal(A.playDoneSound(() => { throw new Error('no audio'); }), false, 'a missing audio device is not an error'); + const wav = readFileSync(new URL('../public/strata-done-sound.wav', import.meta.url)); + assert.equal(wav.toString('latin1', 0, 4), 'RIFF'); + assert.equal(wav.toString('latin1', 8, 12), 'WAVE'); +}); + +test('approval notifications: shell first, the page second, nothing when off or when Strata is in front', async () => { + const notice = { title: 'T', body: 'B' }; + const seen = []; + assert.equal(await A.showNotice(notice, { post: async () => ({ shown: true }), page: () => { seen.push('page'); return true; } }), true); + assert.deepEqual(seen, []); + assert.equal(await A.showNotice(notice, { post: async () => ({ shown: false }), page: () => { seen.push('page'); return true; } }), true); + assert.equal(await A.showNotice(notice, { post: async () => { throw new Error('no shell'); }, page: () => { seen.push('page2'); return false; } }), false); + assert.deepEqual(seen, ['page', 'page2']); + assert.equal(await A.approvalNeeded(false, 'write_file', false), false); + assert.equal(await A.approvalNeeded(true, 'write_file', true), false, 'the person is looking at Strata'); + A.setTranslationLanguage('de'); + assert.match(A.approvalNotice('write_file').body, /write_file/); + assert.notEqual(A.approvalNotice('write_file').title, 'Strata needs your answer'); + A.setTranslationLanguage('en'); + assert.equal(A.approvalNotice('').body, 'The assistant wants to use a tool. Open Strata to approve or deny.'); +}); + +test('every new string exists in all eight languages with the same slots, and does not collide with another catalog', async () => { + const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; + const read = async name => JSON.parse(readFileSync(new URL(`../src/locales/${name}.json`, import.meta.url), 'utf8')); + const withFrench = [...languages, 'fr']; // French is a ninth language of this catalog; the app learns it with the i18n work + const gh = Object.fromEntries(await Promise.all(withFrench.map(async l => [l, await read(`gh-${l}`)]))); + const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort(); + const others = new Set(); + for (const name of ['en', 'tune-en', 'tools-en', 'fix-en']) for (const v of Object.values(await read(name))) others.add(v); + for (const l of withFrench) { + assert.deepEqual(Object.keys(gh[l]), Object.keys(gh.en), l); + for (const [id, source] of Object.entries(gh.en)) { + assert.ok(gh[l][id].trim(), `${l}:${id} is empty`); + assert.deepEqual(slots(gh[l][id]), slots(source), `${l}:${id}`); + if (l !== 'en') assert.notEqual(gh[l][id], source, `${l}:${id} is still English`); + } + } + for (const [id, text] of Object.entries(gh.en)) assert.ok(!others.has(text), `already in another catalog: ${id} ${text}`); + const busyId = Object.keys(gh.en).find(id => gh.en[id].startsWith('Port {0} is used by another program')); + for (const l of languages) { + A.setTranslationLanguage(l); + assert.equal(A.tr('Energy since start'), gh[l].gh01, l); + assert.equal(A.tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.', [47831, 51234]), + gh[l][busyId].replaceAll('{0}', '47831').replaceAll('{1}', '51234'), l); + } + A.setTranslationLanguage('en'); +}); + +test('the interface size scales the whole page, up to 200 percent, and a saved value is checked (#3970)', () => { + const store = readFileSync(new URL('../src/lib/store.ts', import.meta.url), 'utf8'); + assert.match(store, /setProperty\('zoom', state\.uiScale === 1 \? '' : String\(state\.uiScale\)\)/); + assert.match(store, /setProperty\('--st-ui-scale', '1'\)/, 'the token stays at 1 so nothing is scaled twice'); + assert.match(store, /UI_SCALES = \[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]/); + assert.match(store, /\[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]\.includes\(Number\(parsed\.uiScale\)\)/); + const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8'); + assert.match(settings, /Makes all text, buttons and menus in Strata larger or smaller\./); +}); + +test('the port, tray, sound and notification rows are in Settings, and only the desktop app shows the port and the tray', () => { + const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8'); + assert.match(settings, /label: 'Sound when work finishes'/); + assert.match(settings, /label: 'Notify me when Strata needs an answer'/); + assert.match(settings, /\.\.\.\(shell\?\.tray \? \[\{ section: 'General', label: 'Minimise to tray'/); + assert.match(settings, /\.\.\.\(shell\?\.desktop \? \[\{ section: 'General', label: 'App port'/); + const store = readFileSync(new URL('../src/lib/store.ts', import.meta.url), 'utf8'); + assert.match(store, /frame\.code === 'waiting-approval'/); + assert.match(store, /workFinished\(state\.doneSound/); + assert.match(store, /announcePortNotice/); +}); + +test('the host route for the shell: a browser has no shell, the port choice is saved and checked, a notification is not shown', { timeout: 40000 }, async t => { + const { spawn } = await import('node:child_process'); + const { once } = await import('node:events'); + const { createServer } = await import('node:net'); + const { mkdirSync } = await import('node:fs'); + const free = 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 home = mkdtempSync(join(tmpdir(), 'strata-shell-route-')); + let child, exited; + t.after(async () => { if (child && child.exitCode === null) { child.kill(); await exited; } rmSync(home, { recursive: true, force: true, maxRetries: 3 }); }); + mkdirSync(join(home, 'data')); + const port = await free(), base = `http://127.0.0.1:${port}`; + const env = { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_WORKSPACE: join(home, 'work'), STRATA_SETTINGS_FILE: join(home, 'settings.json'), STRATA_COMPONENTS_DIR: join(home, 'components'), STRATA_CONTROL_DIR: join(home, 'no-control'), STRATA_HARNESS_DIR: join(home, 'no-harness'), STRATA_NATIVE_REPO: join(home, 'no-repo'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await free()), STRATA_TUNNEL_PORT: String(await free()), STRATA_BIND: '127.0.0.1', STRATA_REAL_ENGINE: '0', STRATA_AGENT: 'off', STRATA_NO_ACQUIRE: '1', STRATA_PORT_NOTICE: 'busy:47831:' + port, STRATA_TEST_LOCALE: 'de-DE', LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'), XDG_DATA_HOME: join(home, 'xdg-data'), XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config') }; + delete env.STRATA_SHELL_BRIDGE; delete env.STRATA_SHELL_TOKEN; + child = spawn(process.execPath, ['server/index.mjs'], { cwd: join(import.meta.dirname, '..'), windowsHide: true, stdio: 'ignore', env }); + exited = once(child, 'exit'); + let up = false; + for (let n = 0; n < 150 && !up; n++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await new Promise(r => setTimeout(r, 100)); } + assert.ok(up, 'the fixture host started'); + const get = async path => (await fetch(base + path)).json(); + const post = (path, body) => fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const first = await get('/api/shell'); + assert.equal(first.desktop, false); assert.equal(first.tray, false); assert.equal(first.port, port); assert.equal(first.defaultPort, 47831); + assert.equal(first.pinnedPort, null); assert.equal(first.minimizeToTray, false); + assert.deepEqual(first.portNotice, { wanted: 47831, used: port }); + assert.deepEqual(await get('/api/locale'), { locale: 'de-DE', region: 'DE', currency: null, source: 'test' }, 'the host names the regional format; the page maps it to a currency'); + const saved = await post('/api/shell/prefs', { port: 47900, tray: true, language: 'de' }); + assert.equal(saved.status, 200); + const after = await saved.json(); + assert.equal(after.pinnedPort, 47900); assert.equal(after.minimizeToTray, true); + assert.deepEqual(JSON.parse(readFileSync(join(home, 'shell-prefs.json'), 'utf8')), { port: 47900, tray: true, language: 'de' }); + const refused = await post('/api/shell/prefs', { port: 80 }); + assert.equal(refused.status, 400); + assert.match((await refused.json()).error, /between 1024 and 65535/); + assert.equal((await get('/api/shell')).pinnedPort, 47900, 'a refused port changes nothing'); + assert.equal((await (await post('/api/shell/prefs', { port: null })).json()).pinnedPort, null); + assert.deepEqual(await (await post('/api/shell/notify', { title: 'T', body: 'B' })).json(), { shown: false }); +}); diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs index 9e7c7ae7..a6682ca8 100644 --- a/apps/host/tests/locale-gaps.test.mjs +++ b/apps/host/tests/locale-gaps.test.mjs @@ -12,7 +12,7 @@ const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64 test('every tr("...") literal and every command hint has a key in the English catalog, so no language is stuck in English (#3479)', async () => { const known = new Set(); - for (const name of ['en', 'tune-en', 'tools-en', 'fix-en']) for (const v of Object.values(await read(name))) known.add(String(v)); + for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en']) for (const v of Object.values(await read(name))) known.add(String(v)); const missing = []; const scan = async dir => { for (const entry of await readdir(dir, { withFileTypes: true })) { From 3b908cc4f739ea60e49885aa89c8fb1851b9b7c5 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:55:58 +0100 Subject: [PATCH 159/177] Tests: the new catalog is checked in nine languages, French included --- apps/host/tests/gh-app-features.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/host/tests/gh-app-features.test.mjs b/apps/host/tests/gh-app-features.test.mjs index 7c12c2bc..701832c1 100644 --- a/apps/host/tests/gh-app-features.test.mjs +++ b/apps/host/tests/gh-app-features.test.mjs @@ -143,9 +143,9 @@ test('approval notifications: shell first, the page second, nothing when off or }); test('every new string exists in all eight languages with the same slots, and does not collide with another catalog', async () => { - const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; + const languages = ['en', 'zh', 'ja', 'de', 'fr', 'es', 'ru', 'pt', 'ko']; const read = async name => JSON.parse(readFileSync(new URL(`../src/locales/${name}.json`, import.meta.url), 'utf8')); - const withFrench = [...languages, 'fr']; // French is a ninth language of this catalog; the app learns it with the i18n work + const withFrench = languages; const gh = Object.fromEntries(await Promise.all(withFrench.map(async l => [l, await read(`gh-${l}`)]))); const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort(); const others = new Set(); From f1dadd1710563fc44aee7915cd4b32a30787c303 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:03:44 +0100 Subject: [PATCH 160/177] fused_gr: the persistent hyper-connection read's barrier only calls __nanosleep on sm_70 and newer (the sm_60 build of f-027-int2 failed on it) --- src/kernels/cuda/fused_gr.cu | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 6f6f3232..fe867298 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -2797,7 +2797,9 @@ __device__ __forceinline__ bool grid_sync(unsigned* bar, unsigned long long tick while (vb[32] == gen) { if (vb[48] != 0u) { ab = 1; break; } if (clock64() - t0 > (long long) ticks) { atomicExch(&bar[48], 1u); ab = 1; break; } - __nanosleep(64); +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + __nanosleep(64); // (sm_60 has no nanosleep: the barrier spins) +#endif } } if (vb[48] != 0u) ab = 1; From ee1a6efd5ceab1321b19f974bd06333c0c47684c Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:20:55 +0100 Subject: [PATCH 161/177] docs/STRIX_HALO_WINDOWS.md: a Strix Halo Windows guide, measured again on 0.2.7 (#3029) Structure from the guide in PR #3029 by HaiYunChuang (what the PC reaches, memory and the BIOS, the configuration, what is on by default, traps), rewritten for the 0.2.7 install and with every number measured again: the Terminal and the gfx1151 engines built from f-027-int2 (3e468f5de), a local signed test feed, strata launch as a standard test user on the NucBox EVO-X2 (Adrenalin 26.10.1), tools/strata_bench.py over a tunnel. Qwen IQ3_S: 44 tok/s chat, prompts 755 / 821 / 792 tok/s at 4K / 16K / 32K. DeepSeek 2.00 bpw: 12 to 14 tok/s chat, prompts 214 to 342 tok/s. An interleaved A/B of STRATA_SH_STREAM on Windows gfx1151 (three pairs): off is 6.9% faster in chat decode, prompts unchanged. What launch chose and logged is quoted instead of a hand-made config. The first guide's tuning rows (engines 0.1.41 to 0.1.47) are not repeated. Co-authored-by: HaiYunChuang <97429634+HaiYunChuang@users.noreply.github.com> --- docs/README.md | 2 +- docs/STRIX_HALO.md | 2 + docs/STRIX_HALO_WINDOWS.md | 125 +++++++++++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 1 deletion(-) create mode 100644 docs/STRIX_HALO_WINDOWS.md diff --git a/docs/README.md b/docs/README.md index ed4ebe06..9baad441 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,7 +22,7 @@ Use the guide for your GPU and operating system. Model and feature support can d | --- | --- | | NVIDIA RTX 20 / 30 / 40 / 50 | [Install](INSTALL.md#what-you-need) | | AMD Radeon (RX and AI PRO R9700) | [AMD / HIP](AMD_HIP.md) | -| AMD Ryzen AI Max / Strix Halo | [Strix Halo](STRIX_HALO.md) | +| AMD Ryzen AI Max / Strix Halo | [Strix Halo](STRIX_HALO.md), [on Windows](STRIX_HALO_WINDOWS.md) | | Intel Arc on Linux | [Intel Arc](INTEL_ARC.md) | | Apple Silicon | [Mac / Metal](MAC.md) | | More than one GPU | [Multiple GPUs](MULTI_GPU.md) | diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md index e37db19f..72e55c06 100644 --- a/docs/STRIX_HALO.md +++ b/docs/STRIX_HALO.md @@ -32,6 +32,8 @@ change BIOS or kernel settings. The manual Linux toolchain below is for reproduc DeepSeek V4.1-Flash comes with its own engine package on Windows and needs nothing extra: pick the model and the app or `strata launch` downloads it ([DeepSeek on Strix Halo](#deepseek-v41-flash)). +On Windows, [STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md) has the speeds measured on 0.2.7 with Qwen IQ3_S and DeepSeek, how memory is used and the traps. + ## DeepSeek V4.1-Flash The model runs through its own engine, `strata-dsv41`, as on the other platforms ([DEEPSEEK41.md](DEEPSEEK41.md)); on Windows the diff --git a/docs/STRIX_HALO_WINDOWS.md b/docs/STRIX_HALO_WINDOWS.md new file mode 100644 index 00000000..3f4fca8b --- /dev/null +++ b/docs/STRIX_HALO_WINDOWS.md @@ -0,0 +1,125 @@ +# Strix Halo (Ryzen AI Max, gfx1151) on Windows: install, what you get, what to know + +This page is for a Windows PC with a Ryzen AI Max "Strix Halo" chip (Radeon 8060S / 8050S, `gfx1151`). It says what Strata does there out +of the box, what speed to expect with Qwen3.8-Flash-Next IQ3_S and with DeepSeek V4.1-Flash, and the traps on this hardware. The Linux +build, the toolchain and the opt-in switches are on [STRIX_HALO.md](STRIX_HALO.md); the DeepSeek details are in +[DEEPSEEK41.md](DEEPSEEK41.md). + +The structure of this page comes from the first Windows guide for this PC, written by HaiYunChuang (pull request #3029). It measured +engines 0.1.41 to 0.1.47 with a hand-made configuration (`--mmap-experts`, a list of switches, a batch file). Since then the app and +`strata launch` have taken over most of that, so this version describes the 0.2.7 install and every number in it was measured again. + +## 1. What this PC reaches + +Measured on 2026-10-26 on a GMKtec NucBox EVO-X2 (Ryzen AI Max+ 395, 128 GB shared memory: a 64 GB BIOS carve-out for the graphics chip +and 64 GB that Windows sees; Windows 11 Pro, AMD Adrenalin 26.10.1 / driver 32.0.32015.7029). Strata was the 0.2.7 release candidate +(Terminal and engine 0.1.51 built from commit `3e468f5de`, ROCm 10.2.0a20260930). The server was started with `strata launch` and +nothing else was set by hand; the speeds come from `tools/strata_bench.py` against the running server (three runs per test, medians, +the engine's own timings; the model is loaded before the clock starts). The numbers can still move before the release is cut. + +**Qwen3.8-Flash-Next IQ3_S** (`strata launch --family qwen --model iq3_s`; 131,072 tokens of context, int8 KV, pictures on): + +| Test | Result | +| --- | --- | +| Short chat, answer speed | **44.0 tok/s** (40.6 to 59.5: code-like answers are faster than prose) | +| Short chat, time to first token | 0.60 s | +| 4K prompt, read speed | **755 tok/s** (first token after 5.4 s) | +| 16K prompt | **821 tok/s** (19.6 s) | +| 32K prompt | **792 tok/s** (40.6 s) | +| Coding-agent session, 6 turns | 69% of the prompt came from the conversation cache; answers 47 tok/s; 4.5 s to the first token per turn | + +**DeepSeek V4.1-Flash 2.00 bpw** (`strata launch --family deepseek41 --model ist-das-2.00bpw`, Faster mode, the drafter on; the 4K row is +the default 8K context, the others 64K context with `--context 64k`): + +| Test | Result | +| --- | --- | +| Short chat, answer speed | **12.1 to 13.6 tok/s** | +| 4K prompt | **214 to 226 tok/s** (about 19 s to the first token) | +| 16K prompt | **326 tok/s** (51 s) | +| 32K prompt | **342 tok/s** (97 s) | +| Coding-agent session, 6 turns | 70% from the conversation cache; answers 14.2 tok/s; 17 to 31 s to the first token per turn | + +These are speed measurements. They say nothing about answer quality, and the short-chat range depends on the text. The DeepSeek 2.25 bpw set +and the other Qwen sizes were not measured for this page. + +## 2. Memory and the BIOS + +- Allocate a **fixed carve-out** to the graphics chip in the BIOS (64 GB on the measured PC). The engine counts the carve-out and the + RAM that Windows sees as one pool and does not change any BIOS or driver setting. +- The graphics chip and the CPU share that pool. For Qwen IQ3_S the engine reads the experts into RAM, keeps them there (it does not + register the arena with the GPU driver on an integrated chip) and gives the expert cache every slot: the start log says + `expert cache auto ... -> 24576 slots` and `expert arena: NOT registered with the GPU driver (integrated GPU, UMA mode)`. The process held + about 49 GB and 10 GB of RAM stayed free. Close other large programs before you load a model this size. +- The default of four parallel slots takes 7.5 GiB of the shared pool for slot sessions (the log says `--batch: 4 slot sessions ... take + 7.54 GiB`). With IQ3_S the cache still held every expert, so there was nothing to gain from fewer slots here; with a bigger model there may be. + +## 3. Install + +1. Use the Windows app (`Strata-<version>-windows-x64-setup.exe`) or the Terminal. The engine for this chip is the `windows-x86_64-hip-rdna3` + package; the app or `strata launch` downloads it on the first start, and `strata update` keeps it current. +2. Choose the model in the app, or `strata launch --family qwen --model iq3_s`. With model files you already have, add + `--model-path <folder>` (for IQ3_S the two shards are in one folder: shard 1 is the main model, shard 2 holds the per-layer embedding + table and must stay a separate file). +3. The first start took about 20 minutes on the measured PC with the model files already on disk: the engine package (158 MB), the + check of the 84 GB of model files, the picture reader (0.9 GB), the draft layer (about 5 GB) and the one-time pack. The next start + took under two minutes. + +What `strata launch` wrote for IQ3_S, with no switches of mine (these are the settings to copy if you drive the engine by hand): + +``` +--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp <draft layer> +--max-context 131072 --kv int8 --vision --vram-reserve-mib 700 (backend hip, GPU picture reader) +``` + +and for DeepSeek 2.00 bpw: `--max-context 8192 --dspark auto --dspark-conf 0.65 --prefill-chunk 16384`, with `DS4_ASYNC_T=4` in the +environment and the package's `rocm/bin` folder on the library path. + +## 4. What is on by default + +- On `gfx1151` the engine turns on 19 exact speed switches by itself (the start line lists them; `STRATA_GFX1151_DEFAULTS=0` turns them all + off, and a switch you set is kept). They are the ones that give the same answers as without. `STRATA_HC_Q8=1` is also on here (decode + about 9% faster, near-tie tokens can differ); `STRATA_HC_Q8=0` keeps the old read. +- The hipBLASLt table for `gfx1151` ships in the package and is chosen without a setting (`prefill gemm: hipBLASLt tuning enabled (32 rows, + gfx1151, version 100500)` in the log). A hand-built engine has to be pointed at it: [AMD_HIP.md](AMD_HIP.md). +- `--mmap-experts` is not needed. The first Windows guide found that without it the pinned expert arena used up the graphics memory + budget and decode fell to 28 tok/s on engine 0.1.41; the engine on this page sizes the cache from the shared pool and reaches every slot. +- DeepSeek runs in "Faster" mode here: 5 of 6 experts per word. The app and `strata launch` say so; the quality change is small. + +**`STRATA_SH_STREAM` (the shared expert on its own stream) is on by default on `gfx1151`, and on this Windows PC it is slower.** The first +Windows guide found the same on engine 0.1.41 (+13% decode with it off). Measured again on 0.2.7 with Qwen IQ3_S, three starts each, run +in turn (on, off, on, off, on, off), the same quick suite after every start: + +| Start | `STRATA_SH_STREAM` | Chat decode, median of 9 answers (tok/s) | 4K prompt (tok/s) | +| --- | --- | ---: | ---: | +| 1 | 1 (default) | 43.9 | 742.9 | +| 2 | 0 | 48.3 | 742.9 | +| 3 | 1 | 43.6 | 746.8 | +| 4 | 0 | 46.0 | 740.8 | +| 5 | 1 | 43.2 | 745.5 | +| 6 | 0 | 46.6 | 739.4 | + +With the switch off, decode was **6.9% faster** (46.6 against 43.6, the median of the three starts) and the code-like question 14% faster +(67 against 59 tok/s); all three pairs went the same way. The prompt speed did not change. Setting it takes `strata launch ... --set +STRATA_SH_STREAM=0`; it changes only the order the work runs in, so the answers stay the same. Whether Windows `gfx1151` gets this by +default is a separate decision. This is one model, one PC and short answers; DeepSeek was not tested with it. + + +## 5. Traps + +1. **Keep RAM free.** Qwen IQ3_S held 49 GB of 63.6 GB. A browser with many tabs, or a second model, is enough to push the PC into paging. +2. **Do not run two engines.** One model at a time on this PC; `strata launch --status` shows what is serving, `strata launch --stop` ends it. +3. **The graphics driver.** The 2025-03 driver failed at 32K context for DeepSeek. The measured driver is Adrenalin 26.10.1 (32.0.32015.7029). +4. **If Windows resets the driver** (screen flicker, the engine dies mid-answer), see the driver-reset entry in + [TROUBLESHOOTING.md](TROUBLESHOOTING.md#amd-cards). +5. **Other tuning from the first guide** (a longer `--prefill`, `STRATA_PF_*` switches, `--lookup-chain`): those results are for engines + 0.1.41 to 0.1.47 and a hand-made configuration. They were not repeated here, so they are not part of this page. + +## 6. Reproduce it + +``` +strata launch --family qwen --model iq3_s # then, from a source checkout: +python tools/strata_bench.py --url http://127.0.0.1:8080 --runs 3 --long +``` + +`--long` adds the 32K prompt. For DeepSeek add `--context 64k` to `strata launch` first; the default 8K context skips the 16K prompt and +the agent session. From e240850324fef73ebd9571d650d08f6c38a179ba Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:24:30 +0100 Subject: [PATCH 162/177] Docs: Strix Halo Windows guide, plain emphasis and a stray blank line --- docs/STRIX_HALO_WINDOWS.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/STRIX_HALO_WINDOWS.md b/docs/STRIX_HALO_WINDOWS.md index 3f4fca8b..63bdeb0d 100644 --- a/docs/STRIX_HALO_WINDOWS.md +++ b/docs/STRIX_HALO_WINDOWS.md @@ -98,12 +98,11 @@ in turn (on, off, on, off, on, off), the same quick suite after every start: | 5 | 1 | 43.2 | 745.5 | | 6 | 0 | 46.6 | 739.4 | -With the switch off, decode was **6.9% faster** (46.6 against 43.6, the median of the three starts) and the code-like question 14% faster +With the switch off, decode was 6.9% faster (46.6 against 43.6, the median of the three starts) and the code-like question 14% faster (67 against 59 tok/s); all three pairs went the same way. The prompt speed did not change. Setting it takes `strata launch ... --set STRATA_SH_STREAM=0`; it changes only the order the work runs in, so the answers stay the same. Whether Windows `gfx1151` gets this by default is a separate decision. This is one model, one PC and short answers; DeepSeek was not tested with it. - ## 5. Traps 1. **Keep RAM free.** Qwen IQ3_S held 49 GB of 63.6 GB. A browser with many tabs, or a second model, is enough to push the PC into paging. From c77292f09dbee2a6952b38446cd2790b7ef0b468 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:28:05 +0100 Subject: [PATCH 163/177] gfx1151 on Windows: the shared-expert fork (STRATA_SH_STREAM) is off by default Interleaved A/B on a Strix Halo Windows PC (Qwen IQ3_S, engine 0.1.51): chat decode 43.6 tok/s with the fork, 46.6 without (+6.9%), prompts unchanged. Linux gfx1151 and every other architecture keep their table. STRATA_SH_STREAM=1 turns it back on, STRATA_DEFAULTS=026 keeps v0.2.6's table. arch_default_env(arch, defaults026, windows) is a pure rule; arch_defaults_test checks both platforms. --- include/strata/core/arch_defaults.hpp | 4 ++ src/core/arch_defaults.cpp | 17 ++++++++ src/core/arch_defaults_test.cpp | 60 +++++++++++++++++++++++++++ src/core/verify.cpp | 4 +- 4 files changed, 84 insertions(+), 1 deletion(-) diff --git a/include/strata/core/arch_defaults.hpp b/include/strata/core/arch_defaults.hpp index 7062f4b2..2025af48 100644 --- a/include/strata/core/arch_defaults.hpp +++ b/include/strata/core/arch_defaults.hpp @@ -21,6 +21,10 @@ namespace strata::core { /// "gfx1151:sramecc-:xnack-"): empty for every other architecture. `defaults026` (STRATA_DEFAULTS=026, defaults_026.hpp): the gfx12 table of /// v0.2.6 (the five prompt switches only, without the four 0.2.7 decode switches); the one-argument form asks the environment. std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gcn_arch, bool defaults026); +/// The same with the platform given instead of read from the build (a pure rule, so a test can check both). 0.2.7: on Windows the gfx1151 +/// table leaves STRATA_SH_STREAM out (the fork is off, +6.9% decode on a Strix Halo Windows PC, same ids); Linux gfx1151 and every +/// other architecture are unchanged; `defaults026` keeps it in on both. An explicit STRATA_SH_STREAM=1 turns the fork on anywhere. +std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gcn_arch, bool defaults026, bool windows); std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gcn_arch); /// The integrated Radeons (Phoenix / Hawk Point 780M gfx1103, Strix Point 890M / 880M gfx1150, Strix Halo gfx1151) whose diff --git a/src/core/arch_defaults.cpp b/src/core/arch_defaults.cpp index 47b9ba7a..7f2a89fd 100644 --- a/src/core/arch_defaults.cpp +++ b/src/core/arch_defaults.cpp @@ -15,6 +15,14 @@ std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gc } std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gcn_arch, bool defaults026) { +#if defined(_WIN32) + return arch_default_env(gcn_arch, defaults026, true); +#else + return arch_default_env(gcn_arch, defaults026, false); +#endif +} + +std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gcn_arch, bool defaults026, bool windows) { std::vector<std::pair<std::string, std::string>> t; if (strata::kernels::gfx_arch_is_gfx12(gcn_arch)) { // gfx1200 / gfx1201 (RDNA4): the PROMPT half of the gfx1151 table (reported exact on an R9700 in #1478, re-checked @@ -71,6 +79,15 @@ std::vector<std::pair<std::string, std::string>> arch_default_env(const char* gc {"STRATA_PLE_BATCH", "1"}, // the verify window's PLE key / value projections at once (S25) {"STRATA_SH_STREAM", "1"}, // the shared expert on its own stream: decode +1.8% / +6.7% (UD-Q4_K_XL) (140-m) }; + // 0.2.7: Windows gfx1151 leaves the shared-expert fork off (the HIP default). Interleaved A/B on a Strix Halo Windows PC (Qwen + // IQ3_S, engine 0.1.51, 9 chat answers each, 4K prompt): decode 43.9 / 43.6 / 43.2 tok/s with it, 48.3 / 46.0 / 46.6 without + // (+6.9% median), prompts unchanged, the token ids identical either way (docs/STRIX_HALO_WINDOWS.md). Linux gfx1151 keeps the + // fork on until it is measured there. STRATA_SH_STREAM=1 turns it back on; STRATA_DEFAULTS=026 keeps v0.2.6's table. + if (windows && !defaults026) { + for (auto it = t.begin(); it != t.end(); ++it) { + if (it->first == "STRATA_SH_STREAM") { t.erase(it); break; } + } + } return t; } diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index db193a7f..51f70493 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -48,6 +48,66 @@ int main() { CHECK(kv.first != bits); } } + // 0.2.7: STRATA_SH_STREAM. Windows gfx1151 leaves the shared-expert fork off (it measured slower there, same ids); Linux gfx1151, + // the 026 master switch and every other architecture are unchanged. Pure rule: the platform is an argument. + { + auto find = [](const std::vector<std::pair<std::string, std::string>>& t, const char* k) -> const std::string* { + for (const auto& kv : t) if (kv.first == k) return &kv.second; + return static_cast<const std::string*>(nullptr); + }; + for (const char* a : {"gfx1151", "gfx1151:sramecc-:xnack-"}) { + const auto lin = arch_default_env(a, false, false); + const auto win = arch_default_env(a, false, true); + const auto lin26 = arch_default_env(a, true, false); + const auto win26 = arch_default_env(a, true, true); + const std::string* l = find(lin, "STRATA_SH_STREAM"); + CHECK(l != nullptr && *l == "1"); // Linux gfx1151: unchanged, the fork is on + CHECK(find(win, "STRATA_SH_STREAM") == nullptr); // Windows gfx1151: not in the table, so the HIP default (off) applies + CHECK(find(win26, "STRATA_SH_STREAM") != nullptr); // STRATA_DEFAULTS=026: v0.2.6's table on Windows too + CHECK(find(lin26, "STRATA_SH_STREAM") != nullptr); + CHECK(win26 == lin26 && win26 == lin); // under 026 and on Linux the whole table is the same + CHECK(win.size() + 1 == lin.size()); // Windows loses that one entry and nothing else + for (const auto& kv : win) CHECK(find(lin, kv.first.c_str()) != nullptr && *find(lin, kv.first.c_str()) == kv.second); + } + // other architectures: the platform changes nothing + for (const char* a : {"gfx1100", "gfx1030", "gfx1103", "gfx1150", "gfx1152", "gfx1201", "gfx1200", ""}) { + CHECK(arch_default_env(a, false, true) == arch_default_env(a, false, false)); + CHECK(arch_default_env(a, true, true) == arch_default_env(a, true, false)); + } + CHECK(arch_default_env(nullptr, false, true).empty()); + // the build's own platform answers like the explicit form (the one-argument form reads STRATA_DEFAULTS, unset here) + unset("STRATA_DEFAULTS"); +#if defined(_WIN32) + CHECK(arch_default_env("gfx1151") == arch_default_env("gfx1151", false, true)); + CHECK(find(arch_default_env("gfx1151"), "STRATA_SH_STREAM") == nullptr); +#else + CHECK(arch_default_env("gfx1151") == arch_default_env("gfx1151", false, false)); + CHECK(find(arch_default_env("gfx1151"), "STRATA_SH_STREAM") != nullptr); +#endif + // applying the table: an explicit STRATA_SH_STREAM=1 stays 1, an explicit 0 stays 0, and the Windows table does not set it + unset("STRATA_QFUSE"); + put("STRATA_SH_STREAM", "1"); + apply_arch_defaults("gfx1151"); + CHECK(std::getenv("STRATA_SH_STREAM") != nullptr && std::string(std::getenv("STRATA_SH_STREAM")) == "1"); + put("STRATA_SH_STREAM", "0"); + apply_arch_defaults("gfx1151"); + CHECK(std::string(std::getenv("STRATA_SH_STREAM")) == "0"); + unset("STRATA_SH_STREAM"); + unset("STRATA_QFUSE"); + const auto applied = apply_arch_defaults("gfx1151"); + bool sh_set = false; + for (const auto& n : applied) sh_set = sh_set || n == "STRATA_SH_STREAM"; +#if defined(_WIN32) + CHECK(!sh_set); + CHECK(std::getenv("STRATA_SH_STREAM") == nullptr || std::string(std::getenv("STRATA_SH_STREAM")).empty()); +#else + CHECK(sh_set); + CHECK(std::getenv("STRATA_SH_STREAM") != nullptr && std::string(std::getenv("STRATA_SH_STREAM")) == "1"); +#endif + unset("STRATA_SH_STREAM"); + unset("STRATA_QFUSE"); + unset("STRATA_TSUM"); + } // gfx12: the five prompt switches and four bit-identical decode switches, no bit-changing one unset("STRATA_GFX12_DEFAULTS"); for (const char* a : {"gfx1200", "gfx1201", "gfx1201:sramecc-:xnack-"}) { diff --git a/src/core/verify.cpp b/src/core/verify.cpp index ac3f874a..cdb20bef 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -286,7 +286,9 @@ bool batch_self_commits(const int* rows, int S) { return g_batch_self_commit && // profiler turns the fork off to time the stages, so a profiled run never showed that. #816 reports the same fall on a // gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s). STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not. // Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode -// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1. Read on first use, after that table ran. +// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1 on Linux. On Windows gfx1151 the fork is slower (0.2.7, +// Qwen IQ3_S: decode -6.4% with it, ids identical), so there the table leaves it out and this default (off on HIP) applies. +// Read on first use, after that table ran. bool sh_stream_on() { static const bool on = [] { if (const char* v = std::getenv("STRATA_SH_STREAM")) return v[0] != '0'; From f932e410e652ebad126666527a38eceb684017d2 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:00:50 +0100 Subject: [PATCH 164/177] docs: Windows Strix Halo leaves STRATA_SH_STREAM off, with the token-id check; DeepSeek numbers say which build they come from The Windows guide says what 0.2.7 does and how to turn the switch back on, backed by five fixed greedy prompts (895 ids) run four times with the switch on, off, on, off: identical ids. STRIX_HALO.md and the 0.2.7 release notes get a line. The DeepSeek 4K prompt figures of 2026-10-25 (78.7, 87.2) stay and are labelled with their build; a table of the 0.2.7 candidate changes one thing at a time (chunk size, DS4_DEFAULTS=026). --- docs/STRIX_HALO.md | 29 +++++++++++++++++++++++------ docs/STRIX_HALO_WINDOWS.md | 28 ++++++++++++++++++++-------- docs/release-notes-0.2.7.md | 7 +++++++ 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md index 72e55c06..7e0a23c3 100644 --- a/docs/STRIX_HALO.md +++ b/docs/STRIX_HALO.md @@ -5,8 +5,9 @@ shared by the CPU and the GPU). Strata runs there through the same HIP backend a **Status: experimental.** **DeepSeek V4.1-Flash runs here on Windows** (since 0.2.7): its own engine package is built for gfx1151 and the official IST-DAS -1.75 / 2.00 / 2.25 bpw sets run through it. Measured on the 128 GB box (64 GB BIOS carve-out plus 64 GB seen by Windows) with 2.00 bpw and the default Faster mode: answers 15-17 -tokens/s on code, 10-11 on chat; a 4K prompt 87 tokens/s, an 8K prompt 125 and a 32K prompt 177. The graphics chip and the CPU share the RAM, so the +1.75 / 2.00 / 2.25 bpw sets run through it. Measured on the 128 GB box (64 GB BIOS carve-out plus 64 GB seen by Windows) with 2.00 bpw and the default Faster mode, on the +2026-10-25 build (before the DeepSeek defaults of 0.2.7): answers 15-17 tokens/s on code, 10-11 on chat; a 4K prompt 87 tokens/s, an 8K prompt 125 and a 32K prompt 177. +On the 0.2.7 build the same box reads a 4K prompt at 214-233 tokens/s; the table below says which number comes from which build. The graphics chip and the CPU share the RAM, so the engine counts it once and reads the rest of the experts from the SSD. [DeepSeek on Strix Halo](#deepseek-v41-flash) has the details, the driver it needs and the limits. @@ -47,7 +48,8 @@ package is the AMD one built for gfx1151 (`strata-dsv41-...-windows-x86_64-hip-r | Context | 8K default; 32K and 64K work (an 8-hour 32K soak passed) | | Disk | the sets above; keep the files on the NVMe drive, they are read while it answers | -Measured on the maintainers' box (Ryzen AI Max+ 395, 128 GB unified, Windows 11, 2.00 bpw, Faster mode, DSpark auto, engine 0.1.51): +Measured on the maintainers' box (Ryzen AI Max+ 395, 128 GB unified, Windows 11, 2.00 bpw, Faster mode, DSpark auto, engine 0.1.51) on 2026-10-25, with the +build of that day and the DeepSeek stream's own test harness (before the 0.2.7 DeepSeek defaults; the 0.2.7 numbers are in the next table): | Workload | Result | | --- | --- | @@ -59,6 +61,21 @@ Measured on the maintainers' box (Ryzen AI Max+ 395, 128 GB unified, Windows 11, | 32K prompt | about 177 tokens/s | | Stability | 100-request, 1-hour (243 requests) and 8-hour 32K (646 requests) soaks passed on the engine line this package is built from | +Measured again on 2026-10-26 on the same box with the 0.2.7 release candidate (f-027-int2 `3e468f5de`, engine 0.1.51), installed through `strata launch` from a local +signed test feed, 2.00 bpw, Faster mode, DSpark auto, the default 8K context, `tools/strata_bench.py` through the server (three fresh prompts of 4,125 +tokens, 24 new tokens; chat is the median of nine answers of up to 100 tokens). One change at a time, to see which one moved the 4K prompt: + +| Setup on the 0.2.7 candidate | 4K prompt (tok/s) | Chat decode (tok/s) | +| --- | ---: | ---: | +| what `strata launch` writes (`--prefill-chunk 16384`) | 214-226 | 12.1-13.6 | +| `--prefill-chunk 8192` | 229 (214-234) | 14.9 (12.0-18.2) | +| `--prefill-chunk 8192` and `DS4_DEFAULTS=026` (the 0.2.6 DeepSeek defaults) | 139 (133-144) | 13.7 (11.9-22.0) | +| `--prefill-chunk 1024` and `DS4_DEFAULTS=026` | 133 (129-136) | 14.2 (12.3-22.1) | + +The 0.2.7 DeepSeek defaults account for the gap between 139 and 229; the chunk size matters much less than that on this build. The 0.2.7 +candidate with the 0.2.6 defaults still reads 133-139, above the 78.7-87.2 of 2026-10-25 below. That rest is not explained: the build of that +day, the harness and the prompt were different, and only this table changes one thing at a time. Compare numbers within one table, not across. + The verify window runs synchronously on this PC: setup writes `DS4_ASYNC_T=4` in the config's env (`STRATA_DSV41_ASYNC_T=8` restores the engine's default, any other value overrides). The engine's mailbox ("async") path is sized for cards that hold most of the experts and is slower here: measured 2026-10-25 (2.00 bpw, greedy, 256 tokens): code 15.87-16.33 → 20.14-21.28 tok/s @@ -67,7 +84,7 @@ the scheduling changes, and the drafter's own single-token windows stay async. T (its experts leave no room for it) and does not change. Prompts are read in 8,192-token chunks: setup writes `--prefill-chunk 8192` on this PC (STRATA_DSV41_NO_BIG_CHUNK=1 leaves the -engine's 1,024-token default). Measured 2026-10-25: 4K 78.7 → 87.2, 8K 108.9 → 125.1, 32K 155.2 → 176.9 tok/s; decode unchanged +engine's 1,024-token default). Measured 2026-10-25 (the build of that day, before the 0.2.7 defaults): 4K 78.7 → 87.2, 8K 108.9 → 125.1, 32K 155.2 → 176.9 tok/s; decode unchanged (16.53 → 16.59), because the chunk buffers take ~5 GB from the GPU expert tier and the RAM store's hit rate rises to compensate. The chunk's summation order changes, not the model (the repo's chunk-size KL check: 1024 0.1705, 2048 0.1692, 4096 0.1688, 8192 0.1695). @@ -169,7 +186,7 @@ kernel): they change speed, not answers. Nothing here applies to CUDA or to anot | `STRATA_Q8_PACKED`, `STRATA_Q6_PACKED`, `STRATA_MMVF_ROWS`, `STRATA_ATTN_LANECELL` | Decode layouts and kernels: packed Q8_0 / Q6_K weights, 4-row BF16 GEMV, one-cell-per-thread attention scores. | | `STRATA_EXPERT_V2`, `STRATA_TSUM`, `STRATA_LFUSE` | The grouped decode experts (IQ3_S / IQ4_NL), single-butterfly warp sums, fewer launches around the shared expert and the KV append. | | `STRATA_GDN_SPLIT`, `STRATA_QFUSE`, `STRATA_PLE_BATCH` | The GDN step over four blocks per head, activation images written by their producers, the PLE key / value projections of a verify window at once. | -| `STRATA_SH_STREAM=1` | The shared expert on a second stream beside the routed experts. Off by default on other AMD cards, but it pays on gfx1151 (decode +1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL at 8K). | +| `STRATA_SH_STREAM=1` | The shared expert on a second stream beside the routed experts. Off by default on other AMD cards, but it pays on Linux gfx1151 (decode +1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL at 8K). **Off by default on Windows gfx1151 since 0.2.7:** it measured 6.9% slower there with the same token ids ([STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md)). `STRATA_SH_STREAM=1` turns it back on. | Two further defaults change bits. `STRATA_HC_Q8` reads the hyper-connection weights as 8-bit (`STRATA_HC_Q8=0` restores the BF16 read), and on Windows the prompt is read in chunks of 8192 tokens (`STRATA_GFX1151_CHUNK=0` keeps 6144). About `STRATA_HC_Q8`: it @@ -274,7 +291,7 @@ more than the differences because other jobs shared the box, so read them as unc | IQ3_XXS | 8K | 1,127 -> 1,212 (+7.6%) | 51.64 -> 50.95 (-1.3%) | | IQ3_XXS | 128K | 1,252 -> 1,250 (-0.1%) | 50.88 -> 50.22 (-1.3%) | -With the shared-expert stream (`STRATA_SH_STREAM=1`, now a default) at 8K, 4 pairs: UD-IQ4_XS output 53.1 -> 54.05 (+1.8%), +With the shared-expert stream (`STRATA_SH_STREAM=1`, a default on Linux; Windows leaves it off since 0.2.7) at 8K, 4 pairs: UD-IQ4_XS output 53.1 -> 54.05 (+1.8%), UD-Q4_K_XL 49.5 -> 52.8 (+6.7%), prompt unchanged. **Other switch measurements** (Measured on: the same Ryzen AI Max+ 395) diff --git a/docs/STRIX_HALO_WINDOWS.md b/docs/STRIX_HALO_WINDOWS.md index 63bdeb0d..65681fa9 100644 --- a/docs/STRIX_HALO_WINDOWS.md +++ b/docs/STRIX_HALO_WINDOWS.md @@ -42,6 +42,10 @@ the default 8K context, the others 64K context with `--context 64k`): These are speed measurements. They say nothing about answer quality, and the short-chat range depends on the text. The DeepSeek 2.25 bpw set and the other Qwen sizes were not measured for this page. +The DeepSeek 4K prompt here (214 to 226 tok/s) is higher than the 87 tok/s on [STRIX_HALO.md](STRIX_HALO.md), which was measured on 2026-10-25 with an +earlier build. The 0.2.7 DeepSeek defaults explain most of the gap (the same build with `DS4_DEFAULTS=026` reads 133 to 139 tok/s); the table there +changes one thing at a time. + ## 2. Memory and the BIOS - Allocate a **fixed carve-out** to the graphics chip in the BIOS (64 GB on the measured PC). The engine counts the carve-out and the @@ -76,7 +80,7 @@ environment and the package's `rocm/bin` folder on the library path. ## 4. What is on by default -- On `gfx1151` the engine turns on 19 exact speed switches by itself (the start line lists them; `STRATA_GFX1151_DEFAULTS=0` turns them all +- On `gfx1151` the engine turns on exact speed switches by itself (19 on Linux, 18 on Windows, which leaves `STRATA_SH_STREAM` out, see below; the start line lists them; `STRATA_GFX1151_DEFAULTS=0` turns them all off, and a switch you set is kept). They are the ones that give the same answers as without. `STRATA_HC_Q8=1` is also on here (decode about 9% faster, near-tie tokens can differ); `STRATA_HC_Q8=0` keeps the old read. - The hipBLASLt table for `gfx1151` ships in the package and is chosen without a setting (`prefill gemm: hipBLASLt tuning enabled (32 rows, @@ -85,13 +89,14 @@ environment and the package's `rocm/bin` folder on the library path. budget and decode fell to 28 tok/s on engine 0.1.41; the engine on this page sizes the cache from the shared pool and reaches every slot. - DeepSeek runs in "Faster" mode here: 5 of 6 experts per word. The app and `strata launch` say so; the quality change is small. -**`STRATA_SH_STREAM` (the shared expert on its own stream) is on by default on `gfx1151`, and on this Windows PC it is slower.** The first -Windows guide found the same on engine 0.1.41 (+13% decode with it off). Measured again on 0.2.7 with Qwen IQ3_S, three starts each, run -in turn (on, off, on, off, on, off), the same quick suite after every start: +**`STRATA_SH_STREAM` (the shared expert on its own stream) is off by default on Windows `gfx1151` in 0.2.7, because it is slower there.** It stays +on by default on Linux `gfx1151`, where it was measured to help ([STRIX_HALO.md](STRIX_HALO.md)). The first Windows guide found the Windows +result on engine 0.1.41 (+13% decode with it off). Measured again on the 0.2.7 build as it was before this default changed (the switch was +on), with Qwen IQ3_S, three starts each, run in turn (on, off, on, off, on, off), the same quick suite after every start: | Start | `STRATA_SH_STREAM` | Chat decode, median of 9 answers (tok/s) | 4K prompt (tok/s) | | --- | --- | ---: | ---: | -| 1 | 1 (default) | 43.9 | 742.9 | +| 1 | 1 (the default then) | 43.9 | 742.9 | | 2 | 0 | 48.3 | 742.9 | | 3 | 1 | 43.6 | 746.8 | | 4 | 0 | 46.0 | 740.8 | @@ -99,9 +104,16 @@ in turn (on, off, on, off, on, off), the same quick suite after every start: | 6 | 0 | 46.6 | 739.4 | With the switch off, decode was 6.9% faster (46.6 against 43.6, the median of the three starts) and the code-like question 14% faster -(67 against 59 tok/s); all three pairs went the same way. The prompt speed did not change. Setting it takes `strata launch ... --set -STRATA_SH_STREAM=0`; it changes only the order the work runs in, so the answers stay the same. Whether Windows `gfx1151` gets this by -default is a separate decision. This is one model, one PC and short answers; DeepSeek was not tested with it. +(67 against 59 tok/s); all three pairs went the same way. The prompt speed did not change. + +The answers stay the same: on the same PC and build I ran five fixed greedy prompts (a short question, a code request, an explanation, a +4,091-token prompt and a 16,383-token prompt; 895 generated token ids) through the engine four times, with the switch on, off, on, off. The +token ids were identical in all four runs for every prompt. + +What 0.2.7 does: on Windows `gfx1151` the engine no longer turns the switch on by itself. To turn it back on, use `strata launch ... +--set STRATA_SH_STREAM=1` (or put `STRATA_SH_STREAM=1` in the environment of an engine you start by hand); a value you set is always kept. +`STRATA_DEFAULTS=026` brings back everything 0.2.6 did, including the switch on. This is one model, one PC and short answers; DeepSeek was +not tested with it, and Linux `gfx1151` has not been measured against it. ## 5. Traps diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 6e806ade..a3762278 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -41,6 +41,13 @@ A variable or flag you set yourself (`DS4_ATTN_SLAB=N`, `STRATA_ROUTE_PRIOR=2`, `--ple-io`) still wins over the switch. The older single switches (`DS4_FAST_ATTN=0`, `DS4_ATTN_SLAB=0`, `DS4_COPY_PIN=0`, `DS4_COPY_HUGETLB=0`, `DS4_STORE_SPARE=0`, `DS4_STORE_PUT=0`, `STRATA_ROUTE_PRIOR=0`, ...) work as before. +- **Strix Halo (`gfx1151`) on Windows: the shared expert no longer runs on its own stream.** `STRATA_SH_STREAM` was on by default on + `gfx1151`; on a Windows PC it is slower. Qwen3.8-Flash-Next IQ3_S, three interleaved pairs: chat decode **43.6 -> 46.6 tokens/s (+6.9%)** + with it off, prompts unchanged. The answers are the same: five fixed greedy prompts (up to 16,383 tokens) gave identical token ids with + the switch on and off, in four runs. Linux `gfx1151` keeps it on, other cards are untouched. Turn it back on with + `STRATA_SH_STREAM=1`; `STRATA_DEFAULTS=026` restores the 0.2.6 behaviour. Details and the other numbers of that PC: + [docs/STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md). + ## What is faster if your PC is set up for it These need no engine change; they are settings. Each was measured on the same boxes. From 0afaaa399edd1473bde475ed44fa8da9a697a4ef Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:26:18 +0100 Subject: [PATCH 165/177] Route prior: the 0.2.7 default on a discrete NVIDIA card of 13 GiB or less drops from 2.0 to 1.5 (owner decision 2026-10-26). On the RTX 3060 12 GB (IQ3_XXS) the copy and code check found real defects at 2.0 and none in 19 tasks at 1.5 or 1.0; 1.5 keeps story +15% and code +37% against off. The value lives in strata::kRoutePriorSmallCard (sm120_series.hpp); scope (CUDA discrete <= 13 GiB), STRATA_ROUTE_PRIOR=0, an explicit value and STRATA_DEFAULTS=026 are unchanged. arch_defaults_test, verify.cpp comments, DETAILS.md and the 0.2.7 release notes follow. --- docs/DETAILS.md | 4 ++-- docs/release-notes-0.2.7.md | 14 +++++++++----- include/strata/core/sm120_series.hpp | 12 +++++++++--- src/core/arch_defaults_test.cpp | 15 ++++++++------- src/core/verify.cpp | 10 ++++++---- 5 files changed, 34 insertions(+), 21 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index e0b9a7d1..eb945132 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -957,7 +957,7 @@ them on your own card. | `STRATA_PREFILL_EQUAL=1` | CUDA | A prompt segment is read in chunks of equal size, not full chunks and a short last one. Changes rounding. | | | `STRATA_OWNED_PRICE=exact` | CUDA | The cache sizing prices the prompt path's own buffers by their real allocation. | | | `STRATA_IQ_MT_MIN=1`, `STRATA_IQ3S_MT1=1` | CPU | See [Draft layer](#draft-layer) (reproducible output; the second gives IQ3_S the multi-token kernel for one token on Alder Lake and later without AVX-512). | | -| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended, except that 0.2.7 turns `STRATA_ROUTE_PRIOR=2.0` on by itself on a discrete NVIDIA card of 13 GiB or less (the owner approved the quality trade for 12 GB cards); `STRATA_ROUTE_PRIOR=0` turns it off. It is never a default on a Radeon, an integrated GPU or a bigger card. | +| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended, except that 0.2.7 turns `STRATA_ROUTE_PRIOR=1.5` on by itself on a discrete NVIDIA card of 13 GiB or less (the owner approved the quality trade for 12 GB cards; the first 0.2.7 candidates used 2.0, see the 12 GB default in the release notes for why it is 1.5); `STRATA_ROUTE_PRIOR=0` turns it off and an explicit value wins. It is never a default on a Radeon, an integrated GPU or a bigger card. | | `STRATA_HOST_CORE=last\|sibling` (or `--host-core`) | Windows | `last` puts the host thread on the last physical core, away from the core that gets the GPU's interrupts. `sibling` keeps it on the first core's other hardware thread, so the workers keep every core. The default `first` leaves a hybrid CPU as it is. | One layer-split box went from a ±6% swing to steady and 8% faster. | | `--pool-affinity measure` | Hybrid CPUs, native packs | Times the `all` and `p-cores` layouts at start (about a second) and takes the faster. The measurement is taken once; where the E-cores' speed changes while the engine runs, `--pool-affinity p-cores` is the steady choice. | | | `STRATA_KEEP_EMPTY_TURNS=1`, `STRATA_TOPK_STREAM=0` | | See [TROUBLESHOOTING.md](TROUBLESHOOTING.md). | | @@ -1137,7 +1137,7 @@ On 12.0 cards (sm_120) these also apply: prompt time and start-up time, which is why smaller PCs keep the SSD reads. A prompt chunk above 8192 (`--prefill auto:16384` or `auto:32768`) is not bit-exact on CUDA, so the default stays 8192 on -NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR` raises KL, so below 0.2.7 it was opt-in; 0.2.7 sets 2.0 by itself only on a discrete NVIDIA card of 13 GiB or less. +NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR` raises KL, so below 0.2.7 it was opt-in; 0.2.7 sets 1.5 by itself only on a discrete NVIDIA card of 13 GiB or less. --- diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index a3762278..8c0081cf 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -74,10 +74,14 @@ These need no engine change; they are settings. Each was measured on the same bo ## The 12 GB default: residency-biased routing -**On by default at 2.0 on a discrete NVIDIA card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off; +**On by default at 1.5 on a discrete NVIDIA card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off, an explicit value wins; not a default on a Radeon, a Strix Halo or any integrated GPU, where it was not measured). The router prefers -experts that are already resident, so a window stops waiting on a page-in that the next window would need again. Measured -on the RTX 3060 12 GB (IQ3_XXS), five interleaved pairs of fresh engines: +experts that are already resident, so a window stops waiting on a page-in that the next window would need again. The first +0.2.7 candidates used a bonus of 2.0, and the table below was measured at 2.0 on the RTX 3060 12 GB (IQ3_XXS), five interleaved +pairs of fresh engines. The default was lowered to 1.5 by the owner on 26 October after the copy and code check on that card +(IQ3_XXS) found real defects in the answers at 2.0 and **no defect in 19 tasks at 1.5** (or at 1.0). 1.5 keeps most of the speed: +story **+15%** and code **+37%** against the routing off. That is 19 tasks, not a proof; a longer 61-task check of 0, 1.5 and 2.0 +is still running, and if it shows defects at 1.5 the default falls back to 1.0. The 2.0 measurements: | axis | before | after | |---|---|---| @@ -94,8 +98,8 @@ document prompt), and the whole recipe - routing, a workload-fitted expert profi 896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. It works by choosing a slightly different set of experts, so replies change: the owner approved that trade for 12 GB cards. -**Do not raise the bonus beyond 2.0.** 3.0 measures +17.7% / +24.0% on the test prompts but **-4.5% on held-out content**, -and 4.0 breaks outright - 2.0 is the setting that generalises. +**Do not raise the bonus to 2.0 or more.** 2.0 showed defects in the copy and code check; 3.0 measures +17.7% / +24.0% on the test +prompts but **-4.5% on held-out content**, and 4.0 breaks outright. `STRATA_ROUTE_PRIOR=2` still works if you want the old value. ## What was tried and did not make it diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index 8a6932a6..d21d5b05 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -49,10 +49,16 @@ inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) // `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory. constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0 -/// STRATA_ROUTE_PRIOR when the user set nothing: 2.0 (residency-biased routing, changes which experts run; owner-approved for 12 GB cards) on a -/// discrete CUDA card of 13 GiB or less, 0 everywhere else. Measured on an RTX 3060 12 GB only. +/// The residency-bias bonus a discrete CUDA card of 13 GiB or less gets when the user set nothing: THE one place the value lives. 1.5 since the +/// owner decision of 2026-10-26 (it was 2.0 in the first 0.2.7 candidates): on the RTX 3060 12 GB with IQ3_XXS the copy and code check found real +/// defects at 2.0 and none in 19 tasks at 1.5 or 1.0, and 1.5 keeps the speed (story +15%, code +37% against off). A longer 61-task check of +/// 0 / 1.5 / 2.0 is still running; if it shows defects at 1.5 this falls back to 1.0. +constexpr float kRoutePriorSmallCard = 1.5f; + +/// STRATA_ROUTE_PRIOR when the user set nothing: kRoutePriorSmallCard (residency-biased routing, changes which experts run; owner-approved for 12 GB +/// cards) on a discrete CUDA card of 13 GiB or less, 0 everywhere else. Measured on an RTX 3060 12 GB only. inline float route_prior_default(bool hip, bool integrated, double total_bytes, bool v026 = false) { - return !v026 && !hip && !integrated && total_bytes > 0.0 && total_bytes / 1073741824.0 <= kSmallCardGiB ? 2.0f : 0.0f; + return !v026 && !hip && !integrated && total_bytes > 0.0 && total_bytes / 1073741824.0 <= kSmallCardGiB ? kRoutePriorSmallCard : 0.0f; } /// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index 51f70493..ac80d4dd 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -293,8 +293,8 @@ int main() { using namespace strata; CHECK(is_026_token("026") && is_026_token("0.2.6") && is_026_token("v0.2.6")); CHECK(!is_026_token(nullptr) && !is_026_token("") && !is_026_token("0") && !is_026_token("027")); - // residency-biased routing: 0 under 026 on the card that gets 2.0 otherwise - CHECK(route_prior_default(false, false, 12.0 * GiB, false) == 2.0f); + // residency-biased routing: 0 under 026 on the card that gets 1.5 otherwise + CHECK(route_prior_default(false, false, 12.0 * GiB, false) == 1.5f); CHECK(route_prior_default(false, false, 12.0 * GiB, true) == 0.0f); CHECK(route_prior_default(false, false, 8.0 * GiB, true) == 0.0f); // the wide HC up read: on for a 12.0 card on CUDA, off under 026, off in HIP, off on sm_86 / sm_121 @@ -340,11 +340,12 @@ int main() { { const double GiB = 1073741824.0; using namespace strata; - // residency-biased routing: 2.0 on a discrete CUDA card of 13 GiB or less, nothing else - CHECK(route_prior_default(false, false, 11.9 * GiB) == 2.0f); // RTX 3060 / 5070 12 GB - CHECK(route_prior_default(false, false, 12.0 * GiB) == 2.0f); - CHECK(route_prior_default(false, false, 8.0 * GiB) == 2.0f); // an 8 GB card - CHECK(route_prior_default(false, false, 13.0 * GiB) == 2.0f); // the boundary is inclusive + // residency-biased routing: 1.5 on a discrete CUDA card of 13 GiB or less, nothing else + CHECK(route_prior_default(false, false, 11.9 * GiB) == 1.5f); // RTX 3060 / 5070 12 GB + CHECK(route_prior_default(false, false, 12.0 * GiB) == 1.5f); + CHECK(route_prior_default(false, false, 8.0 * GiB) == 1.5f); // an 8 GB card + CHECK(route_prior_default(false, false, 13.0 * GiB) == 1.5f); // the boundary is inclusive + CHECK(route_prior_default(false, false, 12.0 * GiB) == strata::kRoutePriorSmallCard); // the one place the value lives (1.5 by the owner decision of 2026-10-26; 2.0 before) CHECK(route_prior_default(false, false, 13.5 * GiB) == 0.0f); CHECK(route_prior_default(false, false, 15.7 * GiB) == 0.0f); // 16 GB card: z440's A4000, P100 CHECK(route_prior_default(false, false, 72.0 * GiB) == 0.0f); // RTX PRO 5000 diff --git a/src/core/verify.cpp b/src/core/verify.cpp index cdb20bef..4d651947 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -206,8 +206,10 @@ inline int g_side_mixer() { #endif } // STRATA_ROUTE_PRIOR=lambda: residency-biased routing (the top-10 picked again with a logit bonus for the resident -// experts; route_prior.cu). Unset: 2.0 on a DISCRETE NVIDIA card of 13 GiB or less (CUDA builds only), 0 elsewhere. -// Measured on an RTX 3060 12 GB only (IQ3_XXS, 5 interleaved pairs: +37.6% / +35.2% decode); the owner approved the +// experts; route_prior.cu). Unset: 1.5 (strata::kRoutePriorSmallCard, sm120_series.hpp; it was 2.0 until the owner decision of +// 2026-10-26: defects in the copy and code check at 2.0, none in 19 tasks at 1.5) on a DISCRETE NVIDIA card of 13 GiB or less +// (CUDA builds only), 0 elsewhere. +// Measured on an RTX 3060 12 GB only (IQ3_XXS, 5 interleaved pairs at 2.0: +37.6% / +35.2% decode; at 1.5 story +15%, code +37%); the owner approved the // quality trade for 12 GB cards (it changes which experts run). Not a default in a HIP build (a 12 GB Radeon, or a // Strix Halo whose reported VRAM is a small carve-out of unified memory: unmeasured there) and not on an integrated GPU. // STRATA_ROUTE_PRIOR=0 turns it off, any other value wins everywhere. The default is read from the device properties @@ -2002,8 +2004,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; } // STRATA_ROUTE_PRIOR=lambda (changes the output): the top-10 picked again with a logit bonus for the resident - // experts; the weights stay the router's (route_prior.cu). The default is g_route_prior() above: 2.0 on a - // discrete CUDA card of 13 GiB or less, off elsewhere (measured on an RTX 3060 12 GB: story +37.6%, code +35.2%; + // experts; the weights stay the router's (route_prior.cu). The default is g_route_prior() above: 1.5 on a + // discrete CUDA card of 13 GiB or less, off elsewhere (measured on an RTX 3060 12 GB at 2.0: story +37.6%, code +35.2%; // on an RTX PRO 5000 72 GB -1.9% / -0.5%, on 2x RTX A4000 -4.2% / +11.0%, hence not a default on bigger cards). const float route_prior = g_route_prior(); if (route_prior > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) From 10c8cc629f65f068705a43c7fbc3a7b464dfd904 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:45:47 +0100 Subject: [PATCH 166/177] Prefill fused IQ experts: opt-in f16 mma path STRATA_PF_FUSED_F16=1 and warp-specialized kernel STRATA_PF_FUSED_WS=1 (#3779, #3712) Problem: the NT = 256 kernels still decode every 32 values to int8 and scale the int32 products in FP32. Change, both opt-in and both rounding-level (the output is not bit-identical to the int8 kernels; they are the PR's "rounding-level" switches): - STRATA_PF_FUSED_F16=1 (implies the NT = 256 set): the decoded weights times their block scales and the activations times theirs as F16, m16n8k16 F16 products into FP32 accumulators. The k order inside a 16-value group is permuted the same way for both operands. - STRATA_PF_FUSED_WS=1: native_ws_kernel, producer warps decode into an F16 ring in shared memory and consumer warps run the same F16 products (named barriers), so it has the F16 path's rounding. One block per multiprocessor; about 101 KB of shared memory at its defaults, so it is set up on sm_80 / sm_90 cards and says "not available" and keeps the 512-thread kernels on an sm_86 / sm_89 / sm_120 card (99 KB). Compile-time knobs STRATA_WS_PROD / _SLOTS / _NB / _KS / _HTAB. - Both take a WideBatch like the NT = 256 kernels, so STRATA_PF_BATCH above 128 reaches them. CUDA only (under !__HIPCC__); the Turing pass compiles the F16 instances against __trap() stubs and never runs them (dev_info stops before the NT = 256 setup on Turing). - With neither variable set the kernels, their launches and their shared-memory sizes are as before (the F16 template parameter defaults to false). Differs from the PR as submitted: when STRATA_PF_FUSED_Q2N=1 is on as well (#3809, after the PR was written) the WS setup also sets up the Q2_0 gate/up instance. Tests: prefill_fused_iq_test_f16 and prefill_fused_iq_test_ws (ctest) run the fused-experts test (double-precision reference and MMQ) with the switch set. The test now skips (77) when a requested NT / F16 / WS kernel set is not set up on the device, so a card that cannot run WS does not report a pass for the 512-thread kernels. Limits of the test for these two arms only: with STRATA_PF_FUSED_F16=1 or _WS=1 the test uses the limits it already has for STRATA_PF_F16 (F16 products): fused against the int8-rounded model rel RMS 5e-3 (2e-3 otherwise) and against MMQ 5e-3 (1e-3 otherwise). Measured with F16 on an RTX A4000 (sm_86, z440), over the 11 pairs: against the int8-rounded model rel RMS 2.85e-3 to 2.90e-3 and worst row 5.9e-3 to 8.1e-3; against MMQ the same; against the FP32 reference 1.438e-2 to 1.480e-2 with MMQ at 1.435e-2 to 1.478e-2 (the fused path stays within 1.003x of MMQ's rel RMS and 1.03x of its worst row). The rounding is the F16 rounding of the weights times their scales and of the activations times theirs (an 11-bit mantissa, about 2^-11 relative per operand), which the int8-rounded model does not have; it is not a different summation order. The same arm on an RTX PRO 5000 (sm_120): up to 2.90e-3 (rel RMS), worst row up to 8.1e-3. The default path and the NT=256 arm keep the old limits and their printed errors are unchanged: with no switch set the test prints identical output (52 lines) from the base tree and this tree, on an RTX A4000 (sm_86) and on an RTX PRO 5000 (sm_120). Reporter's numbers (linxuhao, CMP 170HX): one MoE layer of 3,256 tokens 8.27 ms (NT = 256) to 7.90 ms (F16) and 7.65 ms (WS); prompts +2..+6 % over the 256-thread kernels, 1 of 11 greedy answers changes. Teacher-forced KL against the bitwise base on their 20-prompt set: F16 / WS mean 0.0062, median 0.00006, max 0.076, top-1 100 %. Theirs, not measured here. Original change by linxuhao (PR #3779, commit 579cbfbb). --- CMakeLists.txt | 7 + include/strata/prefill/moe_fused.hpp | 3 +- include/strata/prefill/moe_fused_iq.hpp | 6 +- src/prefill/moe_fused_iq.cu | 501 ++++++++++++++++++++++-- src/prefill/prefill.cpp | 3 +- tests/cuda/prefill_fused_iq_test.cpp | 17 +- 6 files changed, 497 insertions(+), 40 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a7183b2e..216c669b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2092,6 +2092,13 @@ if(STRATA_NATIVE_EXPERTS) # same references; the batches of the test reach them through the Batch overload of experts_native (77 below sm_80) add_test(NAME prefill_fused_iq_test_nt256 COMMAND prefill_fused_iq_test) set_tests_properties(prefill_fused_iq_test_nt256 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_NT=256" SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_F16=1 (f16 mma, rounding level) and STRATA_PF_FUSED_WS=1 (warp-specialized, the same F16 products; + # about 101 KB of shared memory at its defaults, more than an sm_86 / sm_89 / sm_120 card's 99 KB, so it is set up on + # sm_80 and sm_90 cards and the test skips (77) elsewhere) + add_test(NAME prefill_fused_iq_test_f16 COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_f16 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_F16=1" SKIP_RETURN_CODE 77 TIMEOUT 600) + add_test(NAME prefill_fused_iq_test_ws COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_ws PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_WS=1" 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) diff --git a/include/strata/prefill/moe_fused.hpp b/include/strata/prefill/moe_fused.hpp index 47df7144..b69bf660 100644 --- a/include/strata/prefill/moe_fused.hpp +++ b/include/strata/prefill/moe_fused.hpp @@ -66,7 +66,8 @@ struct Batch { const uint8_t* blob[kMaxBatch] = {}; }; /// Batch with room for kBatchRoom experts (e1 - e0 <= kBatchRoom): only the opt-in launches of STRATA_PF_BATCH above -/// kMaxBatch on the native NT = 256 kernels (moe_fused_iq.hpp, native_wide()) take it; every other launch takes Batch. +/// kMaxBatch on the native NT = 256 or warp-specialized kernels (moe_fused_iq.hpp, native_wide()) take it; every other +/// launch takes Batch. struct WideBatch { int e0 = 0, e1 = 0; const uint8_t* blob[kBatchRoom] = {}; diff --git a/include/strata/prefill/moe_fused_iq.hpp b/include/strata/prefill/moe_fused_iq.hpp index a5ebd54f..5cae47a1 100644 --- a/include/strata/prefill/moe_fused_iq.hpp +++ b/include/strata/prefill/moe_fused_iq.hpp @@ -38,10 +38,10 @@ void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, v /// through Alloc's 256-byte takes from a 256-aligned cache slot or cudaMalloc). void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha, float* dm, void* stream); -/// The NT = 256 kernels (STRATA_PF_FUSED_NT=256) are set up on the current device: experts_native takes a WideBatch -/// (STRATA_PF_BATCH up to kBatchRoom experts a launch). +/// The NT = 256 kernels (STRATA_PF_FUSED_NT=256 or _F16=1) or the warp-specialized kernel (STRATA_PF_FUSED_WS=1) are +/// set up on the current device: experts_native takes a WideBatch (STRATA_PF_BATCH up to kBatchRoom experts a launch). bool native_wide(); -/// experts_native() of a WideBatch, on the NT = 256 kernels; only when native_wide(). +/// experts_native() of a WideBatch, on the NT = 256 kernels or the warp-specialized kernel; only when native_wide(). void experts_native(const WideBatch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha, float* dm, void* stream); diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index de40847c..5d8afd32 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -108,8 +108,9 @@ __host__ __device__ constexpr int grid_bytes(int t) { return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4 : t == T_IQ3_S ? 512 * 4 : 0; } -__host__ __device__ constexpr size_t smem_bytes(int t, int ww, int astages = ASTAGES, int nt = THREADS) { - return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) astages * tile_rows(ww, nt) * AB + +constexpr int WLDH = 144; // F16: bytes per decoded weight row of a stage: 64 halves + 16 (ldmatrix rows apart) +__host__ __device__ constexpr size_t smem_bytes(int t, int ww, int astages = ASTAGES, int nt = THREADS, bool f16 = false) { + return (size_t) 2 * weight_rows(ww) * (f16 ? WLDH : WLD + 16) + (size_t) astages * tile_rows(ww, nt) * AB + (size_t) tile_rows(ww, nt) * 4 + grid_bytes(t); } @@ -172,6 +173,22 @@ __device__ __forceinline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uin : "r"(a0), "r"(a1), "r"(b0), "r"(MAGIC)); } __device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; } +// F16 (STRATA_PF_FUSED_F16): d += A (16 x 16 f16, row) * B (16 x 8 f16, col), FP32 accumulators in place +__device__ __forceinline__ void mma16h(float (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { + asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +} +// four int8 (bytes 0-3) times a scale as two half2: lo = bytes 0, 1, hi = bytes 2, 3. The flipped sign bit makes +// x + 128 the mantissa of 1024 (exact), minus 1152 is x, then one packed multiply. +__device__ __forceinline__ void i8x4_h2(uint32_t w, __half2 sc, uint32_t& lo, uint32_t& hi) { + const uint32_t c = w ^ 0x80808080u; + const __half2 m = __floats2half2_rn(1152.0f, 1152.0f); + const uint32_t l = __byte_perm(c, 0x64646464u, 0x4140), h = __byte_perm(c, 0x64646464u, 0x4342); + const __half2 lv = __hmul2(__hsub2(*(const __half2*) &l, m), sc), hv = __hmul2(__hsub2(*(const __half2*) &h, m), sc); + lo = *(const uint32_t*) &lv; + hi = *(const uint32_t*) &hv; +} // four 8 x 16-byte matrices, row addresses from lanes 0-7, 8-15, 16-23, 24-31: lane (g, t) gets bytes 4t..4t+3 of row g // of each - an mma fragment __device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { @@ -208,6 +225,10 @@ __device__ __forceinline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uin mma8_s8_c(d[2], d[3], a1, b0, MAGIC); } __device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; } +// F16 (STRATA_PF_FUSED_F16) is sm_80+ only (dev_info stops before the NT = 256 setup on Turing): stubs so that its +// native_kernel instantiations compile here +__device__ __forceinline__ void mma16h(float (&)[4], const uint32_t (&)[4], uint32_t, uint32_t) { __trap(); } +__device__ __forceinline__ void i8x4_h2(uint32_t, __half2, uint32_t&, uint32_t&) { __trap(); } __device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) @@ -532,15 +553,22 @@ template <int T> __device__ __forceinline__ const void* grid_src() { // the other waits at a barrier. WW 2 only (its 2 WR = 256 decode units are the block's threads); a work item is 128 // weight rows x one 64-row tile. Every output is the same thread's sum in the same order: the same bits. The NT = 256 // instances take a WideBatch (STRATA_PF_BATCH up to kBatchRoom experts a launch), the default ones Batch. +// +// F16 (STRATA_PF_FUSED_F16=1, NT 256 only; changes the output at rounding level): the decoded weights times their +// scales as F16 and the activations times theirs as F16, m16n8k16 F16 products into FP32 accumulators - no FP32 work +// per 32 values. The k order inside a 16-value group is permuted the same way for both operands (stored half2 word t +// holds values 4t, 4t + 1 and word 4 + t values 4t + 2, 4t + 3), so the activations' int8 ldmatrix fragments become +// the F16 B fragments in registers; the accumulator layout, and so the epilogues, are the int8 kernel's. template <int NT> using BatchOf = std::conditional_t<NT == THREADS, Batch, WideBatch>; -template <int WT, bool GU, int WW, int NT = THREADS> +template <int WT, bool GU, int WW, int NT = THREADS, bool F16 = false> __global__ void __launch_bounds__(NT, NT == THREADS ? 1 : 2) native_kernel(const BatchOf<NT> b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 constexpr int TR = tile_rows(WW, NT), WR = weight_rows(WW); static_assert(2 * WR <= NT, "every decode unit is a thread of the block"); - constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB; + constexpr int WLDX = F16 ? WLDH : WLD; + constexpr int WT_BYTES = WR * WLDX, WS_FLOATS = F16 ? 0 : WR * 4, ACT_STAGE = TR * AB; constexpr bool TWO_PASS = NT != THREADS; // the two-pass loads (load_unit_l) only in the opt-in NT = 256 kernels constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K constexpr int NFB = (GU ? 1280 : 2560) / WR; // weight-row blocks per tile @@ -570,7 +598,7 @@ native_kernel(const BatchOf<NT> b, const NativeGeom geo, const Tables tb, const // fragments come by ldmatrix: lane l gives the address of row (l & 7) of matrix l >> 3 - A: {rows 0-7, rows 8-15} // x {bytes 0-15, 16-31} of a 32-value chunk; B: {tokens nb0 + 0-7, + 8-15} x {bytes 0-15, 16-31}. const int lm = lane >> 3, l8 = lane & 7; - const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLD + 16 * (lm >> 1); + const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLDX + 16 * (lm >> 1); const int b_off = (nb0 + 8 * (lm >> 1) + l8) * AB + 16 * (lm & 1); // this thread's decode unit (the first 2 WR threads): local weight row ur, sub-block uj of each stage const bool dec = tid < 2 * WR; @@ -625,10 +653,23 @@ native_kernel(const BatchOf<NT> b, const NativeGeom geo, const Tables tb, const uint32_t q[8]; float s0, s1; convert<WT>(raw, sgrid, kv, q, s0, s1); + if constexpr (F16) { // two 16-value groups of 8 half2 words (the permuted order above) + uint4* d = (uint4*) (wt + buf * WT_BYTES + ur * WLDX + 64 * uj); +#pragma unroll + for (int k = 0; k < 2; ++k) { + const __half2 sc = __float2half2_rn(k ? s1 : s0); + uint32_t lo[4], hi[4]; +#pragma unroll + for (int w = 0; w < 4; ++w) i8x4_h2(q[4 * k + w], sc, lo[w], hi[w]); + d[2 * k] = make_uint4(lo[0], lo[1], lo[2], lo[3]); + d[2 * k + 1] = make_uint4(hi[0], hi[1], hi[2], hi[3]); + } + } else { uint4* d = (uint4*) (wt + buf * WT_BYTES + ur * WLD + 32 * uj); d[0] = make_uint4(q[0], q[1], q[2], q[3]); d[1] = make_uint4(q[4], q[5], q[6], q[7]); *(float2*) (ws + buf * WS_FLOATS + ur * 4 + 2 * uj) = make_float2(s0, s1); + } }; #pragma unroll for (int s = 0; s < ASTAGES_DEV - 1; ++s) { @@ -667,7 +708,30 @@ native_kernel(const BatchOf<NT> b, const NativeGeom geo, const Tables tb, const #pragma unroll for (int n = 0; n < 2; ++n) #pragma unroll - for (int cc = 0; cc < 2; ++cc) dx[n][cc] = *(const float2*) (sa + (nb0 + 8 * n + 2 * tig + cc) * AB + 64); + for (int cc = 0; cc < 2; ++cc) dx[n][cc] = F16 ? float2{} : *(const float2*) (sa + (nb0 + 8 * n + 2 * tig + cc) * AB + 64); + if constexpr (F16) { +#pragma unroll + for (int h = 0; h < 2; ++h) { + uint32_t bq[4]; // {n0 k 0-15, n0 16-31, n1 0-15, n1 16-31}: token nb0 + 8 n + g + ldsm4(bq, sa + b_off + 32 * h); + uint32_t bh[2][2][2]; // [n][16-value group][b0, b1] +#pragma unroll + for (int n = 0; n < 2; ++n) { + const __half2 dxh = __float2half2_rn(*(const float*) (sa + (nb0 + 8 * n + g) * AB + 64 + 4 * h)); +#pragma unroll + for (int k = 0; k < 2; ++k) i8x4_h2(bq[2 * n + k], dxh, bh[n][k][0], bh[n][k][1]); + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int k = 0; k < 2; ++k) { + uint32_t a[4]; + ldsm4(a, W + a_off + 16 * i * WLDX + 64 * h + 32 * k); + mma16h(acc[i][0], a, bh[0][k][0], bh[0][k][1]); + if (on1) mma16h(acc[i][1], a, bh[1][k][0], bh[1][k][1]); + } + } + } else if constexpr (WT == T_Q2_0 && T75_DEV) { // Turing, Q2_0: one d per 64 values, so the stage's two halves share their weight scale - each row's dot // is d (dx_0 dot_0 + dx_1 dot_1): the activation scales per half, then d once @@ -794,6 +858,336 @@ native_kernel(const BatchOf<NT> b, const NativeGeom geo, const Tables tb, const #endif } +#if !defined(__HIPCC__) +// STRATA_PF_FUSED_WS=1 (sm_80+, opt-in; the F16 products of native_kernel's F16 path, so the same rounding as +// STRATA_PF_FUSED_F16): warp-specialized. 16 warps at the defaults: warps 8-15 (the producers, STRATA_WS_PROD threads) +// decode the weights to F16 and copy the activations into a ring of WS_SLOTS stages; warps 0-7 (the consumers, WS_CONS +// threads, native_kernel's NT = 256 tiling: 128 weight rows x 64 routed rows) run the products. Named barriers per +// slot (full: producers arrive, consumers wait; empty: the reverse) replace the block-wide barrier per stage, and the +// ring runs on across work items, so the decode of the next stages and of the next item overlaps the products and the +// epilogue. +#ifndef STRATA_WS_PROD +#define STRATA_WS_PROD 256 +#endif +#ifndef STRATA_WS_SLOTS +#define STRATA_WS_SLOTS 2 +#endif +// STRATA_WS_NB: n8 tiles a consumer warp (2: 8 consumer warps of 16 routed rows; 4: 4 warps of 32 rows, each weight +// fragment read from shared memory once for twice the products) +#ifndef STRATA_WS_NB +#define STRATA_WS_NB 2 +#endif +constexpr int WS_NB = STRATA_WS_NB; +constexpr int WS_CONS = 32 * 2 * (64 / (8 * WS_NB)), WS_PROD = STRATA_WS_PROD, WS_THREADS = WS_CONS + WS_PROD, WS_SLOTS = STRATA_WS_SLOTS; +// STRATA_WS_KS: 64-value stages per ring slot (one handshake per slot: fewer barriers per product) +#ifndef STRATA_WS_KS +#define STRATA_WS_KS 2 +#endif +constexpr int WS_KS = STRATA_WS_KS; +// STRATA_WS_HTAB (default 0, off; 1 or 2 on): IQ3_XXS / IQ3_S producers decode through one table of (codebook entry, +// 4 sign bits) -> the four signed values as F16 (32 / 64 KB of shared memory): one 8-byte load and two packed multiplies +// a quad instead of the codebook load, the sign masks, the int8 -> F16 conversion. Exact small integers either way: the +// same bits. +#ifndef STRATA_WS_HTAB +#define STRATA_WS_HTAB 0 +#endif +__host__ __device__ constexpr bool ws_htab(int t) { return STRATA_WS_HTAB && (t == T_IQ3_XXS || t == T_IQ3_S); } +__host__ __device__ constexpr size_t ws_htab_bytes(int t) { + return !ws_htab(t) ? 0 : STRATA_WS_HTAB == 2 ? (size_t) (t == T_IQ3_S ? 512 : 256) * 8 + 16 * 8 + : (size_t) (t == T_IQ3_S ? 512 : 256) * 16 * 8; +} +__host__ __device__ constexpr size_t ws_smem_bytes(int t) { + return (size_t) WS_SLOTS * WS_KS * (128 * WLDH + 64 * AB) + 2 * 64 * 4 + grid_bytes(t) + ws_htab_bytes(t); +} +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 +__device__ __forceinline__ void nbar_sync(int id, int n) { asm volatile("bar.sync %0, %1;\n" ::"r"(id), "r"(n) : "memory"); } +__device__ __forceinline__ void nbar_arrive(int id, int n) { asm volatile("bar.arrive %0, %1;\n" ::"r"(id), "r"(n) : "memory"); } +#endif +template <int WT, bool GU> +__global__ void __launch_bounds__(WS_THREADS, 1) +native_ws_kernel(const WideBatch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, + const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + constexpr int WS_UPT = 256 / WS_PROD; // decode units (sub-blocks) a producer thread takes per stage + constexpr int TR = 64, WR = 128, WW = 2; + constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; + constexpr int NFB = (GU ? 1280 : 2560) / WR; + constexpr int ACT_LD = NS * AB; + constexpr int BS = block_bytes(WT); + constexpr int WT_BYTES = WR * WLDH, ACT_STAGE = TR * AB; + constexpr bool GU256 = GU && WT != T_Q2_0; + extern __shared__ __align__(16) uint8_t smem[]; + uint8_t* wt = smem; // [SLOTS][WR][WLDH] F16 weights + uint8_t* stages = smem + WS_SLOTS * WS_KS * WT_BYTES; // [SLOTS * KS][TR][AB] activations + int* srow = (int*) (stages + WS_SLOTS * WS_KS * ACT_STAGE); // [2][TR] (producers only) + static_assert(NS % WS_KS == 0, "whole slots"); + uint8_t* sgrid = (uint8_t*) (srow + 2 * TR); + uint2* htab = (uint2*) (sgrid + grid_bytes(WT)); // ws_htab: [entry][4 sign bits] four F16 + const int tid = threadIdx.x; + if constexpr (grid_bytes(WT) > 0) { + const uint32_t* gs = (const uint32_t*) grid_src<WT>(); + for (int i = tid; i < grid_bytes(WT) / 4; i += WS_THREADS) ((uint32_t*) sgrid)[i] = gs[i]; + } + if constexpr (ws_htab(WT) && STRATA_WS_HTAB == 2) { + const uint32_t* gs = (const uint32_t*) grid_src<WT>(); + constexpr int NE = WT == T_IQ3_S ? 512 : 256; + for (int i = tid; i < NE + 16; i += WS_THREADS) { + if (i < NE) { // the codebook entry's four values as F16 (exact small integers) + const uint32_t gw = gs[i]; + const __half2 lo = __floats2half2_rn((float) (gw & 255), (float) ((gw >> 8) & 255)), + hi = __floats2half2_rn((float) ((gw >> 16) & 255), (float) (gw >> 24)); + htab[i] = make_uint2(*(const uint32_t*) &lo, *(const uint32_t*) &hi); + } else { // four sign bits as the F16 sign-bit masks of the two half2 + const uint32_t sg = (uint32_t) (i - NE); + htab[i] = make_uint2(((sg & 1) << 15) | ((sg & 2) << 30), ((sg & 4) << 13) | ((sg & 8) << 28)); + } + } + } else if constexpr (ws_htab(WT)) { + const uint32_t* gs = (const uint32_t*) grid_src<WT>(); + for (int i = tid; i < (int) (ws_htab_bytes(WT) / 8); i += WS_THREADS) { + const uint32_t gw = gs[i >> 4], sg = (uint32_t) i & 15; + __half h[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float v = (float) ((gw >> (8 * j)) & 255); + h[j] = __float2half_rn((sg >> j) & 1 ? -v : v); + } + const __half2 lo = __halves2half2(h[0], h[1]), hi = __halves2half2(h[2], h[3]); + htab[i] = make_uint2(*(const uint32_t*) &lo, *(const uint32_t*) &hi); + } + } + __syncthreads(); + const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; + const int nmine = (int) blockIdx.x < nwork ? (nwork - 1 - (int) blockIdx.x) / (int) gridDim.x + 1 : 0; + const int qtotal = nmine * NS; + auto item = [&](int k, int& e, int& row0, int& nrows, int& fb) { + const int w = (int) blockIdx.x + k * (int) gridDim.x; + const int2 tl = tb.tiles[t0 + w / NFB]; + fb = w % NFB; e = tl.x; row0 = tl.y; + nrows = min(TR, tb.off[e + 1] - row0); + }; + if (tid >= WS_CONS) { + // ---- producers: weight row ur (both 32-value sub-blocks of a stage), and a share of the activation copies + const int p = tid - WS_CONS, ur = WS_UPT == 2 ? p : p >> 1, uj0 = WS_UPT == 2 ? 0 : p & 1; + uint32_t kv[4] = {0, 0, 0, 0}; + if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { +#pragma unroll + for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3)); + } + int q = 0; + for (int k = 0; k < nmine; ++k) { + int e, row0, nrows, fb; + item(k, e, row0, nrows, fb); + const uint8_t* blob = b.blob[e - b.e0]; + const uint8_t* wrow = GU ? blob + ((ur & 8) ? geo.up_off : 0) + + (size_t) (fb * (WR / 2) + 8 * (ur >> 4) + (ur & 7)) * geo.gu_row + : blob + geo.down_off + (size_t) (fb * WR + ur) * geo.d_row; + auto unit = [&](int s, int uj) -> const uint8_t* { + if (GU256) return wrow + (s >> 2) * BS; + return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS; + }; + auto sub = [&](int s, int uj) { return GU256 ? 2 * (s & 3) + uj : uj; }; + int* sr = srow + (k & 1) * TR; + if (p < TR) sr[p] = p < nrows ? (GU ? src[row0 + p] : row0 + p) : -1; + if (GU) { + for (int sb = 0; sb < 2; ++sb) pf_l2(wrow + sb * BS + (uj0 ? BS - 1 : 0)); + } else { + for (size_t o = 128 * (size_t) uj0; o < geo.d_row; o += 128 * (3 - WS_UPT)) pf_l2(wrow + o); + } + nbar_sync(1 + 2 * WS_SLOTS, WS_PROD); // sr + uint32_t raw[WS_UPT][5], pc[WS_UPT][NP]; + auto issue = [&](int s) { +#pragma unroll + for (int u = 0; u < WS_UPT; ++u) { LdIssue l{pc[u], 0}; uint32_t w5[5]; load_unit_l<WT>(l, unit(s, uj0 + u), sub(s, uj0 + u), w5); } + }; + auto take = [&](int s) { +#pragma unroll + for (int u = 0; u < WS_UPT; ++u) { LdTake l{pc[u], 0}; load_unit_l<WT>(l, unit(s, uj0 + u), sub(s, uj0 + u), raw[u]); } + }; +#pragma unroll + for (int u = 0; u < WS_UPT; ++u) load_unit<WT>(unit(0, uj0 + u), sub(0, uj0 + u), raw[u]); + if (1 < NS) issue(1); +#pragma unroll WS_KS + for (int s = 0; s < NS; ++s, ++q) { + const int qs = q / WS_KS, slot = qs % WS_SLOTS, ks = q % WS_KS, buf = slot * WS_KS + ks; + if (ks == 0 && qs >= WS_SLOTS) nbar_sync(1 + WS_SLOTS + slot, WS_THREADS); // the consumers are done with the slot + uint8_t* st = stages + buf * ACT_STAGE; + for (int c = p; c < TR * 5; c += WS_PROD) { + const int r = c / 5, qq = c % 5; + if (r < nrows) cp16(st + r * AB + qq * 16, act + (size_t) sr[r] * ACT_LD + s * AB + qq * 16); + } + cp_commit(); + if (GU && (s & 3) == 0 && (s >> 2) + 2 < GU_ROWS_K / 256) pf_l2(wrow + ((s >> 2) + 2) * BS + (uj0 ? BS - 1 : 0)); +#pragma unroll + for (int u = 0; u < WS_UPT; ++u) { + if constexpr (ws_htab(WT)) { + const uint32_t* w = raw[u]; + const float sf = WT == T_IQ3_XXS ? half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f + : half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24)); + const __half2 sc = __float2half2_rn(sf); + uint32_t lo[8], hi[8]; +#pragma unroll + for (int l = 0; l < 4; ++l) { + uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255, s8; + if constexpr (WT == T_IQ3_XXS) { + const uint32_t v = (w[2] >> (7 * l)) & 127; + s8 = v | ((__popc(v) & 1) << 7); + } else { + const uint32_t qh = (w[3] >> 16) & 255; + i0 |= (qh << (8 - 2 * l)) & 256; + i1 |= (qh << (7 - 2 * l)) & 256; + s8 = (w[2] >> (8 * l)) & 255; + } + uint2 e0, e1; + if constexpr (STRATA_WS_HTAB == 2) { + constexpr int NE = WT == T_IQ3_S ? 512 : 256; + const uint2 g0 = htab[i0], g1 = htab[i1], m0 = htab[NE + (s8 & 15)], m1 = htab[NE + (s8 >> 4)]; + e0 = make_uint2(g0.x ^ m0.x, g0.y ^ m0.y); + e1 = make_uint2(g1.x ^ m1.x, g1.y ^ m1.y); + } else { + e0 = htab[i0 * 16 + (s8 & 15)]; + e1 = htab[i1 * 16 + (s8 >> 4)]; + } + const __half2 a0 = __hmul2(*(const __half2*) &e0.x, sc), b0 = __hmul2(*(const __half2*) &e0.y, sc), + a1 = __hmul2(*(const __half2*) &e1.x, sc), b1 = __hmul2(*(const __half2*) &e1.y, sc); + lo[2 * l] = *(const uint32_t*) &a0; hi[2 * l] = *(const uint32_t*) &b0; + lo[2 * l + 1] = *(const uint32_t*) &a1; hi[2 * l + 1] = *(const uint32_t*) &b1; + } + uint4* d = (uint4*) (wt + buf * WT_BYTES + ur * WLDH + 64 * (uj0 + u)); +#pragma unroll + for (int k = 0; k < 2; ++k) { + d[2 * k] = make_uint4(lo[4 * k], lo[4 * k + 1], lo[4 * k + 2], lo[4 * k + 3]); + d[2 * k + 1] = make_uint4(hi[4 * k], hi[4 * k + 1], hi[4 * k + 2], hi[4 * k + 3]); + } + continue; + } + uint32_t qv[8]; + float s0, s1; + convert<WT>(raw[u], sgrid, kv, qv, s0, s1); + uint4* d = (uint4*) (wt + buf * WT_BYTES + ur * WLDH + 64 * (uj0 + u)); +#pragma unroll + for (int h = 0; h < 2; ++h) { + const __half2 sc = __float2half2_rn(h ? s1 : s0); + uint32_t lo[4], hi[4]; +#pragma unroll + for (int w = 0; w < 4; ++w) i8x4_h2(qv[4 * h + w], sc, lo[w], hi[w]); + d[2 * h] = make_uint4(lo[0], lo[1], lo[2], lo[3]); + d[2 * h + 1] = make_uint4(hi[0], hi[1], hi[2], hi[3]); + } + } + if (s + 1 < NS) { + take(s + 1); + if (s + 2 < NS) issue(s + 2); + } + if (ks == WS_KS - 1) { + cp_wait<0>(); + nbar_arrive(1 + slot, WS_THREADS); // the slot is full + } + } + } + return; + } + // ---- consumers: WS_NB n8 tiles (8 WS_NB routed rows) by 64 weight rows a warp, F16 products + constexpr int NB = WS_NB; + const int lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3; + const int wf = warp % WW, nb0 = 8 * NB * (warp / WW); + const int lm = lane >> 3, l8 = lane & 7; + const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLDH + 16 * (lm >> 1); + const int b_off = (nb0 + 8 * (lm >> 1) + l8) * AB + 16 * (lm & 1); + int q = 0; + for (int k = 0; k < nmine; ++k) { + int e, row0, nrows, fb; + item(k, e, row0, nrows, fb); + const bool on0 = nb0 < nrows; + float acc[4][NB][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int n = 0; n < NB; ++n) +#pragma unroll + for (int c = 0; c < 4; ++c) acc[i][n][c] = 0.0f; + for (int s = 0; s < NS; ++s, ++q) { + const int qs = q / WS_KS, slot = qs % WS_SLOTS, ks = q % WS_KS, buf = slot * WS_KS + ks; + if (ks == 0) nbar_sync(1 + slot, WS_THREADS); // the slot is full + if (on0) { + const uint8_t* W = wt + buf * WT_BYTES; + const uint8_t* sa = stages + buf * ACT_STAGE; +#pragma unroll + for (int h = 0; h < 2; ++h) { + uint32_t bh[NB][2][2]; +#pragma unroll + for (int pr = 0; pr < NB / 2; ++pr) { + uint32_t bq[4]; + ldsm4(bq, sa + b_off + 16 * pr * AB + 32 * h); +#pragma unroll + for (int nn = 0; nn < 2; ++nn) { + const int n = 2 * pr + nn; + const __half2 dxh = __float2half2_rn(*(const float*) (sa + (nb0 + 8 * n + g) * AB + 64 + 4 * h)); +#pragma unroll + for (int kk = 0; kk < 2; ++kk) i8x4_h2(bq[2 * nn + kk], dxh, bh[n][kk][0], bh[n][kk][1]); + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int kk = 0; kk < 2; ++kk) { + uint32_t a[4]; + ldsm4(a, W + a_off + 16 * i * WLDH + 64 * h + 32 * kk); +#pragma unroll + for (int n = 0; n < NB; ++n) + if (n == 0 || nb0 + 8 * n < nrows) mma16h(acc[i][n], a, bh[n][kk][0], bh[n][kk][1]); + } + } + } + if (ks == WS_KS - 1 && (qs + WS_SLOTS) * WS_KS < qtotal) nbar_arrive(1 + WS_SLOTS + slot, WS_THREADS); // the slot is free + } + if (!on0) continue; + if (GU) { + const int blk = WW * fb + wf; +#pragma unroll + for (int n = 0; n < NB; ++n) { + if (nb0 + 8 * n >= nrows) break; +#pragma unroll + for (int c = 0; c < 2; ++c) { + float h[4], am = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float gt = acc[i][n][c], up = acc[i][n][2 + c]; + h[i] = gt / (1.0f + __expf(-gt)) * up; + am = fmaxf(am, fabsf(h[i])); + } +#pragma unroll + for (int o = 4; o < 32; o <<= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + const int r = nb0 + 8 * n + 2 * tig + c; + if (r < nrows) { + uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB; + const int hh = blk & 1; +#pragma unroll + for (int i = 0; i < 4; ++i) o[32 * hh + 8 * i + g] = (uint8_t) (int8_t) __float2int_rn(h[i] * inv); + if (g == 0) *(float*) (o + 64 + 4 * hh) = am / 127.0f; + } + } + } + } else { + const int rbase = fb * WR; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int n = 0; n < NB; ++n) { + if (nb0 + 8 * n >= nrows) break; +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int r = nb0 + 8 * n + 2 * tig + (c & 1); + if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + 64 * wf + 16 * i + 8 * (c >> 1) + g] = acc[i][n][c]; + } + } + } + } +#endif +} +#endif // !__HIPCC__ + #if defined(__HIPCC__) // ---- Aurora (S23): the native packs' fused experts on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 // (wave32). The CUDA kernel's arithmetic: a 32-value sub-block decoded to int8 (load_unit / convert above) and its @@ -1263,6 +1657,7 @@ struct DevInfo { bool s120 = false; // compute capability 12.0 (sm120_series.hpp): the default for the formats measured there int sms = 0, occ = 1; int occ_nt = 0; // blocks per multiprocessor of the NT = 256 kernels (0: not set up) + bool ws = false; // STRATA_PF_FUSED_WS: the warp-specialized kernels are set up }; std::mutex g_mu; DevInfo g_dev[32]; @@ -1280,26 +1675,43 @@ int host_astages() { } return per[dev]; } -template <int T, bool GU, int WW, int NT = THREADS> bool setup_ww(int& occ) { +template <int T, bool GU, int WW, int NT = THREADS, bool F16 = false> bool setup_ww(int& occ) { cudaFuncAttributes fa{}; - if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW, NT>) != cudaSuccess || fa.ptxVersion < 75) return false; - const size_t sm = smem_bytes(T, WW, host_astages(), NT); - if (cudaFuncSetAttribute(native_kernel<T, GU, WW, NT>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm) != cudaSuccess) + if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW, NT, F16>) != cudaSuccess || fa.ptxVersion < 75) return false; + const size_t sm = smem_bytes(T, WW, host_astages(), NT, F16); + if (cudaFuncSetAttribute(native_kernel<T, GU, WW, NT, F16>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm) != cudaSuccess) return false; int o = 0; - if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel<T, GU, WW, NT>, NT, sm) != cudaSuccess || o < 1) + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel<T, GU, WW, NT, F16>, NT, sm) != cudaSuccess || o < 1) return false; occ = std::min(occ, o); return true; } template <int T, bool GU> bool setup_one(int& occ) { return setup_ww<T, GU, 4>(occ) && setup_ww<T, GU, 2>(occ); } // STRATA_PF_FUSED_NT=256 (sm_80+, opt-in): the 256-thread kernels (native_kernel's NT) -bool nt256_requested() { - static const bool on = [] { const char* v = std::getenv("STRATA_PF_FUSED_NT"); return v != nullptr && std::atoi(v) == 256; }(); +// STRATA_PF_FUSED_F16=1 (sm_80+, opt-in, changes the output at rounding level): the NT = 256 kernels' F16 products +bool f16c_requested() { + static const bool on = [] { const char* v = std::getenv("STRATA_PF_FUSED_F16"); return v != nullptr && v[0] == '1'; }(); return on; } +bool nt256_requested() { + static const bool on = [] { const char* v = std::getenv("STRATA_PF_FUSED_NT"); return v != nullptr && std::atoi(v) == 256; }(); + return on || f16c_requested(); +} +bool ws_requested() { + static const bool on = [] { const char* v = std::getenv("STRATA_PF_FUSED_WS"); return v != nullptr && v[0] == '1'; }(); + return on; +} +template <int T, bool GU> bool setup_ws() { + cudaFuncAttributes fa{}; + if (cudaFuncGetAttributes(&fa, native_ws_kernel<T, GU>) != cudaSuccess || fa.ptxVersion < 80) return false; + if (cudaFuncSetAttribute(native_ws_kernel<T, GU>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) ws_smem_bytes(T)) != + cudaSuccess) return false; + int o = 0; + return cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_ws_kernel<T, GU>, WS_THREADS, ws_smem_bytes(T)) == cudaSuccess && o >= 1; +} template <int T, bool GU> bool setup_nt(int& occ) { - return setup_ww<T, GU, 2, 256>(occ); + return f16c_requested() ? setup_ww<T, GU, 2, 256, true>(occ) : setup_ww<T, GU, 2, 256>(occ); } #endif @@ -1404,6 +1816,13 @@ const DevInfo& dev_info() { d.occ_nt = ok2 ? o2 : 0; if (!ok2) std::fprintf(stderr, "prefill fused experts (native): STRATA_PF_FUSED_NT=256 is not available here\n"); } + if (d.ok && ws_requested()) { + d.ws = setup_ws<T_IQ2_XXS, true>() && setup_ws<T_IQ2_XS, true>() && setup_ws<T_IQ2_S, true>() && + setup_ws<T_IQ3_XXS, true>() && setup_ws<T_IQ3_S, true>() && setup_ws<T_IQ4_XS, true>() && + setup_ws<T_Q2_0, false>() && setup_ws<T_IQ4_NL, false>() && + (!d.q2n || setup_ws<T_Q2_0, true>()); // (the Q2_0 gate/up of STRATA_PF_FUSED_Q2N=1 too) + if (!d.ws) std::fprintf(stderr, "prefill fused experts (native): STRATA_PF_FUSED_WS=1 is not available here\n"); + } cudaGetLastError(); #endif return d; @@ -1463,12 +1882,23 @@ void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Ta if (ww == 4) native_kernel<T, GU, 4><<<grid, THREADS, smem_bytes(T, 4, host_astages()), s>>>(b, g, tb, a, src, o, dm); else native_kernel<T, GU, 2><<<grid, THREADS, smem_bytes(T, 2, host_astages()), s>>>(b, g, tb, a, src, o, dm); } -// the NT = 256 kernels (WW 2) +// the NT = 256 kernels (WW 2), their F16 form (STRATA_PF_FUSED_F16) or the warp-specialized kernel (ws: +// STRATA_PF_FUSED_WS) template <int T, bool GU> -void launch(unsigned grid, const WideBatch& b, const NativeGeom& g, const Tables& tb, const void* act, const int32_t* src, - void* out, float* dm, cudaStream_t s) { - native_kernel<T, GU, 2, 256><<<grid, 256, smem_bytes(T, 2, host_astages(), 256), s>>>(b, g, tb, (const uint8_t*) act, - src, (uint8_t*) out, dm); +void launch(bool ws, unsigned grid, const WideBatch& b, const NativeGeom& g, const Tables& tb, const void* act, + const int32_t* src, void* out, float* dm, cudaStream_t s) { + const uint8_t* a = (const uint8_t*) act; + uint8_t* o = (uint8_t*) out; +#if !defined(__HIPCC__) // (native_ws_kernel and the F16 path are CUDA only; d.ws is never set on HIP) + if (ws) + native_ws_kernel<T, GU><<<grid, WS_THREADS, ws_smem_bytes(T), s>>>(b, g, tb, a, src, o, dm); + else if (f16c_requested()) + native_kernel<T, GU, 2, 256, true><<<grid, 256, smem_bytes(T, 2, host_astages(), 256, true), s>>>(b, g, tb, a, src, o, dm); + else +#else + (void) ws; +#endif + native_kernel<T, GU, 2, 256><<<grid, 256, smem_bytes(T, 2, host_astages(), 256), s>>>(b, g, tb, a, src, o, dm); } // The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has @@ -1625,7 +2055,7 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n return; } #endif - if (d.occ_nt > 0) { // STRATA_PF_FUSED_NT=256: the NT = 256 kernels, which take a WideBatch + if (d.occ_nt > 0 || d.ws) { // STRATA_PF_FUSED_NT=256 / _F16 / _WS: the kernels that take a WideBatch WideBatch w; w.e0 = b.e0; w.e1 = b.e1; @@ -1653,34 +2083,37 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n ck(cudaGetLastError(), "experts_native"); } -bool native_wide() { return dev_info().occ_nt > 0; } +bool native_wide() { const DevInfo& d = dev_info(); return d.occ_nt > 0 || d.ws; } void experts_native(const WideBatch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha, float* dm, void* stream) { if (b.e1 <= b.e0 || n <= 0) return; const DevInfo& d = dev_info(); - if (d.occ_nt <= 0 || !gu_covered(g.gu_type) || !d_covered_on(g.d_type, d)) { + if ((d.occ_nt <= 0 && !d.ws) || !gu_covered(g.gu_type) || !d_covered_on(g.d_type, d)) { std::fprintf(stderr, "prefill fused experts (native, NT = 256): types %d / %d are not covered here\n", g.gu_type, g.d_type); std::exit(1); } const cudaStream_t s = (cudaStream_t) stream; const Tables tb = tables(const_cast<void*>(scratch), n_expert); - // WW 2 (128 x 64 items), as many blocks as are resident; the tiles as in experts_native(const Batch&) + // WW 2 (128 x 64 items), as many blocks as are resident (the WS kernel: one a multiprocessor); the tiles as in + // experts_native(const Batch&) const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); - const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / weight_rows(2)), (int64_t) d.sms * d.occ_nt); - const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / weight_rows(2)), (int64_t) d.sms * d.occ_nt); + const bool ws = d.ws; + const int occ = ws ? 1 : d.occ_nt; + const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / weight_rows(2)), (int64_t) d.sms * occ); + const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / weight_rows(2)), (int64_t) d.sms * occ); switch (g.gu_type) { - case T_IQ2_XXS: launch<T_IQ2_XXS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ2_XS: launch<T_IQ2_XS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ2_S: launch<T_IQ2_S, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ3_XXS: launch<T_IQ3_XXS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_IQ3_S: launch<T_IQ3_S, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - case T_Q2_0: launch<T_Q2_0, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; - default: launch<T_IQ4_XS, true>(g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_XXS: launch<T_IQ2_XXS, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_XS: launch<T_IQ2_XS, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_S: launch<T_IQ2_S, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ3_XXS: launch<T_IQ3_XXS, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ3_S: launch<T_IQ3_S, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_Q2_0: launch<T_Q2_0, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + default: launch<T_IQ4_XS, true>(ws, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; } - if (g.d_type == T_Q2_0) launch<T_Q2_0, false>(g_d, b, g, tb, ha, src, nullptr, dm, s); - else launch<T_IQ4_NL, false>(g_d, b, g, tb, ha, src, nullptr, dm, s); + if (g.d_type == T_Q2_0) launch<T_Q2_0, false>(ws, g_d, b, g, tb, ha, src, nullptr, dm, s); + else launch<T_IQ4_NL, false>(ws, g_d, b, g, tb, ha, src, nullptr, dm, s); ck(cudaGetLastError(), "experts_native (NT = 256)"); } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index d8aa780b..0d19ef90 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -4044,7 +4044,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const size_t kend = seq_start[(size_t) l + 1]; // STRATA_PF_BATCH=N (opt-in): experts per launch (the same rows, so the same bits; a launch is one // persistent grid, so fewer launches leave fewer grid tails) - at most kMaxBatch, or up to - // kBatchRoom in a WideBatch on the native NT = 256 kernels (STRATA_PF_FUSED_NT=256) + // kBatchRoom in a WideBatch on the native NT = 256 kernels (STRATA_PF_FUSED_NT=256 or _F16=1) or + // the warp-specialized kernel (STRATA_PF_FUSED_WS=1) static const int pf_batch = [] { const char* v = std::getenv("STRATA_PF_BATCH"); const int n = v ? std::atoi(v) : 0; diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp index aba76925..90f52f5c 100644 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -83,7 +83,10 @@ struct Geo { // STRATA_PF_F16=1: the covered formats run on F16 weights (moe_f16_kq.cu, native_f16_kernel), not the int8 kernels bool f16_on() { const char* v = std::getenv("STRATA_PF_F16"); - return v != nullptr && v[0] == '1'; + // STRATA_PF_FUSED_F16=1 / STRATA_PF_FUSED_WS=1 (the int8 kernels' f16 mma form, #3779): F16 products too, so the same limits + const char* f = std::getenv("STRATA_PF_FUSED_F16"); + const char* w = std::getenv("STRATA_PF_FUSED_WS"); + return (v != nullptr && v[0] == '1') || (f != nullptr && f[0] == '1') || (w != nullptr && w[0] == '1'); } // that the weights' typical size is that of a 2-3 bit expert (a few hundredths) @@ -669,6 +672,18 @@ int main(int argc, char** argv) { cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0); if (strata::cc_major_of(major) < 8) { std::printf("STRATA_PF_FUSED unset: nothing is set up below sm_80 (skipped)\n"); return 77; } } + // the opt-in kernel sets (STRATA_PF_FUSED_NT=256, _F16=1, _WS=1): a card that cannot set them up (shared memory, + // occupancy) falls back to the 512-thread kernels, and a run of those would pass for the wrong kernels - skip it + { + const char* nt = std::getenv("STRATA_PF_FUSED_NT"); + const char* f16 = std::getenv("STRATA_PF_FUSED_F16"); + const char* ws = std::getenv("STRATA_PF_FUSED_WS"); + const bool asked = (nt && std::atoi(nt) == 256) || (f16 && f16[0] == '1') || (ws && ws[0] == '1'); + if (asked && !fused::native_wide()) { + std::printf("STRATA_PF_FUSED_NT / _F16 / _WS: those kernels are not set up on this device (skipped)\n"); + return 77; + } + } if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } const std::vector<Pair> pairs = { {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, From 8c2a8469472cba709928e1a901c6a53bb6f502ad Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:47:04 +0100 Subject: [PATCH 167/177] Prefill GDN: opt-in STRATA_GDN_TC=1 runs the DeltaNet recurrence as a chunked scan on the tensor cores, sm_80 (#3779, #3712) Problem: the prompt path's DeltaNet recurrence is a large part of the prompt time of a GA100 card. Change, opt-in and rounding-level (the output is not the FP32 kernels' bits): src/prefill/gdn_tc.cuh holds the chunked WY-form recurrence with every product on the tensor cores (f16x3 splits with power-of-two scaling, one block per value head) and its prep kernel; kernels.cu dispatches it before the STRATA_GDN_CHUNKED branch for prompt chunks of 128+ tokens when STRATA_GDN_TC is set. Where it runs and where it does not: - gdn_rec_tc returns "not supported" and the existing kernels run unchanged on a card below sm_80, with fewer than 48 SMs, or with less than 122 KB of shared memory a block (the kernel needs 124,944 B). That excludes sm_86, sm_89 and sm_120 (99 KB opt-in): the code is compiled into those builds and never launched there. It runs on sm_80 and sm_90. A failed scratch allocation (60.3 MB a device) also falls back. - Device code for cards below sm_80 compiles to trapping stubs behind STRATA_GDN_TC_SM80; the whole header sits under !__HIPCC__. - Unset, the dispatch costs one cached flag test per call. Tests: gdn_rec_parity gains the tc variant (T = 1..4099, 8192, 32768, six stress inputs against gdn_rec_kh_kernel, gate 1e-4; "not on this card" where it cannot run), --selftest-frag (each tensor-core helper on one warp against a double reference) and --bench-tc. The new ctest entry gdn_rec_parity_selftest_frag runs the helper self-test, which any sm_80+ card can run (77 below sm_80). The full tc variant can only run on an sm_80 or sm_90 card. Reporter's numbers (linxuhao, CMP 170HX): recurrence 105 -> 34 ms at 3.3K tokens and 1,705 -> 547 ms at 52K; prompts +3.9 % (4K), +6.0 % (16K), +6.7 % (52K) over the same base; within 2.3e-6 of the FP32 kernel in gdn_rec_parity; teacher-forced KL against the bitwise base mean 0.0157, median 0.0011, max 0.098, top-1 100 %; 1 of 5 conversation checks identical and decode -2.6 % in their pair (they think draft acceptance moves with the rounding; not checked). Theirs, not measured here. Original change by linxuhao (PR #3779, commit f1cabc99). --- CMakeLists.txt | 5 + src/prefill/gdn_rec_parity.cu | 417 ++++++++++++++++++++++-- src/prefill/gdn_tc.cuh | 586 ++++++++++++++++++++++++++++++++++ src/prefill/kernels.cu | 47 ++- 4 files changed, 1032 insertions(+), 23 deletions(-) create mode 100644 src/prefill/gdn_tc.cuh diff --git a/CMakeLists.txt b/CMakeLists.txt index 216c669b..18e79aa9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1179,6 +1179,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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) + # STRATA_GDN_TC=1: the tensor-core helpers of the scan, each on one warp against a double-precision reference. Any sm_80+ + # card runs them; the scan itself needs 122 KB of shared memory a block (sm_80, sm_90), where gdn_rec_parity prints + # "not on this card" for the tc variant + add_test(NAME gdn_rec_parity_selftest_frag COMMAND gdn_rec_parity --selftest-frag) + set_tests_properties(gdn_rec_parity_selftest_frag PROPERTIES SKIP_RETURN_CODE 77) # 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) diff --git a/src/prefill/gdn_rec_parity.cu b/src/prefill/gdn_rec_parity.cu index 8df8ef99..7ad1bb1f 100644 --- a/src/prefill/gdn_rec_parity.cu +++ b/src/prefill/gdn_rec_parity.cu @@ -8,10 +8,15 @@ // output, the state after it and the FP16 output must be the same bits. STRATA_GDN_CHUNKED=1's recurrence in chunks // (copied below too) sums in another order: it must stay within 1e-4 of gdn_rec_kh_kernel (largest |difference| over // largest |value|, the output and the state), also at T = 8192 and 32768; up to 8192 both are also measured against -// the recurrence in FP64. +// the recurrence in FP64. STRATA_GDN_TC=1's tensor-core scan (gdn_tc.cuh, included below) is held to the same 1e-4, +// also on stress inputs (the state 100x smaller, 50x larger or zero, v 50x larger, slow gates, coherent keys). // // Synthetic inputs of the model's shape (q/k L2-normalized per key head as gdn_l2_kernel leaves them), no model. // gdn_rec_parity the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk) +// gdn_rec_parity --long and the tensor-core scan at T = 51820 (needs ~7 GB) +// gdn_rec_parity --selftest-frag the tensor-core scan's fragment helpers alone, one warp each, against FP64 +// gdn_rec_parity --bench-tc the tensor-core series alone (gdn_rec_kh_kernel and the scan alternating, nothing else: +// for A / B runs of two builds back to back) // gdn_rec_parity --bench and the timings at T = 2048, 8192 and 32768 (one layer, all 48 value heads); the two // variants' launches alternate, since a card under load steps its clock down after a // fraction of a second (see native_grouped_parity); then both at 1 to 6 blocks per @@ -590,6 +595,41 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con } return cudaSuccess; // launch errors surface at the caller's check; an error above means nothing ran } +// src/prefill/kernels.cu's tensor-core scan (STRATA_GDN_TC=1): the same text, included there too +#include "gdn_tc.cuh" +// src/prefill/kernels.cu's gdn_rec_tc, copied as it is there (with the raw device attributes, as gdn_rec_chunked above) +cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, + cudaStream_t s) { + if (T <= 0) return cudaSuccess; + { + int dev = 0, major = 0, sms = 0, smem = 0; + if (cudaGetDevice(&dev) != cudaSuccess || + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess || + cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) { + cudaGetLastError(); + return cudaErrorNotSupported; + } + if (major < 8 || sms < HV || (size_t) smem < kTcScanSmem<false>) return cudaErrorNotSupported; + } + const GtcScratch sc = gdn_tc_scratch(); + if (sc.ti == nullptr) return cudaErrorMemoryAllocation; + { // once a device + static bool attrs[64] = {}; + int dev = 0; + cudaGetDevice(&dev); + if (dev >= 0 && dev < 64 && !attrs[dev]) { + cudaFuncSetAttribute(gdn_tc_scan_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem<false>); + attrs[dev] = true; + } + } + for (int64_t t0 = 0; t0 < T; t0 += GSB) { + const int nch = (int) ((std::min<int64_t>(GSB, T - t0) + GCH - 1) / GCH); + gdn_tc_prep_kernel<<<dim3((unsigned) nch, HK), 256, kTcPrepSmem, s>>>(h, gate, beta, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, t0, T); + gdn_tc_scan_kernel<false><<<HV, GTC_CW * 32, kTcScanSmem<false>, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + } + return cudaSuccess; +} // the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the // norm stays in its scratch buffer) __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, @@ -650,14 +690,24 @@ __global__ void l2_rows(float* h, float eps) { __syncthreads(); x[threadIdx.x] = v * rsqrtf(part[0] + part[1] + part[2] + part[3] + eps); } -// gate = log of the decay (mostly near 1, some strong), beta in (0, 1) -__global__ void fill_gates(float* gate, float* beta, int64_t n, uint64_t seed) { +// gate = log of the decay (mostly near 1, some strong; slow: -0.001 u, so the state grows for long), beta in (0, 1) +__global__ void fill_gates(float* gate, float* beta, int64_t n, uint64_t seed, bool slow = false) { for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { const float u = uni(seed * 0x9E3779B97F4A7C15ULL + 7 * (uint64_t) i); - gate[i] = -0.02f - 0.8f * u * u * u; + gate[i] = slow ? -0.001f * u : -0.02f - 0.8f * u * u * u; beta[i] = 1.0f / (1.0f + expf(-gauss(seed * 0xD1B54A32D192ED03ULL + (uint64_t) i))); } } +// coherent keys: every token's k row = a key head's k_0 + 0.05 x the row that was there (before l2_rows): the +// chunk's T = (I + A)^-1 then carries large entries, the reason the prep scales its T images by a power of two of their own +__global__ void coherent_k(float* h, uint64_t seed) { + float* x = h + (int64_t) blockIdx.y * C + HK * S + (int64_t) blockIdx.x * S; + x[threadIdx.x] = gauss(seed * 0x9E3779B97F4A7C15ULL + (uint64_t) (blockIdx.x * S + threadIdx.x)) + 0.05f * x[threadIdx.x]; +} +__global__ void scale_v(float* h, int64_t T, float scale) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < T * HV * S; i += (int64_t) gridDim.x * blockDim.x) + h[(i / (HV * S)) * C + 2 * HK * S + i % (HV * S)] *= scale; +} __global__ void count_diff(const uint32_t* a, const uint32_t* b, int64_t n, unsigned long long* out) { unsigned long long d = 0; for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) @@ -738,10 +788,15 @@ unsigned long long diff_words(const void* a, const void* b, size_t bytes) { return h; } +// The model's shapes with gaussian values; the defaults are the bit checks' inputs (the state as after an earlier +// chunk, scale 0.05). The others stress the tensor-core scan's f16 range handling: the state 100x smaller, 50x larger +// or zero (a fresh conversation), v 50x larger, slow gates, coherent keys. struct Inputs { int64_t T = 0; float *h = nullptr, *gate = nullptr, *beta = nullptr, *z = nullptr, *gamma = nullptr, *state0 = nullptr; - explicit Inputs(int64_t t, uint64_t seed) : T(t) { + explicit Inputs(int64_t t, uint64_t seed, float state_scale = 0.05f, float v_scale = 1.0f, bool slow_gates = false, + bool coherent_keys = false) + : T(t) { h = dalloc<float>((size_t) T * C); gate = dalloc<float>((size_t) T * HV); beta = dalloc<float>((size_t) T * HV); @@ -749,11 +804,13 @@ struct Inputs { gamma = dalloc<float>(S); state0 = dalloc<float>((size_t) S * HV * S); fill_gauss<<<4096, 256>>>(h, T * C, 1.0f, seed); + if (coherent_keys) coherent_k<<<dim3(HK, (unsigned) T), S>>>(h, seed + 5); l2_rows<<<dim3(2 * HK, (unsigned) T), S>>>(h, 1e-6f); - fill_gates<<<1024, 256>>>(gate, beta, T * HV, seed + 1); + if (v_scale != 1.0f) scale_v<<<4096, 256>>>(h, T, v_scale); + fill_gates<<<1024, 256>>>(gate, beta, T * HV, seed + 1, slow_gates); fill_gauss<<<4096, 256>>>(z, T * HV * S, 1.0f, seed + 2); fill_gauss<<<1, 128>>>(gamma, S, 0.1f, seed + 3, 1.0f); - fill_gauss<<<1024, 256>>>(state0, (int64_t) S * HV * S, 0.05f, seed + 4); + fill_gauss<<<1024, 256>>>(state0, (int64_t) S * HV * S, state_scale, seed + 4); ck(cudaDeviceSynchronize(), "inputs"); } Inputs(const Inputs&) = delete; @@ -858,8 +915,10 @@ double max_rel_f64(const float* a, const double* ref, size_t n) { // max |a - } return mv > 0.0 ? md / mv : md; } -int check_chunked(int64_t T, uint64_t seed) { - Inputs in(T, seed); +// a recurrence of gdn_rec_chunked's shape (the FP32 chunked pair, the tensor-core scan) on the inputs given +using RecLaunch = cudaError_t (*)(float*, const float*, const float*, const float*, float*, int64_t, cudaStream_t); +int check_variant(const Inputs& in, const char* label, RecLaunch launch, const char* needs) { + const int64_t T = in.T; const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; float* s0 = dalloc<float>(st); float* s1 = dalloc<float>(st); @@ -868,38 +927,307 @@ int check_chunked(int64_t T, uint64_t seed) { ck(cudaMemcpy(s0, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy"); ck(cudaMemcpy(s1, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy"); gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG)>>>(s0, in.h, in.gate, in.beta, o0, in.T); - const cudaError_t e = gdn_rec_chunked(s1, in.h, in.gate, in.beta, o1, in.T, 0); + const cudaError_t e = launch(s1, in.h, in.gate, in.beta, o1, in.T, 0); if (e == cudaErrorNotSupported) { - std::printf(" T=%-6lld chunked: not on this card (sm_80+, 128 SMs, 93.7 KB a block)\n", (long long) T); + std::printf(" T=%-6lld %s: not on this card (%s)\n", (long long) T, label, needs); cudaFree(s0); cudaFree(s1); cudaFree(o0); cudaFree(o1); return 0; } - ck(e, "chunked"); - ck(cudaDeviceSynchronize(), "chunked run"); + ck(e, label); + ck(cudaDeviceSynchronize(), label); const double eo = max_rel(o0, o1, oc_n), es = max_rel(s0, s1, st); const bool bad = !(eo < 1e-4) || !(es < 1e-4); - std::printf("%s T=%-6lld chunked (STRATA_GDN_CHUNKED): output %.2e, state %.2e (max |diff| / max |value|)\n", - bad ? "FAIL" : " ", (long long) T, eo, es); + std::printf("%s T=%-6lld %s: output %.2e, state %.2e (max |diff| / max |value|)\n", bad ? "FAIL" : " ", + (long long) T, label, eo, es); if (T <= 8192) { // both against FP64 (its output: 8 bytes a value, so not at 32K) double* sd = dalloc<double>(st); double* od = dalloc<double>(oc_n); to_f64<<<1024, 256>>>(in.state0, sd, (int64_t) st); gdn_rec_f64_kernel<<<HV, S>>>(sd, in.h, in.gate, in.beta, od, in.T); ck(cudaDeviceSynchronize(), "FP64 run"); - std::printf(" against FP64: gdn_rec_kh_kernel output %.2e, state %.2e; chunked output %.2e, state %.2e\n", + std::printf(" against FP64: gdn_rec_kh_kernel output %.2e, state %.2e; this one output %.2e, state %.2e\n", max_rel_f64(o0, od, oc_n), max_rel_f64(s0, sd, st), max_rel_f64(o1, od, oc_n), max_rel_f64(s1, sd, st)); cudaFree(sd); cudaFree(od); } cudaFree(s0); cudaFree(s1); cudaFree(o0); cudaFree(o1); return bad ? 1 : 0; } +int check_chunked(int64_t T, uint64_t seed) { + Inputs in(T, seed); + return check_variant(in, "chunked (STRATA_GDN_CHUNKED)", gdn_rec_chunked, "sm_80+, 128 SMs, 93.7 KB a block"); +} +constexpr const char* kTcNeeds = "sm_80+, 48 SMs, 122 KB a block"; +int check_tc(int64_t T, uint64_t seed) { + Inputs in(T, seed); + return check_variant(in, "tc (STRATA_GDN_TC=1)", gdn_rec_tc, kTcNeeds); +} +// the tensor-core scan on the stress inputs (Inputs): its f16 range handling has a case for each +int check_tc_stress(int64_t T, uint64_t seed) { + struct Case { const char* label; float state_scale, v_scale; bool slow_gates, coherent_keys; }; + const Case cases[] = {{"tc (STRATA_GDN_TC=1), state0 x 0.01", 5e-4f, 1.0f, false, false}, + {"tc (STRATA_GDN_TC=1), state0 x 50", 2.5f, 1.0f, false, false}, + {"tc (STRATA_GDN_TC=1), state0 = 0", 0.0f, 1.0f, false, false}, + {"tc (STRATA_GDN_TC=1), v x 50", 0.05f, 50.0f, false, false}, + {"tc (STRATA_GDN_TC=1), slow gates", 0.05f, 1.0f, true, false}, + {"tc (STRATA_GDN_TC=1), coherent keys", 0.05f, 1.0f, false, true}}; + int fails = 0; + for (const Case& c : cases) { + Inputs in(T, seed++, c.state_scale, c.v_scale, c.slow_gates, c.coherent_keys); + fails += check_variant(in, c.label, gdn_rec_tc, kTcNeeds); + } + return fails; +} + +// ------------------------------------------------------------------ the tensor-core scan's fragment self-test (--selftest-frag) +// One warp each, random inputs, the reference in double on the host: (b) a 16x128 . 128x32 product through +// gtc_prod_state (the f16 split with the state's 2^es and k's 2^8, ldmatrix), (c) a 16x32 . 32x128 update through +// gtc_update_state (ldmatrix.trans, the 2^ed scale, the accumulator's pre / post scale), (d) a 16x32 . 32x32 product +// through gtc_prod_dt on a full random T of wide range (the prep's 2^et on the B images), (e) the triangle-skipped +// tile sets of gtc_prod_dt against the full ones on triangular T / P: the same bits, since the skipped tiles add +// exact zeros. Most bugs of a tensor-core kernel are fragment-layout bugs: these catch them before the kernel does. +// ((a), the C -> A tf32 shuffle, went with the tf32 form of D^T.) +__device__ void st_stage_k(uint16_t* kh, uint16_t* kl, const float* k) { // k: 32 x 128 f32 -> the hi / lo images x 2^8 + for (int p = threadIdx.x; p < GCH * S / 4; p += 32) { + const int t = p / (S / 4), r = (p % (S / 4)) * 4; + gtc_split_store4(kh + t * GTC_KP + r, kl + t * GTC_KP + r, *reinterpret_cast<const float4*>(k + t * S + r), 256.0f); + } + __syncwarp(); +} +// a 16-row matrix (row stride ld) as 8-column tiles in the C layout: tile j, lane (gid, tig) holds (gid, 8j + 2tig), +// (gid, 8j + 2tig + 1), (gid + 8, 8j + 2tig), (gid + 8, 8j + 2tig + 1) +template <int NT> __device__ void st_load_c(float (&c)[NT][4], const float* m, int ld) { + const int lane = threadIdx.x & 31, gid = lane >> 2, tig = lane & 3; +#pragma unroll + for (int j = 0; j < NT; ++j) { + c[j][0] = m[gid * ld + 8 * j + 2 * tig]; + c[j][1] = m[gid * ld + 8 * j + 2 * tig + 1]; + c[j][2] = m[(gid + 8) * ld + 8 * j + 2 * tig]; + c[j][3] = m[(gid + 8) * ld + 8 * j + 2 * tig + 1]; + } +} +template <int NT> __device__ void st_store_c(const float (&c)[NT][4], float* m, int ld, float scale) { + const int lane = threadIdx.x & 31, gid = lane >> 2, tig = lane & 3; +#pragma unroll + for (int j = 0; j < NT; ++j) { + m[gid * ld + 8 * j + 2 * tig] = c[j][0] * scale; + m[gid * ld + 8 * j + 2 * tig + 1] = c[j][1] * scale; + m[(gid + 8) * ld + 8 * j + 2 * tig] = c[j][2] * scale; + m[(gid + 8) * ld + 8 * j + 2 * tig + 1] = c[j][3] * scale; + } +} +template <int NT> __device__ float st_max_abs(const float (&c)[NT][4]) { + float m = 0.0f; +#pragma unroll + for (int j = 0; j < NT; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) m = fmaxf(m, fabsf(c[j][q])); + return gtc_warp_max(m); +} +__global__ void st_state_kernel(const float* a, const float* k, float* out) { // out (16 x 32) = a (16 x 128) k^T + __shared__ __align__(16) uint16_t kh[GCH * GTC_KP], kl[GCH * GTC_KP]; + st_stage_k(kh, kl, k); + float s[16][4]; + st_load_c<16>(s, a, S); + const int es = gtc_scale_exp(st_max_abs<16>(s)); + float xt[4][4] = {}, qs[4][4] = {}; + gtc_prod_state(s, gtc_pow2(es), kh, kl, kh, kl, xt, qs); + st_store_c<4>(xt, out, GCH, gtc_pow2(-(8 + es))); +} +__global__ void st_update_kernel(const float* s0, const float* dd, const float* k, float eL, float* out) { // out (16 x 128) = eL s0 + dd (16 x 32) k + __shared__ __align__(16) uint16_t kh[GCH * GTC_KP], kl[GCH * GTC_KP]; + st_stage_k(kh, kl, k); + float s[16][4], dt[4][4], ddt[4][4]; + st_load_c<16>(s, s0, S); + st_load_c<4>(dt, dd, GCH); + const int ed = gtc_scale_exp(st_max_abs<4>(dt)); + const float sD = gtc_pow2(ed), sPre = eL * gtc_pow2(ed + 8); +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) ddt[j][q] = dt[j][q] * sD; +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) s[j][q] *= sPre; + gtc_update_state(s, ddt, kh, kl); + st_store_c<16>(s, out, S, gtc_pow2(-(ed + 8))); +} +// out (16 x 32) = d p^T: p's images x 2^eb (the scan's P carry 2^8, its T the prep's 2^et), d x 2^ed from its maximum +template <bool SKIP> __global__ void st_dt_kernel(const float* d, const float* p, int eb, float* out) { + __shared__ __align__(16) uint16_t ph[GCH * GTC_PP], pl[GCH * GTC_PP]; + for (int q = threadIdx.x; q < GCH * GCH / 4; q += 32) { + const int t = q / (GCH / 4), i = (q % (GCH / 4)) * 4; + gtc_split_store4(ph + t * GTC_PP + i, pl + t * GTC_PP + i, *reinterpret_cast<const float4*>(p + t * GCH + i), gtc_pow2(eb)); + } + __syncwarp(); + float dt[4][4], ot[4][4] = {}; + st_load_c<4>(dt, d, GCH); + const int ed = gtc_scale_exp(st_max_abs<4>(dt)); + gtc_prod_dt<SKIP>(dt, gtc_pow2(ed), ph, pl, ot); + st_store_c<4>(ot, out, GCH, gtc_pow2(-(ed + eb))); +} +int st_scale_exp(const std::vector<float>& m) { // the prep's gtc_scale_exp on the host: max |m| into [2^14, 2^15) + float mx = 0.0f; + for (float x : m) mx = std::max(mx, std::fabs(x)); + if (mx == 0.0f) return 0; + int e = 0; + std::frexp(mx, &e); // mx = f 2^e, f in [0.5, 1): floor(log2 mx) = e - 1 + e = 14 - (e - 1); + return e < -40 ? -40 : (e > 40 ? 40 : e); +} +struct StRng { // xorshift64, host side + uint64_t s; + explicit StRng(uint64_t seed) : s(seed) {} + float uni() { s ^= s << 13; s ^= s >> 7; s ^= s << 17; return ((float) (s >> 40) + 0.5f) / 16777216.0f; } + float gauss() { return std::sqrt(-2.0f * std::log(uni())) * std::cos(6.2831853f * uni()); } + float logmag(float lo, float hi) { return (uni() < 0.5f ? -1.0f : 1.0f) * std::pow(10.0f, lo + (hi - lo) * uni()); } +}; +float* st_upload(const std::vector<float>& v) { + float* d = dalloc<float>(v.size()); + ck(cudaMemcpy(d, v.data(), v.size() * 4, cudaMemcpyHostToDevice), "upload"); + return d; +} +std::vector<float> st_download(const float* d, size_t n) { + std::vector<float> v(n); + ck(cudaDeviceSynchronize(), "self-test kernel"); + ck(cudaMemcpy(v.data(), d, n * 4, cudaMemcpyDeviceToHost), "download"); + return v; +} +double st_max_rel(const std::vector<float>& got, const std::vector<double>& ref) { + double md = 0.0, mv = 0.0; + for (size_t i = 0; i < ref.size(); ++i) { + md = std::max(md, std::fabs((double) got[i] - ref[i])); + mv = std::max(mv, std::fabs(ref[i])); + } + return mv > 0.0 ? md / mv : md; +} +int selftest_frag() { + std::printf("--selftest-frag: the tensor-core scan's fragment helpers, one warp each\n"); + int fails = 0; + StRng rng(0x5e1f7e57ULL); + auto unit_rows = [&](std::vector<float>& k, int rows, int cols) { // gaussian rows, L2-normalized + for (int t = 0; t < rows; ++t) { + double ss = 0.0; + for (int r = 0; r < cols; ++r) { k[t * cols + r] = rng.gauss(); ss += (double) k[t * cols + r] * k[t * cols + r]; } + for (int r = 0; r < cols; ++r) k[t * cols + r] = (float) (k[t * cols + r] / std::sqrt(ss)); + } + }; + { // (b) X^T = S^T K^T: f16x3 with the state's 2^es and k's 2^8, B by ldmatrix + std::vector<float> a(16 * S), k(GCH * S); + for (float& x : a) x = rng.logmag(-3.0f, 2.0f); + unit_rows(k, GCH, S); + std::vector<double> ref(16 * GCH); + for (int c = 0; c < 16; ++c) + for (int i = 0; i < GCH; ++i) { + double v = 0.0; + for (int r = 0; r < S; ++r) v += (double) a[c * S + r] * k[i * S + r]; + ref[c * GCH + i] = v; + } + float* da = st_upload(a); + float* dk = st_upload(k); + float* dout = dalloc<float>(16 * GCH); + st_state_kernel<<<1, 32>>>(da, dk, dout); + const double rel = st_max_rel(st_download(dout, 16 * GCH), ref); + const bool bad = !(rel <= 2e-6); + std::printf(" (b) X^T = S^T K^T (16x128 . 128x32, f16x3, 2^es 2^8, ldmatrix): max |diff| / max |ref| %.2e %s\n", rel, bad ? "FAIL" : "ok"); + fails += bad; + cudaFree(da); cudaFree(dk); cudaFree(dout); + } + { // (c) S^T = eL S^T + Dd^T K: ldmatrix.trans, 2^ed, the accumulator scaled before and after + std::vector<float> s0(16 * S), dd(16 * GCH), k(GCH * S); + for (float& x : s0) x = rng.logmag(-3.0f, 2.0f); + for (float& x : dd) x = rng.logmag(-3.0f, 2.0f); + unit_rows(k, GCH, S); + const float eL = 0.25f + 0.75f * rng.uni(); + std::vector<double> ref(16 * S); + for (int c = 0; c < 16; ++c) + for (int r = 0; r < S; ++r) { + double v = (double) eL * s0[c * S + r]; + for (int i = 0; i < GCH; ++i) v += (double) dd[c * GCH + i] * k[i * S + r]; + ref[c * S + r] = v; + } + float* ds = st_upload(s0); + float* dd_ = st_upload(dd); + float* dk = st_upload(k); + float* dout = dalloc<float>(16 * S); + st_update_kernel<<<1, 32>>>(ds, dd_, dk, eL, dout); + const double rel = st_max_rel(st_download(dout, 16 * S), ref); + const bool bad = !(rel <= 2e-6); + std::printf(" (c) S^T = eL S^T + Dd^T K (16x32 . 32x128, f16x3, ldmatrix.trans, 2^ed pre / post scale): %.2e %s\n", rel, bad ? "FAIL" : "ok"); + fails += bad; + cudaFree(ds); cudaFree(dd_); cudaFree(dk); cudaFree(dout); + } + { // (d) D^T = Y^T T^T on f16x3 through gtc_prod_dt, a full random T of wide range with the prep's 2^et + std::vector<float> y(16 * GCH), t(GCH * GCH); + for (float& x : y) x = rng.logmag(-3.0f, 2.0f); + for (float& x : t) x = rng.logmag(-2.0f, 3.0f); + std::vector<double> ref(16 * GCH); + for (int c = 0; c < 16; ++c) + for (int i = 0; i < GCH; ++i) { + double v = 0.0; + for (int ip = 0; ip < GCH; ++ip) v += (double) y[c * GCH + ip] * t[i * GCH + ip]; + ref[c * GCH + i] = v; + } + float* dy = st_upload(y); + float* dt_ = st_upload(t); + float* dout = dalloc<float>(16 * GCH); + st_dt_kernel<false><<<1, 32>>>(dy, dt_, st_scale_exp(t), dout); + const double rel = st_max_rel(st_download(dout, 16 * GCH), ref); + const bool bad = !(rel <= 2e-6); + std::printf(" (d) D^T = Y^T T^T (16x32 . 32x32, f16x3, Y x 2^ey, T x 2^et): %.2e %s\n", rel, bad ? "FAIL" : "ok"); + fails += bad; + cudaFree(dy); cudaFree(dt_); cudaFree(dout); + } + { // (e) the triangle-skipped tile sets against the full ones: T unit lower triangular, P lower triangular + std::vector<float> y(16 * GCH), t(GCH * GCH), d(16 * GCH), p(GCH * GCH); + for (float& x : y) x = rng.logmag(-3.0f, 2.0f); + for (float& x : d) x = rng.logmag(-3.0f, 2.0f); + for (int i = 0; i < GCH; ++i) + for (int j = 0; j < GCH; ++j) { + t[i * GCH + j] = j < i ? rng.logmag(-2.0f, 3.0f) : (j == i ? 1.0f : 0.0f); + p[i * GCH + j] = j <= i ? 2.0f * rng.uni() - 1.0f : 0.0f; + } + std::vector<double> ref_d(16 * GCH), ref_o(16 * GCH); + for (int c = 0; c < 16; ++c) + for (int i = 0; i < GCH; ++i) { + double v = 0.0, w = 0.0; + for (int ip = 0; ip < GCH; ++ip) { v += (double) y[c * GCH + ip] * t[i * GCH + ip]; w += (double) d[c * GCH + ip] * p[i * GCH + ip]; } + ref_d[c * GCH + i] = v; + ref_o[c * GCH + i] = w; + } + float* dy = st_upload(y); + float* dt_ = st_upload(t); + float* dd_ = st_upload(d); + float* dp = st_upload(p); + float* full = dalloc<float>(16 * GCH); + float* skip = dalloc<float>(16 * GCH); + st_dt_kernel<false><<<1, 32>>>(dy, dt_, st_scale_exp(t), full); + st_dt_kernel<true><<<1, 32>>>(dy, dt_, st_scale_exp(t), skip); + const std::vector<float> f1 = st_download(full, 16 * GCH), s1 = st_download(skip, 16 * GCH); + const unsigned long long diff1 = std::memcmp(f1.data(), s1.data(), 16 * GCH * 4) != 0 ? diff_words(full, skip, 16 * GCH * 4) : 0; + const double rel1 = st_max_rel(s1, ref_d); + st_dt_kernel<false><<<1, 32>>>(dd_, dp, 8, full); + st_dt_kernel<true><<<1, 32>>>(dd_, dp, 8, skip); + const std::vector<float> f2 = st_download(full, 16 * GCH), s2 = st_download(skip, 16 * GCH); + const unsigned long long diff2 = std::memcmp(f2.data(), s2.data(), 16 * GCH * 4) != 0 ? diff_words(full, skip, 16 * GCH * 4) : 0; + const double rel2 = st_max_rel(s2, ref_o); + const bool bad = diff1 != 0 || diff2 != 0 || !(rel1 <= 2e-6) || !(rel2 <= 2e-6); + std::printf(" (e) triangle skipping: D^T 10 of 16 tiles %llu words differ (vs FP64 %.2e), o^T 6 of 8 tiles %llu words differ (vs FP64 %.2e) %s\n", + diff1, rel1, diff2, rel2, bad ? "FAIL" : "ok"); + fails += bad; + cudaFree(dy); cudaFree(dt_); cudaFree(dd_); cudaFree(dp); cudaFree(full); cudaFree(skip); + } + std::printf("--selftest-frag: %d failures\n", fails); + return fails; +} float median(std::vector<float> v) { std::sort(v.begin(), v.end()); return v.empty() ? 0.0f : v[v.size() / 2]; } -void bench(int64_t T) { +// tc_only (--bench-tc): the tensor-core series alone, for A / B runs of two builds back to back +void bench(int64_t T, bool tc_only = false) { Inputs in(T, 0xB3); const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; float* state = dalloc<float>(st); @@ -920,14 +1248,14 @@ void bench(int64_t T) { }; const int warm = 3, rounds = T >= 16384 ? 10 : 20; std::vector<float> t_rec[kRecCount], t_norm[2]; - for (int i = 0; i < warm + rounds; ++i) { + for (int i = 0; !tc_only && i < warm + rounds; ++i) { for (int j = 0; j < kRecCount; ++j) { const Rec v = (Rec) ((i + j) % kRecCount); // a different variant first in each round const float ms = timed([&] { run_rec(v, state, in, oc); }); if (i >= warm) t_rec[v].push_back(ms); } } - for (int i = 0; i < warm + rounds; ++i) { + for (int i = 0; !tc_only && i < warm + rounds; ++i) { for (int j = 0; j < 2; ++j) { const int v = (i + j) % 2; const float ms = timed([&] { @@ -938,7 +1266,7 @@ void bench(int64_t T) { } } std::vector<float> t_kc[2]; // gdn_rec_kh_kernel and the chunked recurrence, alternating - const bool can_chunk = gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess && + const bool can_chunk = !tc_only && gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess && cudaDeviceSynchronize() == cudaSuccess; for (int i = 0; can_chunk && i < warm + rounds; ++i) for (int j = 0; j < 2; ++j) { @@ -949,8 +1277,30 @@ void bench(int64_t T) { }); if (i >= warm) t_kc[v].push_back(ms); } + std::vector<float> t_tc[2]; // gdn_rec_kh_kernel and the tensor-core scan, alternating + const bool can_tc = gdn_rec_tc(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess && + cudaDeviceSynchronize() == cudaSuccess; + for (int i = 0; can_tc && i < warm + rounds; ++i) + for (int j = 0; j < 2; ++j) { + const int v = (i + j) % 2; + const float ms = timed([&] { + if (v == 0) gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG)>>>(state, in.h, in.gate, in.beta, oc, in.T); + else ck(gdn_rec_tc(state, in.h, in.gate, in.beta, oc, in.T, 0), "tc"); + }); + if (i >= warm) t_tc[v].push_back(ms); + } const float r0 = median(t_rec[kBefore]), r1 = median(t_rec[kKeyHead]), n0 = median(t_norm[0]), n1 = median(t_norm[1]); std::printf(" T = %lld tokens, one layer (48 value heads), medians of %d alternating runs:\n", (long long) T, rounds); + if (tc_only) { + const float kh = median(t_tc[0]), tc = median(t_tc[1]); + std::printf(" recurrence, gdn_rec_kh_kernel %8.2f ms (%.3f us per token)\n", kh, 1000.0f * kh / (float) T); + std::printf(" recurrence, tensor-core chunked (STRATA_GDN_TC=1) %8.2f ms (%.3f us per token) %.2fx gdn_rec_kh_kernel\n", + tc, 1000.0f * tc / (float) T, kh / tc); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + cudaFree(state); cudaFree(oc); cudaFree(y16); + return; + } std::printf(" recurrence, before (gdn_rec_cols_pipe_kernel) %8.2f ms (%.3f us per token)\n", r0, 1000.0f * r0 / (float) T); std::printf(" recurrence, gdn_rec_kh_kernel %8.2f ms (%.3f us per token) %.2fx\n", r1, @@ -960,6 +1310,11 @@ void bench(int64_t T) { std::printf(" recurrence, chunked (STRATA_GDN_CHUNKED=1) %8.2f ms (%.3f us per token) %.2fx gdn_rec_kh_kernel\n", kc, 1000.0f * kc / (float) T, kh / kc); } + if (can_tc) { + const float kh = median(t_tc[0]), tc = median(t_tc[1]); + std::printf(" recurrence, tensor-core chunked (STRATA_GDN_TC=1) %8.2f ms (%.3f us per token) %.2fx gdn_rec_kh_kernel\n", + tc, 1000.0f * tc / (float) T, kh / tc); + } std::printf(" output norm, before (FP32 and FP16 store) %8.2f ms\n", n0); std::printf(" output norm, FP16 store only %8.2f ms %.2fx\n", n1, n0 / n1); std::printf(" 36 DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n", @@ -1357,18 +1712,36 @@ void fewer_sms(int64_t T) { } // namespace int main(int argc, char** argv) { - bool do_bench = false; - for (int i = 1; i < argc; ++i) + bool do_bench = false, do_self = false, do_long = false, do_bench_tc = false; + for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--bench") == 0) do_bench = true; + if (std::strcmp(argv[i], "--selftest-frag") == 0) do_self = true; + if (std::strcmp(argv[i], "--long") == 0) do_long = true; + if (std::strcmp(argv[i], "--bench-tc") == 0) do_bench_tc = true; + } cudaDeviceProp p{}; ck(cudaGetDeviceProperties(&p, 0), "device"); std::printf("gdn_rec_parity on %s (sm_%d%d)\n", p.name, p.major, p.minor); int fails = 0; + if (do_self) { // the tensor-core helpers alone (one warp each, any sm_80+ card; the device code below sm_80 traps) + if (p.major < 8) { std::printf("--selftest-frag: the tensor-core helpers need sm_80 or newer (skipped)\n"); return 77; } + fails = selftest_frag(); + std::printf("gdn_rec_parity: %d failures\n", fails); + return fails ? 1 : 0; + } + if (do_bench_tc) { // the tensor-core timings alone + for (const int64_t T : {(int64_t) 2048, (int64_t) 8192, (int64_t) 32768}) bench(T, true); + return 0; + } const int64_t Ts[] = {1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257, 1000, 4099}; uint64_t seed = 11; for (const int64_t T : Ts) fails += check_bits(T, seed++); for (const int64_t T : Ts) fails += check_chunked(T, seed++); for (const int64_t T : {(int64_t) 8192, (int64_t) 32768}) fails += check_chunked(T, seed++); + for (const int64_t T : Ts) fails += check_tc(T, seed++); + for (const int64_t T : {(int64_t) 8192, (int64_t) 32768}) fails += check_tc(T, seed++); + for (const int64_t T : {(int64_t) 4099, (int64_t) 32768}) { fails += check_tc_stress(T, seed); seed += 8; } + if (do_long) fails += check_tc(51820, seed++); // the engine's longest prompt (about 7 GB of inputs and outputs) if (do_bench) { std::printf("--bench: the prompt path's DeltaNet recurrence\n"); bench(2048); diff --git a/src/prefill/gdn_tc.cuh b/src/prefill/gdn_tc.cuh new file mode 100644 index 00000000..6d09ea83 --- /dev/null +++ b/src/prefill/gdn_tc.cuh @@ -0,0 +1,586 @@ +// src/prefill/gdn_tc.cuh - the chunked DeltaNet recurrence's scan on the tensor cores (STRATA_GDN_TC=1), sm_80+. +// +// Included inside the anonymous namespace of src/prefill/kernels.cu and of src/prefill/gdn_rec_parity.cu, after +// gdn_chunk_scan_kernel (the harness runs the engine's kernels verbatim: one text, included twice). It uses S, HK, HV, +// C, VPK, GCH, GSB, GTP, gdn_cp16 / gdn_cp_commit / gdn_cp_wait_all from there and reads no environment. +// +// gdn_chunk_scan_kernel's chunk algebra (kernels.cu, "STRATA_GDN_CHUNKED=1"), every product transposed so that a +// warp's slice of the state is the mma A operand and never leaves its registers: a block per value head, warp w owns +// value columns 16w..16w+15 of S^T (16 columns x 128 rows = 16 m16n8 f32 accumulator tiles, 64 registers a lane) and +// all 32 tokens of a chunk, so not one product couples two warps: +// X^T (16c x 32i) = S0^T . K^T f16x3, k = state row (8 k16-steps), n = token (4 tiles) +// QS^T (16c x 32t) = S0^T . Q^T the same A fragments +// Y^T (16c x 32i) = beta_i (V^T - e_i X^T) elementwise on the accumulators +// D^T (16c x 32i) = Y^T . T^T f16x3, k = token i' (2 steps), n = token i: T is zero above its diagonal, +// so 6 of 8 tiles (as P below) +// o^T (16c x 32t) = e_t QS^T + D^T . P^T f16x3, k = i (2 steps), n = t: P zero above its diagonal (6 of 8 tiles) +// Dd^T (16c x 32i) = f_i D^T, f_i = exp(gL - gamma_i) +// S^T (16c x 128r) = eL S0^T + Dd^T . K f16x3, k = token (2 steps), n = state row (16 tiles) +// 324 mma a warp a chunk; the only shared data are the staged inputs (k, q, T and P as f16 hi / lo images, v, the +// per-token scalars), one barrier a chunk. +// +// Numerics (the harness holds the result within 1e-4 of gdn_rec_kh_kernel, as the FP32 chunked pair): an f16 operand +// is split x = hi + lo, hi = f16(x), lo = f16(x - hi), and a product takes hi.hi + hi.lo + lo.hi, dropping lo.lo: with +// both parts normal that is within 3 x 2^-22 |a||b| of the exact product, the 3xTF32 bound, at half the tensor time. +// For the low part to be normal the operand's largest entry must sit in [2^14, 2^15), which a power of two does +// exactly: k and q (unit vectors after gdn_l2_kernel) carry 2^8, P (|P| <= 1) 2^8, the state 2^es from a warp max +// per chunk, Y^T 2^ey and D^T 2^ed likewise, T = (I + A)^-1 (no a-priori bound) 2^et from the prep's warp max; the +// powers are taken out of the per-token scalars and of the accumulator before and after the mma (one FMUL an +// element, exact). (D^T = Y^T T^T on tf32x3 with T split at use, the form before this one, cost 30 mma, 32 shuffles +// and 48 tf32 conversions a warp a chunk against 18 mma now; measured in the commit that changed it.) +#if !defined(__HIPCC__) +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define STRATA_GDN_TC_SM80 1 +#else +#define STRATA_GDN_TC_SM80 0 // device code for older cards: the wrappers trap (gdn_rec_tc never launches there) +#endif + +constexpr int GTC_KP = S + 8; // f16 k / q rows: a 272-B stride puts the 8 rows of a ldmatrix 8x8 on 8 distinct 16-B lanes +constexpr int GTC_VP = S + 4; // f32 v rows: lane (gid, tig) reads word 264 tig + gid, 32 distinct banks +constexpr int GTC_PP = GCH + 8; // f16 T / P rows: an 80-B stride, 8 rows on distinct 16-B lanes +constexpr int GTC_CW = S / 16; // consumer warps a block: 16 value columns each +// dynamic shared memory a block, two buffers each: k / q hi / lo, v, (z), T hi / lo, P hi / lo, the token scalars +// (beta, exp(gamma), exp(gL - gamma), gamma) as float4, (the norm's o^2 partials), T's scale 2^-et: 124,944 B +// without the fused norm, 160,784 with it (the 166,912 opt-in of GA100) +template <bool NORM> +constexpr size_t kTcScanSmem = 2 * (4 * GCH * GTC_KP * 2 + GCH * GTC_VP * 4 + (NORM ? GCH * GTC_VP * 4 : 0) + + 4 * GCH * GTC_PP * 2 + GCH * 16 + (NORM ? GCH * GTC_CW * 4 : 0)) + 16; +static_assert(kTcScanSmem<false> == 124944 && kTcScanSmem<true> == 160784, "gdn_tc.cuh: the shared-memory plan"); +// the prep's scratch for a super-block (gdn_tc_scratch, one a device, 60.3 MB): the T images x 2^et as +// [chunk][vh][2: hi, lo][GCH][GCH] f16 and their scales 2^-et as [chunk][vh], the token scalars as float4 +// [chunk][vh][GCH], the k and q images x 2^8 as [chunk][qh][4: k hi, k lo, q hi, q lo][GCH][S] and the P images x 2^8 +// as [chunk][vh][2: hi, lo][GCH][GCH] - every row a multiple of 16 B, so the scan stages all of it by cp.async +constexpr int GTC_NB = GSB / GCH; +struct GtcScratch { + uint16_t* ti; + float* te; + float4* sc; + uint16_t* kq; + uint16_t* pi; +}; +constexpr size_t kTcTiBytes = (size_t) GTC_NB * HV * 2 * GCH * GCH * 2, kTcTeBytes = (size_t) GTC_NB * HV * 4, + kTcScBytes = (size_t) GTC_NB * HV * GCH * 16, kTcKqBytes = (size_t) GTC_NB * HK * 4 * GCH * S * 2, + kTcPiBytes = (size_t) GTC_NB * HV * 2 * GCH * GCH * 2; +static_assert(kTcTiBytes + kTcTeBytes + kTcScBytes + kTcKqBytes + kTcPiBytes == 60305408, "gdn_tc.cuh: the scratch plan"); +// allocated on first use and kept, as gdn_chunk_scratch (kernels.cu); ti == nullptr when the card had no room +GtcScratch gdn_tc_scratch() { + static unsigned char* bufs[64] = {}; + GtcScratch r = {nullptr, nullptr, nullptr, nullptr, nullptr}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return r; } + if (bufs[dev] == nullptr && cudaMalloc((void**) &bufs[dev], kTcTiBytes + kTcTeBytes + kTcScBytes + kTcKqBytes + kTcPiBytes) != cudaSuccess) { + cudaGetLastError(); + bufs[dev] = nullptr; + return r; + } + unsigned char* p = bufs[dev]; + r.ti = reinterpret_cast<uint16_t*>(p); + r.te = reinterpret_cast<float*>(p + kTcTiBytes); + r.sc = reinterpret_cast<float4*>(p + kTcTiBytes + kTcTeBytes); + r.kq = reinterpret_cast<uint16_t*>(p + kTcTiBytes + kTcTeBytes + kTcScBytes); + r.pi = reinterpret_cast<uint16_t*>(p + kTcTiBytes + kTcTeBytes + kTcScBytes + kTcKqBytes); + return r; +} + +// the warp's largest of non-negative floats: their bits order as unsigned integers, so one redux.sync (sm_80). Under +// the full mask: __activemask() does not reconverge the warp (CUDA guide), and the first call of the scan follows a +// lane-divergent branch (the L2 prefetch of tokens past the end, in the chunk two before the end whenever +// 0 < T - f_t0 < 32), so with it the lanes could reduce under a partial mask and disagree on es. The harness build +// happened to close that branch (BSYNC) before the REDUX.MAX; the engine's build is a separate compile that nothing +// checks. The kernel has no early return, so the full mask costs no reconvergence code. +__device__ __forceinline__ float gtc_warp_max(float v) { +#if STRATA_GDN_TC_SM80 + return __uint_as_float(__reduce_max_sync(0xffffffffu, __float_as_uint(v))); +#else +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +#endif +} +__device__ __forceinline__ float gtc_pow2(int e) { return __int_as_float((e + 127) << 23); } // 2^e, |e| < 127 +// the power of two that puts m = max |x| >= 0 in [2^14, 2^15): f16 hi never overflows (65504) and the low part of +// every entry within 2^-17 of the max stays normal; clamped so that the compensating powers stay far from f32's range +__device__ __forceinline__ int gtc_scale_exp(float m) { + if (m == 0.0f) return 0; + const int e = 14 - ((__float_as_int(m) >> 23) - 127); + return e < -40 ? -40 : (e > 40 ? 40 : e); +} + +// ---- the tensor-core wrappers (PTX ISA "Matrix Fragments": lane = 4 gid + tig) +// m16n8k16 f16: A a0 = (row gid, cols 2tig, 2tig+1) a1 = (gid+8, ..) a2 = (gid, 2tig+8..) a3 = (gid+8, 2tig+8..); +// B b0 = (k 2tig, 2tig+1; n gid) b1 = (k 2tig+8..; n gid); C/D c0 = (gid, 2tig) c1 = (gid, 2tig+1) +// c2 = (gid+8, 2tig) c3 = (gid+8, 2tig+1) - so two adjacent C tiles ARE the next product's A fragment +// ldmatrix m8n8.x4.b16: lanes 8m..8m+7 give the row addresses of matrix m; a lane gets (row gid, cols 2tig, 2tig+1) +// of each matrix (the lower column in the low half), or with .trans (rows 2tig, 2tig+1; col gid) +__device__ __forceinline__ void gtc_ldsm_x4(uint32_t (&r)[4], const void* smem) { +#if STRATA_GDN_TC_SM80 + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"((unsigned) __cvta_generic_to_shared(smem))); +#else + r[0] = r[1] = r[2] = r[3] = 0u; (void) smem; __trap(); +#endif +} +__device__ __forceinline__ void gtc_ldsm_x4_trans(uint32_t (&r)[4], const void* smem) { +#if STRATA_GDN_TC_SM80 + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"((unsigned) __cvta_generic_to_shared(smem))); +#else + r[0] = r[1] = r[2] = r[3] = 0u; (void) smem; __trap(); +#endif +} +__device__ __forceinline__ void gtc_mma_f16(float (&c)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { +#if STRATA_GDN_TC_SM80 + asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +#else + (void) c; (void) a; (void) b0; (void) b1; __trap(); +#endif +} +// the three passes of a split product, small terms first (as qsa_select.cu): lo.hi, hi.lo, hi.hi +__device__ __forceinline__ void gtc_mma3_f16(float (&c)[4], const uint32_t (&ah)[4], const uint32_t (&al)[4], uint32_t bh0, + uint32_t bh1, uint32_t bl0, uint32_t bl1) { + gtc_mma_f16(c, al, bh0, bh1); + gtc_mma_f16(c, ah, bl0, bl1); + gtc_mma_f16(c, ah, bh0, bh1); +} +// x0, x1 -> packed f16 hi (x0 in the low half) and lo = f16(x - hi): x - hi is exact in f32 (hi carries x's exponent) +__device__ __forceinline__ void gtc_split_f16x2(float x0, float x1, uint32_t& hi, uint32_t& lo) { + union { __half2 h; uint32_t u; } cv; + cv.h = __floats2half2_rn(x0, x1); + hi = cv.u; + const float2 r = __half22float2(cv.h); + cv.h = __floats2half2_rn(x0 - r.x, x1 - r.y); + lo = cv.u; +} +// four consecutive elements of an f16 hi / lo row from a float4 x scale (an 8-byte store each) +__device__ __forceinline__ void gtc_split_store4(uint16_t* hi, uint16_t* lo, float4 v, float scale) { + uint32_t h0, l0, h1, l1; + gtc_split_f16x2(v.x * scale, v.y * scale, h0, l0); + gtc_split_f16x2(v.z * scale, v.w * scale, h1, l1); + *reinterpret_cast<uint2*>(hi) = make_uint2(h0, h1); + *reinterpret_cast<uint2*>(lo) = make_uint2(l0, l1); +} +// a float4 from shared memory the compiler does not keep: the per-token scalars are read in three phases of a chunk, +// a component each, and kept across them they cost 24 registers a thread +__device__ __forceinline__ float4 gtc_lds128(const float4* p) { + float4 v; +#if STRATA_GDN_TC_SM80 + asm volatile("ld.shared.v4.f32 {%0,%1,%2,%3}, [%4];" + : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) + : "r"((unsigned) __cvta_generic_to_shared(p))); +#else + v = *p; +#endif + return v; +} +// ---- the products of a chunk, a warp each (the self-test of gdn_rec_parity --selftest-frag runs them one by one) +// X^T = S^T K^T and QS^T = S^T Q^T: A = the state fragments x sA (= 2^es) split in f16 hi / lo just in time per k16-step +// (tiles 2kk and 2kk + 1 of S^T are that step's A fragment), B = the f16 hi / lo images of k and q ([GCH][GTC_KP] in +// shared memory, rows = tokens) by ldmatrix: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's +// row is token 8 n-tile + (lane & 7). The accumulators come out as 2^(8 + es) times the products. 2 x 96 mma. +__device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA, const uint16_t* kh, const uint16_t* kl, + const uint16_t* qh, const uint16_t* ql, float (&xt)[4][4], float (&qs)[4][4]) { + const int lane = threadIdx.x & 31; + const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1); +#pragma unroll + for (int kk = 0; kk < S / 16; ++kk) { + uint32_t ah[4], al[4]; + gtc_split_f16x2(s[2 * kk][0] * sA, s[2 * kk][1] * sA, ah[0], al[0]); + gtc_split_f16x2(s[2 * kk][2] * sA, s[2 * kk][3] * sA, ah[1], al[1]); + gtc_split_f16x2(s[2 * kk + 1][0] * sA, s[2 * kk + 1][1] * sA, ah[2], al[2]); + gtc_split_f16x2(s[2 * kk + 1][2] * sA, s[2 * kk + 1][3] * sA, ah[3], al[3]); +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const int o = off + 16 * hf * GTC_KP + 16 * kk; + uint32_t bh[4], bl[4]; + gtc_ldsm_x4(bh, kh + o); + gtc_ldsm_x4(bl, kl + o); + gtc_mma3_f16(xt[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mma3_f16(xt[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + gtc_ldsm_x4(bh, qh + o); + gtc_ldsm_x4(bl, ql + o); + gtc_mma3_f16(qs[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mma3_f16(qs[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + } +} +// o^T += (sD D^T) (2^8 P^T) on f16x3: A = the D^T tiles x sD (= 2^ed) split per k16-step, B = the f16 hi / lo images +// of P x 2^8 ([GCH][GTC_PP], rows = tokens t) by ldmatrix as in gtc_prod_state. SKIP leaves out the tiles above P's +// diagonal: tokens t < 16 (n-tiles 0, 1) see no i >= 16 (k-step 1). 18 (SKIP) or 24 mma. D^T += (sY Y^T) (2^et T^T) +// is the same product on the T images (T is zero above its diagonal too), the accumulator x 2^(ey + et). +template <bool SKIP> +__device__ __forceinline__ void gtc_prod_dt(const float (&dt)[4][4], float sD, const uint16_t* ph, const uint16_t* pl, + float (&ot)[4][4]) { + const int lane = threadIdx.x & 31; + const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_PP + 8 * ((lane >> 3) & 1); +#pragma unroll + for (int ks = 0; ks < GCH / 16; ++ks) { + uint32_t ah[4], al[4]; + gtc_split_f16x2(dt[2 * ks][0] * sD, dt[2 * ks][1] * sD, ah[0], al[0]); + gtc_split_f16x2(dt[2 * ks][2] * sD, dt[2 * ks][3] * sD, ah[1], al[1]); + gtc_split_f16x2(dt[2 * ks + 1][0] * sD, dt[2 * ks + 1][1] * sD, ah[2], al[2]); + gtc_split_f16x2(dt[2 * ks + 1][2] * sD, dt[2 * ks + 1][3] * sD, ah[3], al[3]); +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + if (SKIP && ks == 1 && hf == 0) continue; + const int o = off + 16 * hf * GTC_PP + 16 * ks; + uint32_t bh[4], bl[4]; + gtc_ldsm_x4(bh, ph + o); + gtc_ldsm_x4(bl, pl + o); + gtc_mma3_f16(ot[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mma3_f16(ot[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + } +} +// S^T += Dd^T (2^8 K) on f16x3: A = the (already scaled) Dd^T tiles split per k16-step, B = the same k images read the +// other way by ldmatrix.trans: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's row is token +// 16 ks + 8 k-half + (lane & 7), its 16-B piece state rows 8 n-tile.. 96 mma. +__device__ __forceinline__ void gtc_update_state(float (&s)[16][4], const float (&dd)[4][4], const uint16_t* kh, + const uint16_t* kl) { + const int lane = threadIdx.x & 31; + const int off = (8 * ((lane >> 3) & 1) + (lane & 7)) * GTC_KP + 8 * (lane >> 4); +#pragma unroll + for (int ks = 0; ks < GCH / 16; ++ks) { + uint32_t ah[4], al[4]; + gtc_split_f16x2(dd[2 * ks][0], dd[2 * ks][1], ah[0], al[0]); + gtc_split_f16x2(dd[2 * ks][2], dd[2 * ks][3], ah[1], al[1]); + gtc_split_f16x2(dd[2 * ks + 1][0], dd[2 * ks + 1][1], ah[2], al[2]); + gtc_split_f16x2(dd[2 * ks + 1][2], dd[2 * ks + 1][3], ah[3], al[3]); +#pragma unroll + for (int hf = 0; hf < S / 16; ++hf) { + const int o = off + 16 * ks * GTC_KP + 16 * hf; + uint32_t bh[4], bl[4]; + gtc_ldsm_x4_trans(bh, kh + o); + gtc_ldsm_x4_trans(bl, kl + o); + gtc_mma3_f16(s[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mma3_f16(s[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + } +} + +// ---- the prep: gdn_chunk_prep_kernel (kernels.cu) for the tensor-core scan, a block per (chunk, key head): the same +// A, solve, T and P, but the Gram products k_t.k_i and q_t.k_i on the tensor cores (f16x3 from the k and q hi / lo +// images x 2^8, which the block builds first in shared memory straight from the float4 registers the rows arrive in, +// rows past the chunk's end zero: 48 mma a warp against ~1,150 LDS a thread for the FFMA form, which was LDS-bound at +// 233 us a 2048-token super-block), and it writes what the scan stages by cp.async with no conversion of its own: the +// same k / q images, P as f16 hi / lo images x 2^8 (the split the scan did, element by element) and the token scalars +// (beta, exp(gamma), exp(gL - gamma), gamma) as a float4 a token, T as f16 hi / lo images x 2^et, et from the warp's +// largest |T| (2^-et beside them in te). The Gram entries are within 3 x 2^-22 of exact (the scan's bound), so T and +// P differ from gdn_chunk_prep_kernel's by that. +constexpr size_t kTcPrepSmem = (size_t) 4 * GCH * GTC_KP * 2 + 2 * GCH * GTP * 4; // the images, then k_t.k_i and q_t.k_i +static_assert(VPK * GCH * GTP * 4 <= 4 * GCH * GTC_KP * 2, "gdn_tc_prep_kernel: A fits where the images were"); +__global__ void __launch_bounds__(256) gdn_tc_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate, + const float* __restrict__ beta, uint16_t* __restrict__ ti, + float* __restrict__ te, float4* __restrict__ sc, + uint16_t* __restrict__ kq, uint16_t* __restrict__ pi, int64_t t0, + int64_t T) { + extern __shared__ __align__(16) float gsm[]; + uint16_t* im = reinterpret_cast<uint16_t*>(gsm); // [4][GCH][GTC_KP] k hi, k lo, q hi, q lo (x 2^8) + float* skk = gsm + 4 * GCH * GTC_KP / 2; // [GCH][GTP] k_t.k_i + float* sqk = skk + GCH * GTP; // [GCH][GTP] q_t.k_i + float* sa = gsm; // [VPK][GCH][GTP] A, then T below the diagonal (over the + // images: read by then) + const int qh = blockIdx.y, ch = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int64_t tb = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - tb); + // after the Gram: warps j and VPK + j take value head j (lane i: token i), the first A, the solve and T, the + // second P and the token scalars; their beta and gate (past the end: gate 0, beta 0, no effect on S) are loaded + // now so that they are in by then + const int j = warp % VPK, vh = qh + j * HK, i = lane; + const bool pv = warp < 2 * VPK && i < n; + const float b = pv ? beta[(tb + i) * HV + vh] : 0.0f; + float gam = pv ? gate[(tb + i) * HV + vh] : 0.0f; + { // k and q as float4, every load issued before the first store; the images to shared and to global + constexpr int NP = GCH * S / 4 / 256; // float4 a thread, each of k and q + float4 kv[NP], qv[NP]; +#pragma unroll + for (int m = 0; m < NP; ++m) { + const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + kv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + HK * S + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f); + qv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f); + } + uint16_t* img = kq + ((size_t) ch * HK + qh) * 4 * GCH * S; +#pragma unroll + for (int m = 0; m < NP; ++m) { + const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + const int o = t * GTC_KP + r; + gtc_split_store4(im + o, im + GCH * GTC_KP + o, kv[m], 256.0f); + gtc_split_store4(im + 2 * GCH * GTC_KP + o, im + 3 * GCH * GTC_KP + o, qv[m], 256.0f); + gtc_split_store4(img + t * S + r, img + GCH * S + t * S + r, kv[m], 256.0f); + gtc_split_store4(img + 2 * GCH * S + t * S + r, img + 3 * GCH * S + t * S + r, qv[m], 256.0f); + } + } + __syncthreads(); + { // the Gram products: warp w takes product w >> 2 (k_t.k_i, q_t.k_i), rows 16 ((w >> 1) & 1).. (the A + // tile, by ldmatrix as a row-major [t][r] 16 x 16), columns 16 (w & 1).. (two n-tiles: B = k^T, stored + // [n][k] = the k rows, by ldmatrix as the scan's gtc_prod_state); the accumulators come out x 2^16 + const int pr = warp >> 2, mt = (warp >> 1) & 1, np = warp & 1; + const uint16_t* ah_ = im + 2 * pr * GCH * GTC_KP + (16 * mt + (lane & 7) + 8 * ((lane >> 3) & 1)) * GTC_KP + 8 * (lane >> 4); + const uint16_t* bh_ = im + (16 * np + 8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1); + float c[2][4] = {}; +#pragma unroll + for (int kk = 0; kk < S / 16; ++kk) { + uint32_t ah[4], al[4], bh[4], bl[4]; + gtc_ldsm_x4(ah, ah_ + 16 * kk); + gtc_ldsm_x4(al, ah_ + GCH * GTC_KP + 16 * kk); + gtc_ldsm_x4(bh, bh_ + 16 * kk); + gtc_ldsm_x4(bl, bh_ + GCH * GTC_KP + 16 * kk); + gtc_mma3_f16(c[0], ah, al, bh[0], bh[1], bl[0], bl[1]); + gtc_mma3_f16(c[1], ah, al, bh[2], bh[3], bl[2], bl[3]); + } + float* g = pr ? sqk : skk; + const int gid = lane >> 2, tig = lane & 3; +#pragma unroll + for (int j = 0; j < 2; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int t = 16 * mt + gid + 8 * (q >> 1), i = 16 * np + 8 * j + 2 * tig + (q & 1); + g[t * GTP + i] = i <= t ? c[j][q] * gtc_pow2(-16) : 0.0f; + } + } + __syncthreads(); + if (warp >= 2 * VPK) return; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const float u = __shfl_up_sync(0xffffffffu, gam, o); + if (lane >= o) gam += u; + } + if (warp >= VPK) { // P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) x 2^8 as f16 hi / lo; the scalars + uint16_t* Ph = pi + ((int64_t) ch * HV + vh) * 2 * GCH * GCH; + uint16_t* Pl = Ph + GCH * GCH; +#pragma unroll + for (int t = 0; t < GCH; ++t) { + const float gt = __shfl_sync(0xffffffffu, gam, t); + const float p = (i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f) * 256.0f; + const __half hi = __float2half_rn(p); + Ph[t * GCH + i] = __half_as_ushort(hi); + Pl[t * GCH + i] = __half_as_ushort(__float2half_rn(p - __half2float(hi))); + } + const float gL = __shfl_sync(0xffffffffu, gam, GCH - 1); + sc[((int64_t) ch * HV + vh) * GCH + i] = make_float4(b, expf(gam), expf(gL - gam), gam); + return; + } + float* a = sa + j * GCH * GTP; +#pragma unroll + for (int t = 0; t < GCH; ++t) { + const float gt = __shfl_sync(0xffffffffu, gam, t), bt = __shfl_sync(0xffffffffu, b, t); + a[t * GTP + i] = i < t ? bt * expf(gt - gam) * skk[t * GTP + i] : (i == t ? 1.0f : 0.0f); + } + __syncwarp(); + // T = (I + A)^-1 by forward substitution, row by row: T[t][i] = -sum_{k < t} A[t][k] T[k][i] over the finished + // rows (diagonal 1, zeros above it: the terms k < i add an exact 0, so the same bits as summing from k = i). + // Lane i keeps its column T[.][i] in registers, so a row needs only A's row t (a broadcast load a term) and A + // is never written: no store and no __syncwarp a row + float tv[GCH]; + tv[0] = i == 0 ? 1.0f : 0.0f; +#pragma unroll + for (int t = 1; t < GCH; ++t) { + float v = 0.0f; +#pragma unroll + for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], tv[k], v); + tv[t] = i < t ? v : (i == t ? 1.0f : 0.0f); + } + // T's images x 2^et (its largest entry in [2^14, 2^15), as the scan scales its own operands) + float mt4[4] = {}; +#pragma unroll + for (int t = 0; t < GCH; ++t) mt4[t & 3] = fmaxf(mt4[t & 3], fabsf(tv[t])); + const int et = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(mt4[0], mt4[1]), fmaxf(mt4[2], mt4[3])))); + const float sT = gtc_pow2(et); + uint16_t* Th = ti + ((int64_t) ch * HV + vh) * 2 * GCH * GCH; + uint16_t* Tl = Th + GCH * GCH; +#pragma unroll + for (int t = 0; t < GCH; ++t) { + const float x = tv[t] * sT; + const __half hi = __float2half_rn(x); + Th[t * GCH + i] = __half_as_ushort(hi); + Tl[t * GCH + i] = __half_as_ushort(__float2half_rn(x - __half2float(hi))); + } + if (i == 0) te[(int64_t) ch * HV + vh] = gtc_pow2(-et); +} + +// ---- the scan: a block per value head (48 blocks, one wave on 48 of the CMP 170HX's 70 SMs), 8 consumer warps of 16 +// value columns each walking every chunk of the super-block with their state slice in registers (written back at the +// end as gdn_chunk_scan_kernel does), the prep's scratch from gdn_tc_prep_kernel. Everything a chunk needs arrives by +// cp.async, issued for the next chunk right after the one __syncthreads a chunk (which publishes the buffer just +// landed and ends every read of the other one): the k / q and P f16 images, T and the token scalars as the prep +// wrote them, v from h (its rows past the chunk's end zero-filled). The 256 threads do no conversion of their own. +// Earlier forms, measured on this card: the scan splitting k / q itself after the state update (0.282 us a token; +// ~300 split instructions a warp a chunk and the staging exposed at the chunk's end); two stager warps with named +// barriers (6 % slower: registers are allocated per SM sub-partition, 16K each, and a block of more than 8 warps puts +// 3 on a sub-partition, which caps the kernel at 168 registers a thread; the consumers need about 200 and spilled. +// 8 warps, 2 a sub-partition, may have 255). +// NORM (step 5: the output norm fused, the FP16 output written here) is not implemented yet; oc_out takes the FP32 +// output as gdn_chunk_scan_kernel writes it. +template <bool NORM> +__global__ void __launch_bounds__(GTC_CW * 32, 1) +gdn_tc_scan_kernel(float* __restrict__ state, const float* __restrict__ h, const uint16_t* __restrict__ tig_, + const float* __restrict__ teg, const float4* __restrict__ scg, const uint16_t* __restrict__ kqg, + const uint16_t* __restrict__ pig, float* __restrict__ oc_out, int64_t t0, int nch, int64_t T) { + static_assert(!NORM, "gdn_tc_scan_kernel: the fused output norm is not implemented yet"); + constexpr int NT = GTC_CW * 32; + extern __shared__ __align__(16) unsigned char gtc_sm[]; + uint16_t* kh = reinterpret_cast<uint16_t*>(gtc_sm); // [2][GCH][GTC_KP] f16 of k x 2^8 (hi) + uint16_t* kl = kh + 2 * GCH * GTC_KP; // [2][GCH][GTC_KP] what hi left out (lo) + uint16_t* qh = kl + 2 * GCH * GTC_KP; // q likewise + uint16_t* ql = qh + 2 * GCH * GTC_KP; + float* sv = reinterpret_cast<float*>(ql + 2 * GCH * GTC_KP); // [2][GCH][GTC_VP] v + uint16_t* th = reinterpret_cast<uint16_t*>(sv + 2 * GCH * GTC_VP); // [2][GCH][GTC_PP] T x 2^et hi / lo + uint16_t* tl = th + 2 * GCH * GTC_PP; + uint16_t* ph = tl + 2 * GCH * GTC_PP; // [2][GCH][GTC_PP] P x 2^8 hi / lo + uint16_t* pl = ph + 2 * GCH * GTC_PP; + float4* sc = reinterpret_cast<float4*>(pl + 2 * GCH * GTC_PP); // [2][GCH] (beta, exp(gamma), exp(gL - gamma), gamma) + float* ste = reinterpret_cast<float*>(sc + 2 * GCH); // [2] 2^-et + const int vh = blockIdx.x, qhd = vh % HK; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, gid = lane >> 2, tig = lane & 3; + const size_t rs = (size_t) HV * S; + // chunk ch into buffer b, this thread's 16-B pieces (one cp.async group): the four k / q images (4 x GCH rows of + // 16 pieces: 8 a thread), v (4 a thread), the two T images (1), the two P images (1), the scalars (warp 0, 1), + // T's scale (thread 0, 4 B) + auto stage = [&](int ch, int b) { + const int64_t c_t0 = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - c_t0); + const uint16_t* img = kqg + ((size_t) ch * HK + qhd) * 4 * GCH * S; +#pragma unroll + for (int m = 0; m < 4 * GCH * S / 8 / NT; ++m) { + const int im = m >> 1, t = ((m & 1) * NT + tid) / (S / 8), r = (tid % (S / 8)) * 8; + uint16_t* dst = (im == 0 ? kh : im == 1 ? kl : im == 2 ? qh : ql) + (b * GCH + t) * GTC_KP + r; + gdn_cp16(reinterpret_cast<float*>(dst), reinterpret_cast<const float*>(img + (im * GCH + t) * S + r)); + } +#pragma unroll + for (int m = 0; m < GCH * S / 4 / NT; ++m) { + const int p = tid + NT * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + float* dst = sv + (b * GCH + t) * GTC_VP + r; + if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + r); + else *reinterpret_cast<float4*>(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + { + const int im = tid / (GCH * GCH / 8), t = (tid % (GCH * GCH / 8)) / (GCH / 8), i = (tid % (GCH / 8)) * 8; + const int64_t src = ((((int64_t) ch * HV + vh) * 2 + im) * GCH + t) * GCH + i; + const int dst = (b * GCH + t) * GTC_PP + i; + gdn_cp16(reinterpret_cast<float*>((im ? tl : th) + dst), reinterpret_cast<const float*>(tig_ + src)); + gdn_cp16(reinterpret_cast<float*>((im ? pl : ph) + dst), reinterpret_cast<const float*>(pig + src)); + } + if (tid < GCH) gdn_cp16(reinterpret_cast<float*>(sc + b * GCH + tid), reinterpret_cast<const float*>(scg + ((int64_t) ch * HV + vh) * GCH + tid)); + if (tid == 0) gdn_cp4(ste + b, teg + (int64_t) ch * HV + vh); + gdn_cp_commit(); + }; + const int c0 = 16 * warp; // the warp's value columns c0 + gid and c0 + gid + 8 + // the state slice as S^T fragments: tile j = rows 8j..8j+7; s[j][0] = S[8j + 2tig][c0 + gid], [1] the row after, + // [2] column + 8, [3] both (64 scalar loads a lane, 32-B runs, once a launch) + float s[16][4]; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float* p = state + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + c0 + gid; + s[j][0] = p[0]; s[j][1] = p[rs]; s[j][2] = p[8]; s[j][3] = p[rs + 8]; + } + stage(0, 0); + const float out_scale = rsqrtf((float) S); + for (int ch = 0; ch < nch; ++ch) { + const int b = ch & 1; + const int64_t c_t0 = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - c_t0); + gdn_cp_wait_all(); // this thread's pieces of chunk ch + __syncthreads(); // every thread's: chunk ch's buffer complete; every read of the other one done + if (ch + 1 < nch) stage(ch + 1, b ^ 1); + const uint16_t* bkh = kh + b * GCH * GTC_KP; + const uint16_t* bkl = kl + b * GCH * GTC_KP; + const uint16_t* bqh = qh + b * GCH * GTC_KP; + const uint16_t* bql = ql + b * GCH * GTC_KP; + const uint16_t* bth = th + b * GCH * GTC_PP; + const uint16_t* btl = tl + b * GCH * GTC_PP; + const uint16_t* bph = ph + b * GCH * GTC_PP; + const uint16_t* bpl = pl + b * GCH * GTC_PP; + const float* bsv = sv + b * GCH * GTC_VP; + const float4* bsc = sc + b * GCH; + // (a) X^T = S0^T K^T and QS^T = S0^T Q^T, the state x 2^es (its largest entry in [2^14, 2^15)). The lane's + // maximum over eight chains (nvcc keeps the order written: one chain was 64 dependent FMNMX before the first mma) + float m8[8] = {}; +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) m8[(2 * j + (q >> 1)) & 7] = fmaxf(m8[(2 * j + (q >> 1)) & 7], fabsf(s[j][q])); + const float m = fmaxf(fmaxf(fmaxf(m8[0], m8[1]), fmaxf(m8[2], m8[3])), fmaxf(fmaxf(m8[4], m8[5]), fmaxf(m8[6], m8[7]))); + const int es = gtc_scale_exp(gtc_warp_max(m)); + float xt[4][4] = {}, qs[4][4] = {}; + gtc_prod_state(s, gtc_pow2(es), bkh, bkl, bqh, bql, xt, qs); + // (b) Y^T = beta_i (V^T - e'_i X^T), e'_i = exp(gamma_i) 2^-(8 + es): lane (gid, tig) holds tokens + // 8nt + 2tig and + 1, columns c0 + gid and + 8 + const float eS = gtc_pow2(-(8 + es)); + float yt[4][4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float4 s0 = gtc_lds128(bsc + 8 * nt + 2 * tig), s1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1); + const float* v = bsv + (8 * nt + 2 * tig) * GTC_VP + c0 + gid; + const float e0 = s0.y * eS, e1 = s1.y * eS; + yt[nt][0] = s0.x * fmaf(-e0, xt[nt][0], v[0]); + yt[nt][1] = s1.x * fmaf(-e1, xt[nt][1], v[GTC_VP]); + yt[nt][2] = s0.x * fmaf(-e0, xt[nt][2], v[8]); + yt[nt][3] = s1.x * fmaf(-e1, xt[nt][3], v[GTC_VP + 8]); + } + // (c) D^T = Y^T T^T on f16x3: Y^T x 2^ey (its largest entry in [2^14, 2^15)), T's images x 2^et from the prep; + // the accumulator comes out x 2^(ey + et) (T above its diagonal skipped) + float my4[4] = {}; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) my4[q] = fmaxf(my4[q], fabsf(yt[nt][q])); + const int ey = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(my4[0], my4[1]), fmaxf(my4[2], my4[3])))); + float dt[4][4] = {}; + gtc_prod_dt<true>(yt, gtc_pow2(ey), bth, btl, dt); + const float sYT = gtc_pow2(-ey) * ste[b]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) dt[nt][q] *= sYT; + // (d) o^T = e_t QS^T + D^T P^T: the accumulator starts as 2^(ed + 8) e_t QS^T (QS^T came out x 2^(8 + es)), + // D^T goes in x 2^ed, P x 2^8; the output is the accumulator x 2^-(ed + 8), then rsqrt(S) as gdn_chunk_scan_kernel + float md4[4] = {}; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) md4[q] = fmaxf(md4[q], fabsf(dt[nt][q])); + const int ed = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(md4[0], md4[1]), fmaxf(md4[2], md4[3])))); + const float sD = gtc_pow2(ed), sO = gtc_pow2(ed + 8), sOi = gtc_pow2(-(ed + 8)), eO = gtc_pow2(ed - es); + float ot[4][4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float e0 = gtc_lds128(bsc + 8 * nt + 2 * tig).y * eO, e1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).y * eO; + ot[nt][0] = qs[nt][0] * e0; ot[nt][1] = qs[nt][1] * e1; ot[nt][2] = qs[nt][2] * e0; ot[nt][3] = qs[nt][3] * e1; + } + gtc_prod_dt<true>(dt, sD, bph, bpl, ot); +#pragma unroll + for (int nt = 0; nt < 4; ++nt) +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int t = 8 * nt + 2 * tig + (q & 1); + if (t < n) oc_out[(c_t0 + t) * rs + (size_t) vh * S + c0 + gid + 8 * (q >> 1)] = (ot[nt][q] * sOi) * out_scale; + } + // (e) S^T = eL S0^T + Dd^T K, Dd^T = f_i D^T: the accumulator x (eL 2^(ed + 8)) before (one rounding, as the + // s *= gL of gdn_chunk_scan_kernel), Dd^T in x 2^ed, K x 2^8, the accumulator x 2^-(ed + 8) after + const float sPre = gtc_lds128(bsc + GCH - 1).y * sO; // exp(gL) +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) s[j][q] *= sPre; + float dd[4][4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float f0 = gtc_lds128(bsc + 8 * nt + 2 * tig).z * sD, f1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).z * sD; + dd[nt][0] = dt[nt][0] * f0; dd[nt][1] = dt[nt][1] * f1; dd[nt][2] = dt[nt][2] * f0; dd[nt][3] = dt[nt][3] * f1; + } + gtc_update_state(s, dd, bkh, bkl); +#pragma unroll + for (int j = 0; j < 16; ++j) +#pragma unroll + for (int q = 0; q < 4; ++q) s[j][q] *= sOi; + } +#pragma unroll + for (int j = 0; j < 16; ++j) { + float* p = state + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + c0 + gid; + p[0] = s[j][0]; p[rs] = s[j][1]; p[8] = s[j][2]; p[rs + 8] = s[j][3]; + } +} +#endif // !__HIPCC__ diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index e99f5ba6..6fb5f714 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -879,6 +879,7 @@ bool gdn_keyhead_ok() { // than they save below ~100 tokens (gdn_rec_parity --bench: 32 tokens 0.58x gdn_rec_kh_kernel, 96 1.03x, 128 1.20x, // 512 1.67x, 2048+ 1.81x) constexpr int64_t kGdnChunkedMin = 128; +constexpr int64_t kGdnTcMin = 128; // STRATA_GDN_TC: the two launches cost ~20 us; below this the kh kernel wins constexpr int GCH = 32; // tokens per chunk (the prep's solve is a lane per token) constexpr int GSB = 2048; // tokens per super-block: the prep's scratch is GSB / GCH chunks of T, P and gamma constexpr int GDV = 16; // value columns per scan block @@ -1147,6 +1148,9 @@ __global__ void __launch_bounds__(128 * VPK) gdn_chunk_scan_kernel(float* __rest #pragma unroll for (int y = 0; y < 4; ++y) state[(size_t) (4 * rq + xx) * rs + (size_t) vh * S + c0 + vv + y] = s[xx][y]; } +// the same scan on the tensor cores (STRATA_GDN_TC=1, gdn_rec_tc below); src/prefill/gdn_rec_parity.cu includes the +// same text +#include "gdn_tc.cuh" // The scratch, one a device: allocated on first use at its largest (GSB / GCH chunks of T, P and gamma: 25.6 MB) and // kept (a device runs its prompt on one stream). A stream-ordered allocation and free per call, even from a pool that @@ -1213,6 +1217,42 @@ cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, con } return cudaSuccess; // launch errors surface at the caller's check; an error above means nothing ran } +// STRATA_GDN_TC=1: gdn_rec_chunked with the scan on the tensor cores (gdn_tc_scan_kernel, gdn_tc.cuh) and the prep +// that also writes its f16 images (gdn_tc_prep_kernel, scratch gdn_tc_scratch), 48 blocks of 256 threads in one wave. An error return means nothing was launched: the card is below +// sm_80, has fewer than 48 SMs, or less than 122 KB of shared memory a block. +cudaError_t gdn_rec_tc(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, + cudaStream_t s) { + if (T <= 0) return cudaSuccess; + { + int dev = 0, major = 0, sms = 0, smem = 0; + if (cudaGetDevice(&dev) != cudaSuccess || + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess || + cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) != cudaSuccess) { + cudaGetLastError(); + return cudaErrorNotSupported; + } + if (strata::cc_major_of(major) < 8 || sms < HV || (size_t) strata::smem_optin_of(smem) < kTcScanSmem<false>) + return cudaErrorNotSupported; + } + const GtcScratch sc = gdn_tc_scratch(); + if (sc.ti == nullptr) return cudaErrorMemoryAllocation; + { // once a device + static bool attrs[64] = {}; + int dev = 0; + cudaGetDevice(&dev); + if (dev >= 0 && dev < 64 && !attrs[dev]) { + cudaFuncSetAttribute(gdn_tc_scan_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kTcScanSmem<false>); + attrs[dev] = true; + } + } + for (int64_t t0 = 0; t0 < T; t0 += GSB) { + const int nch = (int) ((std::min<int64_t>(GSB, T - t0) + GCH - 1) / GCH); + gdn_tc_prep_kernel<<<dim3((unsigned) nch, HK), 256, kTcPrepSmem, s>>>(h, gate, beta, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, t0, T); + gdn_tc_scan_kernel<false><<<HV, GTC_CW * 32, kTcScanSmem<false>, s>>>(state, h, sc.ti, sc.te, sc.sc, sc.kq, sc.pi, y, t0, nch, T); + } + return cudaSuccess; +} #endif #if defined(__HIPCC__) // the Aurora (gfx11) recurrence kernels: AMD builds only // Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value @@ -2715,7 +2755,12 @@ static void gdn_recurrence_impl(int variant, float* state, const float* h, const // STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks for prompt chunks of kGdnChunkedMin+ tokens (other // bits; a shorter chunk, a card it does not fit or a failed scratch allocation takes the kernels below) static const bool chunked = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) != 0; }(); - if (chunked && T >= kGdnChunkedMin && gdn_rec_chunked(state, h, gate, beta, y, T, (cudaStream_t) stream) == cudaSuccess) { + // STRATA_GDN_TC=1 (opt-in): the chunked recurrence with the scan on the tensor cores (gdn_tc.cuh) for prompt + // chunks of kGdnTcMin+ tokens: within 1e-4 of the kernels below (gdn_rec_parity), 3.75x gdn_rec_kh_kernel on a + // CMP 170HX; a shorter chunk, a card it does not fit or a failed scratch allocation takes the kernels below + static const bool tc = [] { const char* v = std::getenv("STRATA_GDN_TC"); return v != nullptr && std::atoi(v) != 0; }(); + if (tc && T >= kGdnTcMin && gdn_rec_tc(state, h, gate, beta, y, T, (cudaStream_t) stream) == cudaSuccess) { + } else if (chunked && T >= kGdnChunkedMin && gdn_rec_chunked(state, h, gate, beta, y, T, (cudaStream_t) stream) == cudaSuccess) { } else if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits) gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T); else From 0f7224d1681000a0ecf0f8fbea36e116817c8455 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:49:33 +0100 Subject: [PATCH 168/177] Conversation checkpoints: opt-in STRATA_CKPT_ASYNC (background device-to-host copy) and STRATA_CKPT_VRAM_SLOTS (#3779, #3712) Problem: on a slow host link a turn checkpoint copies the whole GDN state to the host on the request path (118 MB at 1.64 GB/s on a PCIe Gen2 x4 card, 72 ms; an independent RTX 3090 on PCIe 3.0 x16 showed 73 ms to 62 ms with the switch). Restoring a parked conversation copies it back. Change, both opt-in and CUDA only (off on HIP, gfx906 and Metal): - STRATA_CKPT_ASYNC=1: the GDN state is copied device to device into a VRAM stage (one buffer the size of the state, allocated at the first checkpoint save, plus a pinned host buffer of the same size; if either allocation fails the save falls back to the synchronous copy), and a background thread moves it in 4 MiB pieces into the checkpoint's host vector. Every reader joins first and only for the copy it needs (restore, snapshot save and restore, the parked copies, the serve loop at each request start, the SAVE/RESTORE session handler). - STRATA_CKPT_VRAM_SLOTS=N (with ASYNC): the last N saved GDN states stay in VRAM, tag-checked, only allocated while 1.5 GB stays free; a restore of a checkpoint whose tag a slot holds copies device to device. - STRATA_TRACE lines carry a steady-clock timestamp; STRATA_PARK_TRACE prints the timing of the save steps. - Unset: the code adds a mutex-guarded no-op join per checkpoint save, restore and snapshot, a tag field that stays 0 and a few clock reads; the copies are the synchronous ones as before. Differs from the PR as submitted: the PR put a join into conversation_file.cpp (put_checkpoint), which broke the conversation_file_test and session_save_reclaim_test builds without CUDA and matched only the copied vector, not the one the copy in flight writes, so a SAVE within one checkpoint copy after a turn could write an incomplete GDN state (found by bitaccesscomau; fixed in the PR's last commit 33a8146a). This commit carries that fix: conversation_file.cpp stays as it is and the join runs first in the SAVE/RESTORE handler of generate.cpp. The commit 33a8146a is therefore not a separate commit here. One more join, found by running the new ctest entries: conversation_snapshot_sources (the SAVE path of a session file) saves the running state with the background copy and the caller writes it to the file at once, after the handler's join has already run. It now joins the copy of that checkpoint before it returns; without it a session file written with STRATA_CKPT_ASYNC=1 could hold an incomplete GDN state (conversation_snapshot_test failed at "both files read" before the join). Tests: conversation_snapshot_test now joins after each save and, with STRATA_TEST_BIG_GDN=1 (a GDN state over 1 MiB, so the async path is taken), runs as the new ctest entries conversation_snapshot_test_ckpt_async and conversation_snapshot_test_ckpt_vram_slots: every checkpoint, capture and restore must give the same bytes as the plain run. Not covered: no test destroys a checkpoint while its copy is in flight (readers join; the cache's eviction paths do not); the reporter saw 3 of about 35 engine starts stop answering after a park with evictions, on the paths with the switches off, and could not reproduce it in 15 reruns. The VRAM stage has no headroom check of its own (an RTX 3090 with 147 MiB minimum free showed no failure in 42 of 42 saves; the allocation failure falls back silently). Reporter's numbers (linxuhao, CMP 170HX): turn checkpoint 71.4 -> 0.9 ms, restore 114-126 -> 28-47 ms. Independent data (bitaccesscomau, RTX 3090 24 GB, PCIe 3.0 x16, release defaults, 4 pairs): checkpoint save 73.2 -> 62.4 ms, tiny-prompt time to first token median ratio 1.038, outputs byte-identical. Theirs, not measured here. Original change by linxuhao (PR #3779, commits 0d512925 and 33a8146a). --- CMakeLists.txt | 8 + include/strata/core/conversation_cache.hpp | 3 + include/strata/core/conversation_snapshot.hpp | 7 + src/core/conversation_copy.hpp | 3 + src/core/conversation_snapshot_test.cpp | 47 +++-- src/core/conversation_state.cpp | 161 +++++++++++++++++- src/program/generate.cpp | 12 +- 7 files changed, 222 insertions(+), 19 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 18e79aa9..a5d060e2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -710,6 +710,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the same test with a GDN state over 1 MiB and the opt-in background checkpoint copy (STRATA_CKPT_ASYNC=1), alone and with + # recent states kept in VRAM (STRATA_CKPT_VRAM_SLOTS): every checkpoint, capture and restore must give the same bytes + add_test(NAME conversation_snapshot_test_ckpt_async COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test_ckpt_async PROPERTIES + ENVIRONMENT "STRATA_TEST_BIG_GDN=1;STRATA_CKPT_ASYNC=1" SKIP_RETURN_CODE 77 TIMEOUT 300) + add_test(NAME conversation_snapshot_test_ckpt_vram_slots COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test_ckpt_vram_slots PROPERTIES + ENVIRONMENT "STRATA_TEST_BIG_GDN=1;STRATA_CKPT_ASYNC=1;STRATA_CKPT_VRAM_SLOTS=3" SKIP_RETURN_CODE 77 TIMEOUT 300) add_executable(conversation_validation_test src/core/conversation_validation_test.cpp) target_link_libraries(conversation_validation_test PRIVATE strata_engine) add_test(NAME conversation_validation_test COMMAND conversation_validation_test) diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index b977ac49..0adf0917 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -25,6 +25,9 @@ struct ConversationCheckpoint { std::vector<ConversationImageKey> imgs; std::vector<uint8_t> gdn, ple, tails, dead, block_pos; uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention + // STRATA_CKPT_VRAM_SLOTS: the tag of the device copy of `gdn` (0: none). Set by conversation_checkpoint_save, the + // only writer of a checkpoint's GDN bytes besides a whole copy (which keeps them equal, so it keeps the tag). + uint64_t dev_tag = 0; // A shared-prefix pin (the request key pin=N): this checkpoint is the read-only prefix many suffix queries branch // from, so retention never evicts it (conv_cache.hpp) and a parked conversation holding it stays parked. A run-time // mark only: it is not in the session file, a request that pins the same prefix again sets it. diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index dcee29fa..962bf33f 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -70,6 +70,13 @@ bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const ModelGeometry& g, std::string& error); bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session, const ModelGeometry& g, std::string& error); +/// STRATA_CKPT_ASYNC=1 (CUDA, opt-in): conversation_checkpoint_save copies the GDN state into a device staging buffer +/// and moves it into the checkpoint's host vector on a background thread (the PCIe copy overlaps what follows: the +/// rest of the prompt, the reply). This waits for that copy; every reader of a checkpoint's bytes calls it first +/// (restore, snapshot save / restore, the parked copies, the session file, the serve loop at each request). No-op +/// when nothing is in flight. +/// `only` (non-null): wait only when the copy in flight is into that checkpoint's GDN bytes. +void conversation_checkpoint_join(const void* only = nullptr); bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, const ModelGeometry& g, std::string& error); // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index 7ffb87f4..0a65c4de 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -14,6 +14,7 @@ #include <thread> #include <vector> +namespace strata::core { void conversation_checkpoint_join(const void* only); } namespace strata::core::conversation_detail { /// The private copy streams and ordering events (below) belong to a thread, but a thread can be short-lived: the layer @@ -152,6 +153,7 @@ inline ConversationCheckpoint copy_checkpoint_beating(const ConversationCheckpoi o.ids = copy_beating(c.ids); o.imgs = copy_beating(c.imgs); o.gdn = copy_beating(c.gdn); + o.dev_tag = c.dev_tag; // the same bytes o.ple = copy_beating(c.ple); o.tails = copy_beating(c.tails); o.dead = copy_beating(c.dead); @@ -164,6 +166,7 @@ inline ConversationCheckpoint copy_checkpoint_beating(const ConversationCheckpoi } inline std::vector<ConversationCheckpoint> copy_checkpoints_beating(const std::vector<ConversationCheckpoint>& cs) { + for (const auto& c : cs) core::conversation_checkpoint_join(c.gdn.data()); std::vector<ConversationCheckpoint> out; out.reserve(cs.size()); for (const auto& c : cs) out.push_back(copy_checkpoint_beating(c)); diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index 074a3ae9..a8e80ce6 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -12,11 +12,27 @@ #include <string> #include <cstdlib> #include <limits> +#include <utility> #include <vector> using namespace strata::core; using namespace strata::kernels; +namespace { +// STRATA_CKPT_ASYNC=1 (the ctest entries conversation_snapshot_test_ckpt_async / _vram_slots): the checkpoint's GDN bytes land in +// the background; the test reads them at once, so it joins after each save (the engine's readers join before they read) +template <class... A> bool ckpt_save(A&&... a) { + const bool ok = conversation_checkpoint_save(std::forward<A>(a)...); + conversation_checkpoint_join(nullptr); + return ok; +} +template <class... A> bool snap_save(A&&... a) { + const bool ok = conversation_snapshot_save(std::forward<A>(a)...); + conversation_checkpoint_join(nullptr); + return ok; +} +} // namespace + namespace { int checks = 0; void check(bool ok, const char* label) { @@ -115,6 +131,7 @@ void full_session(int fmt, int mode, int experts) { 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; + if (std::getenv("STRATA_TEST_BIG_GDN")) { g.ssm_state_size=64; g.ssm_v_heads=64; } // a GDN state over 1 MiB: the async checkpoint path SessionState ss; ss.max_cells=96; ss.qsa_states=&main.state; ss.layer_hi=g.n_layers; ss.gdn_alloc=g.n_gdn_layers(); ss.qsa_alloc=g.n_qsa_layers(); // the whole-model carve @@ -142,15 +159,15 @@ void full_session(int fmt, int mode, int experts) { fill(13); ConversationCheckpoint checkpoint; checkpoint.ids.assign(ids.begin(),ids.begin()+3); - check(conversation_checkpoint_save(checkpoint,ss,g,err),"save complete running checkpoint"); + check(ckpt_save(checkpoint,ss,g,err),"save complete running checkpoint"); checkpoint.used = 17; checkpoints.push_back(std::move(checkpoint)); const ConversationView view{ids,images,checkpoints,true}; SavedConversation a,b,restored; - check(conversation_snapshot_save(a,view,ss,g,draft.state,err),"capture complete A"); + check(snap_save(a,view,ss,g,draft.state,err),"capture complete A"); check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture"); fill(177); - check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B"); + check(snap_save(b,view,ss,g,draft.state,err),"capture complete B"); { // disk save path: metadata + streamed K/V give the same file as the captured image SavedConversation meta; @@ -184,11 +201,11 @@ void full_session(int fmt, int mode, int experts) { auto bad=a; bad.kv.back().k.pop_back(); check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid, "reject invalid late draft before any main-layer write"); - check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture B after refused restore"); + check(snap_save(restored,view,ss,g,draft.state,err),"capture B after refused restore"); check(restored.live.gdn==b.live.gdn && restored.live.dead==b.live.dead && equal(restored.kv[0],b.kv[0]) && equal(restored.kv[1],b.kv[1]),"refusal preserves all tested state"); check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore complete A"); - check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture restored A"); + check(snap_save(restored,view,ss,g,draft.state,err),"capture restored A"); check(restored.live.gdn==a.live.gdn && restored.live.ple==a.live.ple && restored.live.tails==a.live.tails && restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos && equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key"); @@ -204,7 +221,7 @@ void full_session(int fmt, int mode, int experts) { want_state.ids=got_state.ids=a.checkpoints[0].ids; check(conversation_kv_save(want_main,main.state,g,at,true,err) && conversation_kv_save(want_draft,draft.state,g,at,false,err) && - conversation_checkpoint_save(want_state,ss,g,err),"capture the rewound prefix"); + ckpt_save(want_state,ss,g,err),"capture the rewound prefix"); fill(201); // another conversation in the session const SavedConversation untouched=a; check(conversation_snapshot_restore_prefix(a,(int64_t)a.live.ids.size()+1,ss,g,draft.state,err)== @@ -216,7 +233,7 @@ void full_session(int fmt, int mode, int experts) { check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"mount the checkpoint over it"); check(conversation_kv_save(got_main,main.state,g,at,true,err) && conversation_kv_save(got_draft,draft.state,g,at,false,err) && - conversation_checkpoint_save(got_state,ss,g,err),"capture the borrowed prefix"); + ckpt_save(got_state,ss,g,err),"capture the borrowed prefix"); check(equal(got_main,want_main) && equal(got_draft,want_draft), "borrowed K/V equals the whole restore's prefix"); check(got_state.gdn==want_state.gdn && got_state.ple==want_state.ple && got_state.tails==want_state.tails && @@ -236,10 +253,10 @@ void full_session(int fmt, int mode, int experts) { cuda_check(cudaMemcpy(main.state.idx_pooled+(ids.size()/4)*g.idx_key_dim, main.state.idx_dead,sizes.dead,cudaMemcpyDeviceToDevice)); SavedConversation fresh,incremental; - check(conversation_snapshot_save(fresh,view,ss,g,draft.state,err),"full capture reference after growth or rewind"); + check(snap_save(fresh,view,ss,g,draft.state,err),"full capture reference after growth or rewind"); size_t peak=0,reused=0; check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.state,peak,err),"admit incremental capture peak"); - check(conversation_snapshot_save(incremental,view,ss,g,draft.state,err,std::move(reuse),&reused),"capture with retained pages"); + check(snap_save(incremental,view,ss,g,draft.state,err,std::move(reuse),&reused),"capture with retained pages"); check(incremental.bytes() <= peak,"incremental allocation stays within admitted bound"); check(incremental.live.gdn==fresh.live.gdn && incremental.live.ple==fresh.live.ple && incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) && @@ -261,7 +278,7 @@ void full_session(int fmt, int mode, int experts) { conversation_snapshot_bytes(view,ss,g,nullptr,without,err) && without<with_draft, "a stage image's estimate leaves the draft out"); SavedConversation stage,stage_b,stage_back; - check(conversation_snapshot_save(stage,view,ss,g,nullptr,err),"capture a stage image"); + check(snap_save(stage,view,ss,g,nullptr,err),"capture a stage image"); check(stage.kv.size()==a.kv.size()-1 && equal(stage.kv[0],a.kv[0]) && stage.live.gdn==a.live.gdn, "a stage image holds the session's own layers, no draft"); check(stage.bytes()<a.bytes(),"a stage image is smaller by the draft ring"); @@ -269,21 +286,21 @@ void full_session(int fmt, int mode, int experts) { check(!conversation_snapshot_validate(stage,ss,g,draft.state,err),"a stage image is refused where a draft is expected"); check(!conversation_snapshot_validate(a,ss,g,nullptr,err),"an image with a draft is refused where none is expected"); fill(201); - check(conversation_snapshot_save(stage_b,view,ss,g,nullptr,err),"capture another stage state"); + check(snap_save(stage_b,view,ss,g,nullptr,err),"capture another stage state"); check(conversation_snapshot_restore(a,ss,g,nullptr,err)==ConversationRestore::invalid, "restoring a draft image as a stage image is refused before any write"); - check(conversation_snapshot_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage_b.live.gdn && + check(snap_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage_b.live.gdn && equal(stage_back.kv[0],stage_b.kv[0]),"the refusal left the stage untouched"); check(conversation_snapshot_restore(stage,ss,g,nullptr,err)==ConversationRestore::restored,"restore a stage image"); - check(conversation_snapshot_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage.live.gdn && + check(snap_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage.live.gdn && stage_back.live.dead==stage.live.dead && equal(stage_back.kv[0],stage.kv[0]),"stage A/B/A exactness"); // its retained K/V: the next park copies only what changed, and equals a full capture ConversationKvReuse reuse{stage.kv,65,65,{}}; SavedConversation fresh,incremental; size_t peak=0,reused=0; - check(conversation_snapshot_save(fresh,view,ss,g,nullptr,err),"full stage capture reference"); + check(snap_save(fresh,view,ss,g,nullptr,err),"full stage capture reference"); check(conversation_snapshot_capture_bytes(reuse,view,ss,g,nullptr,peak,err),"admit an incremental stage capture"); - check(conversation_snapshot_save(incremental,view,ss,g,nullptr,err,std::move(reuse),&reused),"incremental stage capture"); + check(snap_save(incremental,view,ss,g,nullptr,err,std::move(reuse),&reused),"incremental stage capture"); check(reused>0 && incremental.bytes()<=peak && equal(incremental.kv[0],fresh.kv[0]) && incremental.live.gdn==fresh.live.gdn,"an incremental stage capture reuses pages and equals a full one"); SavedConversation split_image=stage; diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index c64e09d9..36a8a6da 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -1,10 +1,16 @@ #include "strata/core/conversation_snapshot.hpp" #include "conversation_checked.hpp" #include "conversation_copy.hpp" +#include <chrono> +#include <cstdio> +#include <cstdlib> #include <algorithm> #include <array> +#include <cstring> +#include <future> #include <limits> +#include <mutex> namespace strata::core { namespace { @@ -162,8 +168,68 @@ bool window_checkpoint_restore(const strata::core::ConversationCheckpoint& c, st namespace strata::core { #endif +namespace { +struct CkptAsync { + std::mutex mu; + std::future<cudaError_t> pending; + const void* dst = nullptr; // the checkpoint bytes the copy in flight writes + void* stage = nullptr; + void* host = nullptr; // pinned: the DMA lands here, then a plain memcpy (no driver staging beside the decode) + cudaStream_t stream = nullptr; + size_t cap = 0; + int dev = -1; +}; +CkptAsync& ckpt_async() { static CkptAsync a; return a; } +// STRATA_CKPT_VRAM_SLOTS=N (with STRATA_CKPT_ASYNC): the last N saved GDN states stay in VRAM (allocated only while +// more than 1.5 GB stays free); a restore of a checkpoint whose tag a slot holds copies device to device. +struct VramSlot { void* p = nullptr; size_t n = 0; uint64_t tag = 0, used = 0; int dev = -1; }; +struct VramSlots { std::vector<VramSlot> s; uint64_t clock = 0, next_tag = 0; }; +VramSlots& vram_slots() { static VramSlots v; return v; } +int vram_slots_n() { + static const int n = [] { const char* v = std::getenv("STRATA_CKPT_VRAM_SLOTS"); return v ? std::max(0, std::min(16, std::atoi(v))) : 0; }(); + return n; +} +// a slot for `n` bytes on `dev`: a free one, a new one if VRAM allows, else the least recently used (nullptr: none) +VramSlot* vram_slot_for(size_t n, int dev) { + VramSlots& v = vram_slots(); + VramSlot* best = nullptr; + for (VramSlot& x : v.s) + if (x.dev == dev && x.n == n && (best == nullptr || x.used < best->used)) best = &x; + if ((int) v.s.size() < vram_slots_n()) { + size_t fr = 0, tot = 0; + if (cudaMemGetInfo(&fr, &tot) == cudaSuccess && fr > n + ((size_t) 3 << 29)) { + VramSlot x; + if (cudaMalloc(&x.p, n) == cudaSuccess) { x.n = n; x.dev = dev; v.s.push_back(x); return &v.s.back(); } + } + (void) cudaGetLastError(); + } + return best; +} +bool ckpt_async_on() { +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) + return false; +#else + static const bool on = [] { const char* v = std::getenv("STRATA_CKPT_ASYNC"); return v != nullptr && v[0] == '1'; }(); + return on; +#endif +} +} // namespace + +void conversation_checkpoint_join(const void* only) { + CkptAsync& a = ckpt_async(); + std::lock_guard<std::mutex> lk(a.mu); + if (a.pending.valid() && (only == nullptr || only == a.dst)) { + const cudaError_t e = a.pending.get(); + if (e != cudaSuccess) std::fprintf(stderr, "strata: STRATA_CKPT_ASYNC: a checkpoint copy failed (%s)\n", cudaGetErrorString(e)); + } +} + bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, const ModelGeometry& g, std::string& error) { + const auto j0 = std::chrono::steady_clock::now(); + conversation_checkpoint_join(nullptr); // (the staging buffer is reused) + if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: save join %.2f ms\n", + std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - j0).count()); #if defined(STRATA_GPU_METAL) (void) ss; (void) g; return strata::metal_engine::window_checkpoint_save(c, error); @@ -173,7 +239,65 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& const size_t layers = owned_qsa(ss); c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0); c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); - if (!copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error) || + bool staged = false; + if (ckpt_async_on() && c.gdn.size() >= ((size_t) 1 << 20)) { + CkptAsync& a = ckpt_async(); + int dev = 0; + (void) cudaGetDevice(&dev); + if (a.stage != nullptr && (a.cap < c.gdn.size() || a.dev != dev)) { + const int cur = dev; + (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaFreeHost(a.host); + (void) cudaStreamDestroy(a.stream); (void) cudaSetDevice(cur); + a.stage = a.host = nullptr; a.stream = nullptr; a.cap = 0; + } + if (a.stage == nullptr) { + if (cudaMalloc(&a.stage, c.gdn.size()) == cudaSuccess && cudaMallocHost(&a.host, c.gdn.size()) == cudaSuccess && + cudaStreamCreateWithFlags(&a.stream, cudaStreamNonBlocking) == cudaSuccess) { a.cap = c.gdn.size(); a.dev = dev; } + else { if (a.stage) (void) cudaFree(a.stage); if (a.host) (void) cudaFreeHost(a.host); a.stage = a.host = nullptr; } + } + (void) cudaGetLastError(); + static const bool atr = std::getenv("STRATA_PARK_TRACE") != nullptr; + VramSlot* slot = vram_slots_n() > 0 ? vram_slot_for(c.gdn.size(), dev) : nullptr; + if (slot != nullptr) slot->tag = 0; // (being rewritten) + void* dsrc = slot != nullptr ? slot->p : a.stage; + c.dev_tag = 0; + if (dsrc != nullptr && copy(dsrc, ss.gdn_state, c.gdn.size(), error)) { // device to device: fast + const auto q1 = std::chrono::steady_clock::now(); + if (slot != nullptr) { + VramSlots& v = vram_slots(); + slot->tag = c.dev_tag = ++v.next_tag; + slot->used = ++v.clock; + } + uint8_t* dst = c.gdn.data(); + const size_t n = c.gdn.size(); + void* host = a.host; + const uint8_t* stage = (const uint8_t*) dsrc; + cudaStream_t st = a.stream; + if (atr) std::fprintf(stderr, "strata parktrace: async ckpt d2d %.2f ms\n", + std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - q1).count()); + std::lock_guard<std::mutex> lk(a.mu); + // the DMA in 4 MiB pieces, one in flight: a D2H copy queues behind the one before it on the copy engine, and + // the decode's own small reads would otherwise wait for the whole 100+ MB at the link's ~1.6 GB/s + a.dst = dst; + a.pending = std::async(std::launch::async, [dst, host, stage, n, st, dev] { + (void) cudaSetDevice(dev); + cudaEvent_t done = nullptr; + cudaError_t e = cudaEventCreateWithFlags(&done, cudaEventDisableTiming | cudaEventBlockingSync); + constexpr size_t PIECE = (size_t) 4 << 20; + for (size_t o = 0; e == cudaSuccess && o < n; o += PIECE) { + const size_t k = std::min(PIECE, n - o); + e = cudaMemcpyAsync((uint8_t*) host + o, stage + o, k, cudaMemcpyDeviceToHost, st); + if (e == cudaSuccess) e = cudaEventRecord(done, st); + if (e == cudaSuccess) e = cudaEventSynchronize(done); + if (e == cudaSuccess) std::memcpy(dst + o, (const uint8_t*) host + o, k); + } + if (done) (void) cudaEventDestroy(done); + return e; + }); + staged = true; + } + } + if ((!staged && !copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error)) || !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false; for (size_t j = 0; j < layers; ++j) { const auto& st = owned(ss, j); @@ -186,6 +310,14 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss, const ModelGeometry& g, std::string& error) { + const VramSlot* hit = nullptr; + if (c.dev_tag != 0) { + int dev = 0; + (void) cudaGetDevice(&dev); + for (VramSlot& x : vram_slots().s) + if (x.tag == c.dev_tag && x.dev == dev && x.n == c.gdn.size()) { x.used = ++vram_slots().clock; hit = &x; } + } + if (hit == nullptr) conversation_checkpoint_join(c.gdn.data()); #if defined(STRATA_GPU_METAL) (void) g; if (!strata::metal_engine::window_checkpoint_restore(c, error)) return false; @@ -197,7 +329,7 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionSta ConversationStateSizes z; if (!conversation_session_sizes(g, ss, z, error)) return false; if (!sync(error)) return false; // the copies below no longer ride the legacy stream's implicit ordering - if (!copy(ss.gdn_state, c.gdn.data(), c.gdn.size(), error) || + if (!copy(ss.gdn_state, hit != nullptr ? hit->p : (const void*) c.gdn.data(), c.gdn.size(), error) || !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false; for (size_t j = 0; j < owned_qsa(ss); ++j) { const auto& st = owned(ss, j); @@ -302,6 +434,12 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView const SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error, ConversationKvReuse reuse, size_t* reused_bytes) { + conversation_checkpoint_join(nullptr); + static const bool ptr = std::getenv("STRATA_PARK_TRACE") != nullptr; + auto now = [] { return std::chrono::steady_clock::now(); }; + auto ms = [](std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) { + return std::chrono::duration<double, std::milli>(b - a).count(); }; + const auto p0 = now(); size_t estimate = 0; if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; // Build into a new object so a failure cannot publish a partial snapshot. @@ -309,16 +447,25 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView captured.geometry = geometry_key(g); captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; captured.live.ids = view.ids; captured.live.imgs = view.images; + const auto p1 = now(); captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints); + const auto p2 = now(); const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; captured.kv = std::move(reuse.kv); const size_t layers = owned_qsa(ss); captured.kv.resize(layers + (draft ? 1 : 0)); if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; + const auto p3 = now(); const int64_t upto = (int64_t) view.ids.size(); for (size_t j = 0; j < layers; ++j) if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error, unchanged, reused_bytes)) return false; + if (ptr) { + size_t kvb = 0; + for (const auto& k : captured.kv) kvb += k.bytes(); + std::fprintf(stderr, "strata parktrace: sync %.1f ms, %zu checkpoints copied %.1f ms, live state %.1f ms, K/V %zu MB %.1f ms\n", + ms(p0, p1), captured.checkpoints.size(), ms(p1, p2), ms(p2, p3), kvb >> 20, ms(p3, now())); + } // The draft's final cell may not have been computed when the output cap was // reached. Refresh that page even when the main prefix continued unchanged. if (draft && !conversation_kv_save(captured.kv.back(), *draft, g, upto, false, error, @@ -337,6 +484,8 @@ bool conversation_snapshot_sources(SavedConversation& meta, std::vector<SessionK captured.live.ids = view.ids; captured.live.imgs = view.images; captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints); if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; + // STRATA_CKPT_ASYNC: the caller writes `meta` to the session file at once, so the running state's copy lands first + conversation_checkpoint_join(captured.live.gdn.data()); const int64_t upto = (int64_t) view.ids.size(); const size_t layers = owned_qsa(ss); std::vector<SessionKvSource> out(layers + 1); @@ -399,6 +548,8 @@ bool conversation_snapshot_validate(const SavedConversation& image, const Sessio ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error) { + conversation_checkpoint_join(image.live.gdn.data()); + for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid; if (!sync(error)) return ConversationRestore::transfer_failed; const int64_t upto = (int64_t) image.live.ids.size(); @@ -433,16 +584,22 @@ bool conversation_snapshot_validate(const SavedConversation& image, const Sessio } ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss, const ModelGeometry& g, const QsaState& draft, std::string& error) { + conversation_checkpoint_join(image.live.gdn.data()); + for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); return conversation_snapshot_restore(image, ss, g, &draft, error); } ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto, SessionState& ss, const ModelGeometry& g, const QsaState& draft, std::string& error) { + conversation_checkpoint_join(image.live.gdn.data()); + for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); return conversation_snapshot_restore_prefix(image, upto, ss, g, &draft, error); } ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto, SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error) { + conversation_checkpoint_join(image.live.gdn.data()); + for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); // a layer split's image (stage images) is restored stage by stage, never in part if (!image.stage_images.empty()) { fail(error, "a layer split's image restored as a single session"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 187df09a..c7737371 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1816,6 +1816,7 @@ public: bool on() const { return on_; } void give(ConvCheckpoint&& c) { if (!on_ || c.gdn.empty()) return; + strata::core::conversation_checkpoint_join(c.gdn.data()); clear_marks(c); std::lock_guard<std::mutex> lk(mu_); if (free_.size() < cap_) free_.push_back(std::move(c)); @@ -1839,7 +1840,7 @@ public: } private: static void clear_marks(ConvCheckpoint& c) { - c.ids.clear(); c.imgs.clear(); c.used = 0; c.pinned = false; + c.ids.clear(); c.imgs.clear(); c.used = 0; c.pinned = false; c.dev_tag = 0; for (ConvCheckpoint& part : c.stage_parts) clear_marks(part); } bool on_; @@ -9935,6 +9936,7 @@ int main(int argc, char** argv) { if (parts != nullptr) { if (parts->size() != stages.size() + 1) return false; c.gdn = std::move((*parts)[0].gdn); + c.dev_tag = (*parts)[0].dev_tag; c.ple = std::move((*parts)[0].ple); c.tails = std::move((*parts)[0].tails); c.dead = std::move((*parts)[0].dead); @@ -11242,7 +11244,8 @@ int main(int argc, char** argv) { const bool trace = std::getenv("STRATA_TRACE") != nullptr; auto tr = [&](const char* what, long long a = -1, long long b = -1) { if (!trace) return; - std::fprintf(stderr, "strata trace: %s %lld %lld\n", what, a, b); + std::fprintf(stderr, "strata trace: %s %lld %lld @%.1f\n", what, a, b, + std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count()); std::fflush(stderr); }; { @@ -12443,6 +12446,9 @@ int main(int argc, char** argv) { std::fflush(stdout); }; strata::core::progress_at(save ? "saving a session" : "restoring a session"); + // the background copy of the last turn checkpoint (STRATA_CKPT_ASYNC) lands before anything below copies, frees + // or writes the checkpoints (a join inside the session file writer would match only the copy of a checkpoint) + strata::core::conversation_checkpoint_join(nullptr); if (path.empty()) { refuse("missing path"); continue; } if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; } if (o.peer_device >= 1) { refuse("session files do not support --peer-device"); continue; } @@ -12875,6 +12881,8 @@ int main(int argc, char** argv) { } cur = ids; const Clock::time_point r0 = Clock::now(); + tr("r0"); + strata::core::conversation_checkpoint_join(nullptr); // STRATA_CKPT_ASYNC: the last save's copy has landed const int64_t streamed0 = sp.chain_experts_streamed(); // the DONE line's experts_streamed= is the difference // ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are // exactly the start of this prompt - at most n - 1 of them, the last token is always the first window From f73b3c86a45e1decf3ab67f77ea2f811d46a255a Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:51:09 +0100 Subject: [PATCH 169/177] Conversation cache: opt-in STRATA_PARK_ASYNC=1 parks the K/V in the background and moves the dropped checkpoints (#3779, #3712) Problem: parking the outgoing conversation copies its K/V device to host and deep-copies its checkpoints before the next prompt can start: 213 ms at a 3K context, 334 ms at 13K on a PCIe Gen2 x4 card (the reporter's CMP 170HX). Change, opt-in and CUDA only (off on HIP, gfx906 and Metal): - STRATA_PARK_ASYNC=1: conversation_kv_save copies the device K/V device to device into a VRAM stage (only while 1.5 GB stay free beside it; otherwise the save copies as before), and a background thread moves the stage into the host buffers in 4 MiB pieces through two pinned buffers. conversation_park_join waits for it: every reader of a parked image's K/V, the cache before it frees an entry, and the image itself (SavedConversation::pending) before its buffers go. ConversationBuffer::resize_for_overwrite leaves the added bytes unfilled for that copy; the buffer's segments use an allocator that value-initializes only when a fill value is given, and resize(n, value) is unchanged for every other caller. - With it, the checkpoints this request drops right after the park (all of them when another state comes in, else the ones off this prompt's path) move into the parked image instead of being copied, and a background allocation refills STRATA_CKPT_POOL for the next save. Only the main session's checkpoints move, not an idle batch slot's (the park_source of #2526 serves both). - conversation_snapshot_save takes dropped checkpoints' storage (the existing STRATA_CKPT_POOL) for its copies; with the pool off, nothing is taken. - Unset: park_drops is null, no storage is taken, the K/V copies are the synchronous ones; the added work is the K/V size sum for the stage request and a few join calls. Differs from the PR as submitted: the PR's join in conversation_file.cpp (put_payload) is not ported; the SAVE/RESTORE handler of generate.cpp joins the park first (see the previous commit, which carries the PR's 33a8146a fix). Hand-merged into the park_source / ParkSource refactor of #2526. Not covered: if the background copy fails after resize_for_overwrite, the parked image keeps unfilled bytes; the failure is logged. A restore of such an image would read them. No test of the park path with a failing copy. Tests: the PARK_ASYNC path has no unit test in this commit (it needs a card with 1.5 GB free for the stage); the reporter's A/B/A conversation check covers it, see the checklist. Reporter's numbers (linxuhao, CMP 170HX): park 213 -> 64-75 ms (3K), 334 -> 68 ms (13K); greedy answers identical on their 11 prompts and the A/B/A conversation check. Theirs, not measured here. Original change by linxuhao (PR #3779, commit 3e0c141c). --- include/strata/core/conversation_buffer.hpp | 23 ++- include/strata/core/conversation_cache.hpp | 4 + include/strata/core/conversation_snapshot.hpp | 21 ++- src/core/conversation_copy.hpp | 44 ++++- src/core/conversation_snapshot.cpp | 171 +++++++++++++++++- src/core/conversation_state.cpp | 30 ++- src/program/generate.cpp | 57 +++++- sycl/src/core/conversation_state.cpp | 4 +- 8 files changed, 340 insertions(+), 14 deletions(-) diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp index d8a45177..2ba8aaa6 100644 --- a/include/strata/core/conversation_buffer.hpp +++ b/include/strata/core/conversation_buffer.hpp @@ -7,6 +7,7 @@ #include <cstdint> #include <cstring> #include <initializer_list> +#include <memory> #include <utility> #include <vector> @@ -61,7 +62,8 @@ public: (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; return total; } - void resize(size_t n, uint8_t value = 0) { + void resize(size_t n, uint8_t value = 0) { resize_impl(n, &value); } + void resize_impl(size_t n, const uint8_t* value) { if (n > size_) { const size_t held = size_; const bool growing = held != 0; @@ -70,7 +72,8 @@ public: const size_t extra = n - size_ - extend; segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); if (extend) { - segments_.back().resize(segments_.back().size() + extend, value); + if (value) segments_.back().resize(segments_.back().size() + extend, *value); + else segments_.back().resize(segments_.back().size() + extend); size_ += extend; } while (size_ < n) { @@ -78,7 +81,8 @@ public: const size_t previous = segments_.empty() ? 0 : segments_.back().capacity(); Segment segment; segment.reserve(segment_capacity(count, previous, growing, held)); - segment.resize(count, value); + if (value) segment.resize(count, *value); + else segment.resize(count); segments_.push_back(std::move(segment)); size_ += count; progress_beat(); // #2049: zero-filling 16 MiB of fresh pages is slow when the host is paging @@ -93,6 +97,9 @@ public: } } void pop_back() { resize(size_ - 1); } + // resize() without the zero fill of what it adds (the fresh pages are not touched here): only for a caller that + // writes every added byte before anything reads it (STRATA_PARK_ASYNC's background copy) + void resize_for_overwrite(size_t n) { resize_impl(n, nullptr); } // fn(pointer, count, absolute_offset); false aborts a transfer immediately. template<class Fn> bool visit(size_t offset, size_t count, Fn fn) { @@ -123,7 +130,15 @@ public: } private: - using Segment = std::vector<uint8_t>; + // value-initializes only when asked (resize's explicit fill value): resize_for_overwrite leaves the bytes alone + template<class T> struct DefaultInit : std::allocator<T> { + template<class U> struct rebind { using other = DefaultInit<U>; }; + DefaultInit() = default; + template<class U> DefaultInit(const DefaultInit<U>&) noexcept {} + template<class U> void construct(U* p) { ::new ((void*) p) U; } + template<class U, class... A> void construct(U* p, A&&... a) { ::new ((void*) p) U(std::forward<A>(a)...); } + }; + using Segment = std::vector<uint8_t, DefaultInit<uint8_t>>; // A fresh capture allocates exactly its payload. Later appends reserve // geometrically growing segments, bounded by 16 MiB. Small chat turns then // extend the final allocation instead of adding one transfer per turn. diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 0adf0917..92dd6e73 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -9,6 +9,7 @@ #include <cstddef> #include <cstdint> #include <deque> +#include <memory> #include <utility> #include <vector> @@ -173,6 +174,9 @@ struct SavedConversation { bool cvec = true; // with a layer split, the later stages' own images, one per stage, in stage order std::vector<SavedConversation> stage_images; + // STRATA_PARK_ASYNC: set while a background copy fills this image's K/V; its deleter waits for that copy, and as + // the last member it runs before any buffer is freed (whichever copy of the image goes last) + std::shared_ptr<void> pending; /// Holds a pinned shared prefix (see ConversationCheckpoint::pinned): the parked-conversation budget keeps it. bool pinned() const { diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index 962bf33f..be4412e1 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -77,6 +77,19 @@ bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const Sess /// when nothing is in flight. /// `only` (non-null): wait only when the copy in flight is into that checkpoint's GDN bytes. void conversation_checkpoint_join(const void* only = nullptr); +/// STRATA_PARK_ASYNC: waits until the last parked image's K/V has landed in its host buffers (no-op otherwise); the +/// readers of a parked image's K/V call it first, and the image itself before it frees them (SavedConversation::pending). +void conversation_park_join(); +/// STRATA_PARK_ASYNC=1 (CUDA, opt-in): between begin and launch, conversation_kv_save copies the device K/V device to +/// device into a VRAM stage (only while 1.5 GB of VRAM stays free beside it; else as before) and records where it +/// goes; launch moves the stage into the host buffers on a background thread (4 MiB pieces through two pinned +/// buffers), so the next prompt starts at once. conversation_park_join (above) waits for it. +/// begin: false when it is off (the saves then copy as before); `need` is the K/V bytes the saves will copy. +bool conversation_park_async_begin(size_t need); +/// The recorded copies start (the device copies into the stage have landed when it returns); false: a copy failed. +bool conversation_park_async_launch(std::string& error); +/// Abandons a begun park that was not launched (the error paths): nothing was queued to the background. +void conversation_park_async_abandon(); bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, const ModelGeometry& g, std::string& error); // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two @@ -135,9 +148,15 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, const SessionState& session, const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error); +// `storage` (optional, STRATA_CKPT_POOL): dropped checkpoints whose vectors the image's running state and checkpoint +// copies go into (their pages are in: no fresh pages to fault); the ones not used are left in it. +// `moved` (optional): checkpoints the caller drops after this, moved into the image after the copies of the view's +// (the image holds the same checkpoints as with all of them in the view; nothing is copied for these) bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session, const ModelGeometry& g, const QsaState* draft, std::string& error, - ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); + ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr, + std::vector<ConversationCheckpoint>* storage = nullptr, + std::vector<ConversationCheckpoint>* moved = nullptr); bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, const ModelGeometry& g, const QsaState* draft, std::string& error); ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session, diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index 0a65c4de..e9a98134 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -165,11 +165,51 @@ inline ConversationCheckpoint copy_checkpoint_beating(const ConversationCheckpoi return o; } -inline std::vector<ConversationCheckpoint> copy_checkpoints_beating(const std::vector<ConversationCheckpoint>& cs) { +/// copy_beating into `out`'s storage (its capacity kept: a vector whose pages are in takes the copy without faults) +template<class V> +inline void assign_beating(V& out, const V& src) { + out.clear(); + out.reserve(src.size()); + const size_t step = std::max<size_t>(1, ((size_t) 1 << 20) / sizeof(typename V::value_type)); + for (size_t at = 0; at < src.size(); at += step) { + out.insert(out.end(), src.begin() + (std::ptrdiff_t) at, + src.begin() + (std::ptrdiff_t) std::min(src.size(), at + step)); + if (const long us = test_slow_copy_us(); us > 0) std::this_thread::sleep_for(std::chrono::microseconds(us)); + core::progress_beat(); + } +} + +/// copy_checkpoint_beating into `o`, a dropped checkpoint's storage (STRATA_CKPT_POOL): the same bytes +inline void copy_checkpoint_into(ConversationCheckpoint& o, const ConversationCheckpoint& c) { + assign_beating(o.ids, c.ids); + assign_beating(o.imgs, c.imgs); + assign_beating(o.gdn, c.gdn); + o.dev_tag = c.dev_tag; + assign_beating(o.ple, c.ple); + assign_beating(o.tails, c.tails); + assign_beating(o.dead, c.dead); + assign_beating(o.block_pos, c.block_pos); + o.used = c.used; + o.pinned = c.pinned; + o.stage_parts.clear(); + for (const auto& part : c.stage_parts) o.stage_parts.push_back(copy_checkpoint_beating(part)); +} + +/// `storage` (optional): dropped checkpoints whose vectors the copies go into, taken from its back while it lasts +inline std::vector<ConversationCheckpoint> copy_checkpoints_beating(const std::vector<ConversationCheckpoint>& cs, + std::vector<ConversationCheckpoint>* storage = nullptr) { for (const auto& c : cs) core::conversation_checkpoint_join(c.gdn.data()); std::vector<ConversationCheckpoint> out; out.reserve(cs.size()); - for (const auto& c : cs) out.push_back(copy_checkpoint_beating(c)); + for (const auto& c : cs) { + if (storage != nullptr && !storage->empty()) { + out.push_back(std::move(storage->back())); + storage->pop_back(); + copy_checkpoint_into(out.back(), c); + } else { + out.push_back(copy_checkpoint_beating(c)); + } + } return out; } diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 76e69b5f..b9967651 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -5,9 +5,13 @@ #include <cuda_runtime.h> #include <array> +#include <cstdio> +#include <cstdlib> #include <cstring> +#include <future> #include <limits> #include <memory> +#include <mutex> namespace strata::core { namespace { @@ -110,6 +114,39 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error return true; } +struct ParkAsync { + std::mutex mu; + std::future<cudaError_t> pending; + struct Item { uint8_t* dst; size_t n, at; }; + std::vector<Item> items; + uint8_t* stage = nullptr; + size_t cap = 0, used = 0; + void* host[2] = {nullptr, nullptr}; // pinned, 4 MiB each + cudaStream_t stream = nullptr; + int dev = -1; + bool active = false; +}; +ParkAsync& park_async() { static ParkAsync a; return a; } +constexpr size_t kParkPiece = (size_t) 4 << 20; +bool park_async_on() { +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) + return false; +#else + static const bool on = [] { const char* v = std::getenv("STRATA_PARK_ASYNC"); return v != nullptr && v[0] == '1'; }(); + return on; +#endif +} +bool on_device(const void* p) { +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) + (void) p; // (no pointer-attribute query in the shims: the slot takes no part, as when the query fails) + return false; +#else + cudaPointerAttributes at{}; + if (cudaPointerGetAttributes(&at, p) != cudaSuccess) { cudaGetLastError(); return false; } + return at.type == cudaMemoryTypeDevice; +#endif +} + bool transfer(void* dst, const void* src, size_t n, std::string& error) { if (!n) return true; if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; } @@ -171,9 +208,20 @@ bool conversation_kv_save(ConversationKv& image, const QsaState& st, const Model const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0) : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0; if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } - dst[i]->resize(sizes[i]); + // STRATA_PARK_ASYNC: device bytes go to the VRAM stage now and into the buffer on the background thread + ParkAsync& a = park_async(); + const bool staged = a.active && src[i] != nullptr && sizes[i] > keep && a.used + (sizes[i] - keep) <= a.cap && + on_device(src[i]); + if (staged) dst[i]->resize_for_overwrite(sizes[i]); + else dst[i]->resize(sizes[i]); if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { - return transfer(p, src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr, n, error); + const uint8_t* s = src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr; + if (!staged) return transfer(p, s, n, error); + const cudaError_t e = conversation_detail::copy_nonblocking(a.stage + a.used, s, n, true); + if (e != cudaSuccess) { error = std::string("conversation snapshot stage copy: ") + cudaGetErrorString(e); return false; } + a.items.push_back({p, n, a.used}); + a.used += n; + return true; })) return false; if (reused_bytes) *reused_bytes += keep; } @@ -253,6 +301,7 @@ bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelG bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, std::string& error) { + conversation_park_join(); if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; const auto dst = pools(st); @@ -265,6 +314,7 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t captured, int64_t upto, bool index, std::string& error) { + conversation_park_join(); if (upto < 0 || upto > captured) { error = "conversation snapshot: prefix beyond the captured K/V"; return false; @@ -314,6 +364,7 @@ bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const Mode bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, uint64_t& fingerprint, std::string& error) { + conversation_park_join(); if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; std::array<uint8_t, 65536> buffer; uint64_t hash = 1469598103934665603ull; @@ -355,4 +406,120 @@ bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, con return true; } +void conversation_park_join() { + ParkAsync& a = park_async(); + std::lock_guard<std::mutex> lk(a.mu); + if (a.pending.valid()) { + const cudaError_t e = a.pending.get(); + if (e != cudaSuccess) std::fprintf(stderr, "strata: STRATA_PARK_ASYNC: a parked K/V copy failed (%s)\n", cudaGetErrorString(e)); + } +} + +bool conversation_park_async_begin(size_t need) { + conversation_park_join(); // (the stage is reused) + ParkAsync& a = park_async(); + a.active = false; + a.items.clear(); + a.used = 0; + if (!park_async_on() || need == 0) return false; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { (void) cudaGetLastError(); return false; } + if (a.stage != nullptr && (a.cap < need || a.dev != dev)) { + const int cur = dev; + (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaSetDevice(cur); + a.stage = nullptr; a.cap = 0; + } + if (a.stream != nullptr && a.dev != dev) { + const int cur = dev; + (void) cudaSetDevice(a.dev); (void) cudaStreamDestroy(a.stream); + (void) cudaFreeHost(a.host[0]); (void) cudaFreeHost(a.host[1]); (void) cudaSetDevice(cur); + a.stream = nullptr; a.host[0] = a.host[1] = nullptr; + } + a.dev = dev; + if (a.stream == nullptr && + (cudaStreamCreateWithFlags(&a.stream, cudaStreamNonBlocking) != cudaSuccess || + cudaMallocHost(&a.host[0], kParkPiece) != cudaSuccess || cudaMallocHost(&a.host[1], kParkPiece) != cudaSuccess)) { + if (a.host[0]) (void) cudaFreeHost(a.host[0]); + if (a.host[1]) (void) cudaFreeHost(a.host[1]); + if (a.stream) (void) cudaStreamDestroy(a.stream); + a.stream = nullptr; a.host[0] = a.host[1] = nullptr; + (void) cudaGetLastError(); + return false; + } + if (a.stage == nullptr) { + size_t fr = 0, tot = 0; + if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < need + ((size_t) 3 << 29) || + cudaMalloc((void**) &a.stage, need) != cudaSuccess) { + a.stage = nullptr; + (void) cudaGetLastError(); + return false; + } + a.cap = need; + } + a.active = true; + return true; +} + +void conversation_park_async_abandon() { + ParkAsync& a = park_async(); + if (!a.active) return; + a.active = false; + a.items.clear(); + cudaStream_t s = nullptr; + if (conversation_detail::private_stream(s) == cudaSuccess) (void) cudaStreamSynchronize(s); // nothing reads the stage after + (void) cudaGetLastError(); +} + +bool conversation_park_async_launch(std::string& error) { + ParkAsync& a = park_async(); + if (!a.active) return true; + a.active = false; + cudaStream_t s = nullptr; + cudaError_t e = conversation_detail::private_stream(s); + if (e == cudaSuccess) e = cudaStreamSynchronize(s); // the device-to-device copies into the stage + if (e != cudaSuccess) { + a.items.clear(); + error = std::string("conversation snapshot stage: ") + cudaGetErrorString(e); + return false; + } + if (a.items.empty()) return true; + std::vector<ParkAsync::Item> items; + items.swap(a.items); + const uint8_t* stage = a.stage; + void* host[2] = {a.host[0], a.host[1]}; + cudaStream_t st = a.stream; + const int dev = a.dev; + std::lock_guard<std::mutex> lk(a.mu); + // two pinned pieces in turn: the next piece's DMA runs while this one is copied into its segment + a.pending = std::async(std::launch::async, [items = std::move(items), stage, host, st, dev] { + (void) cudaSetDevice(dev); + cudaEvent_t done[2] = {nullptr, nullptr}; + cudaError_t e = cudaEventCreateWithFlags(&done[0], cudaEventDisableTiming | cudaEventBlockingSync); + if (e == cudaSuccess) e = cudaEventCreateWithFlags(&done[1], cudaEventDisableTiming | cudaEventBlockingSync); + struct Piece { uint8_t* dst; size_t n; }; + Piece held[2] = {{nullptr, 0}, {nullptr, 0}}; + int b = 0; + auto land = [&](int k) { + if (held[k].dst == nullptr || e != cudaSuccess) return; + e = cudaEventSynchronize(done[k]); + if (e == cudaSuccess) std::memcpy(held[k].dst, host[k], held[k].n); + held[k] = {nullptr, 0}; + }; + for (const auto& it : items) + for (size_t o = 0; e == cudaSuccess && o < it.n; o += kParkPiece) { + const size_t n = std::min(kParkPiece, it.n - o); + land(b); + if (e == cudaSuccess) e = cudaMemcpyAsync(host[b], stage + it.at + o, n, cudaMemcpyDeviceToHost, st); + if (e == cudaSuccess) e = cudaEventRecord(done[b], st); + if (e == cudaSuccess) held[b] = {it.dst + o, n}; + b ^= 1; + } + land(b); + land(b ^ 1); + for (cudaEvent_t d : done) if (d) (void) cudaEventDestroy(d); + return e; + }); + return true; +} + } // namespace strata::core diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 36a8a6da..bfbc7db2 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -433,8 +433,11 @@ bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error, - ConversationKvReuse reuse, size_t* reused_bytes) { + ConversationKvReuse reuse, size_t* reused_bytes, + std::vector<ConversationCheckpoint>* storage, + std::vector<ConversationCheckpoint>* moved) { conversation_checkpoint_join(nullptr); + conversation_park_join(); static const bool ptr = std::getenv("STRATA_PARK_TRACE") != nullptr; auto now = [] { return std::chrono::steady_clock::now(); }; auto ms = [](std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) { @@ -446,9 +449,19 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView SavedConversation captured; captured.geometry = geometry_key(g); captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; + if (storage != nullptr && !storage->empty()) { // the running state into a dropped checkpoint's vectors + captured.live = std::move(storage->back()); + storage->pop_back(); + captured.live.stage_parts.clear(); + } captured.live.ids = view.ids; captured.live.imgs = view.images; const auto p1 = now(); - captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints); + captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints, storage); + if (moved != nullptr) + for (auto& c : *moved) { + conversation_checkpoint_join(c.gdn.data()); + captured.checkpoints.push_back(std::move(c)); + } const auto p2 = now(); const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; captured.kv = std::move(reuse.kv); @@ -457,6 +470,12 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; const auto p3 = now(); const int64_t upto = (int64_t) view.ids.size(); + // STRATA_PARK_ASYNC: the K/V bytes these saves copy (the stage they need; an over-estimate by the kept prefix) + size_t kv_need = 0; + for (size_t j = 0; j < layers; ++j) kv_need += conversation_kv_bytes(owned(ss, j), g, upto, true); + if (draft) kv_need += conversation_kv_bytes(*draft, g, upto, false); + const bool staged = conversation_park_async_begin(kv_need); + struct Abandon { bool on; ~Abandon() { if (on) conversation_park_async_abandon(); } } abandon{staged}; for (size_t j = 0; j < layers; ++j) if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error, unchanged, reused_bytes)) return false; @@ -470,6 +489,9 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView // reached. Refresh that page even when the main prefix continued unchanged. if (draft && !conversation_kv_save(captured.kv.back(), *draft, g, upto, false, error, std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false; + abandon.on = false; + if (staged && !conversation_park_async_launch(error)) return false; + if (staged) captured.pending = std::shared_ptr<void>(new char, [](void* p) { conversation_park_join(); delete (char*) p; }); image = std::move(captured); return true; } @@ -550,6 +572,7 @@ ConversationRestore conversation_snapshot_restore(const SavedConversation& image const ModelGeometry& g, const QsaState* draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); + conversation_park_join(); if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid; if (!sync(error)) return ConversationRestore::transfer_failed; const int64_t upto = (int64_t) image.live.ids.size(); @@ -586,6 +609,7 @@ ConversationRestore conversation_snapshot_restore(const SavedConversation& image const ModelGeometry& g, const QsaState& draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); + conversation_park_join(); return conversation_snapshot_restore(image, ss, g, &draft, error); } ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto, @@ -593,6 +617,7 @@ ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation const QsaState& draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); + conversation_park_join(); return conversation_snapshot_restore_prefix(image, upto, ss, g, &draft, error); } ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto, @@ -600,6 +625,7 @@ ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation const QsaState* draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); + conversation_park_join(); // a layer split's image (stage images) is restored stage by stage, never in part if (!image.stage_images.empty()) { fail(error, "a layer split's image restored as a single session"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index c7737371..84836cd0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -253,6 +253,10 @@ bool admit_merge_first_env() { // checkpoints it drops (evicted, pruned, a batch slot's old one) and saves the next checkpoint into them, so a save // resizes nothing (no zero-fill of ~118 MB of fresh vectors) and a slot's copy reuses their pages. Every byte is // overwritten by the copy, so the checkpoints are the same +bool park_async_env() { // STRATA_PARK_ASYNC (strata/core/conversation_snapshot.hpp) + static const bool on = [] { const char* v = std::getenv("STRATA_PARK_ASYNC"); return v != nullptr && v[0] == '1'; }(); + return on; +} bool ckpt_pool_env() { static const bool on = [] { const char* v = std::getenv("STRATA_CKPT_POOL"); @@ -9673,6 +9677,10 @@ int main(int argc, char** argv) { }; // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. + // STRATA_PARK_ASYNC: set by the request around its park - the live checkpoints it drops right after (they move + // into the parked image instead of being copied); a background allocation then refills STRATA_CKPT_POOL + std::function<bool(const ConvCheckpoint&)> park_drops; + std::future<void> pool_refill; auto park_source = [&](const ParkSource& src, size_t held) -> bool { // #2049: parking copies the outgoing conversation's running checkpoints and K/V into host memory, which // is a silent stretch of the "request" stage; when the OS has paged that memory out it takes minutes. @@ -9813,8 +9821,39 @@ int main(int argc, char** argv) { (long long) o.conversation_cache_min_free_mib); strata::core::SavedConversation image; size_t reused_bytes = 0; - if (!strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err, - std::move(reuse), &reused_bytes)) return false; + // STRATA_CKPT_POOL: the running state and the checkpoint copies go into dropped checkpoints' vectors + // (the ones this request drops refill the pool right after); what is left goes back + std::vector<ConvCheckpoint> storage; + if (ckpt_pool.on() && n_st == 0) + for (size_t k = 0; k <= view.checkpoints.size(); ++k) { + ConvCheckpoint c = ckpt_pool.take(); + if (c.gdn.empty()) break; + storage.push_back(std::move(c)); + } + std::vector<ConvCheckpoint> moved; // STRATA_PARK_ASYNC: the ones this request drops (view: the rest) + if (park_drops && n_st == 0 && src.with_reuse) { // (the main session's checkpoints only, not an idle slot's) + size_t w = 0; + for (size_t i = 0; i < checks.size(); ++i) { + if (park_drops(static_cast<const ConvCheckpoint&>(checks[i]))) { moved.push_back(std::move(checks[i])); continue; } + if (w != i) checks[w] = std::move(checks[i]); + ++w; + } + checks.erase(checks.begin() + (std::ptrdiff_t) w, checks.end()); + } + const size_t moved_gdn = moved.empty() ? 0 : moved.front().gdn.size(); + const bool saved = strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err, + std::move(reuse), &reused_bytes, storage.empty() ? nullptr : &storage, + moved.empty() ? nullptr : &moved); + for (ConvCheckpoint& c : storage) ckpt_pool.give(std::move(c)); + if (!saved) return false; + // the next checkpoint save would fault in fresh pages for what moved out: one is allocated now + if (moved_gdn > 0 && ckpt_pool.on() && + (!pool_refill.valid() || pool_refill.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) + pool_refill = std::async(std::launch::async, [&ckpt_pool, moved_gdn] { + ConvCheckpoint c; + c.gdn.resize(moved_gdn); + ckpt_pool.give(std::move(c)); + }); for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V) auto& st = stages[k]; const strata::core::OnDevice on(st->dev); @@ -12449,6 +12488,7 @@ int main(int argc, char** argv) { // the background copy of the last turn checkpoint (STRATA_CKPT_ASYNC) lands before anything below copies, frees // or writes the checkpoints (a join inside the session file writer would match only the copy of a checkpoint) strata::core::conversation_checkpoint_join(nullptr); + strata::core::conversation_park_join(); // (STRATA_PARK_ASYNC: the last park's K/V) if (path.empty()) { refuse("missing path"); continue; } if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; } if (o.peer_device >= 1) { refuse("session files do not support --peer-device"); continue; } @@ -13122,6 +13162,19 @@ int main(int argc, char** argv) { : 0; const bool park_worth = o.conversation_cache_park_gain <= 0 || park_held == 0 || (int64_t) live.size() >= (int64_t) park_held + o.conversation_cache_park_gain; + // STRATA_PARK_ASYNC: the checkpoints this request drops after its park - all of them when another state + // comes in (a parked conversation, a borrow, a batch slot) or the cvec changes, else the ones off this + // prompt's path (off_path below) - move into the parked image + struct ParkDrops { + std::function<bool(const ConvCheckpoint&)>& f; + ~ParkDrops() { f = nullptr; } + } park_drops_reset{park_drops}; + if (park_async_env()) { + const bool drops_all = incoming.has_value() || borrow || slot_source >= 0 || want_cvec != cvec_cached; + park_drops = [&, drops_all](const ConvCheckpoint& c) { + return drops_all || (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); + }; + } if (borrow && !pin_sibling && park_worth) { conversations.guard(parked.serial); // parking the outgoing conversation must not evict the donor const bool parked_ok = park_current(0); diff --git a/sycl/src/core/conversation_state.cpp b/sycl/src/core/conversation_state.cpp index f6bd041d..1911db77 100644 --- a/sycl/src/core/conversation_state.cpp +++ b/sycl/src/core/conversation_state.cpp @@ -258,7 +258,9 @@ bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error, - ConversationKvReuse reuse, size_t* reused_bytes) { + ConversationKvReuse reuse, size_t* reused_bytes, + std::vector<ConversationCheckpoint>* /*storage: STRATA_CKPT_POOL, CUDA only*/, + std::vector<ConversationCheckpoint>* /*moved: STRATA_PARK_ASYNC, CUDA only*/) { size_t estimate = 0; if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; // Build into a new object so a failure cannot publish a partial snapshot. From ca378670b2eccf1c11bedc418c1a9a486bc1a3ac Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:52:35 +0100 Subject: [PATCH 170/177] Conversation cache: opt-in ready checkpoint pool STRATA_CKPT_POOL_READY=N, gathered small checkpoint copies STRATA_CKPT_GATHER=1, park traces (#3779, #3712) Problem (reporter, CMP 170HX, PCIe Gen2 x4): a conversation switch's park still paid 38-52 ms for the live state, because the STRATA_CKPT_POOL pool was empty at every park (a switch takes two checkpoints), so the 118 MB GDN vector was allocated fresh and page-faulted; and a checkpoint's 37 small synchronous device-to-host copies queue behind the 4 MiB DMA pieces of STRATA_CKPT_ASYNC. Change: - STRATA_CKPT_POOL_READY=N (opt-in, 1..16, with STRATA_CKPT_POOL on): the pool keeps N ready checkpoints, pre-sized to the session's state sizes with their pages in, topped up on a background thread after any take (not with a layer split). - STRATA_CKPT_GATHER=1 (CUDA, opt-in): the small running-state vectors (ple, and each layer's indexer tail, dead row and block position) are gathered device to device into one buffer and fetched with one copy into a pinned buffer. - The park stage is allocated rounded up to 64 MiB (a growing conversation does not cudaFree/cudaMalloc it every time) and a VRAM-resident K/V skips the pointer attribute query. - The background helpers (pool top-up, the checkpoint DMA, the park DMA) leave the host's pinned core (aux_cpus.hpp); no output depends on where a thread runs. - A parked image whose live GDN state is still being copied joins before its buffers are freed (SavedConversation::live_pending). - STRATA_PARK_TRACE prints the joins, the live-state vectors' readiness and the K/V sub-timers. Differs from the PR as submitted: the PR made STRATA_CKPT_POOL=1 allocate two ready checkpoints at startup (+236 MB of host RSS) and read STRATA_CKPT_POOL=N as a count. That changes what an existing switch does, so here STRATA_CKPT_POOL=1 keeps its meaning (the pool holds dropped checkpoints only, nothing is allocated ahead of time) and the ready pool has its own variable, STRATA_CKPT_POOL_READY. A user of the PR's STRATA_CKPT_POOL=2 sets STRATA_CKPT_POOL=1 STRATA_CKPT_POOL_READY=2. The PR's one-checkpoint refill after a park with STRATA_PARK_ASYNC is replaced by the top-up, as in the PR, and so is only active with the new variable. Merged by hand into #2526's park_source. With none of the new variables set: the stage size is rounded up only when the park stage is on, the extra code is trace output behind STRATA_PARK_TRACE and the join calls. Reporter's numbers (linxuhao, CMP 170HX): park at a 3K context 64-75 -> 21-40 ms (all park switches together, A/B/A conversation check identical, greedy 11 of 11 identical). Theirs, not measured here. Original change by linxuhao (PR #3779, commit 56088e71). --- include/strata/core/conversation_cache.hpp | 4 +- src/core/conversation_copy.hpp | 19 +++ src/core/conversation_snapshot.cpp | 44 ++++++- src/core/conversation_state.cpp | 145 ++++++++++++++++++--- src/program/generate.cpp | 60 +++++++-- 5 files changed, 233 insertions(+), 39 deletions(-) diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 92dd6e73..c35aef88 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -175,8 +175,10 @@ struct SavedConversation { // with a layer split, the later stages' own images, one per stage, in stage order std::vector<SavedConversation> stage_images; // STRATA_PARK_ASYNC: set while a background copy fills this image's K/V; its deleter waits for that copy, and as - // the last member it runs before any buffer is freed (whichever copy of the image goes last) + // one of the last members it runs before any buffer is freed (whichever copy of the image goes last) std::shared_ptr<void> pending; + // STRATA_CKPT_ASYNC: the same for the background copy that fills `live.gdn` (the park's running state) + std::shared_ptr<void> live_pending; /// Holds a pinned shared prefix (see ConversationCheckpoint::pinned): the parked-conversation budget keeps it. bool pinned() const { diff --git a/src/core/conversation_copy.hpp b/src/core/conversation_copy.hpp index e9a98134..10775755 100644 --- a/src/core/conversation_copy.hpp +++ b/src/core/conversation_copy.hpp @@ -2,6 +2,7 @@ #include "strata/core/conversation_cache.hpp" #include "strata/core/progress.hpp" +#include "strata/platform/aux_cpus.hpp" #include <cuda_runtime.h> @@ -14,6 +15,10 @@ #include <thread> #include <vector> +#if defined(__linux__) +#include <sched.h> +#endif + namespace strata::core { void conversation_checkpoint_join(const void* only); } namespace strata::core::conversation_detail { @@ -105,6 +110,20 @@ inline long test_copy_fail_at() { return v; } +/// First thing a background copy thread does (STRATA_CKPT_ASYNC, STRATA_PARK_ASYNC): a thread the host creates +/// inherits the host's one CPU (strata/platform/aux_cpus.hpp), where its memcpys would take turns with the decode. +/// Wide first: the mask the aux placement keeps as this thread's own is the one restore() puts back (a request with +/// aux_cpus=0), and the host's one CPU must not be it. No output depends on where a thread runs. +inline void background_thread_placement() { +#if defined(__linux__) + cpu_set_t all; + CPU_ZERO(&all); + for (int c = 0; c < CPU_SETSIZE; ++c) CPU_SET(c, &all); + (void) sched_setaffinity(0, sizeof all, &all); // the kernel keeps the CPUs the process may use + strata::aux_cpus::pin_current_thread(); // (a no-op while the feature is off) +#endif +} + /// `queued`: the copy is only queued on the private stream, and the caller synchronizes the device (or orders a /// later launch after it with order_after_queued) before anything reads the target or writes the source. inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes, bool queued = false) { diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index b9967651..77d5703a 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -5,6 +5,7 @@ #include <cuda_runtime.h> #include <array> +#include <chrono> #include <cstdio> #include <cstdlib> #include <cstring> @@ -146,6 +147,14 @@ bool on_device(const void* p) { return at.type == cudaMemoryTypeDevice; #endif } +// STRATA_PARK_TRACE: where conversation_kv_save's time goes since the park's begin (ms): the pointer-attribute +// queries, the host buffer resizes and the copies (into the stage, or the synchronous ones). Read by the park trace. +struct KvSaveTrace { double attrs = 0, resize = 0, copy = 0; }; +KvSaveTrace& kv_save_trace() { static KvSaveTrace t; return t; } +bool park_trace_on() { + static const bool on = std::getenv("STRATA_PARK_TRACE") != nullptr; + return on; +} bool transfer(void* dst, const void* src, size_t n, std::string& error) { if (!n) return true; @@ -210,11 +219,17 @@ bool conversation_kv_save(ConversationKv& image, const QsaState& st, const Model if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } // STRATA_PARK_ASYNC: device bytes go to the VRAM stage now and into the buffer on the background thread ParkAsync& a = park_async(); + const bool trace = park_trace_on(); + auto tick = [trace] { return trace ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; }; + const auto t0 = tick(); + // (kv_mode 0: the pools are device memory by construction, so no pointer-attribute query) const bool staged = a.active && src[i] != nullptr && sizes[i] > keep && a.used + (sizes[i] - keep) <= a.cap && - on_device(src[i]); + (st.kv_mode == 0 || on_device(src[i])); + const auto t1 = tick(); if (staged) dst[i]->resize_for_overwrite(sizes[i]); else dst[i]->resize(sizes[i]); - if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { + const auto t2 = tick(); + const bool copied = dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { const uint8_t* s = src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr; if (!staged) return transfer(p, s, n, error); const cudaError_t e = conversation_detail::copy_nonblocking(a.stage + a.used, s, n, true); @@ -222,7 +237,14 @@ bool conversation_kv_save(ConversationKv& image, const QsaState& st, const Model a.items.push_back({p, n, a.used}); a.used += n; return true; - })) return false; + }); + if (trace) { + auto ms = [](std::chrono::steady_clock::time_point x, std::chrono::steady_clock::time_point y) { + return std::chrono::duration<double, std::milli>(y - x).count(); }; + KvSaveTrace& t = kv_save_trace(); + t.attrs += ms(t0, t1); t.resize += ms(t1, t2); t.copy += ms(t2, tick()); + } + if (!copied) return false; if (reused_bytes) *reused_bytes += keep; } return true; @@ -415,7 +437,13 @@ void conversation_park_join() { } } +void conversation_kv_save_trace(double& attrs_ms, double& resize_ms, double& copy_ms) { + const KvSaveTrace& t = kv_save_trace(); + attrs_ms = t.attrs; resize_ms = t.resize; copy_ms = t.copy; +} + bool conversation_park_async_begin(size_t need) { + if (park_trace_on()) kv_save_trace() = {}; // (the sums cover this park's saves) conversation_park_join(); // (the stage is reused) ParkAsync& a = park_async(); a.active = false; @@ -447,14 +475,17 @@ bool conversation_park_async_begin(size_t need) { return false; } if (a.stage == nullptr) { + // rounded up to 64 MiB: the next parks of a growing conversation reuse it instead of re-allocating (a cudaFree + // synchronizes the device, and the checkpoint DMA is in flight at this point) + const size_t want = (need + ((size_t) 64 << 20) - 1) & ~(((size_t) 64 << 20) - 1); size_t fr = 0, tot = 0; - if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < need + ((size_t) 3 << 29) || - cudaMalloc((void**) &a.stage, need) != cudaSuccess) { + if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < want + ((size_t) 3 << 29) || + cudaMalloc((void**) &a.stage, want) != cudaSuccess) { a.stage = nullptr; (void) cudaGetLastError(); return false; } - a.cap = need; + a.cap = want; } a.active = true; return true; @@ -492,6 +523,7 @@ bool conversation_park_async_launch(std::string& error) { std::lock_guard<std::mutex> lk(a.mu); // two pinned pieces in turn: the next piece's DMA runs while this one is copied into its segment a.pending = std::async(std::launch::async, [items = std::move(items), stage, host, st, dev] { + conversation_detail::background_thread_placement(); (void) cudaSetDevice(dev); cudaEvent_t done[2] = {nullptr, nullptr}; cudaError_t e = cudaEventCreateWithFlags(&done[0], cudaEventDisableTiming | cudaEventBlockingSync); diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index bfbc7db2..594a2d8a 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -213,6 +213,60 @@ bool ckpt_async_on() { return on; #endif } +// STRATA_CKPT_GATHER=1 (CUDA, opt-in): the small running-state vectors (ple, then each layer's indexer tail, dead row +// and block position: 1 + 3 x layers pieces) are gathered device to device into one buffer, allocated once, and +// fetched with ONE copy into a pinned buffer, then copied into the vectors. A small D2H copy issued while the +// checkpoint DMA (STRATA_CKPT_ASYNC) is in flight waits behind the 4 MiB piece on the copy engine: one such wait +// instead of 37. The same bytes in the same places. One set of buffers: the mutex serializes the saves a layer +// split runs on one thread per stage (STRATA_CKPT_THREADS), which otherwise gather through the same buffer. +struct CkptGather { std::mutex mu; void* stage = nullptr; void* host = nullptr; size_t cap = 0; int dev = -1; }; +CkptGather& ckpt_gather() { static CkptGather a; return a; } +bool ckpt_gather_on() { +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) + return false; +#else + static const bool on = [] { const char* v = std::getenv("STRATA_CKPT_GATHER"); return v != nullptr && v[0] == '1'; }(); + return on; +#endif +} +// 1: the vectors are filled; 0: no buffers (the caller copies them one by one); -1: a copy failed (`error` set) +int ckpt_gather_small(ConversationCheckpoint& c, const SessionState& ss, const ConversationStateSizes& z, + size_t layers, std::string& error) { + const size_t ple = c.ple.size(), tails = c.tails.size(), dead = c.dead.size(), block_pos = c.block_pos.size(); + const size_t total = ple + tails + dead + block_pos; + if (total == 0) return 1; + CkptGather& a = ckpt_gather(); + std::lock_guard<std::mutex> lk(a.mu); + int dev = 0; + (void) cudaGetDevice(&dev); + if (a.stage != nullptr && (a.cap < total || a.dev != dev)) { + const int cur = dev; + (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaFreeHost(a.host); (void) cudaSetDevice(cur); + a.stage = a.host = nullptr; a.cap = 0; + } + if (a.stage == nullptr) { + if (cudaMalloc(&a.stage, total) == cudaSuccess && cudaMallocHost(&a.host, total) == cudaSuccess) { a.cap = total; a.dev = dev; } + else { if (a.stage) (void) cudaFree(a.stage); if (a.host) (void) cudaFreeHost(a.host); a.stage = a.host = nullptr; } + (void) cudaGetLastError(); + if (a.stage == nullptr) return 0; + } + // the pieces in the vectors' order, queued on the private stream (in order), then the one copy to the host + uint8_t* s = (uint8_t*) a.stage; + if (!copy(s, ss.ple_hist, ple, error, true)) return -1; + for (size_t j = 0; j < layers; ++j) { + const auto& st = owned(ss, j); + if (!copy(s + ple + j * z.tail, st.idx_tail, z.tail, error, true) || + !copy(s + ple + tails + j * z.dead, st.idx_dead, z.dead, error, true) || + !copy(s + ple + tails + dead + j * z.block_pos, st.idx_block_pos, z.block_pos, error, true)) return -1; + } + if (!copy(a.host, a.stage, total, error)) return -1; + const uint8_t* h = (const uint8_t*) a.host; + if (ple) std::memcpy(c.ple.data(), h, ple); + if (tails) std::memcpy(c.tails.data(), h + ple, tails); + if (dead) std::memcpy(c.dead.data(), h + ple + tails, dead); + if (block_pos) std::memcpy(c.block_pos.data(), h + ple + tails + dead, block_pos); + return 1; +} } // namespace void conversation_checkpoint_join(const void* only) { @@ -224,8 +278,12 @@ void conversation_checkpoint_join(const void* only) { } } -bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, - const ModelGeometry& g, std::string& error) { +namespace { +// conversation_checkpoint_save; `staged` (STRATA_CKPT_ASYNC): the GDN bytes land in `c.gdn` on the background thread +// after this returns (conversation_checkpoint_join waits for them) +bool checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, const ModelGeometry& g, std::string& error, + bool& staged) { + staged = false; const auto j0 = std::chrono::steady_clock::now(); conversation_checkpoint_join(nullptr); // (the staging buffer is reused) if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: save join %.2f ms\n", @@ -237,9 +295,13 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ConversationStateSizes z; if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; const size_t layers = owned_qsa(ss); + static const bool atr = std::getenv("STRATA_PARK_TRACE") != nullptr; + const bool ready = c.gdn.size() == z.gdn; // (a pooled checkpoint's pages are in; a fresh vector faults them all) + const auto r0 = std::chrono::steady_clock::now(); c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0); c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); - bool staged = false; + if (atr) std::fprintf(stderr, "strata parktrace: save vectors %s, resize %.2f ms\n", ready ? "ready" : "fresh", + std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - r0).count()); if (ckpt_async_on() && c.gdn.size() >= ((size_t) 1 << 20)) { CkptAsync& a = ckpt_async(); int dev = 0; @@ -256,7 +318,7 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& else { if (a.stage) (void) cudaFree(a.stage); if (a.host) (void) cudaFreeHost(a.host); a.stage = a.host = nullptr; } } (void) cudaGetLastError(); - static const bool atr = std::getenv("STRATA_PARK_TRACE") != nullptr; + const auto q0 = std::chrono::steady_clock::now(); VramSlot* slot = vram_slots_n() > 0 ? vram_slot_for(c.gdn.size(), dev) : nullptr; if (slot != nullptr) slot->tag = 0; // (being rewritten) void* dsrc = slot != nullptr ? slot->p : a.stage; @@ -274,12 +336,13 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& const uint8_t* stage = (const uint8_t*) dsrc; cudaStream_t st = a.stream; if (atr) std::fprintf(stderr, "strata parktrace: async ckpt d2d %.2f ms\n", - std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - q1).count()); + std::chrono::duration<double, std::milli>(q1 - q0).count()); std::lock_guard<std::mutex> lk(a.mu); // the DMA in 4 MiB pieces, one in flight: a D2H copy queues behind the one before it on the copy engine, and // the decode's own small reads would otherwise wait for the whole 100+ MB at the link's ~1.6 GB/s a.dst = dst; a.pending = std::async(std::launch::async, [dst, host, stage, n, st, dev] { + conversation_detail::background_thread_placement(); (void) cudaSetDevice(dev); cudaEvent_t done = nullptr; cudaError_t e = cudaEventCreateWithFlags(&done, cudaEventDisableTiming | cudaEventBlockingSync); @@ -297,15 +360,33 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& staged = true; } } - if ((!staged && !copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error)) || - !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false; - for (size_t j = 0; j < layers; ++j) { - const auto& st = owned(ss, j); - if (!copy(c.tails.data() + j * z.tail, st.idx_tail, z.tail, error) || - !copy(c.dead.data() + j * z.dead, st.idx_dead, z.dead, error) || - !copy(c.block_pos.data() + j * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false; - } - return true; + if (!staged && !copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error)) return false; + const auto s0 = std::chrono::steady_clock::now(); + const bool ok = [&] { + // STRATA_CKPT_GATHER=1: the small vectors through one device gather and one copy (else one copy each) + if (ckpt_gather_on()) { + const int r = ckpt_gather_small(c, ss, z, layers, error); + if (r != 0) return r > 0; + } + if (!copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false; + for (size_t j = 0; j < layers; ++j) { + const auto& st = owned(ss, j); + if (!copy(c.tails.data() + j * z.tail, st.idx_tail, z.tail, error) || + !copy(c.dead.data() + j * z.dead, st.idx_dead, z.dead, error) || + !copy(c.block_pos.data() + j * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false; + } + return true; + }(); + if (atr) std::fprintf(stderr, "strata parktrace: save small copies %.2f ms\n", + std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - s0).count()); + return ok; +} +} // namespace + +bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + bool staged = false; + return checkpoint_save(c, ss, g, error, staged); } bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss, @@ -430,18 +511,22 @@ bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const return true; } +// (conversation_snapshot.cpp) STRATA_PARK_TRACE: conversation_kv_save's time since the park's begin, by part (ms) +void conversation_kv_save_trace(double& attrs_ms, double& resize_ms, double& copy_ms); + bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error, ConversationKvReuse reuse, size_t* reused_bytes, std::vector<ConversationCheckpoint>* storage, std::vector<ConversationCheckpoint>* moved) { - conversation_checkpoint_join(nullptr); - conversation_park_join(); static const bool ptr = std::getenv("STRATA_PARK_TRACE") != nullptr; auto now = [] { return std::chrono::steady_clock::now(); }; auto ms = [](std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) { return std::chrono::duration<double, std::milli>(b - a).count(); }; + const auto pj = now(); + conversation_checkpoint_join(nullptr); // the last turn checkpoint's DMA (STRATA_CKPT_ASYNC) + conversation_park_join(); // the previous park's K/V DMA const auto p0 = now(); size_t estimate = 0; if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; @@ -467,7 +552,17 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView captured.kv = std::move(reuse.kv); const size_t layers = owned_qsa(ss); captured.kv.resize(layers + (draft ? 1 : 0)); - if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; + bool live_staged = false; + const bool live_saved = checkpoint_save(captured.live, ss, g, error, live_staged); + // STRATA_CKPT_ASYNC: the running state lands in live.gdn after the save returns; the image waits for that copy + // before the vector is freed (an eviction within the copy's ~70 ms), as `pending` does for the K/V. The join is + // selective: a no-op once the copy has landed or another checkpoint's is in flight. + if (live_staged) + captured.live_pending = std::shared_ptr<void>(new char, [dst = (const void*) captured.live.gdn.data()](void* p) { + conversation_checkpoint_join(dst); + delete (char*) p; + }); + if (!live_saved) return false; const auto p3 = now(); const int64_t upto = (int64_t) view.ids.size(); // STRATA_PARK_ASYNC: the K/V bytes these saves copy (the stage they need; an over-estimate by the kept prefix) @@ -475,15 +570,25 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView for (size_t j = 0; j < layers; ++j) kv_need += conversation_kv_bytes(owned(ss, j), g, upto, true); if (draft) kv_need += conversation_kv_bytes(*draft, g, upto, false); const bool staged = conversation_park_async_begin(kv_need); + const auto p4 = now(); struct Abandon { bool on; ~Abandon() { if (on) conversation_park_async_abandon(); } } abandon{staged}; - for (size_t j = 0; j < layers; ++j) + double kv_max = 0, kv_sum = 0; // (STRATA_PARK_TRACE: the per-layer save time) + for (size_t j = 0; j < layers; ++j) { + const auto k0 = now(); if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error, unchanged, reused_bytes)) return false; + const double kt = ms(k0, now()); + kv_sum += kt; kv_max = std::max(kv_max, kt); + } if (ptr) { size_t kvb = 0; for (const auto& k : captured.kv) kvb += k.bytes(); - std::fprintf(stderr, "strata parktrace: sync %.1f ms, %zu checkpoints copied %.1f ms, live state %.1f ms, K/V %zu MB %.1f ms\n", - ms(p0, p1), captured.checkpoints.size(), ms(p1, p2), ms(p2, p3), kvb >> 20, ms(p3, now())); + double attrs_ms = 0, resize_ms = 0, copy_ms = 0; + conversation_kv_save_trace(attrs_ms, resize_ms, copy_ms); // (the main layers' saves above) + std::fprintf(stderr, "strata parktrace: joins %.1f ms, sync %.1f ms, %zu checkpoints copied %.1f ms, live state %.1f ms, " + "begin %.1f ms, K/V %zu MB %.1f ms (layer max %.2f, sum %.2f; attrs %.2f, resize %.2f, copy %.2f)\n", + ms(pj, p0), ms(p0, p1), captured.checkpoints.size(), ms(p1, p2), ms(p2, p3), ms(p3, p4), kvb >> 20, + ms(p4, now()), kv_max, kv_sum, attrs_ms, resize_ms, copy_ms); } // The draft's final cell may not have been computed when the output cap was // reached. Refresh that page even when the main prefix continued unchanged. diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 84836cd0..4833ed74 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -264,6 +264,20 @@ bool ckpt_pool_env() { }(); return on; } +// STRATA_CKPT_POOL_READY=N (opt-in, N = 1..16, read once; only with the pool on, STRATA_CKPT_POOL): the pool keeps N ready +// checkpoints, each a running-state image with its pages in (~118 MB on Qwen3.8-Flash-Next), allocated on a background +// thread after any take. Unset: the pool holds the dropped checkpoints only, as with STRATA_CKPT_POOL=1 before - that +// variable alone allocates nothing ahead of time and its value is not a count. +size_t ckpt_pool_ready_env() { + static const size_t n = [] { + const char* v = std::getenv("STRATA_CKPT_POOL_READY"); + const long k = v ? std::atol(v) : 0; + return k >= 1 ? (size_t) std::min(16L, k) : (size_t) 0; + }(); + return n; +} +// how many dropped checkpoints the pool keeps (a batch admission drops and takes about two): 2, or more when STRATA_CKPT_POOL_READY asks +size_t ckpt_pool_cap_env() { return std::max<size_t>(2, ckpt_pool_ready_env()); } // STRATA_CKPT_THREADS=1 (read once; off by default): a layer split's checkpoint saves every stage's part at once, the // first on the calling thread and each later stage's on a thread of its own device (kept for the process: the copies' // private streams are per thread), instead of one stage after the other. Each part is the same copy of the same state @@ -1813,11 +1827,14 @@ bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, /// STRATA_CKPT_POOL: the storage of dropped checkpoints, for the next save or slot copy to reuse. `give` keeps a /// checkpoint's vectors (its tokens, pictures and marks cleared), `take` hands one back (an empty checkpoint when none -/// is kept). At most `cap` are kept (a batch admission drops and takes about two), the rest are freed as before. +/// is kept). At most `cap` are kept (a batch admission drops and takes about two; STRATA_CKPT_POOL=N), the rest are +/// freed as before. class CheckpointPool { public: explicit CheckpointPool(bool on, size_t cap = 2) : on_(on), cap_(cap) {} bool on() const { return on_; } + size_t cap() const { return cap_; } + size_t held() { std::lock_guard<std::mutex> lk(mu_); return free_.size(); } void give(ConvCheckpoint&& c) { if (!on_ || c.gdn.empty()) return; strata::core::conversation_checkpoint_join(c.gdn.data()); @@ -1890,7 +1907,6 @@ public: done_.wait(lk, [&] { return pending_ == 0; }); job_ = nullptr; } -private: static void spread_current_thread() { #if defined(__linux__) // wide first: the mask the aux placement keeps as this thread's own is the one restore() puts back (a request @@ -1902,6 +1918,7 @@ private: strata::aux_cpus::pin_current_thread(); // (a no-op while the feature is off) #endif } +private: void loop(size_t k) { strata::platform::name_this_thread("strata-ckpt", (int) k); spread_current_thread(); @@ -9557,7 +9574,7 @@ int main(int argc, char** argv) { strata::prefill::KvaFloorRegistry kva_floors; // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused. STRATA_SLOT_CKPT_MOVE turns it on too: a moved // checkpoint frees nothing at the next prune, so every save would fault in fresh pages (17 -> 40-60 ms) - CheckpointPool ckpt_pool(ckpt_pool_env() || slot_ckpt_move_env()); + CheckpointPool ckpt_pool(ckpt_pool_env() || slot_ckpt_move_env(), ckpt_pool_cap_env()); uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it int64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none) // --prefill-pipe: the plan of the prompt segment being read (read_part sets it around its runs), for the @@ -9681,6 +9698,32 @@ int main(int argc, char** argv) { // into the parked image instead of being copied); a background allocation then refills STRATA_CKPT_POOL std::function<bool(const ConvCheckpoint&)> park_drops; std::future<void> pool_refill; + // STRATA_CKPT_POOL_READY=N (with STRATA_CKPT_POOL): the pool holds N checkpoints whose vectors already have the + // session's sizes (the ones conversation_checkpoint_save resizes to, so a pooled one is never resized) with their + // pages in: a fresh 118 MB vector costs ~40 ms of page faults at a save. Topped up on a background thread, off the + // host's core, whenever a take leaves it short; one top-up at a time. Allocation only: a save overwrites every byte. + // Not with a layer split (its checkpoints carry stage parts; saved as before). Unset: no ready checkpoints, nothing + // allocated ahead of time. + auto pool_topup = [&] { + if (ckpt_pool_ready_env() == 0 || !ckpt_pool.on() || !stages.empty()) return; + const ConvStateSizes pool_z = conv_state_sizes(g, ss); + if (pool_z.gdn == 0) return; + if (pool_refill.valid() && pool_refill.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return; + const size_t have = ckpt_pool.held(); + if (have >= ckpt_pool_ready_env()) return; + pool_refill = std::async(std::launch::async, [&ckpt_pool, want = ckpt_pool_ready_env() - have, z = pool_z, + layers = (size_t) std::max<int64_t>(ss.qsa_alloc, 0), + ple = ss.ple_hist != nullptr] { + StageThreads::spread_current_thread(); // (a thread the host starts inherits its one CPU: aux_cpus.hpp) + for (size_t k = 0; k < want; ++k) { + ConvCheckpoint c; + c.gdn.resize(z.gdn); c.ple.resize(ple ? z.ple : 0); c.tails.resize(layers * z.tail); + c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); + ckpt_pool.give(std::move(c)); + } + }); + }; + pool_topup(); // the first request's checkpoints find the pool full auto park_source = [&](const ParkSource& src, size_t held) -> bool { // #2049: parking copies the outgoing conversation's running checkpoints and K/V into host memory, which // is a silent stretch of the "request" stage; when the OS has paged that memory out it takes minutes. @@ -9840,20 +9883,12 @@ int main(int argc, char** argv) { } checks.erase(checks.begin() + (std::ptrdiff_t) w, checks.end()); } - const size_t moved_gdn = moved.empty() ? 0 : moved.front().gdn.size(); const bool saved = strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err, std::move(reuse), &reused_bytes, storage.empty() ? nullptr : &storage, moved.empty() ? nullptr : &moved); for (ConvCheckpoint& c : storage) ckpt_pool.give(std::move(c)); if (!saved) return false; - // the next checkpoint save would fault in fresh pages for what moved out: one is allocated now - if (moved_gdn > 0 && ckpt_pool.on() && - (!pool_refill.valid() || pool_refill.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) - pool_refill = std::async(std::launch::async, [&ckpt_pool, moved_gdn] { - ConvCheckpoint c; - c.gdn.resize(moved_gdn); - ckpt_pool.give(std::move(c)); - }); + pool_topup(); // what the park took (and what moved out) is allocated again, in the background for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V) auto& st = stages[k]; const strata::core::OnDevice on(st->dev); @@ -9970,6 +10005,7 @@ int main(int argc, char** argv) { return true; } ConvCheckpoint c = parts == nullptr ? ckpt_pool.take() : ConvCheckpoint{}; // (STRATA_CKPT_POOL) + if (parts == nullptr) pool_topup(); // the next save finds one ready c.ids.assign(cur.begin(), cur.begin() + L); c.imgs = imgs_below(req_imgs, L); if (parts != nullptr) { From 85e3dde522cb9ff17a6a01f064910d03646e44fb Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:52:54 +0100 Subject: [PATCH 171/177] Conversation cache: opt-in STRATA_PARK_VRAM_MIB=N keeps parked conversations' K/V in VRAM in front of the host copy (#3779, #3712) Problem: restoring a parked conversation copies its K/V from the host over the link: 27-107 ms over a PCIe Gen2 x4 link. Change, opt-in and only with STRATA_PARK_ASYNC=1 (CUDA only): a park also keeps the whole K/V of its image in a VRAM slot of its own (64 MiB granules, up to N MiB in all, only while 1.5 GB of VRAM stays free beside it); the background copy to the host reads from the slot, and a restore of that image copies device to device from the slot (about 1 ms) without waiting for the background copy. Each K/V layer carries its own join-and-release token, so any order of destruction is safe (the layers outlive their image when they are retained for the next park). Under VRAM pressure the elastic K/V's growth releases every slot and the stage, then retries once (both growth sites in generate.cpp). With the variable unset the slot code is not reached: the budget is 0, a restore finds dev_tag 0 and takes the host path, and the growth sites see conversation_park_vram_release_all() return 0 and behave as before. Tests: none of its own (it needs a card with the VRAM for the slot and a parked conversation); see the checklist for the reporters' A/B/A conversation check with STRATA_PARK_VRAM_MIB set. Reporter's numbers (linxuhao, CMP 170HX): restore of a 3K conversation 28-47 -> 7-12 ms; outputs identical. The first restore of a run is slower (41.6 / 56.9 ms) than later ones (6.5-12.6 ms) and they have not found why. Theirs, not measured here. Original change by linxuhao (PR #3779, commit bafca410). --- include/strata/core/conversation_cache.hpp | 8 + include/strata/core/conversation_snapshot.hpp | 15 ++ src/core/conversation_snapshot.cpp | 221 +++++++++++++++++- src/core/conversation_state.cpp | 28 ++- src/program/generate.cpp | 15 +- 5 files changed, 275 insertions(+), 12 deletions(-) diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index c35aef88..34898345 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -62,6 +62,14 @@ struct ConversationKv { int format = 0; int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; ConversationBuffer k, v, k_scale, v_scale, pooled; + // STRATA_PARK_VRAM_MIB: the tag this layer's parts were recorded under in the park's VRAM slot (0: none). Set by + // conversation_kv_save; a restore that finds the slot copies from it instead of from the buffers above. + uint64_t dev_tag = 0; + // STRATA_PARK_VRAM_MIB: set while a background copy fills the buffers above from the slot; its deleter waits for + // that copy and releases the slot. This layer's own token (not shared): the layers outlive their image when they + // are retained for the next park (ConversationCache::retain), and go in any order. Last member: it goes before + // any buffer. + std::shared_ptr<void> pending; size_t bytes() const { return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes(); } diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index be4412e1..28071715 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -90,6 +90,21 @@ bool conversation_park_async_begin(size_t need); bool conversation_park_async_launch(std::string& error); /// Abandons a begun park that was not launched (the error paths): nothing was queued to the background. void conversation_park_async_abandon(); +/// STRATA_PARK_VRAM_MIB=N (with STRATA_PARK_ASYNC): a park also keeps the whole K/V of its image in VRAM, in a slot +/// of its own taken at begin while the slots' total stays within N MiB (and 1.5 GB of VRAM stays free), so a restore +/// of that image copies device to device from the slot (conversation_kv_restore / _prefix) instead of host to +/// device, and does not wait for the background copy. The slot lives as long as the image and its K/V layers +/// (SavedConversation::pending, ConversationKv::pending). Default 0: off. +/// The tag of the begun park's slot (0: none); kept until the next begin, for the tokens. +uint64_t conversation_park_slot_tag(); +/// Frees the slot under `tag` (no-op for 0 or a slot already gone); the caller joined the copy that reads it. +void conversation_park_slot_release(uint64_t tag); +/// VRAM pressure: joins the background copy, then frees every slot and the stage. Returns the bytes freed (0, and +/// nothing is touched, while STRATA_PARK_VRAM_MIB is unset). +size_t conversation_park_vram_release_all(); +/// conversation_park_join, unless every K/V layer of `image` has its slot (the restore then reads no host buffer +/// the background copy could still be filling; a layer that falls back to the host joins for itself). +void conversation_park_join_for(const SavedConversation& image); bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, const ModelGeometry& g, std::string& error); // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 77d5703a..0e4c440b 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -115,6 +115,103 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error return true; } +// STRATA_PARK_VRAM_MIB=N (with STRATA_PARK_ASYNC): a park also keeps the whole K/V of its image in VRAM, in a slot +// of its own, while the slots' total stays within N MiB; a restore of that image copies from the slot device to +// device (~1 ms) instead of from the host buffers over PCIe, and needs no wait for the background copy. A slot is +// released with the image or its K/V layers (their tokens), or all at once under VRAM pressure +// (conversation_park_vram_release_all). Host thread only; the background copy only reads a slot's bytes, and every +// reuse or free of one comes after a join (conversation_park_async_begin, release_all). +struct VramKvSlot { + void* p = nullptr; + size_t cap = 0, used = 0; + uint64_t tag = 0; // 0: free (kept for reuse by size) + int dev = -1; + struct Part { uint64_t tag; size_t part, offset, bytes; }; // one layer's part (k, v, k_scale, v_scale, pooled) + std::vector<Part> parts; +}; +struct VramKv { + std::vector<std::unique_ptr<VramKvSlot>> slots; + uint64_t next_tag = 1; // slot and layer tags, never reused +}; +VramKv& vram_kv() { static VramKv v; return v; } +size_t park_vram_budget() { + static const size_t b = [] { + const char* v = std::getenv("STRATA_PARK_VRAM_MIB"); + const long long mib = v != nullptr ? std::atoll(v) : 0; + return mib > 0 ? (size_t) mib << 20 : (size_t) 0; + }(); + return b; +} +bool park_trace() { static const bool on = std::getenv("STRATA_PARK_TRACE") != nullptr; return on; } +void vram_kv_free(VramKvSlot& s) { + int cur = s.dev; + (void) cudaGetDevice(&cur); + if (cur != s.dev) (void) cudaSetDevice(s.dev); + (void) cudaFree(s.p); + if (cur != s.dev) (void) cudaSetDevice(cur); + (void) cudaGetLastError(); + s.p = nullptr; s.cap = 0; +} +void vram_kv_release(VramKvSlot& s) { s.tag = 0; s.used = 0; s.parts.clear(); } // free, kept for reuse +// A slot of `need` bytes on `dev`: the best-fitting free one, else (the free ones freed first) a new one, rounded up +// to 64 MiB so a growing conversation's next parks reuse it, while the slots' total stays within the budget and +// 1.5 GB of VRAM stays free beside it. nullptr, with `why`, otherwise. +VramKvSlot* vram_kv_take(size_t need, int dev, const char*& why) { + VramKv& v = vram_kv(); + const size_t budget = park_vram_budget(); + if (budget == 0) { why = "off"; return nullptr; } + VramKvSlot* best = nullptr; + for (auto& s : v.slots) + if (s->tag == 0 && s->dev == dev && s->cap >= need && (best == nullptr || s->cap < best->cap)) best = s.get(); + if (best == nullptr) { + size_t held = 0; + for (size_t i = 0; i < v.slots.size();) { + if (v.slots[i]->tag != 0) { held += v.slots[i]->cap; ++i; continue; } + vram_kv_free(*v.slots[i]); + v.slots.erase(v.slots.begin() + (std::ptrdiff_t) i); + } + const size_t want = (need + ((size_t) 64 << 20) - 1) & ~(((size_t) 64 << 20) - 1); + if (held > budget || want > budget - held) { why = "budget"; return nullptr; } + size_t fr = 0, tot = 0; + if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < want + ((size_t) 3 << 29)) { + (void) cudaGetLastError(); + why = "vram"; + return nullptr; + } + void* p = nullptr; + if (cudaMalloc(&p, want) != cudaSuccess) { (void) cudaGetLastError(); why = "cudaMalloc"; return nullptr; } + auto s = std::make_unique<VramKvSlot>(); + s->p = p; s->cap = want; s->dev = dev; + best = s.get(); + v.slots.push_back(std::move(s)); + } + best->tag = v.next_tag++; + best->used = 0; + best->parts.clear(); + return best; +} +// The live slot on the current device holding parts under `tag` (nullptr: none, or tag 0) +const VramKvSlot* vram_kv_find(uint64_t tag) { + if (tag == 0) return nullptr; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { (void) cudaGetLastError(); return nullptr; } + for (const auto& s : vram_kv().slots) { + if (s->tag == 0 || s->dev != dev) continue; + for (const auto& p : s->parts) + if (p.tag == tag) return s.get(); + } + return nullptr; +} +// Whether the slot holds, under `tag`, at least sizes[i] bytes of every part i that has any; `at` gets the offsets +bool vram_kv_locate(const VramKvSlot& s, uint64_t tag, const std::array<size_t,5>& sizes, std::array<size_t,5>& at) { + std::array<bool,5> have{}; + for (const auto& p : s.parts) + if (p.tag == tag && p.part < at.size() && p.bytes >= sizes[p.part]) { have[p.part] = true; at[p.part] = p.offset; } + for (size_t i = 0; i < sizes.size(); ++i) + if (sizes[i] > 0 && !have[i]) return false; + return true; +} + struct ParkAsync { std::mutex mu; std::future<cudaError_t> pending; @@ -126,6 +223,8 @@ struct ParkAsync { cudaStream_t stream = nullptr; int dev = -1; bool active = false; + VramKvSlot* slot = nullptr; // STRATA_PARK_VRAM_MIB: the begun park's slot (the stage is not used then) + uint64_t slot_tag = 0; // its tag, kept past launch for the image's and its layers' tokens }; ParkAsync& park_async() { static ParkAsync a; return a; } constexpr size_t kParkPiece = (size_t) 4 << 20; @@ -211,12 +310,44 @@ bool conversation_kv_save(ConversationKv& image, const QsaState& st, const Model const auto src = pools(st); const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; const std::array<ConversationBuffer*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + // STRATA_PARK_VRAM_MIB: this layer's parts go into the park's slot under a fresh tag (0: no slot this park) + image.dev_tag = park_async().slot != nullptr ? vram_kv().next_tag++ : 0; for (size_t i = 0; i < dst.size(); ++i) { // Recopy the partial page and the indexer's moving spare row. Completed // pages/rows strictly before the first rewritten token remain identical. const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0) : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0; if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } + { // STRATA_PARK_VRAM_MIB: with a slot, the whole part goes device to device into it (a restore of this image + // reads it from there) and the host buffer gets only the bytes past the kept prefix, read from the slot on + // the background thread; a part the slot cannot take is copied synchronously - never through the stage, + // whose offsets launch would read from the slot + ParkAsync& a = park_async(); + if (a.slot != nullptr) { + VramKvSlot& s = *a.slot; + const bool fits = src[i] != nullptr && sizes[i] > 0 && s.used + sizes[i] <= s.cap && + (st.kv_mode == 0 || on_device(src[i])); // (kv_mode 0: the pools are device memory) + if (fits) { + const size_t at0 = s.used; + const cudaError_t e = conversation_detail::copy_nonblocking(static_cast<uint8_t*>(s.p) + at0, src[i], sizes[i], true); + if (e != cudaSuccess) { error = std::string("conversation snapshot slot copy: ") + cudaGetErrorString(e); return false; } + s.parts.push_back({image.dev_tag, i, at0, sizes[i]}); + s.used += sizes[i]; + dst[i]->resize_for_overwrite(sizes[i]); + if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { + a.items.push_back({p, n, at0 + at}); + return true; + })) return false; + } else { + dst[i]->resize(sizes[i]); + if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { + return transfer(p, src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr, n, error); + })) return false; + } + if (reused_bytes) *reused_bytes += keep; + continue; + } + } // STRATA_PARK_ASYNC: device bytes go to the VRAM stage now and into the buffer on the background thread ParkAsync& a = park_async(); const bool trace = park_trace_on(); @@ -323,10 +454,20 @@ bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelG bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, std::string& error) { - conversation_park_join(); + // STRATA_PARK_VRAM_MIB: from the image's VRAM slot when it holds every part (no host buffer is read: no join) + const VramKvSlot* slot = vram_kv_find(image.dev_tag); + if (slot == nullptr) conversation_park_join(); if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; const auto dst = pools(st); + std::array<size_t,5> sizes{}, off{}; + for (size_t i = 0; i < src.size(); ++i) sizes[i] = src[i]->size(); + if (slot != nullptr && !vram_kv_locate(*slot, image.dev_tag, sizes, off)) { slot = nullptr; conversation_park_join(); } + if (slot != nullptr) { + for (size_t i = 0; i < src.size(); ++i) + if (!transfer(dst[i], static_cast<const uint8_t*>(slot->p) + off[i], sizes[i], error)) return false; + return refresh_residency(st, g, upto, error); + } for (size_t i = 0; i < src.size(); ++i) if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error); @@ -336,7 +477,8 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t captured, int64_t upto, bool index, std::string& error) { - conversation_park_join(); + const VramKvSlot* slot = vram_kv_find(image.dev_tag); // (STRATA_PARK_VRAM_MIB, as in conversation_kv_restore) + if (slot == nullptr) conversation_park_join(); if (upto < 0 || upto > captured) { error = "conversation snapshot: prefix beyond the captured K/V"; return false; @@ -349,6 +491,14 @@ bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& for (size_t i = 0; i < src.size(); ++i) if (sizes[i] > src[i]->size()) { error = "conversation snapshot: prefix beyond the K/V payload"; return false; } const auto dst = pools(st); + // STRATA_PARK_VRAM_MIB: the prefix is the leading bytes of each part in the slot too + std::array<size_t,5> off{}; + if (slot != nullptr && !vram_kv_locate(*slot, image.dev_tag, sizes, off)) { slot = nullptr; conversation_park_join(); } + if (slot != nullptr) { + for (size_t i = 0; i < src.size(); ++i) + if (!transfer(dst[i], static_cast<const uint8_t*>(slot->p) + off[i], sizes[i], error)) return false; + return refresh_residency(st, g, upto, error); + } for (size_t i = 0; i < src.size(); ++i) if (!src[i]->visit(0, sizes[i], [&](const uint8_t* p, size_t n, size_t at) { return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error); @@ -449,10 +599,23 @@ bool conversation_park_async_begin(size_t need) { a.active = false; a.items.clear(); a.used = 0; + a.slot = nullptr; + a.slot_tag = 0; if (!park_async_on() || need == 0) return false; int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess) { (void) cudaGetLastError(); return false; } - if (a.stage != nullptr && (a.cap < need || a.dev != dev)) { + // STRATA_PARK_VRAM_MIB: a slot of the whole K/V instead of the stage, while the budget allows - taken before the + // stage would be re-allocated, so a growing conversation's park pays no cudaFree (a device sync) when it gets one + const char* why = ""; + a.slot = vram_kv_take(need, dev, why); + a.slot_tag = a.slot != nullptr ? a.slot->tag : 0; + if (park_trace() && park_vram_budget() != 0) { + if (a.slot != nullptr) + std::fprintf(stderr, "strata parktrace: kv slot %zu MB tag %llu\n", need >> 20, (unsigned long long) a.slot_tag); + else + std::fprintf(stderr, "strata parktrace: kv slot: none (%s)\n", why); + } + if (a.stage != nullptr && ((a.slot == nullptr && a.cap < need) || a.dev != dev)) { const int cur = dev; (void) cudaSetDevice(a.dev); (void) cudaFree(a.stage); (void) cudaSetDevice(cur); a.stage = nullptr; a.cap = 0; @@ -472,8 +635,13 @@ bool conversation_park_async_begin(size_t need) { if (a.stream) (void) cudaStreamDestroy(a.stream); a.stream = nullptr; a.host[0] = a.host[1] = nullptr; (void) cudaGetLastError(); + if (a.slot != nullptr) { vram_kv_release(*a.slot); a.slot = nullptr; a.slot_tag = 0; } // (STRATA_PARK_VRAM_MIB) return false; } + if (a.slot != nullptr) { // STRATA_PARK_VRAM_MIB: the slot stands in for the stage this park + a.active = true; + return true; + } if (a.stage == nullptr) { // rounded up to 64 MiB: the next parks of a growing conversation reuse it instead of re-allocating (a cudaFree // synchronizes the device, and the checkpoint DMA is in flight at this point) @@ -499,6 +667,7 @@ void conversation_park_async_abandon() { cudaStream_t s = nullptr; if (conversation_detail::private_stream(s) == cudaSuccess) (void) cudaStreamSynchronize(s); // nothing reads the stage after (void) cudaGetLastError(); + if (a.slot != nullptr) { vram_kv_release(*a.slot); a.slot = nullptr; a.slot_tag = 0; } // (STRATA_PARK_VRAM_MIB) } bool conversation_park_async_launch(std::string& error) { @@ -510,13 +679,16 @@ bool conversation_park_async_launch(std::string& error) { if (e == cudaSuccess) e = cudaStreamSynchronize(s); // the device-to-device copies into the stage if (e != cudaSuccess) { a.items.clear(); + if (a.slot != nullptr) { vram_kv_release(*a.slot); a.slot = nullptr; a.slot_tag = 0; } // (STRATA_PARK_VRAM_MIB) error = std::string("conversation snapshot stage: ") + cudaGetErrorString(e); return false; } + // STRATA_PARK_VRAM_MIB: the host copies read the slot; it stays until the image and its K/V layers go (their tokens) + const uint8_t* stage = a.slot != nullptr ? static_cast<const uint8_t*>(a.slot->p) : a.stage; + a.slot = nullptr; if (a.items.empty()) return true; std::vector<ParkAsync::Item> items; items.swap(a.items); - const uint8_t* stage = a.stage; void* host[2] = {a.host[0], a.host[1]}; cudaStream_t st = a.stream; const int dev = a.dev; @@ -554,4 +726,45 @@ bool conversation_park_async_launch(std::string& error) { return true; } +uint64_t conversation_park_slot_tag() { return park_async().slot_tag; } + +void conversation_park_slot_release(uint64_t tag) { + if (tag == 0) return; + for (auto& s : vram_kv().slots) + if (s->tag == tag) { vram_kv_release(*s); return; } +} + +size_t conversation_park_vram_release_all() { + if (park_vram_budget() == 0) return 0; // off: nothing was taken, and the stage stays as it was + conversation_park_join(); // the background copy may be reading a slot or the stage + ParkAsync& a = park_async(); + VramKv& v = vram_kv(); + size_t freed = 0; + for (size_t i = 0; i < v.slots.size();) { + if (a.active && v.slots[i].get() == a.slot) { ++i; continue; } // a park in progress keeps its own + freed += v.slots[i]->cap; + vram_kv_free(*v.slots[i]); + v.slots.erase(v.slots.begin() + (std::ptrdiff_t) i); + } + if (a.stage != nullptr && !a.active) { + int cur = a.dev; + (void) cudaGetDevice(&cur); + if (cur != a.dev) (void) cudaSetDevice(a.dev); + (void) cudaFree(a.stage); + if (cur != a.dev) (void) cudaSetDevice(cur); + (void) cudaGetLastError(); + freed += a.cap; + a.stage = nullptr; a.cap = 0; + } + return freed; +} + +void conversation_park_join_for(const SavedConversation& image) { + size_t hits = 0; + for (const auto& k : image.kv) hits += vram_kv_find(k.dev_tag) != nullptr ? 1 : 0; + if (park_trace() && park_vram_budget() != 0) + std::fprintf(stderr, "strata parktrace: kv restore: %zu of %zu layers from the slot\n", hits, image.kv.size()); + if (hits < image.kv.size()) conversation_park_join(); +} + } // namespace strata::core diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 594a2d8a..4bfd47d6 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -552,6 +552,9 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView captured.kv = std::move(reuse.kv); const size_t layers = owned_qsa(ss); captured.kv.resize(layers + (draft ? 1 : 0)); + // STRATA_PARK_VRAM_MIB: the retained layers' tokens go now (joined above, so no wait): held past the launch below, + // their replacement would join the copy just launched + for (auto& k : captured.kv) k.pending.reset(); bool live_staged = false; const bool live_saved = checkpoint_save(captured.live, ss, g, error, live_staged); // STRATA_CKPT_ASYNC: the running state lands in live.gdn after the save returns; the image waits for that copy @@ -596,7 +599,22 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false; abandon.on = false; if (staged && !conversation_park_async_launch(error)) return false; - if (staged) captured.pending = std::shared_ptr<void>(new char, [](void* p) { conversation_park_join(); delete (char*) p; }); + if (staged) { + // STRATA_PARK_VRAM_MIB: the image's slot goes with the image, after the copy that reads it; each K/V layer + // carries a token of its own too (the layers outlive the image when they are retained for the next park, and + // the copy fills their buffers). Without a slot: the image's join as before, no layer tokens. + const uint64_t slot = conversation_park_slot_tag(); + auto token = [slot] { + return std::shared_ptr<void>(new char, [slot](void* p) { + conversation_park_join(); + conversation_park_slot_release(slot); + delete (char*) p; + }); + }; + captured.pending = token(); + if (slot != 0) + for (auto& k : captured.kv) k.pending = token(); + } image = std::move(captured); return true; } @@ -677,7 +695,7 @@ ConversationRestore conversation_snapshot_restore(const SavedConversation& image const ModelGeometry& g, const QsaState* draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); - conversation_park_join(); + conversation_park_join_for(image); // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid; if (!sync(error)) return ConversationRestore::transfer_failed; const int64_t upto = (int64_t) image.live.ids.size(); @@ -714,7 +732,7 @@ ConversationRestore conversation_snapshot_restore(const SavedConversation& image const ModelGeometry& g, const QsaState& draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); - conversation_park_join(); + conversation_park_join_for(image); // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) return conversation_snapshot_restore(image, ss, g, &draft, error); } ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto, @@ -722,7 +740,7 @@ ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation const QsaState& draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); - conversation_park_join(); + conversation_park_join_for(image); // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) return conversation_snapshot_restore_prefix(image, upto, ss, g, &draft, error); } ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto, @@ -730,7 +748,7 @@ ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation const QsaState* draft, std::string& error) { conversation_checkpoint_join(image.live.gdn.data()); for (const auto& c : image.checkpoints) conversation_checkpoint_join(c.gdn.data()); - conversation_park_join(); + conversation_park_join_for(image); // (STRATA_PARK_VRAM_MIB: no wait when the K/V comes from its slot) // a layer split's image (stage images) is restored stage by stage, never in part if (!image.stage_images.empty()) { fail(error, "a layer split's image restored as a single session"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 4833ed74..318c507c 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8146,12 +8146,18 @@ int main(int argc, char** argv) { return false; } int64_t fresh = 0; - const bool ok = strata::core::qsa_kv_elastic_grow(target, [&]() -> strata::core::VmmChunk { + auto grow_take = [&]() -> strata::core::VmmChunk { if (kvg.spare.empty()) { ++fresh; return 0; } // the cache is at its floor: new memory const strata::core::VmmChunk h = kvg.spare.back(); kvg.spare.pop_back(); return h; - }); + }; + bool ok = strata::core::qsa_kv_elastic_grow(target, grow_take); + // STRATA_PARK_VRAM_MIB: the parked conversations' VRAM copies of their K/V give way to the K/V itself + if (!ok && strata::core::conversation_park_vram_release_all() > 0) { + (void) cudaGetLastError(); + ok = strata::core::qsa_kv_elastic_grow(target, grow_take); + } kvg.fresh += fresh; kvg.cells = strata::core::qsa_kv_elastic_cells(); ++kvg.grows; @@ -13328,7 +13334,10 @@ int main(int argc, char** argv) { } } // the elastic K/V: a parked conversation is restored whole, and it may be longer than this prompt - if (incoming && !kvg_ensure((int64_t) incoming->live.ids.size() + 256, kv_quiesce)) { + // (STRATA_PARK_VRAM_MIB: the parked K/V copies in VRAM go first, then one more try) + if (incoming && !kvg_ensure((int64_t) incoming->live.ids.size() + 256, kv_quiesce) && + (strata::core::conversation_park_vram_release_all() == 0 || + !kvg_ensure((int64_t) incoming->live.ids.size() + 256, kv_quiesce))) { std::printf("ERR the K/V cannot grow to the parked conversation: no VRAM is left\n"); return 1; } From 0e63d59c01179917fc4296229acdd5719f7f8489 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:53:53 +0100 Subject: [PATCH 172/177] docs: conversation cache copies on a slow host link, STRATA_CKPT_ASYNC and the park switches (#3779, #3712) One section in DETAILS.md for the switches the four conversation-cache commits add: what each copies where, its VRAM and host memory cost, that they stay off on HIP, gfx906 and Metal, and the measured times. Rewritten from the PR's section: the times are labelled as the reporter's (linxuhao, one CMP 170HX on PCIe Gen2 x4; we have no sm_80 card and measured none of them), the independent RTX 3090 data of bitaccesscomau is added, and the pool row describes STRATA_CKPT_POOL_READY=N instead of the PR's change to the meaning of STRATA_CKPT_POOL=N (STRATA_CKPT_POOL=1 is unchanged). Original section by linxuhao (PR #3779, commit a04f4399). --- docs/DETAILS.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 2d0f6310..1ce07f55 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1400,3 +1400,23 @@ mean KL from the stock model 0.063 nats (max 4.1), perplexity +15% on code, +2.3 the original 2,682 in 46 s. Speed: 4K IQ2_XS 465 prompt / 78.7 output tokens/s against 467 / 78.3 for the original. - UD-Q4_K_XL on a 64 GB PC with a 12 GB RTX 5070: 7-8.5 tok/s, picks the same tokens as llama.cpp on the same file at 97.5-99% of the positions of short greedy answers and 90-91% after a 16K prompt ([UNSLOTH_Q4.md](UNSLOTH_Q4.md#quality-against-llamacpp-on-the-same-file)). + +## Conversation cache copies on a slow host link (CUDA, opt-in) + +Where the card sits behind a slow host link, the conversation cache's copies are on the critical path of the next request. A turn checkpoint copies the DeltaNet state (118 MB on Qwen3.8-Flash-Next) from the card to the host. Parking a conversation copies its K/V and its checkpoints before the next prompt can start. These switches move the copies card-to-card in VRAM or onto background threads. All are off unless you set them. On HIP, gfx906 and Metal `STRATA_CKPT_ASYNC`, `STRATA_CKPT_GATHER` and `STRATA_PARK_ASYNC` stay off, and so do the two slot switches that need them. The answers and the parked images are the same bytes. + +The times below were measured by the author of the change (linxuhao, PR #3779) on one CMP 170HX (GA100, sm_80) on a PCIe Gen2 x4 link. We have no sm_80 card and did not measure them. Some of their park figures were taken with other opt-in switches set. + +| Switch | What | Reporter's figure (CMP 170HX) | +|---|---|---| +| `STRATA_CKPT_ASYNC=1` | A turn checkpoint's state is copied card-to-card into a VRAM stage and moved to the host by a background thread. A reader waits only for the copy it needs. The stage is one buffer the size of the state, allocated at the first save; if the allocation fails the save copies as before. | checkpoint 104-105 -> 34-35 ms (fresh vectors), 71.4 -> 0.9 ms (reused vectors) | +| `STRATA_CKPT_VRAM_SLOTS=N` (0-16, with `STRATA_CKPT_ASYNC=1`) | The last N saved states also stay in VRAM (N x 118 MB, only while 1.5 GB stay free). A restore from one copies card-to-card. | restore 114-126 -> 28-47 ms | +| `STRATA_PARK_ASYNC=1` | A park copies the K/V card-to-card into a VRAM stage (only while 1.5 GB stay free) and moves it to the host in the background. The checkpoints the request drops move into the parked image instead of being copied. | park of a 3.3K / 13K-token conversation 212-217 / 329-334 -> 64-75 / 68 ms | +| `STRATA_CKPT_POOL_READY=N` (1-16, with `STRATA_CKPT_POOL=1`) | The checkpoint pool keeps N ready checkpoints, sized at start and topped up in the background, so a save never faults in a fresh vector. It holds N x 118 MB of host memory from start-up. `STRATA_CKPT_POOL=1` alone is unchanged: it reuses dropped checkpoints and allocates nothing ahead of time. | with `STRATA_PARK_ASYNC=1` and `STRATA_CKPT_GATHER=1`: park 21.5-40.1 / 26.9 ms | +| `STRATA_CKPT_GATHER=1` | A checkpoint's 37 small card-to-host copies are gathered into one buffer and fetched with one copy. Not tested with a layer split across cards. | (in the row above) | +| `STRATA_PARK_VRAM_MIB=N` (with `STRATA_PARK_ASYNC=1`) | A park also keeps the K/V in VRAM slots (64 MiB granules, up to N MiB, only while 1.5 GB stay free). Switching back restores it card-to-card. | second and later restores of a run 33-51 -> 7-13 ms; the first is not faster | +| `STRATA_PARK_TRACE=1` | Diagnostic: the park's joins and timers on stderr. | - | + +An independent user (bitaccesscomau, one RTX 3090 on PCIe 3.0 x16) tried the `STRATA_CKPT_ASYNC=1` commit on its own on 0.2.6: the checkpoint save went from 73.2 to 62.4 ms, the first token of a short prompt came about 13 ms of 350 ms sooner (median of 4 pairs), and the answers were byte-identical. On a fast link the gain is small. + +The serve loop's `strata trace:` lines (`STRATA_TRACE`) now end with `@<ms>`, a steady-clock timestamp. From 0049fa73fff7c490b48faf8b6059e08239871a74 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:55:06 +0100 Subject: [PATCH 173/177] Decode window: opt-in STRATA_GRAPH_PRIO=1 gives the window graph's kernel nodes their stream's priority (#3779, #3712) Problem: the decode window graph runs every kernel node at the launch stream's priority, so the one-block indexer kernels of the side branch wait behind the queued blocks of the big q GEMV, and the shared expert competes with the routed experts. Change, opt-in (bitwise by construction: no kernel changes, the same launches on the same inputs; only the dispatch order moves): with STRATA_GRAPH_PRIO=1 the side mixer's branch stream (GDN gates, QSA indexer chain) is created at the device's highest priority, cs_ and side2_ in the middle, the shared expert's stream at the lowest, and the window graph is instantiated with cudaGraphInstantiateFlagUseNodePriority. If a driver did not copy the stream priority into the nodes, the capture-time notes (the branch forks and the priority streams' tails) set the attribute per node. One log line per captured window prints the node priority histogram. A card whose priority range is 0..0 changes nothing. CUDA only: the members and the three methods sit under !STRATA_USE_HIP && !STRATA_HIP_GFX906 && !STRATA_GPU_METAL; graph_prio_on() is false there. Merged by hand with #3702 (the window-graph eviction): instantiate_evicting now takes both keep_t and the flags, and the retry after freeing other window sizes keeps the flags (the merged code would otherwise have dropped the node priorities on that retry). With the variable unset: every stream is created as before and the capture-time notes return at once. Tests: none of its own (a priority is a scheduling hint with no value to compare). The window graphs are exercised by the engine; see the checklist for the reporter's greedy-answer identity check. Reporter's numbers (linxuhao, CMP 170HX, IQ3_S, --spec 3, 3K context, interleaved in one session, each arm with STRATA_QIL=1): reference 125.3 / 126.6, GRAPH_PRIO 127.8 / 129.0, reference 125.0 / 126.8 tok/s, +1.8 %. Greedy 11 of 11 identical. In the later per-feature pair together with STRATA_MMVQ_IL_PF: decode +1.3 %. Theirs, not measured here. Original change by linxuhao (PR #3779, commit 68c487c3). --- include/strata/core/verify.hpp | 12 ++- src/core/verify.cpp | 191 +++++++++++++++++++++++++++++++-- 2 files changed, 191 insertions(+), 12 deletions(-) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 2b2d9a0e..60707b97 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -426,10 +426,20 @@ private: /// whose graph does not fit used to end the engine ("verify: instantiate: out of memory"); a freed size is captured /// again when it is next used. bool instantiate_evicting(cudaGraphExec_t& ex, cudaGraph_t graph, const std::vector<int>& key, const char* what, - std::string& err, int keep_t = -1); + std::string& err, int keep_t = -1, unsigned long long flags = 0); /// Free the graph of the largest window size other than `keep_t` (and the prelaunched one); `evicted`: there was one. bool evict_window_graph(int keep_t, bool& evicted, std::string& err); bool no_window_eviction_ = false; ///< capture_all wants every size at once: it must not free one to capture another + // STRATA_GRAPH_PRIO (record_window / capture): the captured tails of the priority streams at their joins and the + // main stream's tails at their forks, so that a capture that dropped the stream priorities can be repaired per + // node (apply_node_priorities walks each tail back to its fork) +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // (the three methods are no-ops there) + std::vector<cudaGraphNode_t> prio_forks_; + std::vector<std::pair<cudaGraphNode_t, int>> prio_tails_; +#endif + void note_prio_fork(cudaStream_t from); + void note_prio_tail(cudaStream_t on, int prio); + void apply_node_priorities(cudaGraph_t graph, int T); void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_ void accumulate_profile(const unsigned long long* stamps); void accumulate_profile_inner(const unsigned long long* stamps); ///< one window's stamps (host copy) into prof_sum_ diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a87e995d..8a12c185 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -64,6 +64,7 @@ #include <algorithm> #include <atomic> #include <map> +#include <set> #include <mutex> #include <string> #include <optional> @@ -183,6 +184,38 @@ inline bool g_qfuse_hc() { return false; #endif } +// STRATA_GRAPH_PRIO=1 (opt-in): the window graph's kernel nodes keep their capturing stream's +// priority (side_ high, sh_cs_ low). Unset / 0: every node at the launch stream's priority, as before. +[[maybe_unused]] inline bool graph_prio_on() { // (every HIP caller is guarded off) +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) + return false; +#else + static const bool on = [] { const char* v = std::getenv("STRATA_GRAPH_PRIO"); return v != nullptr && std::atoi(v) != 0; }(); + return on; +#endif +} +// STRATA_GRAPH_PRIO: the capture and graph queries by CUDA version (13 renamed the edge-data forms: the same split as +// verify_kernels.cu's and the PDL edge check above). Nothing is returned for the edge data. +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) +inline cudaError_t prio_capture_deps(cudaStream_t s, cudaStreamCaptureStatus* st, const cudaGraphNode_t** deps, size_t* n) { +#if CUDART_VERSION >= 13000 + return cudaStreamGetCaptureInfo(s, st, nullptr, nullptr, deps, nullptr, n); +#elif CUDART_VERSION >= 12030 + return cudaStreamGetCaptureInfo_v3(s, st, nullptr, nullptr, deps, nullptr, n); +#else + return cudaStreamGetCaptureInfo_v2(s, st, nullptr, nullptr, deps, n); +#endif +} +inline cudaError_t prio_node_deps(cudaGraphNode_t node, cudaGraphNode_t* deps, size_t* n) { +#if CUDART_VERSION >= 13000 + return cudaGraphNodeGetDependencies(node, deps, nullptr, n); +#elif CUDART_VERSION >= 12030 + return cudaGraphNodeGetDependencies_v2(node, deps, nullptr, n); +#else + return cudaGraphNodeGetDependencies(node, deps, n); +#endif +} +#endif // fork 34a35db + b063c13 (Eddoursul), STRATA_SIDE_MIXER=1 / =2: the mixer's work that reads only the layer's input on // branches of the window's graph (bitwise the same outputs); 0 = in line, and no branch stream is created. Unset: 2 on a // compute capability 12.0 card (sm120_series.hpp; STRATA_SM120_PERF=0 turns it off), 0 elsewhere. @@ -966,9 +999,24 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& sink_.staging = (unsigned long long) staging_; sink_.staging_cap = kStagingBlobs; (void) TS; + // STRATA_GRAPH_PRIO=1 (opt-in): the window's streams carry priorities that their captured kernel + // nodes keep (the window graph is instantiated with cudaGraphInstantiateFlagUseNodePriority): the GDN gates / QSA + // indexer branch (side_) at the device's highest, cs_ and side2_ in the middle, the shared expert (sh_cs_) at the + // lowest (= the default). The indexer chain's 1-block kernels are then dispatched ahead of the q GEMV's queued + // blocks, and the shared expert behind the experts. Unset: every stream at the default priority, as before. + int gp_lo = 0, gp_hi = 0; +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + const bool gprio = graph_prio_on() && cudaDeviceGetStreamPriorityRange(&gp_lo, &gp_hi) == cudaSuccess && gp_lo != gp_hi; + if (graph_prio_on() && !gprio) (void) cudaGetLastError(); // (only a failed range query's error: unset clears nothing) +#else + const bool gprio = false; // (HIP: the default priority, as make_stream's below) +#endif + const int gp_mid = gprio ? (gp_lo + gp_hi) / 2 : 0; + if (gprio) std::fprintf(stderr, "strata verify: STRATA_GRAPH_PRIO: stream priorities side %d, cs / side2 %d, shared expert %d\n", + gp_hi, gp_mid, gp_lo); // STRATA_PIPED_CONCURRENT=1 (opt-in): a prompt can run on the same GPU while the batch windows run, so the windows' // streams get the device's highest priority (HIP: the default priority, as the drafter's) - auto make_stream = [](cudaStream_t* s) -> cudaError_t { + auto make_stream = [&](cudaStream_t* s, int gp = 0) -> cudaError_t { #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) static const bool hi = [] { // (STRATA_PIPED_CONCURRENT_PRIO=0: the default priority) const char* v = std::getenv("STRATA_PIPED_CONCURRENT"); @@ -982,6 +1030,12 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& return cudaSuccess; cudaGetLastError(); // (only the failed priority call's error: the default path clears nothing) } + if (gprio) { // STRATA_GRAPH_PRIO: this stream's own priority (gp) + if (cudaStreamCreateWithPriority(s, cudaStreamNonBlocking, gp) == cudaSuccess) return cudaSuccess; + cudaGetLastError(); + } +#else + (void) gp; #endif return cudaStreamCreateWithFlags(s, cudaStreamNonBlocking); }; @@ -1003,8 +1057,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& return false; } if (ext_stream_ != nullptr) cs_ = ext_stream_; // set_stream (pipelined windows): the stage's shared stream - else if (make_stream(&cs_) != cudaSuccess) cs_ = nullptr; - if (cs_ == nullptr || make_stream(&sh_cs_) != cudaSuccess) { + else if (make_stream(&cs_, gp_mid) != cudaSuccess) cs_ = nullptr; + if (cs_ == nullptr || make_stream(&sh_cs_, gp_lo) != cudaSuccess) { err = "verify: stream create failed"; return false; } @@ -1050,10 +1104,10 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& } } if (g_side_mixer() > 0 && - (cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess || + ((gprio ? make_stream(&side_, gp_hi) : cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking)) != cudaSuccess || cudaEventCreateWithFlags(&mfork_, cudaEventDisableTiming) != cudaSuccess || cudaEventCreateWithFlags(&mjoin_, cudaEventDisableTiming) != cudaSuccess || - cudaStreamCreateWithFlags(&side2_, cudaStreamNonBlocking) != cudaSuccess || + (gprio ? make_stream(&side2_, gp_mid) : cudaStreamCreateWithFlags(&side2_, cudaStreamNonBlocking)) != cudaSuccess || cudaEventCreateWithFlags(&pfork_, cudaEventDisableTiming) != cudaSuccess || cudaEventCreateWithFlags(&pjoin_, cudaEventDisableTiming) != cudaSuccess)) { err = "verify: the mixer branch's stream / events could not be created"; @@ -1129,6 +1183,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const bool side_mixer = side_mixer_mode >= 1; const bool side_proj = side_mixer_mode >= 2 && !batch_rec_; // fork b063c13: the GDN gate projection, the QSA queries auto branch = [&](cudaEvent_t e, cudaStream_t from, cudaStream_t to, const char* what) { + if (to == side_) note_prio_fork(from); // STRATA_GRAPH_PRIO: where the high-priority branch leaves cs if (cudaEventRecord(e, from) == cudaSuccess && cudaStreamWaitEvent(to, e, 0) == cudaSuccess) return true; err = std::string("verify: the mixer branch could not ") + what; return false; @@ -1432,6 +1487,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data, (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV, n, side_); + note_prio_tail(side_, 1); if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the GDN gates' branch could not join"; return false; } } if (!q8_attn) quant_in(xm, (int) N); @@ -1715,6 +1771,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { idx_append(side_); idx_query(side_); idx_select(side_); + note_prio_tail(side_, 1); if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the indexer's branch could not join"; return false; } } if (side_proj) { // the queries beside the keys and values (fork b063c13) @@ -1931,6 +1988,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const bool sh_fork_late = sh_fork && sh_fork_late_env && !ar_on(); cudaStream_t sh_stream = sh_fork ? sh_cs_ : cs; if (sh_fork && !sh_fork_late) { + note_prio_fork(cs); cudaEventRecord(ev_fork_, cs); cudaStreamWaitEvent(sh_cs_, ev_fork_, 0); } @@ -2009,6 +2067,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs); } if (sh_fork_late) { + note_prio_fork(cs); cudaEventRecord(ev_fork_, cs); cudaStreamWaitEvent(sh_cs_, ev_fork_, 0); } @@ -2046,7 +2105,10 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { err = std::string("verify shared expert: ") + e.what(); return false; } - if (sh_fork) cudaEventRecord(ev_join_, sh_cs_); + if (sh_fork) { + note_prio_tail(sh_cs_, -1); + cudaEventRecord(ev_join_, sh_cs_); + } } if (strata::kernels::cpu::expert_layout().native) { // APR: Hadamard-folded gate/up take H (s * x); xm itself stays as it is (the shared expert above and the @@ -2466,6 +2528,10 @@ bool Verifier::capture(int T, std::string& err) { err = "verify: begin capture failed"; return false; } +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) + prio_forks_.clear(); + prio_tails_.clear(); +#endif std::string rerr; const bool ok = record_window(T, cs_, rerr); cudaGraph_t graph = nullptr; @@ -2576,7 +2642,14 @@ bool Verifier::capture(int T, std::string& err) { #endif } #endif - const bool made = instantiate_evicting(exec_t, graph, {}, "verify: instantiate: ", err, T); + unsigned long long iflags = 0; +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) + if (graph_prio_on()) { // STRATA_GRAPH_PRIO: the nodes run at their own (captured or repaired) priorities + apply_node_priorities(graph, T); + iflags = cudaGraphInstantiateFlagUseNodePriority; + } +#endif + const bool made = instantiate_evicting(exec_t, graph, {}, "verify: instantiate: ", err, T, iflags); cudaGraphDestroy(graph); if (!made) return false; const cudaError_t ue = cudaGraphUpload(exec_t, cs_); @@ -3733,19 +3806,115 @@ bool Verifier::evict_window_graph(int keep_t, bool& evicted, std::string& err) { return true; } +// STRATA_GRAPH_PRIO: the capture-time notes. A fork note keeps cs's current tail (the node the branch's first kernel +// will depend on); a tail note keeps a priority stream's current tail and the priority its nodes should run at +// (1 = the device's highest, -1 = its lowest). No-ops with the switch off, outside a capture, and on HIP / Metal. +void Verifier::note_prio_fork(cudaStream_t from) { +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) + if (!graph_prio_on()) return; + cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone; + const cudaGraphNode_t* deps = nullptr; + size_t nd = 0; + if (prio_capture_deps(from, &st, &deps, &nd) != cudaSuccess || st != cudaStreamCaptureStatusActive) { + (void) cudaGetLastError(); + return; + } + for (size_t i = 0; i < nd; ++i) prio_forks_.push_back(deps[i]); +#else + (void) from; +#endif +} + +void Verifier::note_prio_tail(cudaStream_t on, int prio) { +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) + if (!graph_prio_on()) return; + cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone; + const cudaGraphNode_t* deps = nullptr; + size_t nd = 0; + if (prio_capture_deps(on, &st, &deps, &nd) != cudaSuccess || st != cudaStreamCaptureStatusActive) { + (void) cudaGetLastError(); + return; + } + for (size_t i = 0; i < nd; ++i) prio_tails_.push_back({deps[i], prio}); +#else + (void) on; (void) prio; +#endif +} + +// STRATA_GRAPH_PRIO: what priorities the captured kernel nodes carry (a histogram, logged once per window graph). If the +// capture copied none from the streams (design 1's R1: some drivers read back 0 everywhere), each priority stream's +// nodes are found by walking its noted tails back to the noted forks and the attribute is set per node. +void Verifier::apply_node_priorities(cudaGraph_t graph, int T) { +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) + int lo = 0, hi = 0; + if (cudaDeviceGetStreamPriorityRange(&lo, &hi) != cudaSuccess) { (void) cudaGetLastError(); return; } + auto histogram = [&](std::map<int, int>& h) { + size_t nn = 0; + cudaGraphGetNodes(graph, nullptr, &nn); + std::vector<cudaGraphNode_t> nodes(nn); + cudaGraphGetNodes(graph, nodes.data(), &nn); + h.clear(); + for (cudaGraphNode_t nd : nodes) { + cudaGraphNodeType ty; + if (cudaGraphNodeGetType(nd, &ty) != cudaSuccess || ty != cudaGraphNodeTypeKernel) continue; + cudaKernelNodeAttrValue v{}; + if (cudaGraphKernelNodeGetAttribute(nd, cudaKernelNodeAttributePriority, &v) == cudaSuccess) ++h[v.priority]; + else { (void) cudaGetLastError(); ++h[999]; } + } + }; + std::map<int, int> h; + histogram(h); + bool captured = false; + for (auto& [p, c] : h) captured = captured || (p != 0 && p != 999 && c > 0); + int repaired = 0, walked_forks = (int) prio_forks_.size(), walked_tails = (int) prio_tails_.size(); + if (!captured && !prio_tails_.empty()) { // the fallback: per node from the capture-time notes + std::set<cudaGraphNode_t> stop(prio_forks_.begin(), prio_forks_.end()), seen; + for (auto& [tail, pr] : prio_tails_) { + std::vector<cudaGraphNode_t> stack{tail}; + while (!stack.empty()) { + cudaGraphNode_t nd = stack.back(); + stack.pop_back(); + if (stop.count(nd) || !seen.insert(nd).second) continue; + cudaGraphNodeType ty; + if (cudaGraphNodeGetType(nd, &ty) == cudaSuccess && ty == cudaGraphNodeTypeKernel) { + cudaKernelNodeAttrValue v{}; + v.priority = pr > 0 ? hi : lo; + if (cudaGraphKernelNodeSetAttribute(nd, cudaKernelNodeAttributePriority, &v) == cudaSuccess) ++repaired; + else (void) cudaGetLastError(); + } + size_t nd_n = 0; + prio_node_deps(nd, nullptr, &nd_n); + std::vector<cudaGraphNode_t> deps(nd_n); + if (nd_n > 0 && prio_node_deps(nd, deps.data(), &nd_n) == cudaSuccess) + for (size_t i = 0; i < nd_n; ++i) stack.push_back(deps[i]); + else (void) cudaGetLastError(); + } + } + histogram(h); + } + std::string s; + for (auto& [p, c] : h) s += " " + std::to_string(c) + " x prio " + (p == 999 ? std::string("?") : std::to_string(p)) + ";"; + std::fprintf(stderr, "strata verify: the %d-token window's kernel node priorities (range %d..%d):%s %s (%d forks, %d tails noted%s)\n", + T, lo, hi, s.c_str(), captured ? "captured from the streams" : "NOT captured from the streams", + walked_forks, walked_tails, repaired > 0 ? (", " + std::to_string(repaired) + " nodes set from the notes").c_str() : ""); +#else + (void) graph; (void) T; +#endif +} + bool Verifier::instantiate_evicting(cudaGraphExec_t& ex, cudaGraph_t graph, const std::vector<int>& key, - const char* what, std::string& err, int keep_t) { + const char* what, std::string& err, int keep_t, unsigned long long flags) { // #997: every layout of active slots keeps its own graph pair (20-30 MiB each on an L40S), and with an expert cache // sized to the reserve the next window graph - a batch layout or a one-request window captured on first use - can // find no VRAM left: free the least recently used layouts until it fits (they are captured again when needed) - cudaError_t ie = cudaGraphInstantiate(&ex, graph, 0); + cudaError_t ie = cudaGraphInstantiate(&ex, graph, flags); int freed = 0; for (bool evicted = true; ie == cudaErrorMemoryAllocation && evicted;) { (void) cudaGetLastError(); if (!evict_batch_graph(key, evicted, err)) return false; if (evicted) { ++freed; - ie = cudaGraphInstantiate(&ex, graph, 0); + ie = cudaGraphInstantiate(&ex, graph, flags); } } if (freed > 0) @@ -3758,7 +3927,7 @@ bool Verifier::instantiate_evicting(cudaGraphExec_t& ex, cudaGraph_t graph, cons if (!evict_window_graph(keep_t, evicted, err)) return false; if (evicted) { ++freed_sizes; - ie = cudaGraphInstantiate(&ex, graph, 0); + ie = cudaGraphInstantiate(&ex, graph, flags); } } if (freed_sizes > 0) From c2d3fe500075e77df858cbfe2aa8edd02f6d6e90 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:55:30 +0100 Subject: [PATCH 174/177] mmvq_il_parity: the L2-residency arms (--hot / --gap / --persist / --ab), the clock warm-up and MMVQ_IL_TMIN (#3779, #3712) Harness only; no engine code. The bench part of mmvq_il_parity times the interleaved matvec cold (24 copies of the weights rotated past the L2), hot (one copy), hot with other weights' reads in between (--gap MB, what a window's GEMVs do between a prefetch and its consumer), and with the timed weights in a persisting L2 set-aside (--persist); --ab runs the five arms per case in one process, because the clocks ramp over the first ~100 ms of a run. A 150 ms warm-up of launches runs before the first timed case, and MMVQ_IL_TMIN bounds T from below. The parity part is unchanged: without --bench the same checks run in the same order (every rows choice against native_mmvq, bitwise). The bench code is CUDA only (the test is built with STRATA_ENABLE_CUDA); the persisting-L2 calls are left out under STRATA_HIP_GFX906. Original change by linxuhao (PR #3779, commit 1f4b8139). --- src/kernels/mmvq_il_parity.cpp | 155 ++++++++++++++++++++++++++------- 1 file changed, 122 insertions(+), 33 deletions(-) diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 9e78015a..415baa4b 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -1,7 +1,15 @@ // src/kernels/mmvq_il_parity.cpp - native_mmvq_il (2-4 columns from the interleaved q8_1 copy, fork F4) against // native_mmvq's multi-column kernels, bitwise, for every rows-a-warp choice; --bench times both per call. // -// build/mmvq_il_parity [--bench [--emit-table]] +// build/mmvq_il_parity [--bench [--emit-table] [--hot] [--gap MB] [--persist] [--ab]] +// +// --hot times one copy of the weights (they sit in L2 after the first call: the ceiling of an L2 +// prefetch); --gap MB reads MB megabytes of OTHER weights (native_mmvq over other copies) before every timed call, as +// the window's GEMVs do between a prefetch and its consumer (a memset gap was tried first: its write-backs drain +// during the timed call and make every arm slower than cold); --persist puts the timed weights in a persisting L2 +// set-aside (cudaLimitPersistingL2CacheSize + an access-policy window on the stream) so the gap's reads stream past +// them. --ab runs the arms cold / hot / hot+gap / hot+gap+persist / cold per case in ONE process (the clocks ramp +// over the first ~100 ms of a run, so arms in separate runs are not comparable). MMVQ_IL_TMIN / MMVQ_IL_TMAX bound T. // // --emit-table (with --bench) prints the rows-a-warp table this card measured, in the source form of kIlRows in // native_mmvq.cu: per cell the rows count (1/2/4) that takes at least 3% off native_mmvq's time, else 0. @@ -29,6 +37,58 @@ using namespace strata::kernels; struct Cell { int type, T, n_out; double ref; double il[5]; }; std::vector<Cell> g_cells; +bool g_hot = false, g_persist = false, g_ab = false; +std::size_t g_gap_bytes = 0; +std::size_t g_gap_now = 0; // the gap in force for the current arm (--ab) or g_gap_bytes +// time `reps` calls of `fn` on `s`; with --gap each call is preceded by `gap` (other weights' reads) and timed on its own +template <class F, class G> +double time_us(F fn, int reps, cudaStream_t s, G gap) { + cudaEvent_t e0, e1; + (void) cudaEventCreate(&e0); + (void) cudaEventCreate(&e1); + float total = 0; + for (int rep = 0; rep < 2; ++rep) { // rep 0 warms, rep 1 times + total = 0; + if (g_gap_now == 0) { + (void) cudaEventRecord(e0, s); + for (int i = 0; i < reps; ++i) fn(i); + (void) cudaEventRecord(e1, s); + (void) cudaEventSynchronize(e1); + (void) cudaEventElapsedTime(&total, e0, e1); + } else { + for (int i = 0; i < reps; ++i) { + gap(); + (void) cudaEventRecord(e0, s); + fn(i); + (void) cudaEventRecord(e1, s); + (void) cudaEventSynchronize(e1); + float ms = 0; + (void) cudaEventElapsedTime(&ms, e0, e1); + total += ms; + } + } + } + (void) cudaEventDestroy(e0); + (void) cudaEventDestroy(e1); + return 1000.0 * total / reps; +} +// --persist: the matrix `w` (wbytes) persisting in L2 for every kernel on `s`; off: the window cleared +void persist_window(cudaStream_t s, void* w, std::size_t wbytes, bool on) { +#if !defined(STRATA_HIP_GFX906) + cudaStreamAttrValue v{}; + v.accessPolicyWindow.base_ptr = on ? w : nullptr; + v.accessPolicyWindow.num_bytes = on ? wbytes : 0; + v.accessPolicyWindow.hitRatio = 1.0f; + v.accessPolicyWindow.hitProp = cudaAccessPropertyPersisting; + v.accessPolicyWindow.missProp = cudaAccessPropertyStreaming; + if (cudaStreamSetAttribute(s, cudaStreamAttributeAccessPolicyWindow, &v) != cudaSuccess) { + std::printf("--persist: the access policy window was refused: %s\n", cudaGetErrorString(cudaGetLastError())); + } +#else + (void) s; (void) w; (void) wbytes; // (no L2 access policy window in the gfx906 compat layer) + std::printf("--persist: not available in this build (%s)\n", on ? "on" : "off"); +#endif +} struct Case { const char* name; int type, n_in, n_out, block_elems, block_bytes, scale_at[2]; @@ -98,15 +158,20 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { const uint16_t h = sane_half(rng); std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2); } - const int copies = bench ? (int) std::max<std::size_t>(1, std::min<std::size_t>(24, (192u << 20) / wbytes)) : 1; + // --hot: one copy (timed hot); with --gap, 1 + the copies the gap reads (dw[1..]) - the timed call always reads dw[0] + const int gap_copies = g_gap_bytes > 0 ? (int) std::min<std::size_t>(23, (g_gap_bytes + wbytes - 1) / wbytes) : 0; + const int copies = bench && (!g_hot || g_ab) ? (int) std::max<std::size_t>(1, std::min<std::size_t>(24, (192u << 20) / wbytes)) : 1 + gap_copies; std::vector<void*> dw(copies, nullptr); for (int i = 0; i < copies; ++i) { if (!ck(cudaMalloc(&dw[i], wbytes), "malloc w") || !ck(cudaMemcpy(dw[i], w.data(), wbytes, cudaMemcpyHostToDevice), "copy w")) return 1; } int bad = 0; + if (bench && g_persist && !g_ab) persist_window(s, dw[0], wbytes, true); + g_gap_now = g_gap_bytes; const int t_max = std::getenv("MMVQ_IL_TMAX") ? std::atoi(std::getenv("MMVQ_IL_TMAX")) : 8; // 147-verify: 5-8 columns - for (int T = 1; T <= t_max; ++T) { + const int t_min = std::getenv("MMVQ_IL_TMIN") ? std::atoi(std::getenv("MMVQ_IL_TMIN")) : 1; + for (int T = t_min; T <= t_max; ++T) { std::vector<float> x((std::size_t) T * c.n_in); std::normal_distribution<float> nd(0.f, 1.f); for (auto& v : x) v = nd(rng); @@ -124,10 +189,25 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { if (T >= 2) native_q8_1_interleave(xq, xil, c.n_in, T, s); native_mmvq(c.type, dw[0], xq, yref, c.n_in, c.n_out, T, s); ck(cudaStreamSynchronize(s), "ref"); + auto gap = [&]() { // --gap: other weights' reads between the timed calls (the window's traffic) + for (int j = 1; j <= gap_copies; ++j) native_mmvq(c.type, dw[j], xq, yref, c.n_in, c.n_out, T, s); + }; std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size()); ck(cudaMemcpy(a.data(), yref, ybytes, cudaMemcpyDeviceToHost), "read ref"); double best_ref = 0, best_il[5] = {0, 0, 0, 0, 0}; int table_r = 0; + struct Arm { const char* name; bool hot; std::size_t gap; bool persist; }; + const Arm arms_ab[] = {{"cold", false, 0, false}, {"hot", true, 0, false}, {"hot+gap", true, g_gap_bytes, false}, + {"hot+gap+persist", true, g_gap_bytes, true}, {"cold2", false, 0, false}}; + const Arm arms_one[] = {{g_hot ? "hot" : "cold", g_hot, g_gap_bytes, g_persist}}; + const Arm* arms = g_ab ? arms_ab : arms_one; + const int n_arms = g_ab ? 5 : 1; + for (int ai = 0; ai < (bench ? n_arms : 1); ++ai) { + if (bench) { + g_hot = arms[ai].hot; + g_gap_now = arms[ai].gap; + if (arms[ai].persist != g_persist) { g_persist = arms[ai].persist; persist_window(s, dw[0], wbytes, g_persist); } + } for (int r : {0, 1, 2, 4}) { native_mmvq_il_tune(r); cudaMemset(yil, 0xff, ybytes); @@ -148,45 +228,21 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { } (void) used; if (bench && r != 0) { - cudaEvent_t e0, e1; - cudaEventCreate(&e0); - cudaEventCreate(&e1); - const int reps = 200; - for (int rep = 0; rep < 2; ++rep) { // rep 0 warms, rep 1 times - cudaEventRecord(e0, s); - for (int i = 0; i < reps; ++i) native_mmvq_il(c.type, dw[i % copies], xq, xil, yil, c.n_in, c.n_out, T, s); - cudaEventRecord(e1, s); - cudaEventSynchronize(e1); - } - float ms; - cudaEventElapsedTime(&ms, e0, e1); - best_il[r] = 1000.0 * ms / reps; - cudaEventDestroy(e0); - cudaEventDestroy(e1); + best_il[r] = time_us([&](int i) { native_mmvq_il(c.type, dw[g_hot ? 0 : i % copies], xq, xil, yil, c.n_in, c.n_out, T, s); }, 200, s, gap); } } native_mmvq_il_tune(0); if (bench) { - cudaEvent_t e0, e1; - cudaEventCreate(&e0); - cudaEventCreate(&e1); - const int reps = 200; - for (int rep = 0; rep < 2; ++rep) { - cudaEventRecord(e0, s); - for (int i = 0; i < reps; ++i) native_mmvq(c.type, dw[i % copies], xq, yref, c.n_in, c.n_out, T, s); - cudaEventRecord(e1, s); - cudaEventSynchronize(e1); - } - float ms; - cudaEventElapsedTime(&ms, e0, e1); - best_ref = 1000.0 * ms / reps; + best_ref = time_us([&](int i) { native_mmvq(c.type, dw[g_hot ? 0 : i % copies], xq, yref, c.n_in, c.n_out, T, s); }, 200, s, gap); (void) table_r; g_cells.push_back({c.type, T, c.n_out, best_ref, {0, best_il[1], best_il[2], 0, best_il[4]}}); - std::printf("BENCH %-26s T=%d multi %.1f us | il rows1 %.1f rows2 %.1f rows4 %.1f us\n", c.name, T, best_ref, - best_il[1], best_il[2], best_il[4]); + std::printf("BENCH %-26s T=%d %-16s multi %.1f us | il rows1 %.1f rows2 %.1f rows4 %.1f us\n", c.name, T, + arms[ai].name, best_ref, best_il[1], best_il[2], best_il[4]); } + } // arms cudaFree(dx); cudaFree(xq); cudaFree(xil); cudaFree(yref); cudaFree(yil); } + if (bench && g_persist) persist_window(s, dw[0], wbytes, false); for (void* p : dw) cudaFree(p); return bad; } @@ -298,10 +354,43 @@ int check_tables() { int main(int argc, char** argv) { const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; const bool emit = bench && argc > 2 && std::string(argv[2]) == "--emit-table"; + for (int i = 2; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--hot") g_hot = true; + else if (a == "--ab") g_ab = true; + else if (a == "--persist") g_persist = true; + else if (a == "--gap" && i + 1 < argc) g_gap_bytes = (std::size_t) std::atoi(argv[++i]) << 20; + } cudaStream_t s; cudaStreamCreate(&s); +#if !defined(STRATA_HIP_GFX906) + if (g_persist || g_ab) { + int dev = 0, l2 = 0, maxp = 0, maxw = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&l2, cudaDevAttrL2CacheSize, dev); + cudaDeviceGetAttribute(&maxp, cudaDevAttrMaxPersistingL2CacheSize, dev); + cudaDeviceGetAttribute(&maxw, cudaDevAttrMaxAccessPolicyWindowSize, dev); + std::size_t want = std::min<std::size_t>(20u << 20, (std::size_t) maxp), got = 0; + const cudaError_t e = cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, want); + cudaDeviceGetLimit(&got, cudaLimitPersistingL2CacheSize); + std::printf("--persist: L2 %d MiB, max persisting %d MiB, max window %d MiB; set-aside asked %zu MiB -> %s, granted %zu MiB\n", + l2 >> 20, maxp >> 20, maxw >> 20, want >> 20, cudaGetErrorString(e), got >> 20); + } +#endif + if (bench) std::printf("bench arms: %s%s%s\n", g_hot ? "hot (one copy) " : "cold (192 MB rotation) ", + g_gap_bytes ? ("gap " + std::to_string(g_gap_bytes >> 20) + " MB ").c_str() : "", g_persist ? "persist" : ""); int bad = 0; bad += check_tables(); + if (bench) { // ~150 ms of launches so the clocks are up before the first timed case + void* wu = nullptr; float* yu = nullptr; void* xu = nullptr; + if (cudaMalloc(&wu, 6144u * 2560u) == cudaSuccess && cudaMalloc((void**) &yu, 2560 * 4) == cudaSuccess && + cudaMalloc(&xu, native_q8_1_bytes(6144, 1)) == cudaSuccess) { + (void) cudaMemset(wu, 0, 6144u * 2560u); (void) cudaMemset(xu, 0, native_q8_1_bytes(6144, 1)); + for (int i = 0; i < 6000; ++i) native_mmvq(12, wu, xu, yu, 6144, 2560, 1, s); + (void) cudaStreamSynchronize(s); + (void) cudaFree(wu); (void) cudaFree(yu); (void) cudaFree(xu); + } + } const char* only = std::getenv("MMVQ_IL_ONLY"); // 143-dense: only the cases whose name contains this for (const Case& c : CASES) if (only == nullptr || std::strstr(c.name, only) != nullptr) bad += run_case(c, bench, s); From 8b95bffb0bf2bb7460f0a12e97e23cfa6c7ebbbf Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:56:17 +0100 Subject: [PATCH 175/177] Decode: opt-in STRATA_MMVQ_IL_PF=1 hoisted-load, exact-integer interleaved GEMV kernels for Q6_K (#3779, #3712) Problem: the interleaved small-batch matvec (native_mmvq_il) has one weight block in flight per warp: its four `if (kbx < bpr)` sections each sit behind their own branch, so on a GA100 (ncu: 432 GB/s on the qkv Q6_K matrix) the loads of a group are not issued together. Change, opt-in (every variant is bitwise native_mmvq): native_mmvq_il_pf_kernel issues every weight load of a group (4 virtual warps x R rows) before any of the group's dots, with the addresses clamped to the row's last block for a tail, and with the ring variants the next group's loads before this group's dots. The per-lane accumulation order is the plain kernel's. P2's forms replace conversions by exact ones where the value is a small integer: (float)p becomes p + 1.5 * 2^23 minus 1.5 * 2^23 for |p| < 2^22, and the saturating byte subtract of Q6_K's codes (0..63, so nothing saturates) becomes two instructions. Q4_K, Q5_K, IQ4_XS and Q6_K have the variants; Q3_K (the Q2_0 pack's type) keeps the plain kernel. - STRATA_MMVQ_IL_PF=1: the measured table (kIlPf_80 / kIlPf58_80: Q6_K only, read only when the card is sm_80; on every other card 1 does nothing); =2..6: one variant for every type and shape (A/B only, any CUDA card). - Unset or 0: the plain kernels through the same launch code (the variant argument is 0, and the added code is one cached environment read and a switch). - CUDA only; HIP has no interleaved path. Tests: mmvq_il_parity --pf a,b,.. bit-checks each listed variant against native_mmvq for every type and shape, T = 1..8 and rows 0/1/2/4, and with --bench times them interleaved (PFBENCH lines) and prints the joint (variant, rows) table in the source form of kIlPf_<cc>. New ctest entry mmvq_il_parity_pf runs it with --pf 0,2,3,4,5,6 on whatever card is present. Reporter's numbers (linxuhao, CMP 170HX): decode +1.4 % (two reference / on / reference / on sets) over the plain kernels; with STRATA_GRAPH_PRIO decode +1.3 % in their per-feature pair (4K prompts +3.9 %, 16K +1.2 %, 52K +0.2 % in the same pair, which the reporter reads as noise). Q4_K, Q5_K and IQ4_XS variants tie the plain kernels there. Theirs, not measured here. Original change by linxuhao (PR #3779, commit 116992ab). --- CMakeLists.txt | 4 + include/strata/kernels/native_mmvq.hpp | 3 + src/kernels/cuda/native_mmvq.cu | 550 ++++++++++++++++++++++++- src/kernels/cuda/q8_1_il.cuh | 52 +++ src/kernels/mmvq_il_parity.cpp | 174 ++++++-- 5 files changed, 739 insertions(+), 44 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a5d060e2..250a22f1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1132,6 +1132,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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 opt-in STRATA_MMVQ_IL_PF kernels (hoisted group loads, exact integer forms): every variant bit-checked against + # native_mmvq for every type, shape, T and rows choice + add_test(NAME mmvq_il_parity_pf COMMAND mmvq_il_parity --pf 0,2,3,4,5,6) + set_tests_properties(mmvq_il_parity_pf PROPERTIES TIMEOUT 900) # 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) diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index ce11095c..1d511b07 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -166,5 +166,8 @@ void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, cons int native_mmvq_il_rows_for(int cc, int ggml_type, int ncols, int n_out); // Tests and benchmarks: every native_mmvq_il call takes `rows` a warp (0: the table). void native_mmvq_il_tune(int rows); +// Tests and benchmarks: the P1 / P2 kernel variant for every native_mmvq_il call (0: today's kernel, 2-6 as +// STRATA_MMVQ_IL_PF; -1: the environment). +void native_mmvq_il_pf(int pf); } // namespace strata::kernels diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 2cc1c75a..4867ec7f 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -650,6 +650,66 @@ __device__ __forceinline__ float q6_q8_dot_impl(int vl, int vh, const int* __res } return d * sumf; } +#if !defined(__HIPCC__) // CUDA only: the native_mmvq_il_pf_kernel family below (itself CUDA only) is the only user +// q6_q8_dot_impl with the two scales already in registers (the interleaved kernels' hoisted loads, P1): the same +// expression in the same order +__device__ __forceinline__ float q6_q8_dot_sc(int vl, int vh, const int* __restrict__ u, int sc0, int sc1, float d, + const float* __restrict__ d8) { + float sumf = 0.0f; + const int scs[2] = {sc0, sc1}; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int sc = scs[i]; + const int vil = (vl >> (4 * i)) & 0x0f0f0f0f; + const int vih = ((vh >> (4 * i)) << 4) & 0x30303030; + const int vi = __vsubss4(vil | vih, 0x20202020); + sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc); + } + return d * sumf; +} + +// P1: loads the compiler may not sink into a later branch (it moved the Q6_K scale and d loads of the hoisted group +// into the dot sections, where each one is a dependent L1 round trip); the same ld.global.nc the __restrict__ loads use +__device__ __forceinline__ int ldg_nc_u16(const void* p) { unsigned v; asm volatile("ld.global.nc.u16 %0, [%1];" : "=r"(v) : "l"(p)); return int(v); } +__device__ __forceinline__ int ldg_nc_s8(const void* p) { int v; asm volatile("ld.global.nc.s8 %0, [%1];" : "=r"(v) : "l"(p)); return v; } +__device__ __forceinline__ int ldg_nc_u8(const void* p) { unsigned v; asm volatile("ld.global.nc.u8 %0, [%1];" : "=r"(v) : "l"(p)); return int(v); } +__device__ __forceinline__ int ldg_nc_s32(const void* p) { int v; asm volatile("ld.global.nc.s32 %0, [%1];" : "=r"(v) : "l"(p)); return v; } +__device__ __forceinline__ int ldg_nc_b2(const void* p, int i32) { // load_int_b2 pinned: two u16, little-endian + const auto* x = static_cast<const uint16_t*>(p) + 2 * i32; + return ldg_nc_u16(x) | (ldg_nc_u16(x + 1) << 16); +} +// P1: base + k * stride as one IMAD.WIDE.U32 (an asm so the front end does not share k * stride between pointers and +// turn each into a 64-bit add pair) +__device__ __forceinline__ const void* madw(const void* base, int k, int stride) { + const void* r; + asm("mad.wide.u32 %0, %1, %2, %3;" : "=l"(r) : "r"(k), "r"(stride), "l"(base)); + return r; +} +// P2: (float) p for |p| < 2^22 as an add on the FMA pipe instead of the quarter-rate I2F: p + 1.5 * 2^23 +// as float bits is exactly 1.5 * 2^23 + p (unit ulp), and the subtraction is exact (Sterbenz), so the value is the +// conversion's, +0 included +__device__ __forceinline__ float i2f_small(int p_plus_magic) { return __int_as_float(p_plus_magic) - 12582912.0f; } +constexpr int kI2fMagic = 0x4B400000; +// P2: __vsubss4(x, 0x20202020) for bytes of x in [0, 63] (Q6_K's codes, so nothing saturates): x | 0x80 is x + 0x80 per +// byte, minus 0x20 never borrows (0x60..0x9f), and the xor takes the 0x80 back: the same int8 bytes, 2 instructions +// instead of ptxas's 8 for the saturating subtract sm_80 lacks +__device__ __forceinline__ int sub32_bytes(int x) { return (x + 0x60606060) ^ 0x80808080; } +// q6_q8_dot_sc with P2's integer forms: the dp4a inputs are the same 32-bit values, (dp * sc) the same int, and +// i2f_small its exact float (|dp * sc| <= 4 * 32 * 127 * 128 = 2.1M < 2^22), so every FFMA sees the bits q6_q8_dot_impl's does +__device__ __forceinline__ float q6_q8_dot_fast(int vl, int vh, const int* __restrict__ u, int sc0, int sc1, float d, + const float* __restrict__ d8) { + float sumf = 0.0f; + const int scs[2] = {sc0, sc1}; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int vil = (vl >> (4 * i)) & 0x0f0f0f0f; + const int vih = ((vh >> (4 * i)) << 4) & 0x30303030; + const int vi = sub32_bytes(vil | vih); + sumf += d8[i] * i2f_small(STRATA_DP4A(vi, u[i], 0) * scs[i] + kI2fMagic); + } + return d * sumf; +} +#endif // !__HIPCC__ __device__ __forceinline__ float q6_q8_dot(const Q6KBlock* __restrict__ w, const Q81Block* __restrict__ x, int iqs) { @@ -835,6 +895,7 @@ constexpr int MAX_NCOLS = 8; // every column bitwise equal to it. struct Q5KTraits { using Block = Q5KBlock; + [[maybe_unused]] static constexpr int TYPE = 13; // ggml type static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI; __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); } struct W { int vl[2], vh[2]; uint16_t aux[2]; half2 dm; int bq8_offset; }; @@ -876,6 +937,7 @@ struct Q5KTraits { }; struct Q4KTraits { using Block = Q4KBlock; + [[maybe_unused]] static constexpr int TYPE = 12; // ggml type static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI; __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); } struct W { int v[2]; uint16_t aux[2]; half2 dm; int bq8_offset; }; @@ -946,6 +1008,7 @@ struct Q20Traits { }; struct Q3KTraits { using Block = Q3KBlock; + [[maybe_unused]] static constexpr int TYPE = 11; // ggml type static constexpr int DIV = 256, T = 16, KBY = 8, BPI = WARPS * WARP / 16; __device__ static int kqs(int tid) { return tid % 16; } struct W { int vl, vh; float d; const uint8_t* scales; int scale_offset, bq8_offset; }; @@ -972,6 +1035,7 @@ struct Q3KTraits { }; struct Q6KTraits { using Block = Q6KBlock; + [[maybe_unused]] static constexpr int TYPE = 14; // ggml type static constexpr int DIV = 256, T = 32, KBY = 8, BPI = WARPS * WARP / 32; __device__ static int kqs(int tid) { return tid % 32; } struct W { int vl, vh; float d; const int8_t* scales; int bq8_offset; }; @@ -999,6 +1063,7 @@ struct Q6KTraits { }; struct IQ4XSTraits { using Block = IQ4XSBlock; + [[maybe_unused]] static constexpr int TYPE = 23; // ggml type static constexpr int DIV = 256, T = 8, KBY = 8, BPI = 4 * WARPS * WARP / 32; __device__ static int kqs(int tid) { return 4 * (tid % 8); } struct W { int2 v[4]; int ls; float dw; }; @@ -1556,10 +1621,141 @@ struct IlIQ4XS { out[c] = d * sumi; } } + // P1 (native_mmvq_il_pf_kernel): the block's bytes as loaded, the table lookup and the scale decode deferred to + // applyr so the loads of a whole group issue before any of them is consumed; the same integers and floats as apply + static constexpr bool HAS_PF = true; + struct RP { const uint8_t *qs, *sl, *blk; }; // a row's blocks for this lane: its qs ints, its scales_l byte, the block + __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) { + const auto* b = reinterpret_cast<const uint8_t*>(row); + return {b + 8 + 4 * iqs, b + 4 + iqs / 8, b}; + } + struct WR { int q[4]; int sl, sh, d; }; + // the pointers of block kbx (RP::at), and the loads of block kbx + dv from them (dv a compile-time offset, so the + // group's loads share one pointer set and differ by an immediate) + __device__ static RP at(const RP& rp, int kbx) { + constexpr int S = int(sizeof(F::Block)); + return {static_cast<const uint8_t*>(madw(rp.qs, kbx, S)), static_cast<const uint8_t*>(madw(rp.sl, kbx, S)), + static_cast<const uint8_t*>(madw(rp.blk, kbx, S))}; + } + __device__ static WR loadr(const RP& rp, int dv) { + constexpr int S = int(sizeof(F::Block)); + const auto* qs = reinterpret_cast<const int*>(rp.qs + dv * S); + WR r; +#pragma unroll + for (int j = 0; j < 4; ++j) r.q[j] = ldg_nc_s32(qs + j); + r.sl = ldg_nc_u8(rp.sl + dv * S); + r.sh = ldg_nc_u16(rp.blk + dv * S + 2); + r.d = ldg_nc_u16(rp.blk + dv * S); + return r; + } + // the activations: position-major (every int of the 8 at a stride of nb), so the kernel's block pointers are not used + __device__ static int xb(int) { return 0; } + __device__ static int xp(int) { return 0; } + template <int NC, bool FAST, class X> + __device__ static void applyr(const WR& rr, const X& x, const int*, const float*, int kby, int iqs, float (&out)[NC]) { + F::W r; +#pragma unroll + for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(rr.q[j]); + r.ls = ((rr.sl >> (iqs & 0x04)) & 0x0f) | (((rr.sh >> (iqs / 2)) & 0x03) << 4); + r.dw = __half2float(__ushort_as_half((unsigned short) rr.d)); + if constexpr (!FAST) { + apply<NC>(r, x, kby, iqs, out); + } else { + // P2: sumi (|sumi| <= 32 * 127 * 127 = 516K < 2^22) through i2f_small, then times (float)(ls - 32): the product + // |sumi * (ls - 32)| < 2^24 is exact in fp32, so it is the float of the int apply() converts; the same d * sumi + const int b = kby + iqs / 4; + int u0[4][NC], u1[4][NC]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + x.u(b, j, u0[j]); + x.u(b, j + 4, u1[j]); + } + float d8[NC]; + x.scales(b, d8); + const float fls = float(r.ls - 32); +#pragma unroll + for (int c = 0; c < NC; ++c) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi = STRATA_DP4A(r.v[j].x, u0[j][c], sumi); + sumi = STRATA_DP4A(r.v[j].y, u1[j][c], sumi); + } + const float fsumi = i2f_small(sumi + kI2fMagic) * fls; + const float d = r.dw * d8[c]; + out[c] = d * fsumi; + } + } + } }; struct IlQ4K { using F = Q4KTraits; static constexpr bool PM = false; + static constexpr bool HAS_PF = true; // P1: F::W holds every byte of the block already (no pointer into it) + struct RP { const uint8_t *qs, *sc, *blk; int iqs; }; // this lane's ql ints, its scale words, the block (dm) + __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) { + const auto* b = reinterpret_cast<const uint8_t*>(row); + const int bq8_offset = 2 * ((iqs / 2) / 4), jm = (bq8_offset / 2) & 1; + return {b + 16 + 16 * bq8_offset + 4 * ((iqs / 2) % 4), b + 4 + 2 * jm, b, iqs}; + } + using WR = F::W; + __device__ static RP at(const RP& rp, int kbx) { + constexpr int S = int(sizeof(F::Block)); + return {static_cast<const uint8_t*>(madw(rp.qs, kbx, S)), static_cast<const uint8_t*>(madw(rp.sc, kbx, S)), + static_cast<const uint8_t*>(madw(rp.blk, kbx, S)), rp.iqs}; + } + __device__ static WR loadr(const RP& rp, int dv) { // F::load's bytes and aux arithmetic, block dv past rp's + constexpr int S = int(sizeof(F::Block)); + const auto* ql = reinterpret_cast<const int*>(rp.qs + dv * S); + const auto* sc = rp.sc + dv * S; + WR r; + r.bq8_offset = 2 * ((rp.iqs / 2) / 4); + r.v[0] = ldg_nc_s32(ql); + r.v[1] = ldg_nc_s32(ql + 4); + const uint32_t s0 = ldg_nc_u16(sc), s2 = ldg_nc_u16(sc + 4), s4 = ldg_nc_u16(sc + 8); + const int dm = ldg_nc_s32(rp.blk + dv * S); + const int j = r.bq8_offset / 2; + const uint32_t hi = uint32_t(-int32_t(j >= 2)); + r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); + { half2 h; std::memcpy(&h, &dm, 4); r.dm = h; } + return r; + } + __device__ static int xb(int iqs) { return 2 * ((iqs / 2) / 4); } // the lane's q8_1 block and int within a 256-chunk + __device__ static int xp(int iqs) { return (iqs / 2) % 4; } + template <int NC, bool FAST, class X> + __device__ static void applyr(const WR& r, const X& x, const int* qb, const float* db, int kby, int iqs, float (&out)[NC]) { + if constexpr (!FAST) { + apply<NC>(r, x, kby, iqs, out); + } else { // P2: q4_q8_dot_impl with (dot1 * sc), (dot2 * m) through i2f_small (|dot1 * sc| <= 15240 * 63, |dot2 * m| <= 1016 * 63) + int u[4][NC]; + float d8[2][NC]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + x.qat(qb + i * X::QB, u[2 * i]); + x.qat(qb + i * X::QB + x.qp(4), u[2 * i + 1]); + x.dat(db + i * X::DB, d8[i]); + } + const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux); + const uint8_t* m = sc + 2; + const float2 dm4f = __half22float2(r.dm); +#pragma unroll + for (int c = 0; c < NC; ++c) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int v0i = (r.v[0] >> (4 * i)) & 0x0f0f0f0f; + const int v1i = (r.v[1] >> (4 * i)) & 0x0f0f0f0f; + const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1][c], STRATA_DP4A(v0i, u[2 * i][c], 0)); + const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1][c], STRATA_DP4A(0x01010101, u[2 * i][c], 0)); + sumf_d += d8[i][c] * i2f_small(dot1 * sc[i] + kI2fMagic); + sumf_m += d8[i][c] * i2f_small(dot2 * m[i] + kI2fMagic); + } + out[c] = dm4f.x * sumf_d - dm4f.y * sumf_m; + } + } + } template <int NC, class X> __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { int u[4][NC]; @@ -1583,6 +1779,78 @@ struct IlQ4K { struct IlQ5K { using F = Q5KTraits; static constexpr bool PM = false; + static constexpr bool HAS_PF = true; // P1: as IlQ4K + struct RP { const uint8_t *qs, *qh, *sc, *blk; int iqs; }; + __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) { + const auto* b = reinterpret_cast<const uint8_t*>(row); + const int bq8_offset = 2 * ((iqs / 2) / 4), jm = (bq8_offset / 2) & 1; + return {b + 48 + 16 * bq8_offset + 4 * ((iqs / 2) % 4), b + 16 + 4 * ((iqs / 2) % 4), b + 4 + 2 * jm, b, iqs}; + } + using WR = F::W; + __device__ static RP at(const RP& rp, int kbx) { + constexpr int S = int(sizeof(F::Block)); + return {static_cast<const uint8_t*>(madw(rp.qs, kbx, S)), static_cast<const uint8_t*>(madw(rp.qh, kbx, S)), + static_cast<const uint8_t*>(madw(rp.sc, kbx, S)), static_cast<const uint8_t*>(madw(rp.blk, kbx, S)), rp.iqs}; + } + __device__ static WR loadr(const RP& rp, int dv) { // F::load's bytes and aux arithmetic, block dv past rp's + constexpr int S = int(sizeof(F::Block)); + const auto* ql = reinterpret_cast<const int*>(rp.qs + dv * S); + const auto* qh = reinterpret_cast<const int*>(rp.qh + dv * S); + const auto* sc = rp.sc + dv * S; + WR r; + r.bq8_offset = 2 * ((rp.iqs / 2) / 4); + r.vl[0] = ldg_nc_s32(ql); + r.vl[1] = ldg_nc_s32(ql + 4); + r.vh[0] = ldg_nc_s32(qh) >> r.bq8_offset; + r.vh[1] = ldg_nc_s32(qh + 4) >> r.bq8_offset; + const uint32_t s0 = ldg_nc_u16(sc), s2 = ldg_nc_u16(sc + 4), s4 = ldg_nc_u16(sc + 8); + const int dm = ldg_nc_s32(rp.blk + dv * S); + const int j = r.bq8_offset / 2; + const uint32_t hi = uint32_t(-int32_t(j >= 2)); + r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); + { half2 h; std::memcpy(&h, &dm, 4); r.dm = h; } + return r; + } + __device__ static int xb(int iqs) { return 2 * ((iqs / 2) / 4); } + __device__ static int xp(int iqs) { return (iqs / 2) % 4; } + template <int NC, bool FAST, class X> + __device__ static void applyr(const WR& r, const X& x, const int* qb, const float* db, int kby, int iqs, float (&out)[NC]) { + if constexpr (!FAST) { + apply<NC>(r, x, kby, iqs, out); + } else { // P2: q5_q8_dot_impl with (dot1 * sc), (dot2 * m) through i2f_small (|dot1 * sc| <= 31496 * 63 < 2^22) + int u[4][NC]; + float d8[2][NC]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + x.qat(qb + i * X::QB, u[2 * i]); + x.qat(qb + i * X::QB + x.qp(4), u[2 * i + 1]); + x.dat(db + i * X::DB, d8[i]); + } + const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux); + const uint8_t* m = sc + 2; + const float2 dm5f = __half22float2(r.dm); +#pragma unroll + for (int c = 0; c < NC; ++c) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int vl0i = (r.vl[0] >> (4 * i)) & 0x0f0f0f0f; + const int vl1i = (r.vl[1] >> (4 * i)) & 0x0f0f0f0f; + const int vh0i = ((r.vh[0] >> i) << 4) & 0x10101010; + const int vh1i = ((r.vh[1] >> i) << 4) & 0x10101010; + const int v0i = vl0i | vh0i; + const int v1i = vl1i | vh1i; + const int dot1 = STRATA_DP4A(v0i, u[2 * i][c], STRATA_DP4A(v1i, u[2 * i + 1][c], 0)); + const int dot2 = STRATA_DP4A(0x01010101, u[2 * i][c], STRATA_DP4A(0x01010101, u[2 * i + 1][c], 0)); + sumf_d += d8[i][c] * i2f_small(dot1 * sc[i] + kI2fMagic); + sumf_m += d8[i][c] * i2f_small(dot2 * m[i] + kI2fMagic); + } + out[c] = dm5f.x * sumf_d - dm5f.y * sumf_m; + } + } + } template <int NC, class X> __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { int u[4][NC]; @@ -1608,6 +1876,7 @@ struct IlQ5K { struct IlQ3K { using F = Q3KTraits; static constexpr bool PM = false; + static constexpr bool HAS_PF = false; // the Q2_0 pack's type: keeps native_mmvq_il_kernel (F::W points into the block) template <int NC, class X> __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) { int u[4][NC]; @@ -1662,8 +1931,210 @@ struct IlQ6K { out[c] = q6_q8_dot_impl(r.vl, r.vh, uc, r.scales, r.d, dc); } } + // P1: the two scale bytes loaded with the rest (F::W keeps a pointer into the block, which would put their loads + // in the compute phase); q6_q8_dot_sc is q6_q8_dot_impl's expression + static constexpr bool HAS_PF = true; + // a row's four lane-adjusted byte pointers (ql, qh, scales, d): a block's loads are then one IMAD.WIDE each from kbx + struct RP { const uint8_t *ql, *qh, *sc, *d; }; + __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) { + const auto* b = reinterpret_cast<const uint8_t*>(row); + const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; + return {b + 4 * iqs, b + 128 + 4 * (8 * (iqs / 16) + iqs % 8), b + 192 + scale_offset, b + 208}; // load_int_b2's int iqs + } + struct WR { int vl, vh, sc0, sc1, d; }; + __device__ static RP at(const RP& rp, int kbx) { + constexpr int S = int(sizeof(F::Block)); + return {static_cast<const uint8_t*>(madw(rp.ql, kbx, S)), static_cast<const uint8_t*>(madw(rp.qh, kbx, S)), + static_cast<const uint8_t*>(madw(rp.sc, kbx, S)), static_cast<const uint8_t*>(madw(rp.d, kbx, S))}; + } + __device__ static WR loadr(const RP& rp, int dv) { // block dv past rp's: immediates off its four pointers + constexpr int S = int(sizeof(F::Block)); + WR r; + r.vl = ldg_nc_b2(rp.ql + dv * S, 0); + r.vh = ldg_nc_b2(rp.qh + dv * S, 0); + r.sc0 = ldg_nc_s8(rp.sc + dv * S); + r.sc1 = ldg_nc_s8(rp.sc + dv * S + 4); + r.d = ldg_nc_u16(rp.d + dv * S); + return r; + } + __device__ static int xb(int iqs) { return 4 * (iqs / 16) + (iqs % 16) / 8; } + __device__ static int xp(int iqs) { return iqs % 8; } + template <int NC, bool FAST, class X> + __device__ static void applyr(const WR& r, const X& x, const int* qb, const float* db, int kby, int iqs, float (&out)[NC]) { + const int vh = r.vh >> (2 * ((iqs % 16) / 8)); + int u[2][NC]; + float d8[2][NC]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + x.qat(qb + 2 * i * X::QB, u[i]); + x.dat(db + 2 * i * X::DB, d8[i]); + } + const float d = __half2float(__ushort_as_half((unsigned short) r.d)); +#pragma unroll + for (int c = 0; c < NC; ++c) { + const int uc[2] = {u[0][c], u[1][c]}; + const float dc[2] = {d8[0][c], d8[1][c]}; + out[c] = FAST ? q6_q8_dot_fast(r.vl, vh, uc, r.sc0, r.sc1, d, dc) : q6_q8_dot_sc(r.vl, vh, uc, r.sc0, r.sc1, d, dc); + } + } }; +// P1: native_mmvq_il_kernel with every weight load of a group (the 4 virtual warps x R rows) issued +// before any of the group's dots - the four `if (kbx < bpr)` sections of the kernel below each sit behind their own +// branch, so a warp had one 2-row x 1-block group in flight (ncu: 432 GB/s on the qkv Q6_K matrix). The addresses are +// clamped to the row's last block (a tail re-reads it; its dot is skipped), and with DB the next group's loads are +// issued before this group's dots (two register sets, ping-pong, no copies). The per-lane accumulation order is the +// kernel below's: acc[v] += block(4m + v) in ascending m, ((acc0 + acc1) + acc2) + acc3, warp_sum - the same bits. +// STRATA_MMVQ_IL_PF=1: hoisted group loads (4 blocks a SM); =3: + P2's exact integer forms (the traits' applyr<FAST>); +// =4: as 3 at 5 blocks a SM; =2 / =5: as 3 / 4 with the ring (DB 2: a section's registers reloaded with the next group's +// blocks right after its dots); unset / 0: the kernel below. +template <typename I, int NC, int R, int DB, int MINB, bool FAST> +__launch_bounds__(4 * WARP, MINB) +__global__ void native_mmvq_il_pf_kernel(const typename I::F::Block* __restrict__ w, const int* __restrict__ xq, + const float* __restrict__ xd, float* __restrict__ y, int n_in, int n_out) { + using F = typename I::F; + using WR = typename I::WR; + constexpr int SUB = WARP / F::T; // weight blocks a chunk covers + const int lane = int(threadIdx.x) & (WARP - 1); + const auto x = q8_1_cols<NC, I::PM>(xq, xd, n_in / Q8K); + using X = std::remove_const_t<decltype(x)>; + const int bpr = n_in / F::DIV; + const int kqs = F::kqs(lane); + const int sub = lane / F::T; + const int nm = (bpr + SUB - 1) / SUB; + for (int grp = int(blockIdx.x) * 4 + (int(threadIdx.x) >> 5); grp * R < n_out; grp += int(gridDim.x) * 4) { + const int row0 = grp * R; + typename I::RP wr[R]; +#pragma unroll + for (int i = 0; i < R; ++i) wr[i] = I::rowptrs(w + std::size_t(min(row0 + i, n_out - 1)) * bpr, kqs); // a partial last group recomputes its last row + float acc[4][R][NC]; +#pragma unroll + for (int v = 0; v < 4; ++v) +#pragma unroll + for (int i = 0; i < R; ++i) +#pragma unroll + for (int c = 0; c < NC; ++c) acc[v][i][c] = 0.0f; + // the groups whose four chunks are whole blocks for every lane run with no branch at all (ptxas sinks a load + // whose only use sits behind a branch into it, which is what put the scale loads back into the dot sections); + // the tail group clamps its loads and predicates its dots + const int m_full = bpr / SUB; + // a full group's 4 x R blocks: one pointer set per row at the group's first block, the other three at immediates + // (v * SUB blocks on); a clamped (tail) group addresses each block on its own + auto load_group = [&](int m0, bool clamp, WR (&wv)[4][R]) { + if (!clamp) { +#pragma unroll + for (int i = 0; i < R; ++i) { + const typename I::RP p0 = I::at(wr[i], SUB * m0 + sub); +#pragma unroll + for (int v = 0; v < 4; ++v) wv[v][i] = I::loadr(p0, v * SUB); + } + } else { +#pragma unroll + for (int v = 0; v < 4; ++v) { + const int kbx = min(SUB * (m0 + v) + sub, bpr - 1); +#pragma unroll + for (int i = 0; i < R; ++i) wv[v][i] = I::loadr(I::at(wr[i], kbx), 0); + } + } + }; + // the lane's activation ints and scales of the group's first chunk; a section's are an immediate on + const int* xq0 = x.qbase(I::xb(kqs) + sub * F::KBY, I::xp(kqs)); + const float* xd0 = x.dbase(I::xb(kqs) + sub * F::KBY); + auto dot_group = [&](int m0, bool pred, const WR (&wv)[4][R]) { + const int* qg = static_cast<const int*>(madw(xq0, SUB * m0 * F::KBY, X::QB * 4)); + const float* dg = static_cast<const float*>(madw(xd0, SUB * m0 * F::KBY, X::DB * 4)); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const int kbx = SUB * (m0 + v) + sub; + if (!pred || kbx < bpr) { +#pragma unroll + for (int i = 0; i < R; ++i) { + float o[NC]; + I::template applyr<NC, FAST>(wv[v][i], x, qg + v * SUB * F::KBY * X::QB, dg + v * SUB * F::KBY * X::DB, + kbx * F::KBY, kqs, o); +#pragma unroll + for (int c = 0; c < NC; ++c) acc[v][i][c] += o[c]; + } + } + } + }; + int m0 = 0; + if constexpr (DB == 0) { + for (; m0 + 4 <= m_full; m0 += 4) { + WR wv[4][R]; + load_group(m0, false, wv); + dot_group(m0, false, wv); + } + } else if constexpr (DB == 2) { + // a ring: after a section's dots its registers take the next group's blocks of that section, so the warp + // always has about a group's worth of loads in flight at the register cost of one group (the loads sit + // behind a uniform branch whose consumers are in the next iteration, so nothing can sink) + WR wv[4][R]; + if (m0 + 4 <= m_full) load_group(0, false, wv); + for (; m0 + 4 <= m_full; m0 += 4) { + const bool more = m0 + 8 <= m_full; + typename I::RP pn[R]; + if (more) { +#pragma unroll + for (int i = 0; i < R; ++i) pn[i] = I::at(wr[i], SUB * (m0 + 4) + sub); + } + const int* qg = static_cast<const int*>(madw(xq0, SUB * m0 * F::KBY, X::QB * 4)); + const float* dg = static_cast<const float*>(madw(xd0, SUB * m0 * F::KBY, X::DB * 4)); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const int kbx = SUB * (m0 + v) + sub; +#pragma unroll + for (int i = 0; i < R; ++i) { + float o[NC]; + I::template applyr<NC, FAST>(wv[v][i], x, qg + v * SUB * F::KBY * X::QB, dg + v * SUB * F::KBY * X::DB, + kbx * F::KBY, kqs, o); +#pragma unroll + for (int c = 0; c < NC; ++c) acc[v][i][c] += o[c]; + } + if (more) { +#pragma unroll + for (int i = 0; i < R; ++i) wv[v][i] = I::loadr(pn[i], v * SUB); + } + } + } + } else { // two register sets: a group's loads issue before the previous group's dots; no branch inside the loop + WR wa[4][R], wb[4][R]; + if (m0 + 4 <= m_full) load_group(0, false, wa); + for (; m0 + 12 <= m_full; m0 += 8) { + load_group(m0 + 4, false, wb); + dot_group(m0, false, wa); + load_group(m0 + 8, false, wa); + dot_group(m0 + 4, false, wb); + } + if (m0 + 8 <= m_full) { + load_group(m0 + 4, false, wb); + dot_group(m0, false, wa); + dot_group(m0 + 4, false, wb); + m0 += 8; + } else if (m0 + 4 <= m_full) { + dot_group(m0, false, wa); + m0 += 4; + } + } + if (m0 < nm) { + WR wv[4][R]; + load_group(m0, true, wv); + dot_group(m0, true, wv); + } +#pragma unroll + for (int i = 0; i < R; ++i) +#pragma unroll + for (int c = 0; c < NC; ++c) { + float s = acc[0][i][c]; + s += acc[1][i][c]; + s += acc[2][i][c]; + s += acc[3][i][c]; + s = warp_sum(s); + if (lane == 0 && row0 + i < n_out) y[std::size_t(c) * n_out + row0 + i] = s; + } + } +} + template <typename I, int NC, int R> __launch_bounds__(4 * WARP) __global__ void native_mmvq_il_kernel(const typename I::F::Block* __restrict__ w, const int* __restrict__ xq, @@ -1717,23 +2188,57 @@ __global__ void native_mmvq_il_kernel(const typename I::F::Block* __restrict__ w } } +int g_il_pf = -1; // native_mmvq_il_pf (tests, benchmarks): the variant for every launch; -1: STRATA_MMVQ_IL_PF +int il_pf_env() { + static const int env = [] { const char* v = std::getenv("STRATA_MMVQ_IL_PF"); return v ? std::atoi(v) : 0; }(); + return env; +} +int il_pf_table(int type, int ncols, int n_out); // the sm_80 table below: pf << 4 | rows, 0 = today's kernel and table +// the variant of one launch (g_il_pf, else STRATA_MMVQ_IL_PF: 0 / unset today's kernel, 1 the measured table, 2-6 that +// variant for every type and shape), and with the table its rows a warp (0: the rows table's) +int il_pf_for(int type, int ncols, int n_out, int* rows) { + *rows = 0; + if (g_il_pf >= 0) return g_il_pf; + const int env = il_pf_env(); + if (env != 1) return env; + const int t = il_pf_table(type, ncols, n_out); + *rows = t & 15; + return t >> 4; +} +// one (type, columns, rows) launch: today's kernel, or the variant il_pf_for names for a type that has them +template <typename I, int NC, int R> +void launch_il_one(unsigned blocks, const typename I::F::Block* w, const int* xq, const float* xd, float* y, int n_in, int n_out, + cudaStream_t s, int pf) { + if constexpr (I::HAS_PF) { + switch (pf) { + case 6: native_mmvq_il_pf_kernel<I, NC, R, 0, 4, false><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return; + case 2: native_mmvq_il_pf_kernel<I, NC, R, 2, 4, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return; + case 3: native_mmvq_il_pf_kernel<I, NC, R, 0, 4, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return; + case 4: native_mmvq_il_pf_kernel<I, NC, R, 0, 5, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return; + case 5: native_mmvq_il_pf_kernel<I, NC, R, 2, 5, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return; + default: break; + } + } + native_mmvq_il_kernel<I, NC, R><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); +} + template <typename I, int R> -void launch_il(const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s) { +void launch_il(const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s, int pf) { const auto* w = static_cast<const typename I::F::Block*>(weights); const unsigned blocks = unsigned(((n_out + R - 1) / R + 3) / 4); if (ncols == 1) { // 143-dense: one column reads the plain q8_1 blocks (x_il is then the caller's x_q8_1) - native_mmvq_il_kernel<I, 1, R><<<blocks, 4 * WARP, 0, s>>>(w, static_cast<const int*>(x_il), nullptr, y, n_in, n_out); + launch_il_one<I, 1, R>(blocks, w, static_cast<const int*>(x_il), nullptr, y, n_in, n_out, s, pf); return; } const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols); const int* xq = I::PM ? parts.pm : parts.bm; const float* xd = parts.d; switch (ncols) { -#define STRATA_IL_CASE(N) case N: native_mmvq_il_kernel<I, N, R><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); break; +#define STRATA_IL_CASE(N) case N: launch_il_one<I, N, R>(blocks, w, xq, xd, y, n_in, n_out, s, pf); break; STRATA_IL_CASE(2) STRATA_IL_CASE(3) STRATA_IL_CASE(4) #undef STRATA_IL_CASE // 147-verify: 5..8 columns (the cp = 8 copy) at 1 or 2 rows a warp; launch_il_rows maps 4 rows to 2 there -#define STRATA_IL_CASE(N) case N: if constexpr (R <= 2) native_mmvq_il_kernel<I, N, R><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); break; +#define STRATA_IL_CASE(N) case N: if constexpr (R <= 2) launch_il_one<I, N, R>(blocks, w, xq, xd, y, n_in, n_out, s, pf); break; STRATA_IL_CASE(5) STRATA_IL_CASE(6) STRATA_IL_CASE(7) STRATA_IL_CASE(8) #undef STRATA_IL_CASE default: throw std::invalid_argument("native_mmvq_il requires 1 <= ncols <= 8"); @@ -1742,11 +2247,14 @@ void launch_il(const void* weights, const void* x_il, float* y, int n_in, int n_ template <typename I> void launch_il_rows(int r, const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s) { + int pf_rows = 0; + const int pf = il_pf_for(I::F::TYPE, ncols, n_out, &pf_rows); + if (pf_rows != 0) r = pf_rows; // the pf table measured its rows with its kernel if (ncols > 4 && r == 4) r = 2; // 5..8 columns: 1 or 2 rows a warp switch (r) { - case 1: launch_il<I, 1>(weights, x_il, y, n_in, n_out, ncols, s); break; - case 4: launch_il<I, 4>(weights, x_il, y, n_in, n_out, ncols, s); break; - default: launch_il<I, 2>(weights, x_il, y, n_in, n_out, ncols, s); break; + case 1: launch_il<I, 1>(weights, x_il, y, n_in, n_out, ncols, s, pf); break; + case 4: launch_il<I, 4>(weights, x_il, y, n_in, n_out, ncols, s, pf); break; + default: launch_il<I, 2>(weights, x_il, y, n_in, n_out, ncols, s, pf); break; } } @@ -3054,6 +3562,20 @@ constexpr IlRows kIlRows_80[] = { {14, {{0, 0, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 2, 4, 2, 2}}}, // Q6_K {11, {{1, 2, 2, 2, 2}, {1, 1, 2, 2, 2}, {1, 2, 2, 2, 2}}}, // Q3_K }; +// sm_80 P1/P2: the hoisted-load / exact-integer kernel variant and its rows a warp per cell, pf << 4 | rows +// (0x32 = variant 3 at 2 rows a warp; 0 = today's kernel with kIlRows_80), read off mmvq_il_parity --bench --emit-table +// --pf 0,3,4 on the CMP 170HX with the same 3% rule against native_mmvq; STRATA_MMVQ_IL_PF=1 takes it. Every variant is +// bitwise native_mmvq (the tool checks every case, T 1-8, rows 1/2/4, each variant). +struct IlPf { int type; uint8_t v[3][5]; }; +struct IlPf58 { int type; uint8_t v[4][5]; }; +// Only Q6_K: the same variants are bitwise and measured for Q4_K / Q5_K / IQ4_XS too, but there they tie today's kernel +// within the run-to-run noise (their emitted cells flip between 0 and a variant), so those types keep kIlRows_80. +constexpr IlPf kIlPf_80[] = { + {14, {{0x31, 0x42, 0x32, 0x42, 0x42}, {0x31, 0x41, 0x32, 0x32, 0x41}, {0x31, 0x41, 0x32, 0x32, 0x32}}}, // Q6_K +}; +constexpr IlPf58 kIlPf58_80[] = { // (rows 4 runs as 2 at 5+ columns, so the emitted 0x34 cells are written 0x32) + {14, {{0x31, 0x42, 0x32, 0x32, 0x32}, {0x31, 0x31, 0x32, 0x32, 0x32}, {0x31, 0x31, 0x02, 0x32, 0x02}, {0x31, 0x31, 0x31, 0x31, 0x31}}}, // Q6_K +}; // Turing (sm_75): read off mmvq_il_parity --bench --emit-table on an RTX 2080 Ti 22 GB (SM 1650 MHz), the same 3% rule. // The plain multi-column kernels are bound by dp4a throughput on Turing from 2 columns on (IQ4_XS 2560x10240 at 4 // columns 81.1 -> 37.4 us, the Q5_K head 1671 -> 1045 us); bitwise equal to native_mmvq. No one-column table here: @@ -3220,9 +3742,22 @@ int il_cc() { return cc[dev]; } int il_rows(int type, int ncols, int n_out) { return native_mmvq_il_rows_for(il_cc(), type, ncols, n_out); } +int il_pf_table(int type, int ncols, int n_out) { + if (il_cc() != 80 || ncols < 2 || ncols > 8) return 0; // only the CMP 170HX measured one + const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; + if (ncols <= 4) { + for (const IlPf& t : kIlPf_80) + if (t.type == type) return t.v[ncols - 2][cls]; + } else { + for (const IlPf58& t : kIlPf58_80) + if (t.type == type) return t.v[ncols - 5][cls]; + } + return 0; +} int g_tune_rows = 0; // native_mmvq_il_tune (tests, benchmarks): rows a warp for every shape (0: the table) } // namespace void native_mmvq_il_tune(int rows) { g_tune_rows = rows; } +void native_mmvq_il_pf(int pf) { g_il_pf = pf; } namespace { // sm_80 and newer (measured on sm_86 and sm_120), Volta (sm_70) and Pascal (sm_60, sm_61), each with its own table @@ -3298,6 +3833,7 @@ void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, cons native_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); } void native_mmvq_il_tune(int) {} +void native_mmvq_il_pf(int) {} #endif // !__HIPCC__ } // namespace strata::kernels diff --git a/src/kernels/cuda/q8_1_il.cuh b/src/kernels/cuda/q8_1_il.cuh index 49c7a5a1..4d64fe07 100644 --- a/src/kernels/cuda/q8_1_il.cuh +++ b/src/kernels/cuda/q8_1_il.cuh @@ -41,6 +41,52 @@ template <int NC, bool PM> struct Q81Il { } } } + // P1 (native_mmvq_il_pf_kernel): the same loads from a pointer the caller strength-reduces - qat(qbase(b, p) + k * QB) + // is u(b + k, p), dat(dbase(b) + k * DB) is scales(b + k) + static constexpr int QB = PM ? CP : 8 * CP, DB = CP; + __device__ __forceinline__ int qp(int dp) const { return PM ? dp * nb * CP : dp * CP; } // ints from p to p + dp + __device__ __forceinline__ const int* qbase(int b, int p) const { return q + std::size_t(PM ? p * nb + b : b * 8 + p) * CP; } + __device__ __forceinline__ const float* dbase(int b) const { return d + std::size_t(b) * CP; } + __device__ __forceinline__ void qat(const int* s, int (&o)[NC]) const { // __ldg: s comes from an asm (madw), so the + if constexpr (CP == 2) { // front end no longer knows it is global + const int2 a = __ldg(reinterpret_cast<const int2*>(s)); + o[0] = a.x; + o[1] = a.y; + } else { + const int4 a = __ldg(reinterpret_cast<const int4*>(s)); + o[0] = a.x; + if constexpr (NC > 1) o[1] = a.y; + if constexpr (NC > 2) o[2] = a.z; + if constexpr (NC > 3) o[3] = a.w; + if constexpr (NC > 4) { + const int4 e = __ldg(reinterpret_cast<const int4*>(s + 4)); + o[4] = e.x; + if constexpr (NC > 5) o[5] = e.y; + if constexpr (NC > 6) o[6] = e.z; + if constexpr (NC > 7) o[7] = e.w; + } + } + } + __device__ __forceinline__ void dat(const float* s, float (&o)[NC]) const { + if constexpr (CP == 2) { + const float2 a = __ldg(reinterpret_cast<const float2*>(s)); + o[0] = a.x; + o[1] = a.y; + } else { + const float4 a = __ldg(reinterpret_cast<const float4*>(s)); + o[0] = a.x; + if constexpr (NC > 1) o[1] = a.y; + if constexpr (NC > 2) o[2] = a.z; + if constexpr (NC > 3) o[3] = a.w; + if constexpr (NC > 4) { + const float4 e = __ldg(reinterpret_cast<const float4*>(s + 4)); + o[4] = e.x; + if constexpr (NC > 5) o[5] = e.y; + if constexpr (NC > 6) o[6] = e.z; + if constexpr (NC > 7) o[7] = e.w; + } + } + } __device__ __forceinline__ void scales(int b, float (&o)[NC]) const { const float* s = d + std::size_t(b) * CP; if constexpr (CP == 2) { @@ -73,6 +119,12 @@ struct Q81One { __device__ __forceinline__ void scales(int b, float (&o)[1]) const { o[0] = __low2float(*reinterpret_cast<const half2*>(x + std::size_t(b) * 36)); } + static constexpr int QB = 9, DB = 9; // a 36-byte block in ints / floats + __device__ __forceinline__ int qp(int dp) const { return dp; } + __device__ __forceinline__ const int* qbase(int b, int p) const { return reinterpret_cast<const int*>(x + std::size_t(b) * 36 + 4) + p; } + __device__ __forceinline__ const float* dbase(int b) const { return reinterpret_cast<const float*>(x + std::size_t(b) * 36); } + __device__ __forceinline__ void qat(const int* s, int (&o)[1]) const { o[0] = __ldg(s); } + __device__ __forceinline__ void dat(const float* s, float (&o)[1]) const { o[0] = __low2float(__ldg(reinterpret_cast<const half2*>(s))); } }; // The activations a kernel for NC columns reads: one column's q8_1 blocks, 2+ columns' interleaved copy (nb blocks a diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 415baa4b..e55d6d01 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -1,7 +1,13 @@ // src/kernels/mmvq_il_parity.cpp - native_mmvq_il (2-4 columns from the interleaved q8_1 copy, fork F4) against // native_mmvq's multi-column kernels, bitwise, for every rows-a-warp choice; --bench times both per call. // -// build/mmvq_il_parity [--bench [--emit-table] [--hot] [--gap MB] [--persist] [--ab]] +// build/mmvq_il_parity [--bench [--emit-table] [--hot] [--gap MB] [--persist] [--ab] [--pf a,b,..] [--rounds N]] +// +// --pf a,b,..: the P1 / P2 kernel variants (native_mmvq_il_pf: 0 = today's kernel, 6 hoisted group loads, 3 + P2's exact +// integer forms, 4 = 3 at 5 blocks a SM, 2 / 5 = 3 / 4 with a ring) are each bit-checked against native_mmvq, and with +// --bench timed interleaved per (case, T, rows): N rounds +// (default 5) of 100 calls each, variant after variant, the median of the rounds printed per variant (PFBENCH lines; the +// table cells take the first listed variant). Without --pf every call takes STRATA_MMVQ_IL_PF (unset: today's kernel). // // --hot times one copy of the weights (they sit in L2 after the first call: the ceiling of an L2 // prefetch); --gap MB reads MB megabytes of OTHER weights (native_mmvq over other copies) before every timed call, as @@ -23,6 +29,7 @@ #include <cuda_runtime.h> #include <algorithm> +#include <array> #include <cmath> #include <cstdint> #include <cstdio> @@ -35,9 +42,11 @@ namespace { using namespace strata::kernels; -struct Cell { int type, T, n_out; double ref; double il[5]; }; +struct Cell { int type, T, n_out, pf; double ref; double il[5]; }; // pf: the variant the il[] times ran (-1: the environment's) std::vector<Cell> g_cells; bool g_hot = false, g_persist = false, g_ab = false; +std::vector<int> g_pf; // --pf: the variants to check and time; empty: the environment's +int g_rounds = 5; std::size_t g_gap_bytes = 0; std::size_t g_gap_now = 0; // the gap in force for the current arm (--ab) or g_gap_bytes // time `reps` calls of `fn` on `s`; with --gap each call is preceded by `gap` (other weights' reads) and timed on its own @@ -195,6 +204,7 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size()); ck(cudaMemcpy(a.data(), yref, ybytes, cudaMemcpyDeviceToHost), "read ref"); double best_ref = 0, best_il[5] = {0, 0, 0, 0, 0}; + std::vector<std::array<double, 5>> pf_il(g_pf.size(), std::array<double, 5>{0, 0, 0, 0, 0}); // per --pf variant int table_r = 0; struct Arm { const char* name; bool hot; std::size_t gap; bool persist; }; const Arm arms_ab[] = {{"cold", false, 0, false}, {"hot", true, 0, false}, {"hot+gap", true, g_gap_bytes, false}, @@ -208,34 +218,60 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { g_gap_now = arms[ai].gap; if (arms[ai].persist != g_persist) { g_persist = arms[ai].persist; persist_window(s, dw[0], wbytes, g_persist); } } + const std::vector<int> pfs = g_pf.empty() ? std::vector<int>{-1} : g_pf; for (int r : {0, 1, 2, 4}) { native_mmvq_il_tune(r); - cudaMemset(yil, 0xff, ybytes); - native_mmvq_il(c.type, dw[0], xq, xil, yil, c.n_in, c.n_out, T, s); - ck(cudaStreamSynchronize(s), "il"); - ck(cudaMemcpy(b.data(), yil, ybytes, cudaMemcpyDeviceToHost), "read il"); - long long diff = 0, nonfinite = 0; - for (std::size_t i = 0; i < a.size(); ++i) { - float fa; - std::memcpy(&fa, &a[i], 4); - if (!std::isfinite(fa)) ++nonfinite; - if (a[i] != b[i]) ++diff; + for (int pf : pfs) { + native_mmvq_il_pf(pf); + cudaMemset(yil, 0xff, ybytes); + native_mmvq_il(c.type, dw[0], xq, xil, yil, c.n_in, c.n_out, T, s); + ck(cudaStreamSynchronize(s), "il"); + ck(cudaMemcpy(b.data(), yil, ybytes, cudaMemcpyDeviceToHost), "read il"); + long long diff = 0, nonfinite = 0; + for (std::size_t i = 0; i < a.size(); ++i) { + float fa; + std::memcpy(&fa, &a[i], 4); + if (!std::isfinite(fa)) ++nonfinite; + if (a[i] != b[i]) ++diff; + } + if (diff != 0 || nonfinite != 0) { + ++bad; + std::printf("FAIL %-26s T=%d rows=%d pf=%d: %lld bits differ, %lld non-finite of %zu\n", c.name, T, r, pf, diff, + nonfinite, a.size()); + } } - const bool used = r != 0 || native_mmvq_il_supported(c.type, T, c.n_out); - if (diff != 0 || nonfinite != 0) { - ++bad; - std::printf("FAIL %-26s T=%d rows=%d: %lld bits differ, %lld non-finite of %zu\n", c.name, T, r, diff, nonfinite, a.size()); - } - (void) used; + native_mmvq_il_pf(-1); if (bench && r != 0) { - best_il[r] = time_us([&](int i) { native_mmvq_il(c.type, dw[g_hot ? 0 : i % copies], xq, xil, yil, c.n_in, c.n_out, T, s); }, 200, s, gap); + auto il_call = [&](int i) { native_mmvq_il(c.type, dw[g_hot ? 0 : i % copies], xq, xil, yil, c.n_in, c.n_out, T, s); }; + if (g_pf.empty()) { + best_il[r] = time_us(il_call, 200, s, gap); + } else { // the variants interleaved, round after round; the median of each one's rounds + std::vector<std::vector<double>> t(g_pf.size()); + for (int round = 0; round < g_rounds; ++round) + for (std::size_t k = 0; k < g_pf.size(); ++k) { + native_mmvq_il_pf(g_pf[k]); + t[k].push_back(time_us(il_call, 100, s, gap)); + } + native_mmvq_il_pf(-1); + std::printf("PFBENCH %-26s T=%d rows=%d:", c.name, T, r); + for (std::size_t k = 0; k < g_pf.size(); ++k) { + std::sort(t[k].begin(), t[k].end()); + const double med = t[k][t[k].size() / 2]; + if (k == 0) best_il[r] = med; + pf_il[k][r] = med; + std::printf(" pf%d %.1f us (min %.1f max %.1f)", g_pf[k], med, t[k].front(), t[k].back()); + } + std::printf("\n"); + } } } native_mmvq_il_tune(0); if (bench) { best_ref = time_us([&](int i) { native_mmvq(c.type, dw[g_hot ? 0 : i % copies], xq, yref, c.n_in, c.n_out, T, s); }, 200, s, gap); (void) table_r; - g_cells.push_back({c.type, T, c.n_out, best_ref, {0, best_il[1], best_il[2], 0, best_il[4]}}); + if (g_pf.empty()) g_cells.push_back({c.type, T, c.n_out, -1, best_ref, {0, best_il[1], best_il[2], 0, best_il[4]}}); + for (std::size_t k = 0; k < g_pf.size(); ++k) + g_cells.push_back({c.type, T, c.n_out, g_pf[k], best_ref, {0, pf_il[k][1], pf_il[k][2], 0, pf_il[k][4]}}); std::printf("BENCH %-26s T=%d %-16s multi %.1f us | il rows1 %.1f rows2 %.1f rows4 %.1f us\n", c.name, T, arms[ai].name, best_ref, best_il[1], best_il[2], best_il[4]); } @@ -256,33 +292,37 @@ void emit_table() { std::printf("// measured on this card by mmvq_il_parity --bench --emit-table\n"); // per cell: the rows count whose WORST ratio to native_mmvq over the cell's measured shapes is the best, taken only // when that worst ratio is under 0.97 (else 0); a class with no measured shape takes its lower neighbour's value - auto pick_cell = [&](int type, int nc, int cls, int prev) { + // pf_sel: the cells of that variant (the environment's when --pf was not given, else 0 = today's kernel); -2: every + // listed variant, the answer then pf << 4 | rows (the kIlPf form), 0 when nothing beats native_mmvq by 3% + auto pick_cell = [&](int type, int nc, int cls, int prev, int pf_sel) { double best_worst = 1e9; int best = -1; bool any = false; - for (int r : {1, 2, 4}) { - double worst = 0; - bool have = false; - for (const Cell& c : g_cells) { - if (c.type != type || c.T != nc) continue; - const int cc = c.n_out < 2048 ? 0 : c.n_out < 4096 ? 1 : c.n_out < 8192 ? 2 : c.n_out < 12288 ? 3 : 4; - if (cc != cls || c.il[r] <= 0) continue; - have = true; - worst = std::max(worst, c.il[r] / c.ref); + for (int pf : (pf_sel == -2 ? (g_pf.empty() ? std::vector<int>{-1} : g_pf) : std::vector<int>{pf_sel})) + for (int r : {1, 2, 4}) { + double worst = 0; + bool have = false; + for (const Cell& c : g_cells) { + if (c.type != type || c.T != nc || c.pf != pf) continue; + const int cc = c.n_out < 2048 ? 0 : c.n_out < 4096 ? 1 : c.n_out < 8192 ? 2 : c.n_out < 12288 ? 3 : 4; + if (cc != cls || c.il[r] <= 0) continue; + have = true; + worst = std::max(worst, c.il[r] / c.ref); + } + any = any || have; + if (have && worst < best_worst) { best_worst = worst; best = pf_sel == -2 ? (std::max(pf, 0) << 4 | r) : r; } } - any = any || have; - if (have && worst < best_worst) { best_worst = worst; best = r; } - } if (!any) return prev; return best_worst < 0.97 ? best : 0; }; + const int pf_today = g_pf.empty() ? -1 : 0; for (int ti = 0; ti < 5; ++ti) { std::printf(" {%d, {", types[ti]); for (int nc = 2; nc <= 4; ++nc) { int prev = 0; std::printf("{"); for (int cls = 0; cls < 5; ++cls) { - prev = pick_cell(types[ti], nc, cls, prev); + prev = pick_cell(types[ti], nc, cls, prev, pf_today); std::printf("%d%s", prev, cls < 4 ? ", " : ""); } std::printf("}%s", nc < 4 ? ", " : ""); @@ -296,19 +336,49 @@ void emit_table() { int prev = 0; std::printf("{"); for (int cls = 0; cls < 5; ++cls) { - prev = pick_cell(types[ti], nc, cls, prev); + prev = pick_cell(types[ti], nc, cls, prev, pf_today); std::printf("%d%s", prev, cls < 4 ? ", " : ""); } std::printf("}%s", nc < 8 ? ", " : ""); } std::printf("}}, // %s\n", names[ti]); } + if (!g_pf.empty()) { // the joint (variant, rows) table over the listed variants: kIlPf_80 / kIlPf58_80 + std::printf("// variant << 4 | rows over --pf (kIlPf_<cc>), 2-4 columns:\n"); + for (int ti = 0; ti < 5; ++ti) { + std::printf(" {%d, {", types[ti]); + for (int nc = 2; nc <= 4; ++nc) { + int prev = 0; + std::printf("{"); + for (int cls = 0; cls < 5; ++cls) { + prev = pick_cell(types[ti], nc, cls, prev, -2); + std::printf("0x%02x%s", prev, cls < 4 ? ", " : ""); + } + std::printf("}%s", nc < 4 ? ", " : ""); + } + std::printf("}}, // %s\n", names[ti]); + } + std::printf("// 5-8 columns (kIlPf58_<cc>):\n"); + for (int ti = 0; ti < 5; ++ti) { + std::printf(" {%d, {", types[ti]); + for (int nc = 5; nc <= 8; ++nc) { + int prev = 0; + std::printf("{"); + for (int cls = 0; cls < 5; ++cls) { + prev = pick_cell(types[ti], nc, cls, prev, -2); + std::printf("0x%02x%s", prev, cls < 4 ? ", " : ""); + } + std::printf("}%s", nc < 8 ? ", " : ""); + } + std::printf("}}, // %s\n", names[ti]); + } + } std::printf("// one column (kIl1RowsShared):\n"); for (int ti = 0; ti < 5; ++ti) { std::printf(" {%d, {", types[ti]); int prev = 0; for (int cls = 0; cls < 5; ++cls) { - prev = pick_cell(types[ti], 1, cls, prev); + prev = pick_cell(types[ti], 1, cls, prev, pf_today); std::printf("%d%s", prev, cls < 4 ? ", " : ""); } std::printf("}}, // %s\n", names[ti]); @@ -342,6 +412,26 @@ int check_tables() { ++bad; std::printf("FAIL table: the sm_60 table is not the P100's\n"); } + // sm_80 has its own tables (kIlRows_80 / kIlRows58_80 / kIl1Rows_80: a CMP 170HX's); the key 81 is what STRATA_MMVQ_IL_SM80=0 + // gives an sm_80 card: no table of its own, so the shared one (and no one-column table). Every answer is 0, 1, 2 or 4. + { + bool differs = false; + for (int type : {23, 12, 13, 14, 11}) + for (int nc = 1; nc <= 8; ++nc) + for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) { + const int a = native_mmvq_il_rows_for(80, type, nc, n_out), b = native_mmvq_il_rows_for(81, type, nc, n_out); + if (a != 0 && a != 1 && a != 2 && a != 4) { ++bad; std::printf("FAIL table: sm_80 rows %d\n", a); } + differs = differs || a != b; + } + if (!differs) { ++bad; std::printf("FAIL table: sm_80 answers like the shared table\n"); } + // spot checks read off the source tables: Q6_K at 3 columns and 2560 rows (class 1) is {0, 2, 2, 2, 2}[1] = 2; one-column + // IQ4_XS at 6144 rows (class 2) is {0, 0, 1, 4, 1}[2] = 1 on sm_80 and 0 (no one-column table) on the key 81 + if (native_mmvq_il_rows_for(80, 14, 3, 2560) != 2 || native_mmvq_il_rows_for(80, 23, 1, 6144) != 1 || + native_mmvq_il_rows_for(81, 23, 1, 6144) != 0) { + ++bad; + std::printf("FAIL table: the sm_80 table is not the CMP 170HX's\n"); + } + } if (native_mmvq_il_rows_for(89, 99, 2, 2560) != 0 || native_mmvq_il_rows_for(89, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(86, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(120, 12, 9, 2560) != 0) { ++bad; @@ -354,12 +444,22 @@ int check_tables() { int main(int argc, char** argv) { const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; const bool emit = bench && argc > 2 && std::string(argv[2]) == "--emit-table"; - for (int i = 2; i < argc; ++i) { + for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; if (a == "--hot") g_hot = true; else if (a == "--ab") g_ab = true; else if (a == "--persist") g_persist = true; else if (a == "--gap" && i + 1 < argc) g_gap_bytes = (std::size_t) std::atoi(argv[++i]) << 20; + else if (a == "--rounds" && i + 1 < argc) g_rounds = std::atoi(argv[++i]); + else if (a == "--pf" && i + 1 < argc) { + const std::string list = argv[++i]; + for (std::size_t p = 0; p < list.size();) { + std::size_t q = list.find(',', p); + if (q == std::string::npos) q = list.size(); + g_pf.push_back(std::atoi(list.substr(p, q - p).c_str())); + p = q + 1; + } + } } cudaStream_t s; cudaStreamCreate(&s); From 56d98f164e6b146f0e228f3ebc5cc187117c8dd4 Mon Sep 17 00:00:00 2001 From: linxuhao <28365479+linxuhao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:57:16 +0100 Subject: [PATCH 176/177] docs: the sm_80 defaults and the opt-in sm_80 switches of #3779, STRATA_GRAPH_PRIO and STRATA_MMVQ_IL_PF (#3779, #3712) DETAILS.md gets two sections: the decode switches (GRAPH_PRIO, MMVQ_IL_PF) with the two sm_80-only defaults named, and the prompt switches (PF_FUSED_NT / BATCH / F16 / WS, GDN_TC, PLE_COMPACT / PLE_COPY_STREAM, EMBED_VRAM, DEQUANT_SIDE) with what is bitwise and what is rounding-level. MMVQ_IL_TABLE.md gets the sm_80 row of the table list and a paragraph on the hoisted-load tables (kIlPf_80 / kIlPf58_80, Q6_K only) and on measuring a card with mmvq_il_parity --bench --emit-table --pf 0,3,4. Rewritten from the PR's text: every figure is labelled as the reporter's (one CMP 170HX; we have no sm_80 card and measured none of them), and the prompt-switch section is new (the PR documented only the decode switches and the conversation cache). Original docs by linxuhao (PR #3779, commit 6d6f0f39). --- docs/DETAILS.md | 24 ++++++++++++++++++++++++ docs/MMVQ_IL_TABLE.md | 16 ++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1ce07f55..c6cb2f6e 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1420,3 +1420,27 @@ The times below were measured by the author of the change (linxuhao, PR #3779) o An independent user (bitaccesscomau, one RTX 3090 on PCIe 3.0 x16) tried the `STRATA_CKPT_ASYNC=1` commit on its own on 0.2.6: the checkpoint save went from 73.2 to 62.4 ms, the first token of a short prompt came about 13 ms of 350 ms sooner (median of 4 pairs), and the answers were byte-identical. On a fast link the gain is small. The serve loop's `strata trace:` lines (`STRATA_TRACE`) now end with `@<ms>`, a steady-clock timestamp. + +## CUDA opt-in decode switches measured on a CMP 170HX (sm_80; off unless you set them) + +The author of the change (linxuhao, PR #3779) measured these on one CMP 170HX (GA100, 70 SMs) with the Qwen3.8-Flash-Next IQ3_S native pack, `--spec 3`, decode after a prompt of about 3,000 words, a fresh engine per run, reference and switch runs interleaved. We have no sm_80 card and did not measure them. Both switches keep every output bit by construction (the greedy answers to 11 prompts were the same with the switch on and off, on their card). Neither does anything on HIP, gfx906 or Metal. + +| Switch | What | Answers | Reporter's figure (CMP 170HX) | +|---|---|---|---| +| `STRATA_GRAPH_PRIO=1` | The verify window graph's kernel nodes run at their capturing stream's priority (`cudaGraphInstantiateFlagUseNodePriority`): the GDN gates and the QSA indexer branch at the highest, the shared expert at the lowest. Nothing changes on a card whose priority range is 0..0. | bit-exact | decode +1.8 % with `STRATA_QIL=1` (both runs above every reference run) | +| `STRATA_MMVQ_IL_PF=1` | Hoisted-load, exact-integer kernels for the interleaved small-batch matvec where the sm_80 table picks them (Q6_K only so far, [MMVQ_IL_TABLE.md](MMVQ_IL_TABLE.md)). On a card that is not sm_80 the value 1 does nothing. `=2` to `=6` force one variant everywhere (A/B only). | bit-exact | decode +1.4 % (two reference / on / reference / on sets) | + +Two sm_80 defaults come with the same change and are on without a switch, only on a compute capability 8.0 card: the wide dense dequant kernels (`STRATA_DEQUANT_WIDE=0` turns them off) and the sm_80 rows tables of the interleaved matvec (`STRATA_MMVQ_IL_SM80=0` turns them off). Both are bitwise. The reporter's figures: prompt GPU time of a 3,259-token prompt 857 -> 792 ms for the dequant, decode +2.7..+3.2 % for the tables. + +## CUDA opt-in prompt switches for sm_80 cards (off unless you set them) + +Also from PR #3779, measured by its author on the same CMP 170HX; none of the figures was measured here. `STRATA_PF_FUSED_NT=256` and `STRATA_PF_BATCH=N` keep every output bit. `STRATA_PF_FUSED_F16=1`, `STRATA_PF_FUSED_WS=1` and `STRATA_GDN_TC=1` change the output at rounding level: the author's teacher-forced KL against the bitwise base on 20 prompts is mean 0.0062 (F16 / WS) and 0.0157 (GDN_TC), top-1 agreement 100 %. + +| Switch | What | Reporter's figure (CMP 170HX) | +|---|---|---| +| `STRATA_PF_FUSED_NT=256` | The fused prompt-expert kernels with 256 threads and two blocks a multiprocessor (bitwise). Adds device code to every CUDA build. | one MoE layer of 3,256 tokens 8.27 ms | +| `STRATA_PF_BATCH=N` | Up to N experts per launch (above 128 only with the 256-thread kernels; bitwise). | with NT=256: prompts +7.6 % (4K), +4.9 % (16K), +4.3 % (52K) | +| `STRATA_PF_FUSED_F16=1` | f16 mma instead of the int8 products in the 256-thread kernels (rounding level). | 7.90 ms for the same layer | +| `STRATA_PF_FUSED_WS=1` | Warp-specialized kernel with the same F16 products; needs about 101 KB of shared memory, so sm_80 and sm_90 only (it says "not available" elsewhere). | 7.65 ms for the same layer | +| `STRATA_GDN_TC=1` | The DeltaNet recurrence of a prompt as a chunked scan on the tensor cores; needs 122 KB of shared memory a block (sm_80, sm_90). | recurrence 105 -> 34 ms at 3.3K tokens; prompts +3.9 % (4K), +6.0 % (16K), +6.7 % (52K) | +| `STRATA_PLE_COMPACT=1`, `STRATA_PLE_COPY_STREAM=1`, `STRATA_EMBED_VRAM=1`, `STRATA_DEQUANT_SIDE=1` | The PLE rows go up raw and are dequantized on the card, on their own stream; the token-embedding table in VRAM; the dense dequant on a side stream (CUDA only). All bitwise. | prompts +2.2 % to +2.6 % for the four together | diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index 1f3bae10..c8e5a7fa 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -15,6 +15,7 @@ Which table a card gets: |---|---| | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | +| sm_80 (A100, A30, CMP 170HX) | `kIlRows_80`, `kIlRows58_80` and `kIl1Rows_80`, read off `--emit-table` by the author of PR #3779 on one CMP 170HX (not an A100: re-measure there); `STRATA_MMVQ_IL_SM80=0` gives the card the shared table again | | sm_89 (Ada) and every other sm_80+ card | `kIlRowsShared` too. Nobody has measured sm_89 yet (we have no such card). | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | @@ -34,3 +35,18 @@ Which table a card gets: The emit rule: per cell, the fastest rows count if it takes at least 3% off the plain kernel's time, else 0; shapes of one class that disagree give 0; a class with no measured shape copies its neighbour below. + +## The hoisted-load kernels (STRATA_MMVQ_IL_PF, sm_80 only so far) + +`STRATA_MMVQ_IL_PF=1` lets a second table pick, per cell, a variant of `native_mmvq_il` that issues every weight load of a +group before its dots and forms the dots as exact integers (`kIlPf_80` for 2-4 tokens and `kIlPf58_80` for 5-8, in +`src/kernels/cuda/native_mmvq.cu`; a cell is `variant << 4 | rows`, 0 = the rows table above with the plain kernel). Every +variant gives the same bits as the plain kernels. Only Q6_K has cells so far: on the CMP 170HX the variants tie the plain +kernel for Q4_K / Q5_K / IQ4_XS within the run-to-run noise. Unset or 0 keeps today's kernels; `=2` to `=6` run one variant +for every type and shape (A/B only). + +To measure a card: `build/mmvq_il_parity --bench --emit-table --pf 0,3,4` (`--emit-table` must come right after `--bench`). +Every listed variant is bit-checked against native_mmvq first, then timed interleaved per case (`--rounds N` rounds of 100 +calls, default 5; the median per variant on the `PFBENCH` lines). The last block (`variant << 4 | rows over --pf`) is in the +source form of `kIlPf_<cc>`. `il_pf_table` reads only sm_80's table today, so a new card's block also needs its lookup +there. Post the whole output on the issue. From 2579635138428041a2397009a8e042fd75911012 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:58:42 +0100 Subject: [PATCH 177/177] sm_80 defaults of #3779 (wide dense dequant, MMVQ-IL sm_80 tables) follow STRATA_DEFAULTS=026: back to the 0.2.6 kernels and the shared table; explicit =1 and =0 still win; arch_defaults_test checks the rule; release-notes line --- docs/MMVQ_IL_TABLE.md | 2 +- docs/release-notes-0.2.7.md | 4 +++- include/strata/core/sm120_series.hpp | 8 ++++++++ src/core/arch_defaults_test.cpp | 4 ++++ src/kernels/cuda/dequant_bf16.cu | 6 +++++- src/kernels/cuda/native_mmvq.cu | 2 +- 6 files changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index 5a2251d7..0d56273a 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -16,7 +16,7 @@ Which table a card gets: | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | | sm_89 (Ada) | `kIlRows_89`, ON by default on compute capability 8.9 cards only (0.2.7): the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. `STRATA_MMVQ_IL_89=0` or `STRATA_DEFAULTS=026` gives the shared table (`kIlRowsShared`) again, as in 0.2.6; an explicit `STRATA_MMVQ_IL_89=1` wins over the master switch. The output is bitwise the same either way (a table only changes how many rows a warp takes). Not measured on an Ada card by us: no sm_89 card has run `mmvq_il_parity` on this code, and the issue saw no end-to-end decode change on a 4090 or a 4080 (issue 3453), so the gain may be a microbenchmark one. The reporter tests 0.2.7 and reports back. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card. To check a card: run `mmvq_il_parity` on it (it must end with `OK`) and an interleaved decode A/B with the variable at 1 and 0. | -| sm_80 (A100, A30, CMP 170HX) | `kIlRows_80`, `kIlRows58_80` and `kIl1Rows_80`, read off `--emit-table` by the author of PR #3779 on one CMP 170HX (not an A100: re-measure there); `STRATA_MMVQ_IL_SM80=0` gives the card the shared table again | +| sm_80 (A100, A30, CMP 170HX) | `kIlRows_80`, `kIlRows58_80` and `kIl1Rows_80`, read off `--emit-table` by the author of PR #3779 on one CMP 170HX (not an A100: re-measure there); `STRATA_MMVQ_IL_SM80=0` or `STRATA_DEFAULTS=026` gives the card the shared table again | | every other sm_80+ card | `kIlRowsShared` | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 6a741600..9837b598 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -27,6 +27,8 @@ same bit for bit; only how many rows a warp takes changes. **We have not measured them on an RTX 40 card**: the tables come from two community runs (an RTX 4070 and an RTX 4080), and the report with the 4090 saw no change in decode speed. If you have an RTX 40 card, please try 0.2.7 and post your decode numbers on issue 3453. Off switch: `STRATA_MMVQ_IL_89=0`. + - NVIDIA A100 / A30 / CMP 170HX class cards (compute capability 8.0): the wide dense dequantizer and decode row tables of PR 3779, on by default, + same output bit for bit, measured only on a CMP 170HX by the contributor. Off switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_MMVQ_IL_SM80=0`. ## Going back to 0.2.6 @@ -38,7 +40,7 @@ Two switches bring back every default that 0.2.7 changed, in one step, for a tes the RAM store's spare slots and put and its settle after a prompt, the dense dequantizer, the F16 gate/up operand, the drafter's markov head and the head's column count, and the RDNA3 dense GEMM all go back to what 0.2.6 did. - **`STRATA_DEFAULTS=026`** (Qwen): the residency-biased routing, the wide and the stream-split hyper-connection reads, the int8 - prompt attention, the RTX 40 (sm_89) decode tables, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). + prompt attention, the RTX 40 (sm_89) and sm_80 decode tables and sm_80 dense dequantizer, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). Long prompts on the approximate read (`STRATA_KVA`) are off by default and stay as `STRATA_KVA` says. A variable or flag you set yourself (`DS4_ATTN_SLAB=N`, `STRATA_ROUTE_PRIOR=2`, `--experts 5`, `--prefill-chunk N`, `--pcie-frac`, diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index 2674b28c..bff1823b 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -72,6 +72,14 @@ inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { retu /// measured on an Ada card by us), off under STRATA_DEFAULTS=026 and in HIP builds. `cc` = 10 * major + minor as the engine resolves it. inline bool mmvq_il_89_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc == 89; } +/// The two sm_80-only defaults of 0.2.7 (#3779: the wide dense dequant and the MMVQ-IL sm_80 tables, both bitwise the old output, measured on a +/// CMP 170HX only) given the text of their variable (nullptr = unset): "1" on and "0" off win, unset is on unless STRATA_DEFAULTS=026. +inline bool sm80_default_on(const char* env, bool v026 = false) { + if (env != nullptr && env[0] == '1') return true; + if (env != nullptr && env[0] == '0') return false; + return !v026; +} + /// The answer for STRATA_MMVQ_IL_89 given the variable's text (nullptr = unset): "1" on and "0" off win over everything, anything else (unset, /// empty, other text) is the rule above. inline bool mmvq_il_89_resolve(const char* env, bool hip, int cc, bool v026 = false) { diff --git a/src/core/arch_defaults_test.cpp b/src/core/arch_defaults_test.cpp index 3195bbba..dfe22283 100644 --- a/src/core/arch_defaults_test.cpp +++ b/src/core/arch_defaults_test.cpp @@ -257,6 +257,10 @@ int main() { CHECK(mmvq_il_89_resolve("1", false, 89, true)); // an explicit =1 wins over the master switch CHECK(mmvq_il_89_resolve("1", false, 86, false)); // (the tables are only looked up for cc 89 anyway) CHECK(mmvq_il_89_resolve("", false, 89, false) && !mmvq_il_89_resolve("", false, 89, true)); // empty text: the rule + // #3779: the two sm_80-only defaults (wide dequant, MMVQ-IL sm_80 tables): on unless STRATA_DEFAULTS=026; "1" and "0" win + CHECK(sm80_default_on(nullptr, false) && !sm80_default_on(nullptr, true)); + CHECK(!sm80_default_on("0", false) && sm80_default_on("1", true)); + CHECK(sm80_default_on("", false) && !sm80_default_on("", true)); // GR_V3 and IMMA CHECK(gr_v3_default(false, 12, 0, false, 72.0 * GiB, false)); CHECK(!gr_v3_default(false, 12, 0, false, 72.0 * GiB, true)); diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index 00e1dd51..9764fe9b 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -5,6 +5,8 @@ #include "strata/kernels/dequant_bf16.hpp" #include "strata/core/tc_sm75.hpp" #include "strata/kernels/iq_kernels.hpp" +#include "strata/core/defaults_026.hpp" +#include "strata/core/sm120_series.hpp" #include <cuda_fp16.h> #include <cuda_runtime.h> @@ -294,7 +296,9 @@ bool dequant_wide_on() { int major = 0, minor = 0; if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { (void) cudaGetLastError(); return false; } - per_dev[dev] = (major == 6 && minor == 1) || (major == 8 && (minor == 6 || minor == 0)) ? 2 : 1; + // sm_80 is the 0.2.7 addition (#3779): STRATA_DEFAULTS=026 gives it the per-group kernels again, as 0.2.6 had + per_dev[dev] = (major == 6 && minor == 1) || (major == 8 && minor == 6) || + (major == 8 && minor == 0 && strata::sm80_default_on(nullptr, strata::qwen_defaults_026())) ? 2 : 1; } return per_dev[dev] == 2; } diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 62bc3c03..c806e163 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -3810,7 +3810,7 @@ int il_cc() { if (cc[dev] == 120 && cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && sms >= 80) cc[dev] = 1201; // STRATA_MMVQ_IL_SM80=0: an sm_80 card takes the shared table as before kIlRows_80 (A/B) - if (cc[dev] == 80) { const char* v = std::getenv("STRATA_MMVQ_IL_SM80"); if (v != nullptr && v[0] == '0') cc[dev] = 81; } + if (cc[dev] == 80 && !strata::sm80_default_on(std::getenv("STRATA_MMVQ_IL_SM80"), strata::qwen_defaults_026())) cc[dev] = 81; // =0 or STRATA_DEFAULTS=026 cudaGetLastError(); } return cc[dev];