diff --git a/bench/results/2026-10-07-v100-decode-kernels/README.md b/bench/results/2026-10-07-v100-decode-kernels/README.md new file mode 100644 index 00000000..f69d1ac6 --- /dev/null +++ b/bench/results/2026-10-07-v100-decode-kernels/README.md @@ -0,0 +1,102 @@ +# V100 (sm_70): three decode kernels that were built for other cards (2026-10-07) + +On a V100 a verify window's GPU work is mostly memory-bound GEMVs that ran at a third to a half of the card's HBM2 +bandwidth. Three kernels Strata already has for other cards are now Volta's defaults, each with exactly the old +arithmetic, so every output is bitwise the old one: + +| What | Was on sm_70 | Now on sm_70 | Switch (old path) | +| --- | --- | --- | --- | +| Routed experts in VRAM (`native_expert_grouped`) | the CUDA layout (mode 0) | gfx906's mode 8: the codebook grid and the group's q8_1 activations in shared memory, SwiGLU + q8_1 in the gate/up epilogue; IQ2_XXS gate/up added to it (CUDA only) | `STRATA_EXP_MODE=0` | +| Dense 2-4 column GEMVs and the head (`native_mmvq_il`) | `native_mmvq` (the interleaved kernel was sm_80+) | the interleaved kernel with a rows table read off a V100 | `STRATA_MMVQ_IL=0` | +| Hyper-connection read, up projection | `gr_up_multi_kernel` | gfx906's `gr_up_fast_kernel` (built for CUDA, now also writes the QFUSE q8_1 tail) | `STRATA_GR_FAST=0` | + +Every other card keeps what it ran: the new paths are picked only when the device is sm_70 (and gfx906 keeps its own +defaults). The idea of putting the lattice codebook in shared memory on Volta comes from 1Cat-vLLM's SM70 GGUF kernels +(`csrc/sm70_turbomind/ops/gguf_dp4a.cuh`); Strata's gfx906 kernels already did the same, so no 1Cat code was copied. + +## Rig + +- Tesla V100-SXM2-32GB (sm_70, PCIe gen3 x16), driver 580.159, a rented container (vast.ai): 2x Xeon Gold 6130, a + cgroup quota of ~15 CPUs, 180 GB RAM. CUDA 12.8, GCC 11.4, Ubuntu 22.04. +- Engine: `main` at `e8ca9af` (0.1.40.2) with this change, `-DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON`. +- Model: setup's IQ2_XS (`./setup.sh --cuda 12 --build --model IQ2_XS`), setup's config (`--spec 4 --kv int8 + --kv-resident 32768 --max-context 131072 --expert-cache auto`) plus `--pool-workers 14` (the container's quota; with + setup's default of 32 workers the pool is throttled and decode halves). + +## Kernels (synthetic or real rows, no engine) + +**Experts**, `native_expert_bench 28 T 0 8` (28 groups = a verify window's VRAM call, the model's +real rows; mode 0 vs mode 8, bitwise equal on all 48 layers): + +| Layer gate/up / down | T = 1 | T = 3 | +| --- | ---: | ---: | +| IQ2_S / Q2_0 (34 layers, e.g. 24) | 118.5 -> 104.8 us | 180.4 -> 150.4 us | +| IQ2_XXS / Q2_0 (11 layers, e.g. 10) | 117.6 -> 91.4 us | 169.9 -> 134.1 us | +| IQ1_M / Q2_0 (3 layers; gate/up keeps the CUDA layout) | | 159.0 -> 144.7 us | + +A strided call (the window's PCIe call, `grid_groups` 1..cap) keeps the CUDA layout: the AMD layouts launch a block +row per possible group, which cost the empty call 11.3 vs 6.5 us. A format without a shared-memory kernel falls back +to the CUDA layout on CUDA, not to R2 (R2 on IQ2_XXS gate/up: 183 vs 113 us). The nib_mask sign handling gfx906 uses +was also the faster one here (158.5 vs 162.2 us on `native_grouped_parity --bench`'s VRAM call). + +**Dense GEMVs**, `mmvq_il_parity --bench` (two runs, mean; `il_rows1/2/4` all bitwise `native_mmvq`'s output), a few +of the cells the table picks (3 columns): + +| Shape | `native_mmvq` | interleaved | +| --- | ---: | ---: | +| Q5_K head 2560 x 248,320 | 1,094 us | 821 us (rows 2) | +| Q6_K 2560 x 12,288 | 68.9 us | 47.9 us (rows 2) | +| Q4_K 2560 x 10,240 | 43.9 us | 32.5 us (rows 2) | +| IQ4_XS 2560 x 6,144 | 28.2 us | 19.3 us (rows 2) | +| Q6_K 2560 x 512 | 7.0 us | 9.2 us (rows 2): the table keeps `native_mmvq` below 2,048 rows | + +**Hyper-connection read**, `fused_gr_bench` (bitwise): the fast norm/up take 4-6 us off a 51-72 us read in the +plain variant. The engine runs the staged variant, whose norm is the split one, so only the up projection changes +there (below). + +## Engine: GPU time per verify window + +`STRATA_DECODE_TIMING=1 STRATA_VERIFY_PROFILE=1`, `tools/ab_engine.py`: one server start per arm and round, the arms' +order alternating, 3 rounds; per round three short chats (256 tokens) and one 6,345-token prompt (122-128 tokens). +`orig` is `e8ca9af` as setup built it, `off` this branch with the three switches above set to the old paths, `v70` +this branch. Medians over the rounds of the engine's own stage table (ms per window, GDN + QSA layers): + +| Stage | orig | off | v70 | +| --- | ---: | ---: | ---: | +| VRAM hits (routed experts) | 4.50 | 4.44 | 3.73 | +| q8 + qkv / q-idx GEMV | 1.60 | 1.57 | 1.40 | +| z | 1.03 | 1.02 | 0.87 | +| head | 0.99 | 0.97 | 0.69 | +| hc-read0 up | 1.08 | 1.08 | 0.96 | +| q + q-idx | 0.76 | 0.75 | 0.68 | +| out-proj | 1.35 | 1.34 | 1.40 | +| everything else on the GPU | 11.49 | 11.49 | 11.51 | +| **GPU work, the waits (A, B, CPU) left out** | **22.80** | **22.66** | **21.24 (-6.8%)** | + +Decode tokens per second over the same runs (medians): + +| Request | orig | off | v70 | +| --- | ---: | ---: | ---: | +| chat 0 | 65.8 | 67.1 | 74.7 | +| chat 1 | 55.0 | 58.1 | 62.7 | +| chat 2 | 57.1 | 58.0 | 59.7 | +| 6,345-token prompt | 52.3 | 48.7 | 52.5 | + +**These decode numbers are noisy and mostly CPU-bound on this rig**: the windows' `waitCPU` (the GPU waiting for the +CPU experts) was 0.3 ms in some server starts and 6-9 ms in others, whatever the arm, which moves decode by 25-30%. +The GPU-side table above is the reliable comparison; on a PC whose CPU keeps up, the window is shorter by about the +1.5 ms it saves. Prompt speed (1,360-1,390 tok/s) does not change: the prompt path uses none of these kernels. + +## Output checks + +Each change keeps the old sums in the old order, so the engine's output is unchanged by construction; checked with: + +- `native_expert_bench` on all 48 layers of the IQ2_XS shard, T = 1-4: mode 8 bitwise mode 0. +- `native_grouped_parity` (every gate/up x down format, window shapes, `STRATA_EXP_MODE` 0, 2, 7, 8): 0 failures. +- `mmvq_il_parity`: OK (every case, T 2-4, rows 1/2/4 and the table, bitwise); `mmvq_multi_parity`: ok. +- `fused_gr_bench` (fast vs old, bitwise), `gr_multi_parity` OK, `gr_parity` 0 failures. +- The whole `ctest` on the V100 (`-DSTRATA_BUILD_TESTS=ON`): 124 passed, 2 skipped (`prefill_fused_*`, sm_80+), 3 failed + for this rig, not the change: `expert_multi_test` (the CPU has no AVX512-VNNI), `platform_memory_test` (`mlock` in + the container), `ple_parity` (wants the Q2_0 pack's second shard; this rig has IQ2_XS). + +Raw: `stage-profile.txt` (the engine's stage lines of every run above), `mmvq-il-bench-v100.txt` (both bench runs). diff --git a/bench/results/2026-10-07-v100-decode-kernels/mmvq-il-bench-v100.txt b/bench/results/2026-10-07-v100-decode-kernels/mmvq-il-bench-v100.txt new file mode 100644 index 00000000..5ee5f9eb --- /dev/null +++ b/bench/results/2026-10-07-v100-decode-kernels/mmvq-il-bench-v100.txt @@ -0,0 +1,96 @@ +BENCH IQ4_XS 2560x10240 T=2 multi 33.3 us | il rows1 28.9 rows2 25.3 rows4 26.7 us +BENCH IQ4_XS 2560x10240 T=3 multi 42.4 us | il rows1 29.9 rows2 26.8 rows4 28.3 us +BENCH IQ4_XS 2560x10240 T=4 multi 52.6 us | il rows1 32.2 rows2 30.7 rows4 33.0 us +BENCH IQ4_XS 2560x6144 T=2 multi 22.5 us | il rows1 19.7 rows2 17.8 rows4 21.5 us +BENCH IQ4_XS 2560x6144 T=3 multi 27.2 us | il rows1 20.5 rows2 18.9 rows4 19.9 us +BENCH IQ4_XS 2560x6144 T=4 multi 33.7 us | il rows1 21.6 rows2 21.0 rows4 22.8 us +BENCH IQ4_XS 4096x2560 T=2 multi 14.0 us | il rows1 13.8 rows2 10.8 rows4 13.7 us +BENCH IQ4_XS 4096x2560 T=3 multi 16.6 us | il rows1 13.7 rows2 10.8 rows4 13.3 us +BENCH IQ4_XS 4096x2560 T=4 multi 19.7 us | il rows1 15.3 rows2 13.6 rows4 12.6 us +BENCH IQ4_XS 2560x512 T=2 multi 5.0 us | il rows1 6.1 rows2 5.4 rows4 9.4 us +BENCH IQ4_XS 2560x512 T=3 multi 5.5 us | il rows1 5.7 rows2 5.9 rows4 7.9 us +BENCH IQ4_XS 2560x512 T=4 multi 6.1 us | il rows1 6.2 rows2 6.2 rows4 8.2 us +BENCH Q4_K 2560x10240 T=2 multi 36.5 us | il rows1 31.2 rows2 29.0 rows4 25.6 us +BENCH Q4_K 2560x10240 T=3 multi 43.7 us | il rows1 38.2 rows2 32.5 rows4 39.9 us +BENCH Q4_K 2560x10240 T=4 multi 54.5 us | il rows1 41.9 rows2 38.2 rows4 50.8 us +BENCH Q4_K 4096x2560 T=2 multi 15.2 us | il rows1 18.4 rows2 13.3 rows4 14.5 us +BENCH Q4_K 4096x2560 T=3 multi 17.7 us | il rows1 18.8 rows2 14.0 rows4 24.9 us +BENCH Q4_K 4096x2560 T=4 multi 21.0 us | il rows1 20.0 rows2 15.5 rows4 25.0 us +BENCH Q4_K odd rows 2560x2051 T=2 multi 10.4 us | il rows1 11.5 rows2 9.0 rows4 9.9 us +BENCH Q4_K odd rows 2560x2051 T=3 multi 11.9 us | il rows1 12.6 rows2 9.4 rows4 16.3 us +BENCH Q4_K odd rows 2560x2051 T=4 multi 14.3 us | il rows1 13.2 rows2 10.6 rows4 16.2 us +BENCH Q5_K 2560x12288 T=2 multi 46.5 us | il rows1 42.5 rows2 37.0 rows4 40.1 us +BENCH Q5_K 2560x12288 T=3 multi 55.8 us | il rows1 50.5 rows2 42.0 rows4 46.3 us +BENCH Q5_K 2560x12288 T=4 multi 70.6 us | il rows1 57.8 rows2 54.9 rows4 69.6 us +BENCH Q5_K 2560x6144 T=2 multi 26.9 us | il rows1 25.4 rows2 23.1 rows4 26.5 us +BENCH Q5_K 2560x6144 T=3 multi 30.7 us | il rows1 29.2 rows2 24.9 rows4 26.4 us +BENCH Q5_K 2560x6144 T=4 multi 36.5 us | il rows1 30.1 rows2 29.8 rows4 36.5 us +BENCH Q5_K 4096x2560 T=2 multi 17.4 us | il rows1 18.9 rows2 15.1 rows4 18.9 us +BENCH Q5_K 4096x2560 T=3 multi 19.5 us | il rows1 21.4 rows2 16.0 rows4 18.7 us +BENCH Q5_K 4096x2560 T=4 multi 22.4 us | il rows1 19.6 rows2 22.2 rows4 27.0 us +BENCH Q5_K head 2560x248320 T=2 multi 882.1 us | il rows1 818.3 rows2 713.2 rows4 716.5 us +BENCH Q5_K head 2560x248320 T=3 multi 1094.5 us | il rows1 922.6 rows2 820.9 rows4 828.8 us +BENCH Q5_K head 2560x248320 T=4 multi 1378.2 us | il rows1 1096.8 rows2 1027.3 rows4 1172.5 us +BENCH Q6_K 2560x12288 T=2 multi 57.3 us | il rows1 51.0 rows2 52.7 rows4 70.7 us +BENCH Q6_K 2560x12288 T=3 multi 69.4 us | il rows1 59.9 rows2 48.5 rows4 64.4 us +BENCH Q6_K 2560x12288 T=4 multi 81.0 us | il rows1 64.2 rows2 58.3 rows4 63.2 us +BENCH Q6_K 2560x10240 T=2 multi 50.8 us | il rows1 45.0 rows2 49.6 rows4 69.1 us +BENCH Q6_K 2560x10240 T=3 multi 58.5 us | il rows1 52.3 rows2 43.4 rows4 50.5 us +BENCH Q6_K 2560x10240 T=4 multi 67.9 us | il rows1 54.6 rows2 51.8 rows4 51.1 us +BENCH Q6_K 4096x2560 T=2 multi 20.3 us | il rows1 19.7 rows2 24.1 rows4 43.6 us +BENCH Q6_K 4096x2560 T=3 multi 23.9 us | il rows1 32.3 rows2 19.3 rows4 28.1 us +BENCH Q6_K 4096x2560 T=4 multi 25.8 us | il rows1 29.6 rows2 22.6 rows4 24.3 us +BENCH Q6_K odd rows 2560x2051 T=2 multi 13.1 us | il rows1 11.7 rows2 15.0 rows4 27.0 us +BENCH Q6_K odd rows 2560x2051 T=3 multi 14.3 us | il rows1 13.4 rows2 12.1 rows4 17.8 us +BENCH Q6_K odd rows 2560x2051 T=4 multi 16.9 us | il rows1 17.5 rows2 14.0 rows4 15.2 us +BENCH Q6_K 2560x512 T=2 multi 6.7 us | il rows1 9.0 rows2 11.4 rows4 23.7 us +BENCH Q6_K 2560x512 T=3 multi 7.0 us | il rows1 11.4 rows2 9.1 rows4 15.5 us +BENCH Q6_K 2560x512 T=4 multi 7.3 us | il rows1 9.2 rows2 10.2 rows4 14.4 us +BENCH IQ4_XS 2560x10240 T=2 multi 33.2 us | il rows1 28.8 rows2 25.3 rows4 26.6 us +BENCH IQ4_XS 2560x10240 T=3 multi 42.6 us | il rows1 30.1 rows2 26.9 rows4 28.7 us +BENCH IQ4_XS 2560x10240 T=4 multi 53.9 us | il rows1 32.3 rows2 31.0 rows4 33.7 us +BENCH IQ4_XS 2560x6144 T=2 multi 22.2 us | il rows1 20.0 rows2 17.6 rows4 21.4 us +BENCH IQ4_XS 2560x6144 T=3 multi 26.9 us | il rows1 20.3 rows2 18.6 rows4 19.9 us +BENCH IQ4_XS 2560x6144 T=4 multi 33.4 us | il rows1 21.4 rows2 20.7 rows4 22.5 us +BENCH IQ4_XS 4096x2560 T=2 multi 14.0 us | il rows1 13.8 rows2 10.7 rows4 13.5 us +BENCH IQ4_XS 4096x2560 T=3 multi 16.5 us | il rows1 13.4 rows2 10.8 rows4 13.2 us +BENCH IQ4_XS 4096x2560 T=4 multi 19.5 us | il rows1 15.3 rows2 13.5 rows4 12.4 us +BENCH IQ4_XS 2560x512 T=2 multi 5.0 us | il rows1 6.0 rows2 5.3 rows4 9.4 us +BENCH IQ4_XS 2560x512 T=3 multi 5.6 us | il rows1 5.7 rows2 5.9 rows4 7.9 us +BENCH IQ4_XS 2560x512 T=4 multi 6.1 us | il rows1 6.1 rows2 6.2 rows4 8.2 us +BENCH Q4_K 2560x10240 T=2 multi 36.3 us | il rows1 31.1 rows2 29.0 rows4 25.6 us +BENCH Q4_K 2560x10240 T=3 multi 43.0 us | il rows1 38.5 rows2 32.1 rows4 39.4 us +BENCH Q4_K 2560x10240 T=4 multi 55.1 us | il rows1 41.0 rows2 37.5 rows4 51.1 us +BENCH Q4_K 4096x2560 T=2 multi 15.1 us | il rows1 18.3 rows2 13.3 rows4 14.5 us +BENCH Q4_K 4096x2560 T=3 multi 17.7 us | il rows1 18.8 rows2 14.0 rows4 24.9 us +BENCH Q4_K 4096x2560 T=4 multi 21.1 us | il rows1 20.0 rows2 15.6 rows4 25.0 us +BENCH Q4_K odd rows 2560x2051 T=2 multi 10.4 us | il rows1 11.5 rows2 9.1 rows4 9.9 us +BENCH Q4_K odd rows 2560x2051 T=3 multi 11.9 us | il rows1 12.7 rows2 9.4 rows4 16.3 us +BENCH Q4_K odd rows 2560x2051 T=4 multi 14.4 us | il rows1 13.2 rows2 10.6 rows4 16.3 us +BENCH Q5_K 2560x12288 T=2 multi 46.2 us | il rows1 42.6 rows2 37.0 rows4 39.6 us +BENCH Q5_K 2560x12288 T=3 multi 55.8 us | il rows1 50.6 rows2 42.5 rows4 46.5 us +BENCH Q5_K 2560x12288 T=4 multi 68.6 us | il rows1 57.1 rows2 54.4 rows4 69.4 us +BENCH Q5_K 2560x6144 T=2 multi 25.6 us | il rows1 24.8 rows2 22.6 rows4 25.4 us +BENCH Q5_K 2560x6144 T=3 multi 30.0 us | il rows1 27.7 rows2 23.7 rows4 25.1 us +BENCH Q5_K 2560x6144 T=4 multi 36.9 us | il rows1 29.7 rows2 29.9 rows4 36.7 us +BENCH Q5_K 4096x2560 T=2 multi 17.4 us | il rows1 18.9 rows2 15.1 rows4 18.8 us +BENCH Q5_K 4096x2560 T=3 multi 19.5 us | il rows1 21.4 rows2 16.0 rows4 18.6 us +BENCH Q5_K 4096x2560 T=4 multi 22.8 us | il rows1 19.5 rows2 22.6 rows4 27.4 us +BENCH Q5_K head 2560x248320 T=2 multi 882.1 us | il rows1 816.8 rows2 713.1 rows4 715.5 us +BENCH Q5_K head 2560x248320 T=3 multi 1105.0 us | il rows1 930.4 rows2 820.9 rows4 833.2 us +BENCH Q5_K head 2560x248320 T=4 multi 1378.6 us | il rows1 1096.7 rows2 1024.5 rows4 1177.9 us +BENCH Q6_K 2560x12288 T=2 multi 58.4 us | il rows1 53.4 rows2 54.9 rows4 72.9 us +BENCH Q6_K 2560x12288 T=3 multi 69.9 us | il rows1 60.4 rows2 48.5 rows4 64.8 us +BENCH Q6_K 2560x12288 T=4 multi 80.9 us | il rows1 64.6 rows2 58.4 rows4 63.3 us +BENCH Q6_K 2560x10240 T=2 multi 47.2 us | il rows1 42.7 rows2 47.4 rows4 65.7 us +BENCH Q6_K 2560x10240 T=3 multi 57.6 us | il rows1 49.1 rows2 41.8 rows4 49.1 us +BENCH Q6_K 2560x10240 T=4 multi 68.0 us | il rows1 54.5 rows2 51.9 rows4 51.2 us +BENCH Q6_K 4096x2560 T=2 multi 20.8 us | il rows1 20.1 rows2 24.6 rows4 44.7 us +BENCH Q6_K 4096x2560 T=3 multi 24.5 us | il rows1 33.3 rows2 19.8 rows4 28.7 us +BENCH Q6_K 4096x2560 T=4 multi 27.1 us | il rows1 30.5 rows2 23.1 rows4 25.3 us +BENCH Q6_K odd rows 2560x2051 T=2 multi 13.3 us | il rows1 11.8 rows2 15.0 rows4 27.3 us +BENCH Q6_K odd rows 2560x2051 T=3 multi 14.6 us | il rows1 13.5 rows2 12.2 rows4 18.0 us +BENCH Q6_K odd rows 2560x2051 T=4 multi 16.9 us | il rows1 17.7 rows2 14.1 rows4 15.4 us +BENCH Q6_K 2560x512 T=2 multi 6.7 us | il rows1 9.1 rows2 11.3 rows4 23.7 us +BENCH Q6_K 2560x512 T=3 multi 7.0 us | il rows1 11.5 rows2 9.1 rows4 15.5 us +BENCH Q6_K 2560x512 T=4 multi 7.4 us | il rows1 9.3 rows2 10.3 rows4 14.4 us diff --git a/bench/results/2026-10-07-v100-decode-kernels/stage-profile.txt b/bench/results/2026-10-07-v100-decode-kernels/stage-profile.txt new file mode 100644 index 00000000..13f0c22b --- /dev/null +++ b/bench/results/2026-10-07-v100-decode-kernels/stage-profile.txt @@ -0,0 +1,9 @@ +ab_off_r0.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.54 conv 0.18 ab 0.36 z 1.00 rec 0.49 out-proj 0.96 hc-read1+router 2.80 shared+quant 1.30 waitA 1.90 VRAM hits 3.18 waitB 0.45 PCIe grp 0.31 waitCPU 6.28 copy+combine 0.49 (gap) 0.05 head 0.95 hc0 norm 0.47 hc0 down 0.77 hc0 up 0.78 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.73 scores+topk 0.56 kv-resolve 0.34 attention 0.60 gate 0.05 out-proj 0.36 hc-read1+router 0.96 shared+quant 0.44 waitA 0.15 VRAM hits 1.04 waitB 0.19 PCIe grp 0.11 waitCPU 2.90 copy+combine 0.17 (gap) 0.02 hc0 norm 0.10 hc0 down 0.26 hc0 up 0.26 | total 34.01 ms/window over 62 windows +ab_off_r1.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.59 conv 0.18 ab 0.36 z 1.03 rec 0.49 out-proj 0.98 hc-read1+router 2.88 shared+quant 1.32 waitA 1.74 VRAM hits 3.39 waitB 0.73 PCIe grp 0.32 waitCPU 6.99 copy+combine 0.50 (gap) 0.05 head 0.98 hc0 norm 0.48 hc0 down 0.80 hc0 up 0.81 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.76 scores+topk 0.57 kv-resolve 0.36 attention 0.62 gate 0.05 out-proj 0.37 hc-read1+router 0.99 shared+quant 0.45 waitA 0.18 VRAM hits 1.10 waitB 0.32 PCIe grp 0.11 waitCPU 3.31 copy+combine 0.18 (gap) 0.02 hc0 norm 0.10 hc0 down 0.27 hc0 up 0.27 | total 36.17 ms/window over 68 windows +ab_off_r2.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.57 conv 0.18 ab 0.36 z 1.02 rec 0.50 out-proj 0.97 hc-read1+router 2.85 shared+quant 1.30 waitA 1.63 VRAM hits 3.35 waitB 0.65 PCIe grp 0.32 waitCPU 6.18 copy+combine 0.50 (gap) 0.05 head 0.97 hc0 norm 0.47 hc0 down 0.79 hc0 up 0.81 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.75 scores+topk 0.56 kv-resolve 0.36 attention 0.62 gate 0.05 out-proj 0.37 hc-read1+router 0.97 shared+quant 0.45 waitA 0.16 VRAM hits 1.09 waitB 0.30 PCIe grp 0.11 waitCPU 2.55 copy+combine 0.18 (gap) 0.02 hc0 norm 0.10 hc0 down 0.26 hc0 up 0.27 | total 34.15 ms/window over 69 windows +ab_orig_r0.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.64 conv 0.19 ab 0.38 z 1.06 rec 0.52 out-proj 1.00 hc-read1+router 2.93 shared+quant 1.33 waitA 2.01 VRAM hits 3.53 waitB 0.55 PCIe grp 0.31 waitCPU 8.34 copy+combine 0.53 (gap) 0.05 head 1.01 hc0 norm 0.49 hc0 down 0.81 hc0 up 0.82 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.24 kv+idx append 0.16 q+q-idx 0.78 scores+topk 0.57 kv-resolve 0.38 attention 0.64 gate 0.05 out-proj 0.38 hc-read1+router 1.00 shared+quant 0.45 waitA 0.17 VRAM hits 1.16 waitB 0.20 PCIe grp 0.11 waitCPU 3.48 copy+combine 0.19 (gap) 0.02 hc0 norm 0.10 hc0 down 0.27 hc0 up 0.27 | total 38.26 ms/window over 72 windows +ab_orig_r1.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.60 conv 0.18 ab 0.37 z 1.03 rec 0.50 out-proj 0.98 hc-read1+router 2.85 shared+quant 1.30 waitA 1.43 VRAM hits 3.39 waitB 0.62 PCIe grp 0.32 waitCPU 0.24 copy+combine 0.48 (gap) 0.05 head 0.99 hc0 norm 0.48 hc0 down 0.79 hc0 up 0.81 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.76 scores+topk 0.57 kv-resolve 0.33 attention 0.62 gate 0.05 out-proj 0.37 hc-read1+router 0.97 shared+quant 0.45 waitA 0.15 VRAM hits 1.11 waitB 0.26 PCIe grp 0.11 waitCPU 0.07 copy+combine 0.17 (gap) 0.02 hc0 norm 0.10 hc0 down 0.26 hc0 up 0.27 | total 25.56 ms/window over 69 windows +ab_orig_r2.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.58 conv 0.19 ab 0.37 z 1.03 rec 0.49 out-proj 0.97 hc-read1+router 2.84 shared+quant 1.30 waitA 1.61 VRAM hits 3.39 waitB 0.57 PCIe grp 0.32 waitCPU 6.50 copy+combine 0.49 (gap) 0.05 head 0.98 hc0 norm 0.48 hc0 down 0.79 hc0 up 0.81 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.75 scores+topk 0.56 kv-resolve 0.33 attention 0.62 gate 0.05 out-proj 0.37 hc-read1+router 0.97 shared+quant 0.45 waitA 0.17 VRAM hits 1.10 waitB 0.26 PCIe grp 0.11 waitCPU 2.95 copy+combine 0.17 (gap) 0.02 hc0 norm 0.10 hc0 down 0.26 hc0 up 0.27 | total 34.78 ms/window over 68 windows +ab_v70_r0.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.40 conv 0.18 ab 0.37 z 0.87 rec 0.50 out-proj 1.01 hc-read1+router 2.80 shared+quant 1.34 waitA 1.69 VRAM hits 2.81 waitB 0.48 PCIe grp 0.34 waitCPU 7.81 copy+combine 0.51 (gap) 0.05 head 0.69 hc0 norm 0.48 hc0 down 0.76 hc0 up 0.72 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.68 scores+topk 0.56 kv-resolve 0.38 attention 0.61 gate 0.05 out-proj 0.39 hc-read1+router 0.96 shared+quant 0.46 waitA 0.17 VRAM hits 0.91 waitB 0.20 PCIe grp 0.12 waitCPU 3.31 copy+combine 0.18 (gap) 0.02 hc0 norm 0.10 hc0 down 0.25 hc0 up 0.24 | total 34.91 ms/window over 66 windows +ab_v70_r1.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.40 conv 0.18 ab 0.37 z 0.87 rec 0.50 out-proj 1.00 hc-read1+router 2.79 shared+quant 1.34 waitA 1.51 VRAM hits 2.82 waitB 0.48 PCIe grp 0.33 waitCPU 0.27 copy+combine 0.50 (gap) 0.05 head 0.69 hc0 norm 0.47 hc0 down 0.77 hc0 up 0.72 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.24 kv+idx append 0.16 q+q-idx 0.67 scores+topk 0.56 kv-resolve 0.37 attention 0.60 gate 0.05 out-proj 0.39 hc-read1+router 0.97 shared+quant 0.46 waitA 0.17 VRAM hits 0.91 waitB 0.21 PCIe grp 0.12 waitCPU 0.10 copy+combine 0.17 (gap) 0.02 hc0 norm 0.10 hc0 down 0.26 hc0 up 0.24 | total 23.96 ms/window over 66 windows +ab_v70_r2.log strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 1.40 conv 0.18 ab 0.37 z 0.88 rec 0.50 out-proj 1.05 hc-read1+router 2.82 shared+quant 1.35 waitA 1.70 VRAM hits 2.89 waitB 0.41 PCIe grp 0.33 waitCPU 5.60 copy+combine 0.50 (gap) 0.05 head 0.70 hc0 norm 0.48 hc0 down 0.78 hc0 up 0.73 | QSA layers: q8+kv-idx 0.11 k/v+norm-rope 0.23 kv+idx append 0.16 q+q-idx 0.68 scores+topk 0.57 kv-resolve 0.40 attention 0.62 gate 0.05 out-proj 0.39 hc-read1+router 0.97 shared+quant 0.46 waitA 0.17 VRAM hits 0.93 waitB 0.15 PCIe grp 0.11 waitCPU 2.98 copy+combine 0.17 (gap) 0.02 hc0 norm 0.10 hc0 down 0.26 hc0 up 0.24 | total 32.50 ms/window over 71 windows diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 4cc98377..9de6d5c4 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -836,7 +836,10 @@ print(r.choices[0].message.content) - **From the internet.** Put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/): `cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC: add `"api_key": "some-long-secret"` to `strata-.json` (or set the `STRATA_API_KEY` environment variable); - clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass + clients then send it as their API key. Several keys (one per client, so one can be withdrawn alone): separate them + with commas, `--api-key key1,key2` or `"api_key": "key1,key2"` as llama.cpp does, or give a list, + `"api_key": ["key1", "key2"]` (the way to use a key that contains a comma); a request passes with any one of them. + Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`. With the key set, any `Host` name reaches the server (see Host names below). @@ -1417,6 +1420,37 @@ expert here: none was page-locked): A coding agent's recorded conversation on the two cards (a 100K-token start, then 8 turns of 1-5K tokens of code, 128 tokens written a turn, the same tokens read by both): 137.4 s off, 130.6 s auto (reading 121.1 -> 114.3 s). +## More opt-in switches measured for 0.1.41 (all off unless you set them) + +None of these changes the default answers; each was measured against the default with interleaved off/on pairs of whole +engine runs (a fresh engine per side, warmed, 200-token greedy answers on three fixed prompts, medians; "pairs faster" counts +the pairs in which the switched arm won). They are here so you can try them on your own card. + +- **`STRATA_GDN_CHUNKED=1`: the DeltaNet recurrence of the prompt in chunks of 32 tokens** (sergiywith, #1372; WY form, FP32, + other bits than the default: first-token KL against the default was 0.002-0.009 nats on average, the same top token in + every prompt tried). The kernel needs 128 SMs in one wave, so by itself it runs only on a card with 128 or more + (RTX 5090: 1.8x on the recurrence). On smaller cards `STRATA_GDN_CHUNKED=2` forces it for a measurement, and it is + slower there: 0.73x on an RTX 3060 (28 SMs) and 0.87x on an RTX 5070 (48 SMs) at 2K-32K tokens (`gdn_rec_parity --bench`), + and the prompt time did not improve: RTX 5070 2K 1.01x, 8K 1.00x of the default's time; RTX 3060 2K, 8K, 16K 1.01x, no pair faster. +- **`STRATA_FS_SLOTS=N`: the Foresight swap space** (q8atnight, #1348): N VRAM slots per layer, refilled on a copy stream + with the experts that just missed and with the ones the next layer's router predicts (`STRATA_FS_AHEAD=0` for the + misses only), so that an expert the cache lacks can be computed on the GPU instead of by the CPU. The model's own router + decides everything; the slots only hold copies of the same bytes (`STRATA_FS_VERIFY=1` reads every landed slot back and + compares it: 0 bad in 2,300+ reads on an RTX 5070). The slots are taken from the VRAM the expert cache would have + (raise `--vram-reserve-mib` by about N x 80 MiB), and in every box measured the smaller cache cost more than the slots + returned: decode 4 slots, median tok/s B/A (pairs faster): RTX 3060 0.95 (0/6) with misses only, 0.91 (0/6) with the + look-ahead; Tesla P100 0.97 (2/6) and 1.00 (4/6); 16 slots on the P100 0.96 (0/6); RTX 5070 0.98 (1/6). The reporter + measured the same on 2x RTX 3090 (the misses per layer are below one there, so the CPU round trip stays). Left off. +- **`STRATA_STAGE_PIN`: pinned stage buffers** (Zhong Uncle, #1237; **on by default** while the host has 3 GiB of RAM to + spare, `STRATA_STAGE_PIN=0` turns it off, `=1` pins without the RAM check). Where the experts are served from the GGUF in + place (`--mmap-experts`, or too little RAM for the arena) the buffers the cache fill copies from are page-locked, so the + copy no longer goes through the driver's bounce buffer (about 0.4-0.6 GiB of pinned RAM, one buffer falls back to + pageable when the driver refuses). Decode, median tok/s on, off, 6 pairs of whole runs: Tesla P100 with the RAM capped at + 24 GB (cgroup) 13.9 -> 15.0 (+8%, 6/6 pairs faster); RTX 5070 `--mmap-experts` +1.2% (5/6); RTX 3060 `--mmap-experts` + -0.1% (5/6). Boxes that hold all experts in RAM never use the stage buffers. +- **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100 + (PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in. + --- ## Experimental speed projection (EXPERIMENTAL, off by default) @@ -1483,6 +1517,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). | | `no progress for 60 s ... reading the prompt` on Linux, and the stall report says `threads waiting on the disk (state D): 16 ...` | The engine waits for the drive, not a deadlock: the n-gram table is read at random (`--ple-io direct`), which a rotational disk cannot keep up with (#605). The engine warns at start when the table is on one; `--ple-io ram` (Linux, needs RAM for the table) or the model on an SSD fixes it. Setup adds `--ple-io ram` itself on a rotational disk when the RAM holds the table (0.1.39). | | `the engine said nothing for ... s during the request` or `... did not finish the request after it was stopped (STOP)` | Issue #481: the engine and the server lost step (the engine waits for its next command, the server for the request's end; GPU at 0 %, nothing in the log). The server ends the engine after 300 s without a line from it during a request (while a prompt is read: each chunk may take three times the previous one's time, the first one up to its tokens at 50 tok/s more), the request ends with an error and the next request starts the engine again. `"engine_silence_s": 600` in `strata-.json` sets the time (0 = wait forever, as before). If you see it, please add the end of the engine log to #481. | +| `the engine said nothing for ... s and used no CPU or disk in that time (frozen ...)` | Issue #1317: a quicker version of the check above for an engine that is not slow but stopped (a deadlock inside a CUDA call, a driver stall): after 90 s without a line, if the engine process has also used no CPU time and moved no disk bytes in that time, the server ends it and the next request starts it again. An engine that is silent but still working is never ended by this check, the server prints one note (`... but is still working; it is not ended`) and leaves it to `engine_silence_s`. `STRATA_ENGINE_STALL_S=180` sets the time, `0` turns the check off (it needs `psutil`, which setup installs). | | `out of memory: cudaFuncSetAttribute` in the log (IQ3_XXS, long prompt) | Fixed in engine 0.1.15: CUDA loaded a kernel's code when it was first needed, and mid-prompt there was no VRAM left for it. Run `START-HERE.bat` (Windows) or `./setup.sh` (Linux) once to update. | | Anything else | The engine log is `strata-.log` in this folder. | diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md new file mode 100644 index 00000000..93cf1b53 --- /dev/null +++ b/docs/MMVQ_IL_TABLE.md @@ -0,0 +1,32 @@ +# The interleaved small-batch matvec (STRATA_MMVQ_IL): how to measure a table for your card + +The decode and verify windows run their dense projections (2 to 4 tokens at a time) through `native_mmvq_il`, which reads an +interleaved copy of the q8_1 activations. Every choice it makes gives the same bits as the plain kernels +(`STRATA_MMVQ_IL=0` turns the whole path off); only the speed differs. How many matrix rows one warp takes +(1, 2 or 4, or 0 = use the plain kernel) is a table in `src/kernels/cuda/native_mmvq.cu`, indexed by the +quantisation type (IQ4_XS, Q4_K, Q5_K, Q6_K), the token count (2-4) and the matrix's row count (five classes). + +Which table a card gets: + +| card | table | +|---|---| +| sm_86 (Ampere consumer) and sm_120 (Blackwell consumer) | `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_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 | + +## Measuring sm_89 (or any other card) + +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`. +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 + interleaved pairs, medians. + +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. diff --git a/docs/NVIDIA_V100.md b/docs/NVIDIA_V100.md index 4bebbbc1..15514a8b 100644 --- a/docs/NVIDIA_V100.md +++ b/docs/NVIDIA_V100.md @@ -35,6 +35,15 @@ select "old" kernels everywhere: which kernel runs is decided per architecture w | QSA prompt attention, Q4_0 KV | the decode kernel | | QSA block scores | the warp kernel (the tensor-core scorer needs sm_80) | +| Part of a decode / verify window | On sm_70 | +| --- | --- | +| Routed experts in VRAM | gfx906's expert mode 8: the codebook grid and the group's activations in shared memory, SwiGLU fused (`STRATA_EXP_MODE=0`: the CUDA layout other cards run) | +| Dense 2-4 column GEMVs and the head | the interleaved `native_mmvq_il` with a Volta rows table (`STRATA_MMVQ_IL=0`: `native_mmvq`) | +| Hyper-connection read, up projection | gfx906's latency-hidden up kernel (`STRATA_GR_FAST=0`: the plain one) | + +All three are bitwise the kernels they replace; on a V100-SXM2 they take a verify window's GPU work from 22.8 to 21.2 ms +([bench/results/2026-10-07-v100-decode-kernels](../bench/results/2026-10-07-v100-decode-kernels/README.md)). + ## Measured One V100-PCIE-32GB, i9-7960X, Unsloth `UD-IQ4_XS` (not a setup model), int8 KV, MTP `--spec 2`; prompt read speed of random-word prompts, tokens/s, @@ -72,3 +81,11 @@ sm_80. 0.1.40 with the P100 as helper cache). One reporter's numbers each; this page's own kernel measurements are V100 only. - Volta's tensor cores take FP16 only: a model's BF16 weights are converted, and a weight outside FP16's range would saturate (none did in the check above). + +## The decode kernels measured on a V100 (opt-in: `STRATA_SM70_TABLE=1`) + +The interleaved 2-4 column matvec with a Volta rows table, expert mode 8 and the latency-hidden norm/up (bitwise the default +kernels' output, GPU work per verify window 22.8 -> 21.2 ms on a V100-SXM2 in the contributor's measurement) are used on +sm_70 only when `STRATA_SM70_TABLE=1` is set. They become the default once the contributor has confirmed them on a V100 with +the 0.1.41 code. Without the variable sm_70 runs what 0.1.40.3 ran. The single switches (`STRATA_EXP_MODE`, `STRATA_MMVQ_IL`, +`STRATA_GR_FAST`) still apply on top. diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 305d352b..9938bb6f 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -263,15 +263,29 @@ public: while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) { // the oldest entry that does not hold a pinned shared prefix leaves; with only pinned ones left the new // image does not fit (the caller skips parking it - the pinned prefix is what the queries come back to) - auto victim = std::find_if(entries_.begin(), entries_.end(), [](const SavedConversation& e) { return !e.pinned(); }); - if (victim == entries_.end()) return false; - bytes_ -= victim->bytes(); - entries_.erase(victim); - ++evictions_; + if (!evict_oldest()) return false; } return true; } + // The parked conversation that has gone unused the longest. This is make_room()'s loop body, so + // the parking path can also free RAM one entry at a time on demand (see the physical-RAM admission + // gate in generate.cpp). A ConversationBuffer is a list of 16 MiB segments and each segment is its + // own allocation, far above glibc's mmap threshold, so dropping an entry returns the whole footprint + // to the kernel at once - the next admission check reads it back from /proc/meminfo. + // False when none can go (empty, or only entries that hold a pinned shared prefix are left). + bool evict_oldest() { + auto victim = std::find_if(entries_.begin(), entries_.end(), [](const SavedConversation& e) { return !e.pinned(); }); + if (victim == entries_.end()) return false; + bytes_ -= victim->bytes(); + entries_.erase(victim); + ++evictions_; + return true; + } + + // The slot count, so a caller that evicts in a loop has a bound it did not invent. + size_t slots() const { return slots_; } + // #342: drop the parked entries an outgoing conversation (its live tokens and checkpoint chain) supersedes: // the same conversation a turn back, whose DEEPEST checkpoint the outgoing chain still holds, so all it adds // is the tail the client rewrote (the reply as it was generated, before the next request re-rendered it) and diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 1238299d..dfc249d8 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -214,6 +214,7 @@ protected: /// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the /// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages: /// it never changes which experts are computed or how. +struct ForesightSwap; class RouterLookahead { public: RouterLookahead() = default; @@ -222,7 +223,11 @@ public: RouterLookahead& operator=(const RouterLookahead&) = delete; /// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd. bool start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src, - std::string& err); + std::string& err, bool allow_cold_source = false); + /// One prefetch design (#1348): the predicted experts that no cache holds also go to the Foresight swap space + /// (ForesightSwap::predict), which copies them to VRAM ahead of the layer. nullptr detaches it (waits for a + /// prediction in progress), so the swap space can be destroyed first. + void set_foresight(ForesightSwap* fs); /// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a /// prediction still running for an earlier layer makes this one skip. void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res); @@ -247,6 +252,7 @@ private: bool quit_ = false, pending_ = false, busy_ = false; int64_t layer_ = -1, n_tok_ = 0; const int32_t* host_res_ = nullptr; + ForesightSwap* fs_ = nullptr; ///< (under mu_) std::vector x_; std::atomic predicted_{0}, skipped_{0}; std::atomic busy_us_{0}; @@ -280,7 +286,10 @@ struct GpuPlanSink { }; /// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10). +struct ForesightSwap; + struct ExpertDispatch { + ForesightSwap* fs = nullptr; ///< Foresight swap space (STRATA_FS_SLOTS; null = off) strata::kernels::cpu::ExpertPool* pool = nullptr; ExpertSource* src = nullptr; RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts @@ -693,8 +702,16 @@ private: // reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds // through the layer it was asked in and the next ones (the pool computes a layer's misses before the next). static constexpr uint64_t kStageAge = 3; + // A stage buffer feeds cudaMemcpyAsync (the cache fill), so it is cudaHostAlloc'd where the driver allows: + // a pageable source would be staged through the driver's bounce buffer - an extra copy at a fraction of + // the transfer rate, with the calling thread doing it. `pinned` picks the free (defined in the .cpp: the + // header has no cuda_runtime.h). + struct StageBufFree { + bool pinned = false; + void operator()(uint8_t* p) const noexcept; + }; std::mutex stage_mu_; - std::vector> stage_buf_; + std::vector> stage_buf_; std::vector stage_key_; std::vector stage_epoch_, stage_used_; std::vector stage_busy_; ///< being filled (outside stage_mu_): never a victim @@ -710,6 +727,7 @@ private: uint64_t epoch_ = 0; int64_t last_layer_ = -1; bool stage_grew_ = false; + bool stage_pin_said_ = false, stage_pin_failed_said_ = false; ///< the one-time notes in claim_stage std::atomic ram_reads_{0}; std::atomic file_read_bytes_{0}; // ---- the Linux I/O path (set_io_prefetch) diff --git a/include/strata/core/foresight_swap.hpp b/include/strata/core/foresight_swap.hpp new file mode 100644 index 00000000..379f4079 --- /dev/null +++ b/include/strata/core/foresight_swap.hpp @@ -0,0 +1,98 @@ +#pragma once +// Foresight swap space (opt-in: STRATA_FS_SLOTS > 0; unset = nothing here exists and the engine is unchanged). +// +// A few VRAM slots per layer on each card, apart from the expert cache, refilled on their own copy stream with experts +// that just missed. The verify pool asks, for every expert it would otherwise give the CPU, whether that expert sits +// in a slot whose copy has landed; if so the expert becomes a plain GPU group (kind 0) pointing at the slot, exactly +// like a cache hit - the grouped kernel reads whatever address the plan carries, so no kernel changes. The host pool +// decides and the GPU follows the plan, so both always agree on who computes an expert. +// +// Safety: a slot is refilled only when every window that may have read it has finished: each plan reference stamps +// the slot with the count of finished verify windows, and a slot is reusable once `depth` more windows finished +// (STRATA_FS_DEPTH, default 4; --pipeline-windows 2 keeps at most two windows in flight). A copy that has not landed +// is simply not used (the CPU computes the expert as before). Not with STRATA_VERIFY_DEVICE_PLAN (the device would +// plan resident layers without the host). +// +// With STRATA_FS_AHEAD=1 (default 1 when the swap space is on) the router look-ahead (RouterLookahead, one layer ahead on the +// previous layer's MoE input) also feeds the slots, not only the page warming of the file tier. +// +// Switches: STRATA_FS_SLOTS (per layer and card), STRATA_FS_BUDGET (copies per card per finished window, default 32), +// STRATA_FS_ADMIT (misses within the last 4 windows before an expert is copied, default 1), STRATA_FS_DEPTH, +// STRATA_FS_VERIFY=1 (test mode: every slot is read back and compared with its source the first time it is used). +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +class ExpertSource; + +struct ForesightSwap { + struct Slot { + int32_t expert = -1; + bool ready = false; ///< the copy has landed (dispatch thread only) + bool loading = false; ///< a copy is assigned and not yet seen landed (dispatch thread only) + std::atomic issued{false}; ///< the filler has queued the copy and recorded `ev` + uint64_t last_ref = 0; ///< finished-window count when a plan last pointed here + unsigned long long dptr = 0; ///< the slot's device address + const uint8_t* src = nullptr; ///< the host blob being copied in + uint64_t bytes = 0; + void* ev = nullptr; ///< cudaEvent_t on the layer's card + }; + + int slots = 0, budget = 32, admit = 1, depth = 4; + int64_t n_layers = 0, n_expert = 0; + std::unique_ptr slot; ///< n_layers x slots + std::vector where; ///< (layer, expert) -> slot in its layer, -1 + std::vector miss_cnt; ///< STRATA_FS_ADMIT > 1: recent misses per (layer, expert) + std::vector miss_at; + std::vector layer_card, layer_dev; + std::vector card_stream; ///< cudaStream_t per card + std::vector card_mem; ///< the slots' allocation per card + std::vector card_dev; + std::vector card_round; + std::vector card_used; + std::atomic completed{0}; ///< finished verify windows (the serve loops count them) + std::atomic failed{false}; + // counters (dispatch thread) + uint64_t hits = 0, copies = 0, busy = 0, over_budget = 0, pending = 0, predicted = 0; // (under smu_) + bool verify = false; ///< STRATA_FS_VERIFY=1: read every landed slot back and compare (slow, tests) + uint64_t verify_ok = 0, verify_bad = 0; + + /// Allocates the slots on each card and starts the filler. `card_of_layer[l]` indexes `devices` (CUDA ids). + bool init(int slots_per_layer, int64_t layers, int64_t experts, const std::vector& card_of_layer, + const std::vector& devices, std::string& err); + ~ForesightSwap(); + + /// The pool, for a routed expert that is not in the cache: true and its device address when a landed slot holds it. + bool take(int64_t layer, int32_t expert, unsigned long long& ptr); + /// The pool, for an expert the CPU computes now: maybe copy it into a slot of its layer for the next windows. + void note_miss(ExpertSource* src, int64_t layer, int32_t expert); + /// The router look-ahead (any thread), for an expert the next layer's router predicts and no cache holds: maybe copy + /// it into a slot of that layer now, so that the copy has landed when the layer's plan is made. One prefetch design + /// with note_miss (the same slots, budget and reuse rule); a prediction only ever moves bytes, the plan is still made + /// by the host pool and the model's own router stays authoritative. + void predict(ExpertSource* src, int64_t layer, int32_t expert); + std::string report() const; + +private: + void request_locked(ExpertSource* src, int64_t layer, int32_t expert, bool predicted); + std::mutex smu_; ///< slot, where, card_* and the counters: the pool thread and the look-ahead thread + std::mutex mu_; + std::condition_variable cv_; + std::deque queue_; ///< slot indices whose copy the filler issues + bool stop_ = false; + std::thread filler_; + void fill_loop(); +}; + +ForesightSwap* foresight_swap_from_env(int64_t layers, int64_t experts, const std::vector& card_of_layer, + const std::vector& devices); + +} // namespace strata::core diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index 799ef7db..fef71027 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -148,6 +148,9 @@ bool native_mmvq_il_supported(int ggml_type, int ncols, int n_out); // warp takes 1, 2 or 4 rows and reads the columns from the interleaved copy; native_mmvq (x_q8_1) when not supported. void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void* x_il, float* y, int n_in, int n_out, int ncols, void* stream); +// The table's rows a warp (0, 1, 2, 4; 0 = native_mmvq's kernels) for a card of compute capability `cc` (major * 10 + minor). +// Per-architecture tables plus STRATA_MMVQ_IL_ROWS; see native_mmvq.cu and docs/MMVQ_IL_TABLE.md. +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); diff --git a/serve/server.py b/serve/server.py index 89eeaa0d..dbe283bb 100644 --- a/serve/server.py +++ b/serve/server.py @@ -230,6 +230,22 @@ def _timeout_env(name: str, default: float) -> float | None: return None if v <= 0 else v +# #1317 part 2: the quick watchdog for a FROZEN engine. engine_silence_s (above) is generous on purpose: a slow PC reads a +# prompt chunk for minutes without a line. But an engine that prints nothing for ENGINE_STALL_S and also uses no CPU time and +# moves no bytes of I/O in that time is not slow, it is idle or frozen (a deadlock in a CUDA call, a driver stall, a lost +# step), and waiting longer cannot help: it is ended, and the next request starts it again. An engine that is silent but +# still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable). +# STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended. +ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0) +STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen +STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window + + +def engine_frozen(base: tuple[float, int], now: tuple[float, int]) -> bool: + """#1317: True when two (cpu seconds, io bytes) samples of the engine show no work between them.""" + return (now[0] - base[0]) <= STALL_CPU_EPS_S and (now[1] - base[1]) <= STALL_IO_EPS_B + + VISION_READY_S = _timeout_env("STRATA_VISION_READY_S", 300.0) VISION_ENCODE_S = _timeout_env("STRATA_VISION_ENCODE_S", 300.0) ENGINE_READY_S = _timeout_env("STRATA_ENGINE_READY_S", 900.0) @@ -562,6 +578,7 @@ class StrataEngine: """ silence_s = ENGINE_SILENCE_S # #481: main() sets the config's engine_silence_s (survives restart()) silent_note = None # #481: why the server ended a silent engine (death_note says it) + gpu_busy = None # #1317: () -> bool, "the GPU is working" (the telemetry's reading); a GPU at work is not frozen last_err = None # #997: an ERR that was its last stdout line (death_note says it) batch = 0 # --batch: the engine's batch slots (0: one request at a time) @@ -1459,6 +1476,8 @@ class StrataEngine: allow = silence + min(len(ids), PP_CHUNK_MAX) / PP_FLOOR_TOK_S if silence > 0 else 0.0 heard, read_to = time.monotonic(), 0 beat = heard + stall_s = ENGINE_STALL_S or 0.0 + stall_state: dict = {} try: while True: wait = 10.0 @@ -1473,6 +1492,12 @@ class StrataEngine: except queue.Empty: if cancel.is_set(): return + if stall_s > 0: + try: + self._stall_check(heard, stall_state, stall_s) + except EngineSilent: + done = True # as above: nothing is listening + raise if allow > 0 and time.monotonic() - heard >= allow: continue # enforce the expired deadline before another heartbeat if time.monotonic() - beat >= 10.0: @@ -1484,6 +1509,8 @@ class StrataEngine: raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") heard = time.monotonic() # any line is output: T, PP, RESUME, INFO ... beat = heard + if stall_state: + stall_state.clear() if line.startswith("T "): allow = silence if cancel.is_set(): @@ -1543,6 +1570,43 @@ class StrataEngine: if not self.can_stop: heard = time.monotonic() + def _activity(self) -> tuple[float, int] | None: + """#1317: (CPU seconds, I/O bytes) the engine process has used so far, or None when they cannot be read.""" + try: + import psutil + pr = psutil.Process(self.proc.pid) + t = pr.cpu_times() + io = pr.io_counters() + return (t.user + t.system, io.read_bytes + io.write_bytes) + except Exception: # noqa: BLE001 - psutil missing, the process gone, no permission: no reading + return None + + def _stall_check(self, heard: float, state: dict, stall_s: float) -> None: + """#1317: called while the engine is silent. Takes a baseline soon after the last line, and at stall_s of silence + compares: no CPU and no I/O in all that time -> the engine is ended (EngineSilent); work going on -> one warning.""" + age = time.monotonic() - heard + if state.get("base") is None: + state["base"] = self._activity() + return + if age < state.get("next", stall_s) or state["base"] is None: + return + now = self._activity() + try: + gpu_working = bool(self.gpu_busy()) if self.gpu_busy is not None else False + except Exception: # noqa: BLE001 - a telemetry hiccup must not decide anything + gpu_working = False + if now is not None and not gpu_working and engine_frozen(state["base"], now): + raise self._silent(f"the engine said nothing for {age:.0f} s and used no CPU or disk in that time (frozen; " + "STRATA_ENGINE_STALL_S sets this, 0 = off)") + if now is not None: # working: look again after another window from here, and say so once + state["base"], state["next"] = now, age + stall_s + if not state.get("warned"): + state["warned"] = True + print(f"[strata] the engine has said nothing for {age:.0f} s but is still working; it is not ended (the " + "limit is engine_silence_s). If it is stuck, \"engine_silence_s\" can be set lower.", flush=True) + else: + state["next"] = float("inf") # no reading (psutil missing): nothing to decide on + def _silent(self, what: str) -> EngineSilent: """#481: end an engine that lost step with the server (its main thread waits for a command the server never sends), so the next request starts it again: killed now, its GPU and RAM go back with the process.""" @@ -2060,6 +2124,18 @@ def engine_args(cfg: dict) -> list[str]: config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32"; see layer_split_value).""" args = list(cfg["args"]) + # #1322: a config with a "vision" section but without --vision in its args (written by an older setup run, or edited by + # hand) advertised images and then refused every picture ("this engine was started without --vision"). The section + # says images are wanted: start the engine with them, and keep the encoder's VRAM free as setup does for a GPU encoder + # (only when the config has no reserve of its own). + if isinstance(cfg.get("vision"), dict) and "--vision" not in args: + args.append("--vision") + note = "added --vision" + if cfg["vision"].get("gpu") and "--vram-reserve-mib" not in args: + args += ["--vram-reserve-mib", "700"] + note += " and --vram-reserve-mib 700" + print(f'[strata] the config has a "vision" section but no --vision in its args: {note} (run setup again with ' + "--vision to write them)", flush=True) if layer_split_of(cfg) and "--layer-split" not in args: args += ["--layer-split", layer_split_value(cfg)] # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV @@ -2863,6 +2939,10 @@ class Service: gpu_index=int(getattr(self, "gpu_index", 0) or 0), gpu_indices=getattr(self, "gpu_indices", None), amd=getattr(self, "backend", None) == "hip") + if getattr(self, "engine", None) is not None and hasattr(self.engine, "gpu_busy"): + # #1317: the quick frozen-engine check does not end an engine whose GPU is busy (a long prompt chunk on a + # slow card keeps the GPU at work while the host thread sleeps) + self.engine.gpu_busy = lambda: (self.telemetry.snapshot()["now"].get("gpu_util") or 0) >= 10 def _tok_s(self): """tok/s over the last RATE_WINDOW_S seconds. Returns 0.0 while nothing is generating. With parallel requests: @@ -5283,27 +5363,47 @@ def host_allowed(host, names, any_host=False) -> bool: or _name_in(name, names)) -def api_key_of(value) -> str: +def key_list(value) -> list[str]: + """#1344: the keys a server accepts. --api-key / STRATA_API_KEY / "api_key" take llama.cpp's form, several keys + separated by commas ("k1,k2"; spaces around each are dropped), or a list in the config ("api_key": ["k1", "k2"], + the way to give a key that contains a comma). A list is taken as it is.""" + if value is None or value == "": + return [] + if isinstance(value, (list, tuple)): + return [str(k) for k in value if str(k)] + return [k.strip() for k in str(value).split(",") if k.strip()] + + +def api_key_of(value): """The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no request: every client got 401 with the right key. A value that is only such characters raises ValueError, it - never means "no key" (#213).""" + never means "no key" (#213). #1344: a config list of keys returns the list (each key stripped, none empty); a + string stays a string (its commas separate keys, see key_list).""" + if isinstance(value, (list, tuple)): + keys = [str(k).strip() for k in value] + if not keys or any(not k for k in keys): + raise ValueError("an API key was given but it is empty") + return keys key = "" if value is None else str(value) - if key and not key.strip(): + if key and not key_list(key): raise ValueError("an API key was given but it is empty") return key.strip() -def key_matches(given: str, key: str) -> bool: +def key_matches(given: str, key) -> bool: """given: a header's value as http.server read it, each byte one character. A key with characters outside ASCII arrives as UTF-8 from most clients and as Latin-1 from some; the right key passes in both forms (#725: the - bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213).""" + bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213). #1344: `key` may name several + keys (see key_list); the given one must match any, and every key is compared whatever the outcome.""" raw = given.encode("latin-1", "replace") - ok = hmac.compare_digest(raw, key.encode()) - try: - ok |= hmac.compare_digest(raw, key.encode("latin-1")) - except UnicodeEncodeError: - pass + ok = False + for k in key_list(key): + ok |= hmac.compare_digest(raw, k.encode()) + try: + ok |= hmac.compare_digest(raw, k.encode("latin-1")) + except UnicodeEncodeError: + pass return ok @@ -5482,7 +5582,8 @@ def main() -> int: help="clamp max_tokens to the remaining context instead of rejecting the request " "(default: reject with 400, like llama.cpp; also \"fit_max_tokens\": true in the config)") ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""), - help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY") + help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. " + "Several keys: separate them with commas (key1,key2), as llama.cpp does") ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " "the config)") diff --git a/serve/test_server.py b/serve/test_server.py index ac655d2e..60e909e8 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -922,6 +922,25 @@ class ApiKeyForms(unittest.TestCase): self.assertTrue(key_matches(as_read("ключ", "utf-8"), "ключ")) self.assertFalse(key_matches(as_read("ключ", "utf-8"), "ключx")) + def test_several_keys_1344(self): + # llama.cpp's form: "k1,k2" is two keys, not one key with a comma; a config list is taken as it is + self.assertEqual(api_key_of("sk-aaa,sk-bbb"), "sk-aaa,sk-bbb") + self.assertEqual(api_key_of(["sk-aaa", " sk-bbb "]), ["sk-aaa", "sk-bbb"]) + self.assertEqual(api_key_of(["a,b"]), ["a,b"]) # a key with a comma: as a list + for bad in (",", " , ", [], [""], ["a", " "]): + with self.assertRaises(ValueError): + api_key_of(bad) + two = "sk-aaa,sk-bbb" + self.assertTrue(key_matches("sk-aaa", two)) + self.assertTrue(key_matches("sk-bbb", two)) + self.assertTrue(key_matches("sk-bbb", "sk-aaa, sk-bbb")) + self.assertFalse(key_matches(two, two)) # the joined text is no key + self.assertFalse(key_matches("sk-ccc", two)) + self.assertFalse(key_matches("", two)) + self.assertTrue(key_matches("a,b", ["a,b", "c"])) + self.assertFalse(key_matches("a", ["a,b", "c"])) + self.assertTrue(key_matches("single", "single")) + def test_a_utf8_key_over_http(self): tok = ByteTokenizer() svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) @@ -1913,6 +1932,18 @@ class PeerDevice(unittest.TestCase): """#665: several GPUs in the config are a layer split, but --peer-device uses the second card as an expert-cache tier, and the engine refuses it beside --layer-split: the server must not add one then.""" + def test_a_vision_section_starts_the_engine_with_images_1322(self): + args = ["--native", "x"] + got = engine_args({"args": list(args), "vision": {"exe": "v", "gpu": True}}) + self.assertEqual(got, args + ["--vision", "--vram-reserve-mib", "700"]) + got = engine_args({"args": list(args), "vision": {"exe": "v", "gpu": False}}) + self.assertEqual(got, args + ["--vision"]) + mine = args + ["--vram-reserve-mib", "1500"] + self.assertEqual(engine_args({"args": list(mine), "vision": {"gpu": True}}), mine + ["--vision"]) + done = args + ["--vision", "--vram-reserve-mib", "700"] # setup wrote it: unchanged + self.assertEqual(engine_args({"args": list(done), "vision": {"gpu": True}}), done) + self.assertEqual(engine_args({"args": list(args)}), args) # no section: no images + def test_split_added_for_several_gpus(self): self.assertEqual(engine_args({"args": ["--native", "x"], "gpu": [0, 1]}), ["--native", "x", "--layer-split", "auto"]) @@ -3947,6 +3978,60 @@ class SilentEngine(unittest.TestCase): engine.proc.kill.assert_called_once() self.assertFalse(engine.alive()) + def test_frozen_engine_is_ended_by_the_stall_watchdog(self): + # #1317 part 2: silent AND no CPU / disk work for the stall window -> ended, long before engine_silence_s + from serve import server + from serve.server import EngineSilent + engine = self.bare(300.0) + engine.lines.put("T 5") + engine._activity = lambda: (12.0, 4096) # the same reading every time: no work + with mock.patch.object(server, "ENGINE_STALL_S", 1.0): + gen = engine.generate([1], 10, {}, threading.Event()) + self.assertEqual(next(gen), 5) + t0 = time.monotonic() + with self.assertRaises(EngineSilent) as cm: + next(gen) + self.assertLess(time.monotonic() - t0, 10) + self.assertIn("frozen", str(cm.exception)) + engine.proc.kill.assert_called_once() + + def test_a_working_silent_engine_is_not_ended_by_the_stall_watchdog(self): + from serve import server + engine = self.bare(300.0) + ticks = iter(range(10 ** 6)) + engine._activity = lambda: (float(next(ticks)), 0) # CPU time advances: it is working + self.later(engine, 3.0, "T 7", "DONE 1 1 1 1 length") + with mock.patch.object(server, "ENGINE_STALL_S", 1.0): + self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [7]) + engine.proc.kill.assert_not_called() + + def test_a_busy_gpu_is_not_a_frozen_engine(self): + # #1317: no CPU and no disk, but the GPU is at work (a long prompt chunk on a slow card): not ended + from serve import server + engine = self.bare(300.0) + engine._activity = lambda: (12.0, 4096) + engine.gpu_busy = lambda: True + self.later(engine, 2.5, "T 7", "DONE 1 1 1 1 length") + with mock.patch.object(server, "ENGINE_STALL_S", 1.0): + self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [7]) + engine.proc.kill.assert_not_called() + + def test_no_reading_means_no_kill_and_zero_is_off(self): + from serve import server + for stall, act in ((1.0, lambda: None), (0, lambda: (1.0, 1))): + engine = self.bare(300.0) + engine._activity = act + self.later(engine, 2.5, "T 7", "DONE 1 1 1 1 length") + with mock.patch.object(server, "ENGINE_STALL_S", stall): + self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [7]) + engine.proc.kill.assert_not_called() + + def test_engine_frozen_samples(self): + from serve.server import engine_frozen + self.assertTrue(engine_frozen((10.0, 100), (10.2, 100))) + self.assertFalse(engine_frozen((10.0, 100), (13.0, 100))) + self.assertFalse(engine_frozen((10.0, 100), (10.0, 100 + (8 << 20)))) + def test_zero_waits_as_before(self): engine = self.bare(0) self.later(engine, 0.5, "T 5", "DONE 1 1 1 1 length") diff --git a/setup.py b/setup.py index be1c23e3..2010fa1b 100644 --- a/setup.py +++ b/setup.py @@ -4571,7 +4571,7 @@ def main() -> int: 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; set --api-key too)") - ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") + 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("--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)") diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp index c4883fe0..d31bf635 100644 --- a/src/core/conversation_cache_test.cpp +++ b/src/core/conversation_cache_test.cpp @@ -98,6 +98,37 @@ int main() { check(cache.best(b, {}, true).tokens == 0 && cache.best(a, {}, true).tokens == 3, "B evicted before A"); check(cache.evictions() == 1, "eviction counter"); } + { + // evict_oldest(): the physical-RAM admission gate in generate.cpp frees parked conversations + // one at a time and re-checks the host's free memory, so this has to be exactly the oldest-first + // step make_room() takes - same accounting, same counters - and it has to stop at empty. + ConversationCache cache(4096, 4); + cache.put(image({1, 2, 3})); + cache.put(image({9, 8, 7})); + check(cache.size() == 2 && cache.slots() == 4, "slots() reports the configured limit"); + const size_t both = cache.bytes(); + check(cache.evict_oldest(), "evict_oldest reports an eviction"); + check(cache.size() == 1 && cache.evictions() == 1, "evict_oldest drops exactly one, oldest first"); + check(cache.best(a, {}, true).tokens == 0 && cache.best(b, {}, true).tokens == 3, + "the oldest conversation went, the newest stayed"); + check(cache.bytes() == both - image({1, 2, 3}).bytes(), "evict_oldest releases the entry's bytes"); + cache.evict_oldest(); + check(cache.size() == 0 && cache.bytes() == 0, "evicting the last parked conversation empties the cache"); + check(!cache.evict_oldest(), "the gate's loop can reach an empty cache: false"); + check(cache.size() == 0 && cache.evictions() == 2, "evict_oldest on an empty cache is a no-op"); + } + { // the RAM gate's eviction skips a conversation that holds a pinned shared prefix, and says so (false) + ConversationCache cache(1 << 20, 4); + auto pinned = image({1, 2, 3}); + pinned.checkpoints.push_back(ConversationCheckpoint{}); + pinned.checkpoints.back().ids = {1, 2}; + pinned.checkpoints.back().pinned = true; + pinned.checkpoints.back().gdn.resize(64, 1); + cache.put(std::move(pinned)); + cache.put(image({9, 8, 7})); + check(cache.evict_oldest() && cache.size() == 1, "the oldest unpinned conversation went (the pinned one is older)"); + check(!cache.evict_oldest() && cache.size() == 1, "only a pinned one is left: nothing more can go"); + } { auto s = image({1, 2, 3}); ConversationCheckpoint cp; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index e045a8ba..7f6fea33 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1,5 +1,7 @@ // 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/foresight_swap.hpp" +#include "strata/core/on_device.hpp" #include "strata/core/remote_experts.hpp" #include "strata/core/peer_experts.hpp" #include "strata/kernels/cpu/expert_layout.hpp" @@ -1147,6 +1149,14 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* d return true; } +// Pinned stage buffers (PR 1237): whether they are the default is decided by the A/B in notes-141-cuda.md. +#define STAGE_PIN_DEFAULT 1 +constexpr uint64_t kStagePinFloor = 3ull << 30; // RAM left available after a pinned stage buffer +void FileExpertSource::StageBufFree::operator()(uint8_t* p) const noexcept { + if (pinned) (void) cudaFreeHost(p); + else delete[] p; +} + // A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once // its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes // first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a @@ -1175,8 +1185,33 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahea v = i; } if (v == stage_buf_.size()) { - stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]); - if (!stage_buf_.back()) { stage_buf_.pop_back(); return false; } + // Pinned, where the driver allows: a stage buffer is the source of the cache fill's cudaMemcpyAsync, + // and a pageable source is staged through the driver's bounce buffer - an extra copy at a fraction of + // the transfer rate, on the calling thread. A failure falls back to pageable for this buffer. + // STRATA_STAGE_PIN: 0 keeps them pageable (as before 0.1.41), 1 always tries to pin, unset (the default) pins while + // the host has kStagePinFloor of RAM to spare beside this buffer (the pool grows to ~257 buffers, 0.4-0.6 GiB): + // a low-RAM box keeps pageable ones instead of paying for the pinning (recommend, never force). + static const int pin_mode = [] { const char* v = std::getenv("STRATA_STAGE_PIN"); return v == nullptr ? -1 : (std::atoi(v) != 0 ? 1 : 0); }(); + bool want_pin = pin_mode != 0; + if (pin_mode < 0) { + uint64_t avail = 0; + want_pin = STAGE_PIN_DEFAULT && available_memory_bytes(avail) && avail >= (uint64_t) stage_blob_ + kStagePinFloor; + } + void* p = nullptr; + const cudaError_t pin_err = want_pin ? cudaHostAlloc(&p, (size_t) stage_blob_, cudaHostAllocDefault) : cudaErrorNotSupported; + const bool pinned = pin_err == cudaSuccess && p != nullptr; + if (!pinned) (void) cudaGetLastError(); // the failed alloc's sticky error is ours, not the caller's + uint8_t* raw = pinned ? (uint8_t*) p : new (std::nothrow) uint8_t[(size_t) stage_blob_]; + if (raw == nullptr) return false; + stage_buf_.emplace_back(raw, StageBufFree{pinned}); + if (pinned && !stage_pin_said_) { + stage_pin_said_ = true; + std::fprintf(stderr, "FileExpertSource: the stage buffers are pinned (cudaHostAlloc)\n"); + } else if (!pinned && want_pin && !stage_pin_failed_said_) { + stage_pin_failed_said_ = true; + std::fprintf(stderr, "FileExpertSource: cudaHostAlloc failed for a stage buffer (%s) - pageable it is\n", + cudaGetErrorString(pin_err)); + } stage_key_.push_back(-1); stage_epoch_.push_back(0); stage_used_.push_back(0); @@ -1848,9 +1883,20 @@ RouterLookahead::~RouterLookahead() { if (thread_.joinable()) thread_.join(); } +void RouterLookahead::set_foresight(ForesightSwap* fs) { + for (;;) { + { + std::lock_guard lk(mu_); + if (fs != nullptr || !busy_) { fs_ = fs; return; } + } + // detaching: a prediction in progress finishes first (the swap space is about to go away) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } +} + bool RouterLookahead::start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, - ExpertSource* src, std::string& err) { - if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; } + ExpertSource* src, std::string& err, bool allow_cold_source) { + if (src == nullptr || (!allow_cold_source && !src->warms())) { err = "RouterLookahead: the expert source does not warm"; return false; } if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; } for (const auto& r : routers) if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; } @@ -1885,6 +1931,7 @@ void RouterLookahead::run() { for (;;) { int64_t layer, nt; const int32_t* host_res; + ForesightSwap* fs; { std::unique_lock lk(mu_); cv_.wait(lk, [&] { return quit_ || pending_; }); @@ -1894,6 +1941,7 @@ void RouterLookahead::run() { layer = layer_; nt = n_tok_; host_res = host_res_; + fs = fs_; } const auto t0 = std::chrono::steady_clock::now(); const int64_t layer0 = layer; @@ -1941,6 +1989,8 @@ void RouterLookahead::run() { } } src_->warm(layer, want.data(), (int64_t) want.size()); + if (fs != nullptr && dj == 0) // the next layer only: a deeper guess is too often wrong to spend a copy on + for (const int64_t e : want) fs->predict(src_, layer, (int32_t) e); predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed); } busy_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), @@ -3120,7 +3170,10 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 kd = 2; // multi-GPU: the second GPU computes it } else if (helper_holds(e)) { // left to the helper: kind -1 until RemoteExperts::begin() claims the row (see above) + } else if (d.fs != nullptr && d.fs->take(d.layers, e, ptr)) { + kd = 0; // Foresight: a landed swap-space slot holds it - a GPU group like a hit } else { + if (d.fs != nullptr) d.fs->note_miss(d.src, d.layers, e); if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) { const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr; if (src != nullptr) { @@ -4105,3 +4158,249 @@ const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) { } } // namespace strata::core + +// ---- Foresight swap space (see include/strata/core/foresight_swap.hpp) ------------------------------------------ +namespace strata::core { + +bool ForesightSwap::init(int slots_per_layer, int64_t layers, int64_t experts, const std::vector& card_of_layer, + const std::vector& devices, std::string& err) { + slots = slots_per_layer; + n_layers = layers; + n_expert = experts; + const size_t ns = (size_t) (layers * slots); + slot.reset(new Slot[ns]); + where.assign((size_t) (layers * experts), -1); + miss_cnt.assign((size_t) (layers * experts), 0); + miss_at.assign((size_t) (layers * experts), 0); + layer_card = card_of_layer; + layer_dev.resize((size_t) layers); + card_dev = devices; + card_stream.assign(devices.size(), nullptr); + card_mem.assign(devices.size(), nullptr); + card_round.assign(devices.size(), ~0ull); + card_used.assign(devices.size(), 0); + const auto& lay = strata::kernels::cpu::expert_layout(); + for (size_t c = 0; c < devices.size(); ++c) { + uint64_t bytes = 0; + for (int64_t l = 0; l < layers; ++l) + if (card_of_layer[(size_t) l] == (int) c) bytes += (uint64_t) slots * (uint64_t) lay.blob_bytes(l); + if (bytes == 0) continue; + const OnDevice on(devices[c]); + cudaStream_t s = nullptr; + if (cudaMalloc(&card_mem[c], bytes) != cudaSuccess || + cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking) != cudaSuccess) { + cudaGetLastError(); + err = "cannot allocate " + std::to_string(bytes >> 20) + " MiB on CUDA" + std::to_string(devices[c]) + + " (raise --vram-reserve-mib by about that much)"; + return false; + } + card_stream[c] = s; + uint64_t off = 0; + for (int64_t l = 0; l < layers; ++l) { + if (card_of_layer[(size_t) l] != (int) c) continue; + layer_dev[(size_t) l] = devices[c]; + const uint64_t bb = (uint64_t) lay.blob_bytes(l); + for (int s2 = 0; s2 < slots; ++s2) { + Slot& sl = slot[(size_t) (l * slots + s2)]; + sl.dptr = (unsigned long long) ((uint8_t*) card_mem[c] + off); + sl.bytes = bb; + cudaEvent_t ev = nullptr; + if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) { + cudaGetLastError(); + err = "cannot create the copy events"; + return false; + } + sl.ev = ev; + off += bb; + } + } + } + filler_ = std::thread([this] { fill_loop(); }); + return true; +} + +ForesightSwap::~ForesightSwap() { + { + std::lock_guard lk(mu_); + stop_ = true; + } + cv_.notify_all(); + if (filler_.joinable()) filler_.join(); + for (size_t c = 0; c < card_dev.size(); ++c) { + const OnDevice on(card_dev[c]); + if (card_stream[c]) cudaStreamSynchronize((cudaStream_t) card_stream[c]); + if (card_mem[c]) cudaFree(card_mem[c]); + if (card_stream[c]) cudaStreamDestroy((cudaStream_t) card_stream[c]); + } + if (slot) + for (int64_t i = 0; i < n_layers * slots; ++i) + if (slot[(size_t) i].ev) cudaEventDestroy((cudaEvent_t) slot[(size_t) i].ev); +} + +void ForesightSwap::fill_loop() { + int cur_dev = -1; + for (;;) { + int64_t idx; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [&] { return stop_ || !queue_.empty(); }); + if (stop_) return; + idx = queue_.front(); + queue_.pop_front(); + } + Slot& sl = slot[(size_t) idx]; + const int64_t l = idx / slots; + const int dev = layer_dev[(size_t) l]; + if (dev != cur_dev) { cudaSetDevice(dev); cur_dev = dev; } + cudaStream_t s = (cudaStream_t) card_stream[(size_t) layer_card[(size_t) l]]; + if (cudaMemcpyAsync((void*) sl.dptr, sl.src, sl.bytes, cudaMemcpyHostToDevice, s) != cudaSuccess || + cudaEventRecord((cudaEvent_t) sl.ev, s) != cudaSuccess) { + cudaGetLastError(); + if (!failed.exchange(true)) std::fprintf(stderr, "strata serve: foresight swap: a copy failed - swap space off\n"); + continue; // never marked issued: the slot is never used + } + sl.issued.store(true, std::memory_order_release); + } +} + +bool ForesightSwap::take(int64_t layer, int32_t expert, unsigned long long& ptr) { + std::lock_guard smu_lk(smu_); + const int s = where[(size_t) (layer * n_expert + expert)]; + if (s < 0) return false; + Slot& sl = slot[(size_t) (layer * slots + s)]; + if (!sl.ready) { + if (!sl.loading || !sl.issued.load(std::memory_order_acquire)) { ++pending; return false; } + const cudaError_t q = cudaEventQuery((cudaEvent_t) sl.ev); + if (q != cudaSuccess) { + if (q != cudaErrorNotReady) cudaGetLastError(); + ++pending; + return false; + } + sl.ready = true; + sl.loading = false; + if (verify) { // test mode: the bytes the GPU will read must be the expert's own + std::vector back((size_t) sl.bytes); + const OnDevice on(layer_dev[(size_t) layer]); + const bool same = cudaMemcpy(back.data(), (const void*) sl.dptr, (size_t) sl.bytes, cudaMemcpyDeviceToHost) == + cudaSuccess && std::memcmp(back.data(), sl.src, (size_t) sl.bytes) == 0; + if (same) ++verify_ok; + else { + cudaGetLastError(); + ++verify_bad; + sl.ready = false; // never serve it + where[(size_t) (layer * n_expert + expert)] = -1; + sl.expert = -1; + return false; + } + } + } + sl.last_ref = completed.load(std::memory_order_acquire); + ptr = sl.dptr; + ++hits; + return true; +} + +void ForesightSwap::note_miss(ExpertSource* src, int64_t layer, int32_t expert) { + std::lock_guard smu_lk(smu_); + request_locked(src, layer, expert, false); +} + +void ForesightSwap::predict(ExpertSource* src, int64_t layer, int32_t expert) { + if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return; + std::lock_guard smu_lk(smu_); + request_locked(src, layer, expert, true); +} + +void ForesightSwap::request_locked(ExpertSource* src, int64_t layer, int32_t expert, bool predicted_copy) { + if (failed.load(std::memory_order_relaxed)) return; + const size_t key = (size_t) (layer * n_expert + expert); + if (where[key] >= 0) return; // already on its way + const uint64_t now = completed.load(std::memory_order_acquire); + if (admit > 1 && !predicted_copy) { + if (now > miss_at[key] + 4) miss_cnt[key] = 0; + miss_at[key] = now; + if (miss_cnt[key] < 255) ++miss_cnt[key]; + if (miss_cnt[key] < admit) return; + } + const int c = layer_card[(size_t) layer]; + if (card_round[(size_t) c] != now) { card_round[(size_t) c] = now; card_used[(size_t) c] = 0; } + if (card_used[(size_t) c] >= budget) { ++over_budget; return; } + if (src == nullptr || !src->pinned(layer, expert)) return; // async copies need the pinned arena + const uint8_t* b = src->blob(layer, expert); + if (b == nullptr) return; + int best = -1; + uint64_t best_ref = ~0ull; + for (int s = 0; s < slots; ++s) { // an empty slot, else the one used longest ago that no window can still read + Slot& sl = slot[(size_t) (layer * slots + s)]; + if (sl.loading) { // copied in but never asked for since: landed long ago -> an ordinary candidate + if (sl.last_ref + (uint64_t) depth > now || !sl.issued.load(std::memory_order_acquire)) continue; + const cudaError_t q = cudaEventQuery((cudaEvent_t) sl.ev); + if (q != cudaSuccess) { if (q != cudaErrorNotReady) cudaGetLastError(); continue; } + sl.loading = false; + sl.ready = true; + } + if (sl.expert < 0) { best = s; break; } + if (sl.last_ref + (uint64_t) depth > now) continue; + if (sl.last_ref < best_ref) { best_ref = sl.last_ref; best = s; } + } + if (best < 0) { ++busy; return; } + Slot& sl = slot[(size_t) (layer * slots + best)]; + if (sl.expert >= 0) where[(size_t) (layer * n_expert + sl.expert)] = -1; + sl.expert = expert; + sl.ready = false; + sl.loading = true; + sl.issued.store(false, std::memory_order_relaxed); + sl.src = b; + sl.last_ref = now; + where[key] = (int16_t) best; + ++card_used[(size_t) c]; + ++copies; + if (predicted_copy) ++predicted; + { + std::lock_guard lk(mu_); + queue_.push_back(layer * slots + best); + } + cv_.notify_one(); +} + +std::string ForesightSwap::report() const { + std::lock_guard smu_lk(const_cast(smu_)); + char buf[320]; + std::snprintf(buf, sizeof buf, "foresight swap: %llu experts served from the swap space, %llu copies (%llu from the " + "router look-ahead), %llu not landed yet, %llu no free slot, %llu over budget%s", + (unsigned long long) hits, (unsigned long long) copies, (unsigned long long) predicted, + (unsigned long long) pending, (unsigned long long) busy, (unsigned long long) over_budget, verify ? "" : ""); + std::string r = buf; + if (verify) r += ", verified " + std::to_string(verify_ok) + " ok / " + std::to_string(verify_bad) + " BAD"; + return r; +} + +ForesightSwap* foresight_swap_from_env(int64_t layers, int64_t experts, const std::vector& card_of_layer, + const std::vector& devices) { + const char* v = std::getenv("STRATA_FS_SLOTS"); + const int slots = v ? std::atoi(v) : 0; + if (slots <= 0) return nullptr; + if (const char* dp = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); dp && std::atoi(dp) != 0) { + std::fprintf(stderr, "strata serve: foresight swap: off beside STRATA_VERIFY_DEVICE_PLAN (the device would plan " + "resident layers without the host)\n"); + return nullptr; + } + auto* f = new ForesightSwap(); + auto env_int = [](const char* name, int def, int lo) { const char* e = std::getenv(name); const int x = e ? std::atoi(e) : def; return x < lo ? lo : x; }; + f->budget = env_int("STRATA_FS_BUDGET", 32, 1); + f->admit = env_int("STRATA_FS_ADMIT", 1, 1); + f->depth = env_int("STRATA_FS_DEPTH", 4, 2); + f->verify = env_int("STRATA_FS_VERIFY", 0, 0) != 0; + std::string err; + if (!f->init(std::min(slots, 64), layers, experts, card_of_layer, devices, err)) { + std::fprintf(stderr, "strata serve: foresight swap: %s - swap space off\n", err.c_str()); + delete f; + return nullptr; + } + std::fprintf(stderr, "strata serve: foresight swap: %d slots per layer on %zu card(s), up to %d copies per card and " + "window, admit after %d miss(es), reuse after %d windows\n", + f->slots, devices.size(), f->budget, f->admit, f->depth); + return f; +} + +} // namespace strata::core diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 210cf228..bd058243 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -23,6 +23,12 @@ constexpr int N = 2560; // n_embd constexpr int HC = 4; // streams constexpr int D = N * HC; // 10240 constexpr int LR = 320; // hc_lr +// the latency-hidden norm/up (gr_norm_fast_kernel / gr_up_fast_kernel, STRATA_GR_FAST): gfx906's, built for CUDA too +#if defined(STRATA_HIP_GFX906) || !defined(__HIPCC__) +#define STRATA_GR_FAST_BUILD 1 +#else +#define STRATA_GR_FAST_BUILD 0 +#endif constexpr int THREADS = 256; constexpr int WARPS = THREADS / 32; constexpr int DOWN_BLOCKS = LR / WARPS; // 40 blocks of 8 rows; one more for the inject rows @@ -741,6 +747,24 @@ __global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) { } } +// the current device is Volta (sm_70): the fast norm/up is its default +bool cur_dev_volta() { +#if defined(__HIPCC__) + return false; +#else + 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 == 7 && minor == 0 ? 2 : 1; + } + return per_dev[dev] == 2; +#endif +} + // The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read // stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory // opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards). @@ -829,7 +853,7 @@ int down_chunk(bool staged, int* tile_out) { // many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection. // kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi // takes first). -#if defined(STRATA_HIP_GFX906) +#if STRATA_GR_FAST_BUILD __global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m); // below, with the AMD fast path __global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m); } // namespace @@ -849,7 +873,7 @@ bool gr_down_max4() { void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { const int n_tok = m.T; -#if defined(STRATA_HIP_GFX906) +#if STRATA_GR_FAST_BUILD // gfx906: the latency-hidden norm/up (STRATA_GR_FAST=0: off) - the same sums in the same order as the kernels // they replace (gr_parity checks the multi-token read against single-token calls bitwise) const bool fast = gr_fast(); @@ -905,7 +929,7 @@ 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); -#if defined(STRATA_HIP_GFX906) +#if STRATA_GR_FAST_BUILD if (fast) gr_up_fast_kernel<<>>(m); else #endif @@ -933,7 +957,7 @@ int env_variant() { std::atomic g_variant[64]; -#if defined(STRATA_HIP_GFX906) +#if STRATA_GR_FAST_BUILD // ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency // hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded // before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB). @@ -1001,7 +1025,11 @@ __global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) { // idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front. __device__ __forceinline__ float xor8(float v) { #pragma unroll +#if defined(__HIPCC__) for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64); +#else + for (int o = 4; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); +#endif return v; } __global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) { @@ -1064,6 +1092,7 @@ __global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) { for (int c = 0; c < HC; ++c) s += g[k][c][col]; m.a[k].mixed[d0 + col] = s / (float) HC; } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE, as gr_up_multi_kernel } #endif @@ -1607,11 +1636,17 @@ void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long } // namespace -#if defined(STRATA_HIP_GFX906) -int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST +#if STRATA_GR_FAST_BUILD +int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST, else the card's default static bool gr_fast() { - static const bool env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? std::atoi(v) != 0 : true; }(); - return g_gr_fast >= 0 ? g_gr_fast != 0 : env; + static const int env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); + if (g_gr_fast >= 0) return g_gr_fast != 0; + if (env >= 0) return env != 0; +#if defined(__HIPCC__) + return true; +#else + { const char* v = std::getenv("STRATA_SM70_TABLE"); return cur_dev_volta() && v != nullptr && std::atoi(v) != 0; } // PR 1401: opt-in // CUDA: on Volta (V100-SXM2: 50.9 -> 46.7 us a read at T 1, bitwise); elsewhere opt-in +#endif } #else int g_gr_fast = -1; diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 1c20986d..7d42b69b 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -2812,7 +2812,23 @@ size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { } +// The AMD layouts below (STRATA_EXP_MODE) also build for CUDA: Volta takes mode 8 by default (exp_mode), every +// other CUDA card keeps mode 0, the CUDA layout above. +#if defined(STRATA_HIP_GFX906) || !defined(__HIPCC__) +#define STRATA_EXP_LAYOUTS 1 +#else +#define STRATA_EXP_LAYOUTS 0 +#endif #if defined(STRATA_HIP_GFX906) +constexpr int kExpModeDefault = 7; +constexpr int kExpFallback = 2; // modes 5-8 on a format without an LDS kernel: R2 +constexpr bool kExpLds16 = false; // IQ2_XXS gate/up: R2 as measured on gfx906 +#else +constexpr int kExpModeDefault = 0; +constexpr int kExpFallback = 0; // ... the CUDA layout (V100, IQ2_XXS gate/up: R2 183 us vs 113) +constexpr bool kExpLds16 = true; // IQ2_XXS gate/up in LDS too +#endif +#if STRATA_EXP_LAYOUTS // ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above). // 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly. // 2 (R2): a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight. @@ -2826,7 +2842,11 @@ __device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs); } #pragma unroll +#if defined(__HIPCC__) for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64); +#else + __trap(); // a 64-lane wavefront: mode 1 is gfx906's only +#endif return s; } template @@ -2979,6 +2999,7 @@ __global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned lon // output is bitwise the mode-2 one. template struct GridOf; template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } }; +template<> struct GridOf<16> { using T = uint64_t; static constexpr int N = 256; __device__ static const T* src() { return iq2xxs_grid; } }; template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } }; template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } }; template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } }; // IQ4_XS: no grid @@ -3092,6 +3113,39 @@ template struct DotG<21, SG> { __device__ static __forceinline__ float f return d * sumi; } }; +// IQ2_XXS: vec_dot_iq2_xxs_q8_1 with the grid in LDS - the same integers, the same floats +template struct DotG<16, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, + const uint64_t* grid) { + const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx; + const int q2 = get_int_b2(bq2->qs, iqs); + const uint8_t* aux8 = (const uint8_t*) &q2; + const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1); + int sumi = 0; +#pragma unroll + for (int k0 = 0; k0 < 8; k0 += 2) { + const uint2 grid_pos = *(const uint2*) (grid + aux8[k0 / 2]); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1); + if constexpr (SG == 1) { + const uint32_t v = (aux32 >> (7 * k0 / 2)) & 0x7F, sg = v | ((__popc(v) & 1) << 7); + const int m0 = nib_mask(sg), m1 = nib_mask(sg >> 4); + sumi = ggml_cuda_dp4a((int) grid_pos.x ^ m0, u0, sumi); + sumi = ggml_cuda_dp4a((int) grid_pos.y ^ m1, u1, sumi); + sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); + } else { + const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + sumi = ggml_cuda_dp4a((int) __vsub4(grid_pos.x ^ signs0, signs0), u0, sumi); + sumi = ggml_cuda_dp4a((int) __vsub4(grid_pos.y ^ signs1, signs1), u1, sumi); + } + } + const int ls = aux32 >> 27 | 1; + sumi = sumi * ls / 8; + const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} }; + template struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } }; @@ -3348,16 +3402,34 @@ __global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned lon } } -int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7 +int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, else the card's default int exp_mode() { - static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }(); - return g_exp_mode >= 0 ? g_exp_mode : m; + static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : -1; }(); + if (g_exp_mode >= 0) return g_exp_mode; + if (m >= 0) return m; +#if defined(STRATA_HIP_GFX906) + return kExpModeDefault; +#else + // Volta (sm_70): mode 8, the grid and the group's activations in shared memory with SwiGLU + q8_1 fused + // (V100-SXM2, a verify window's VRAM call: 227 -> 159 us); every other CUDA card keeps the CUDA layout + static int per_dev[64]; // 0 unknown, else mode + 1 + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return kExpModeDefault; + if (!per_dev[dev]) { + int major = 0, minor = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + const char* sm70 = std::getenv("STRATA_SM70_TABLE"); // PR 1401: Volta's mode 8 is opt-in until confirmed on a V100 + per_dev[dev] = 1 + (major == 7 && minor == 0 && sm70 != nullptr && std::atoi(sm70) != 0 ? 8 : kExpModeDefault); + } + return per_dev[dev] - 1; +#endif } #endif int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only void native_expert_set_mode(int mode, int phase) { -#if defined(STRATA_HIP_GFX906) +#if STRATA_EXP_LAYOUTS g_exp_mode = mode; #else (void) mode; @@ -3416,16 +3488,23 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups; const int gu_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_embd == 2560 && gu_split(L.gu_type)) ? 16 : GU_ROWS; const dim3 ggu((unsigned) ((2 * L.n_ff + gu_rows - 1) / gu_rows), (unsigned) gy); +#if STRATA_EXP_LAYOUTS #if defined(STRATA_HIP_GFX906) const int em0 = exp_mode(); +#else + // CUDA: the AMD layouts launch a block row per possible group, so a call that strides (a verify window's PCIe + // call, grid_groups 1..cap) keeps the CUDA layout: V100, 0 groups 11.3 vs 6.5 us, 1 group of 2 29.6 vs 21.3 + const int em0 = (grid_groups > 0 && grid_groups < cap_groups) ? 0 : exp_mode(); #endif -#if defined(STRATA_HIP_GFX906) - const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && +#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) && L.n_ff % 32 == 0; if (fused_gu && g_exp_phase != 2) { const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups); const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); switch (L.gu_type) { + case 16: native_gu_fused_kernel<16><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; case 18: native_gu_fused_kernel<18><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; case 21: native_gu_fused_kernel<21><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; case 23: native_gu_fused_kernel<23><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; @@ -3437,19 +3516,20 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #else if (g_exp_phase != 2) { #endif -#if defined(STRATA_HIP_GFX906) - const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); +#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); 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); switch (L.gu_type) { + case 16: if (em0 >= 7) native_gu_lds_kernel<16, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<16, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<16, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; } } else { - const int em = exp_mode() >= 5 ? 2 : exp_mode(); + const int em = em0 >= 5 ? kExpFallback : em0; const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups); #define STRATA_GU_AMD(T) \ case T: if (em == 1) native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \ @@ -3472,7 +3552,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #undef STRATA_GU default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1); } -#if defined(STRATA_HIP_GFX906) +#if STRATA_EXP_LAYOUTS } #endif check("native_expert_grouped/gu"); @@ -3497,7 +3577,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long if (g_exp_phase == 1) return; const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8; const dim3 gd((unsigned) ((L.n_embd + d_rows - 1) / d_rows), (unsigned) gy); -#if defined(STRATA_HIP_GFX906) +#if STRATA_EXP_LAYOUTS if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) { const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1); @@ -3506,7 +3586,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long check("native_expert_grouped/down"); return; } - const int em = exp_mode() >= 5 ? 2 : exp_mode(); + const int em = em0 >= 5 ? kExpFallback : em0; const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups); #define STRATA_D_AMD(T) \ case T: if (em == 1) native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \ diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 3ef2dcbf..069f7149 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -2498,31 +2498,111 @@ namespace { // worse card still takes at least 3% off native_mmvq's time, else 0; classes without a measured shape take their // neighbour's value. Every choice is bitwise the same output, so the table is only speed. struct IlRows { int type; uint8_t r[3][5]; }; -constexpr IlRows kIlRows[] = { +constexpr IlRows kIlRowsShared[] = { // sm_86 + sm_120, and the fallback for every other sm_80+ card {23, {{0, 0, 0, 0, 0}, {0, 0, 2, 4, 4}, {0, 1, 1, 1, 1}}}, // IQ4_XS {12, {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}, // Q4_K {13, {{0, 0, 1, 1, 1}, {0, 4, 1, 1, 1}, {0, 1, 1, 1, 2}}}, // Q5_K {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}}, // Q6_K }; -int il_rows(int type, int ncols, int n_out) { +// 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 +// `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 +// 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 +// 1094 -> 821 us, Q6_K 12288 rows 68.9 -> 47.9 us), else 0; unmeasured classes take a neighbour's value (PR 1401) +constexpr IlRows kIlRows_70[] = { + {23, {{0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 4, 2, 2, 2}}}, // IQ4_XS + {12, {{0, 2, 2, 4, 4}, {0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}}}, // Q4_K + {13, {{0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 1, 2, 2, 2}}}, // Q5_K + {14, {{0, 1, 1, 1, 1}, {0, 2, 2, 2, 2}, {0, 2, 2, 4, 2}}}, // Q6_K +}; +struct IlArch { int cc; const IlRows* t; size_t n; }; +constexpr IlArch kIlArch[] = { + {70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)}, // Volta: PR 1401, measured on a V100-SXM2 +}; +// STRATA_MMVQ_IL_ROWS="type:ncols:r0,r1,r2,r3,r4;..." overrides single rows of the table for every card (type = ggml +// type 23/12/13/14, ncols 2-4, r* = rows a warp 0/1/2/4 for the five n_out classes). Parsed once. +struct IlEnvRow { int type, ncols; uint8_t r[5]; }; +const std::vector& il_env_rows() { + static const std::vector v = [] { + std::vector out; + const char* e = std::getenv("STRATA_MMVQ_IL_ROWS"); + if (!e) return out; + std::string str(e); + size_t pos = 0; + while (pos < str.size()) { + size_t end = str.find(';', pos); + if (end == std::string::npos) end = str.size(); + int t = 0, n = 0, r[5] = {0, 0, 0, 0, 0}, used = 0; + if (std::sscanf(str.substr(pos, end - pos).c_str(), "%d:%d:%d,%d,%d,%d,%d%n", &t, &n, &r[0], &r[1], &r[2], &r[3], + &r[4], &used) >= 7 && n >= 2 && n <= 4) { + IlEnvRow x{t, n, {}}; + bool ok = true; + for (int i = 0; i < 5; ++i) { ok = ok && (r[i] == 0 || r[i] == 1 || r[i] == 2 || r[i] == 4); x.r[i] = (uint8_t) r[i]; } + if (ok) out.push_back(x); + else std::fprintf(stderr, "strata: STRATA_MMVQ_IL_ROWS: rows must be 0/1/2/4 - entry ignored\n"); + } else { + std::fprintf(stderr, "strata: STRATA_MMVQ_IL_ROWS: cannot read '%s' (type:ncols:r0,r1,r2,r3,r4) - ignored\n", + str.substr(pos, end - pos).c_str()); + } + pos = end + 1; + } + return out; + }(); + return v; +} +} // namespace +// The rows a warp for a card of compute capability `cc` (major * 10 + minor); 0: native_mmvq's kernels. Pure, so a test +// can check every architecture's table without that card. +int native_mmvq_il_rows_for(int cc, int type, int ncols, int n_out) { + if (ncols < 2 || ncols > 4) return 0; const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; - for (const IlRows& e : kIlRows) - if (e.type == type) return e.r[ncols - 2][cls]; + for (const IlEnvRow& e : il_env_rows()) + if (e.type == type && e.ncols == ncols) return e.r[cls]; + const IlRows* t = kIlRowsShared; + size_t n = sizeof(kIlRowsShared) / sizeof(IlRows); + for (const IlArch& a : kIlArch) + if (a.cc == cc && a.t != nullptr) { 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; } +namespace { +int il_cc() { + static int cc[16] = {}; // by device ordinal, 0 unknown + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return 0; + if (cc[dev] == 0) { + int maj = 0, mnr = 0; + if (cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { cudaGetLastError(); return 0; } + cc[dev] = maj * 10 + mnr; + } + 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 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; } namespace { -// sm_80 and newer only (measured on sm_86 and sm_120): Pascal/Volta/Turing keep native_mmvq's kernels unchanged +// sm_80 and newer (measured on sm_86 and sm_120) and Volta (sm_70, its own table above); Pascal/Turing keep +// native_mmvq's kernels unchanged +// Volta (PR 1401): opt-in with STRATA_SM70_TABLE=1 until the author confirms on a V100 with the final code +bool sm70_opt_in() { const char* v = std::getenv("STRATA_SM70_TABLE"); return v != nullptr && std::atoi(v) != 0; } bool il_arch_ok() { static int ok[16] = {}; // 0 unknown, 1 yes, -1 no, by device ordinal int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false; if (ok[dev] == 0) { int major = 0; - ok[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && major >= 8) ? 1 : -1; + int minor = 0; + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + ok[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + (major >= 8 || (major == 7 && minor == 0 && sm70_opt_in()))) ? 1 : -1; } return ok[dev] > 0; } @@ -2562,6 +2642,7 @@ void native_q8_1_interleave(const void*, void*, int, int, void*) { throw std::invalid_argument("native_q8_1_interleave is CUDA only"); } bool native_mmvq_il_supported(int, int, int) { return false; } +int native_mmvq_il_rows_for(int, int, int, int) { return 0; } void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void*, float* y, int n_in, int n_out, int ncols, void* stream) { native_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 9c08b6e5..149c53b7 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -1,7 +1,10 @@ // 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] +// build/mmvq_il_parity [--bench [--emit-table]] +// +// --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. // // The same Q8_1 bytes feed both paths (quantize_q8_1_rows, then native_q8_1_interleave). Weights are random bytes with // the block scales rewritten as normal fp16 values, so every output is finite (a NaN would compare equal whatever @@ -24,6 +27,8 @@ namespace { using namespace strata::kernels; +struct Cell { int type, T, n_out; double ref; double il[5]; }; +std::vector g_cells; struct Case { const char* name; int type, n_in, n_out, block_elems, block_bytes, scale_at[2]; @@ -157,6 +162,7 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { cudaEventElapsedTime(&ms, e0, e1); best_ref = 1000.0 * ms / reps; (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]); } @@ -165,14 +171,77 @@ int run_case(const Case& c, bool bench, cudaStream_t s) { for (void* p : dw) cudaFree(p); return bad; } + +// the table as kIlRows prints it: per (type, ncols, n_out class) the fastest rows count if >= 3% under native_mmvq, else 0. +// A cell with several measured shapes takes the worst (smallest) gain of the best choice, as the shipped table does for +// two cards; a class with no measured shape prints the value of its neighbour below it (or 0). +void emit_table() { + const int types[] = {23, 12, 13, 14}; + const char* names[] = {"IQ4_XS", "Q4_K", "Q5_K", "Q6_K"}; + std::printf("// measured on this card by mmvq_il_parity --bench --emit-table\n"); + for (int ti = 0; ti < 4; ++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) { + int pick = -1; + for (const Cell& c : g_cells) { + if (c.type != types[ti] || 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) continue; + int best = 0; + double bt = c.ref * 0.97; + for (int r : {1, 2, 4}) + if (c.il[r] > 0 && c.il[r] < bt) { bt = c.il[r]; best = r; } + pick = pick < 0 ? best : (pick == best ? pick : 0); // shapes disagree: native_mmvq + } + if (pick < 0) pick = prev; + prev = pick; + std::printf("%d%s", pick, cls < 4 ? ", " : ""); + } + std::printf("}%s", nc < 4 ? ", " : ""); + } + std::printf("}}, // %s\n", names[ti]); + } +} + +// the per-architecture lookup, no GPU needed for its answers +int check_tables() { + int bad = 0; + for (int type : {23, 12, 13, 14}) + 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 must answer exactly what the measured Ampere table says + if (native_mmvq_il_rows_for(89, type, nc, n_out) != a || native_mmvq_il_rows_for(120, type, nc, n_out) != a) { + ++bad; + std::printf("FAIL table: sm_89/sm_120 differ 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); } + } + // 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) { + ++bad; + std::printf("FAIL table: the sm_70 table is not the V100's\n"); + } + if (native_mmvq_il_rows_for(89, 99, 2, 2560) != 0 || native_mmvq_il_rows_for(89, 12, 5, 2560) != 0) { + ++bad; + std::printf("FAIL table: an unknown type or ncols must be 0\n"); + } + return bad; +} } // namespace 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"; cudaStream_t s; cudaStreamCreate(&s); int bad = 0; + bad += check_tables(); for (const Case& c : CASES) bad += run_case(c, bench, s); + if (emit) emit_table(); std::printf("%s\n", bad ? "mmvq_il_parity: FAIL" : "mmvq_il_parity: OK (every case, T 2-4, rows 1/2/4 and the table, bitwise)"); return bad ? 1 : 0; } diff --git a/src/prefill/gdn_rec_parity.cu b/src/prefill/gdn_rec_parity.cu index dabcc22d..8df8ef99 100644 --- a/src/prefill/gdn_rec_parity.cu +++ b/src/prefill/gdn_rec_parity.cu @@ -5,11 +5,14 @@ // gdn_rec_cols_pipe_kernel elsewhere and with STRATA_GDN_KEYHEAD=0. Both are copied below verbatim, with the output // norm (gdn_out_norm_kernel) and the norm as it was before, which also stored the normalized value in FP32 although // nothing reads it. The two recurrences do the same arithmetic in the same order per value head and column, so the -// output, the state after it and the FP16 output must be the same bits. +// 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. // // 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 --bench and the timings at T = 8192 and 32768 (one layer, all 48 value heads); the two +// 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 // SM, as on cards with more or fewer SMs (scale), and both with the engine's grids on @@ -18,6 +21,7 @@ #include #include +#include #include #include #include @@ -240,6 +244,352 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r]; } } + +// src/prefill/kernels.cu's chunked recurrence (STRATA_GDN_CHUNKED=1), copied as it is there +// STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks of GCH tokens (the WY form of the gated delta rule, as +// flash-linear-attention computes it), all in FP32. Per value head, with g_t = exp(gate_t), gamma_t the gate's sum +// from the chunk's start to t (inclusive) and S0 the state before the chunk: +// A[t][i] = beta_t exp(gamma_t - gamma_i) k_t.k_i (i < t), T = (I + A)^-1 (unit lower triangular), +// Y_t = beta_t (v_t - exp(gamma_t) S0^T k_t), D = T Y (the delta rule's corrections, one per token), +// o_t = exp(gamma_t) S0^T q_t + sum_{i <= t} exp(gamma_t - gamma_i) (q_t.k_i) D_i, +// S = exp(gamma_last) S0 + sum_t exp(gamma_last - gamma_t) k_t D_t^T, +// the same state and outputs as the token-by-token kernels up to FP32 rounding (another order of the sums). +// gdn_chunk_prep_kernel builds T, P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) and gamma for every chunk of a +// super-block at once (a block per chunk and key head: its three value heads share k and q); gdn_chunk_scan_kernel then +// walks the super-block's chunks per (value head, 16 columns): the state slice in registers, the products as small +// register-tiled matmuls from shared memory. Every exponent is <= 0 (gates are negative), so nothing overflows. +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 +constexpr int GKP = S + 4; // the scan's padded q / k rows (8 rows of a warp land on 8 banks) +constexpr int GTP = GCH + 1; // padded T / P rows +static_assert(GCH == 32, "gdn_chunk_prep_kernel: a lane per token of the chunk"); +constexpr size_t kChunkPrepSmem = sizeof(float) * (2 * GCH * (S + 1) + 2 * GCH * GTP); // A over k / q +static_assert(VPK * GCH * GTP <= 2 * GCH * (S + 1), "gdn_chunk_prep_kernel: A fits where k and q were"); +constexpr size_t kChunkScanSmem = sizeof(float) * (3 * GCH * GKP + VPK * (S * GDV + 3 * GCH * GDV)); + +__global__ void __launch_bounds__(256) gdn_chunk_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate, + const float* __restrict__ beta, float* __restrict__ tm, + float* __restrict__ pm, float* __restrict__ gm, int64_t t0, + int64_t T) { + extern __shared__ __align__(16) float gsm[]; + float* sk = gsm; // [GCH][S + 1] + float* sq = sk + GCH * (S + 1); // [GCH][S + 1] + float* skk = sq + GCH * (S + 1); // [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 k and q: + // read by then, so two blocks share an SM) + 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); + { // k and q as float4, every load issued before the first store + 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(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(h + (tb + t) * C + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f); + } +#pragma unroll + for (int m = 0; m < NP; ++m) { + const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + float* dk = sk + t * (S + 1) + r; + float* dq = sq + t * (S + 1) + r; + dk[0] = kv[m].x; dk[1] = kv[m].y; dk[2] = kv[m].z; dk[3] = kv[m].w; + dq[0] = qv[m].x; dq[1] = qv[m].y; dq[2] = qv[m].z; dq[3] = qv[m].w; + } + } + __syncthreads(); + { // lane i, rows warp + 8m: k_t.k_i and q_t.k_i on eight independent sums (rows 129 apart: 32 banks) + constexpr int RW = GCH / 8; + float kk[RW] = {}, qk[RW] = {}; + for (int r = 0; r < S; ++r) { + const float ki = sk[lane * (S + 1) + r]; +#pragma unroll + for (int m = 0; m < RW; ++m) { + kk[m] = fmaf(sk[(warp + 8 * m) * (S + 1) + r], ki, kk[m]); + qk[m] = fmaf(sq[(warp + 8 * m) * (S + 1) + r], ki, qk[m]); + } + } +#pragma unroll + for (int m = 0; m < RW; ++m) { + const int t = warp + 8 * m; + skk[t * GTP + lane] = lane <= t ? kk[m] : 0.0f; + sqk[t * GTP + lane] = lane <= t ? qk[m] : 0.0f; + } + } + __syncthreads(); + if (warp >= VPK) return; + const int vh = qh + warp * HK, i = lane; // warp j: value head j of the key head; lane i: token i (column i) + float* a = sa + warp * GCH * GTP; + const float b = i < n ? beta[(tb + i) * HV + vh] : 0.0f; + float gam = i < n ? gate[(tb + i) * HV + vh] : 0.0f; // past the end: gate 0, beta 0 (no effect on S) +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const float u = __shfl_up_sync(0xffffffffu, gam, o); + if (lane >= o) gam += u; + } + 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 in place: 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) + // - a trip the whole warp shares, so the loads go ahead of the sums + for (int t = 1; t < GCH; ++t) { + float v = 0.0f; +#pragma unroll 8 + for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], a[k * GTP + i], v); + __syncwarp(); + if (i < t) a[t * GTP + i] = v; + __syncwarp(); + } + float* T_ = tm + ((int64_t) ch * HV + vh) * GCH * GCH; + float* P_ = pm + ((int64_t) ch * HV + vh) * GCH * GCH; + for (int t = 0; t < GCH; ++t) { + const float gt = __shfl_sync(0xffffffffu, gam, t); + T_[t * GCH + i] = a[t * GTP + i]; + P_[t * GCH + i] = i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f; + } + gm[((int64_t) ch * HV + vh) * GCH + i] = gam; +} + +__device__ __forceinline__ void gdn_pf_l2(const float* p) { asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); } +__device__ __forceinline__ void gdn_cp_wait_all() { +#if STRATA_GDN_CP_ASYNC + asm volatile("cp.async.wait_all;\n" ::); +#endif +} +// A block per (key head, 16 value columns): 128 threads for each of the key head's three value heads, which share the +// staged k and q rows. 128 blocks, one an SM, in one wave (each walks every chunk: a second wave would double the +// time). A thread owns one token's row of the products (4 columns) and holds that token's T and P rows in registers, +// loaded at the chunk's start so they land during the first product; the next chunk's k (a second buffer), q (after +// this chunk's last read of q), v, gamma and beta load while this chunk computes. Three barriers a chunk. +__global__ void __launch_bounds__(128 * VPK) gdn_chunk_scan_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ beta, const float* __restrict__ tm, + const float* __restrict__ pm, const float* __restrict__ gm, + float* __restrict__ oc_out, int64_t t0, int nch, int64_t T) { + extern __shared__ __align__(16) float gsm[]; + constexpr int NT = 128 * VPK, HEAD = S * GDV + 3 * GCH * GDV; // threads; a head's shared floats + float* kbuf = gsm; // [2][GCH][GKP] k, double-buffered + float* sq = kbuf + 2 * GCH * GKP; // [GCH][GKP] + const int qh = blockIdx.x, c0 = blockIdx.y * GDV, j = threadIdx.x / 128, tid = threadIdx.x % 128; + const int vh = qh + j * HK; + float* ss = sq + GCH * GKP + j * HEAD; // [S][GDV] the state slice at the chunk's start + float* sy = ss + S * GDV; // [GCH][GDV] Y + float* sd = sy + GCH * GDV; // [GCH][GDV] D + float* sdd = sd + GCH * GDV; // [GCH][GDV] exp(gamma_last - gamma_t) D + const int rq = tid >> 2, vq = tid & 3; // the update's tile: rows 4rq..4rq+3; both tiles: columns 4vq..4vq+3 + const int tt = tid >> 2, vv = 4 * vq; // the products' tile: token tt + const size_t rs = (size_t) HV * S; + auto stage_kq = [&](int64_t c_t0, int n, float* dst, bool isq) { // k or q rows of a chunk, cp.async + for (int p = threadIdx.x; p < GCH * (S / 4); p += NT) { + const int t = p / (S / 4), r = (p % (S / 4)) * 4; + if (t < n) gdn_cp16(dst + t * GKP + r, h + (c_t0 + t) * C + (isq ? 0 : HK * S) + qh * S + r); + else *reinterpret_cast(dst + t * GKP + r) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + }; + // this tile's v, gamma, beta and the chunk's last gamma (registers) + auto load_vgb = [&](int ch, int64_t c_t0, int n, float4& v4, float& gam, float& bet, float& glast) { + v4 = tt < n ? __ldg(reinterpret_cast(h + (c_t0 + tt) * C + 2 * HK * S + vh * S + c0 + vv)) + : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + const float* g = gm + ((int64_t) ch * HV + vh) * GCH; + gam = __ldg(g + tt); + glast = __ldg(g + GCH - 1); + bet = tt < n ? __ldg(beta + (c_t0 + tt) * HV + vh) : 0.0f; + }; + float s[4][4]; +#pragma unroll + for (int x = 0; x < 4; ++x) { +#pragma unroll + for (int y = 0; y < 4; ++y) s[x][y] = state[(size_t) (4 * rq + x) * rs + (size_t) vh * S + c0 + vv + y]; + *reinterpret_cast(&ss[(4 * rq + x) * GDV + vv]) = make_float4(s[x][0], s[x][1], s[x][2], s[x][3]); + } + const float out_scale = rsqrtf((float) S); + float4 v4; + float gam, bet, glast; + { + const int n0 = (int) min((int64_t) GCH, T - t0); + stage_kq(t0, n0, kbuf, false); + stage_kq(t0, n0, sq, true); + gdn_cp_commit(); + load_vgb(0, t0, n0, v4, gam, bet, glast); + gdn_cp_wait_all(); + __syncthreads(); + } + for (int ch = 0; ch < nch; ++ch) { + const int64_t c_t0 = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - c_t0); + const bool more = ch + 1 < nch; + const int64_t n_t0 = c_t0 + GCH; + const int nn = more ? (int) min((int64_t) GCH, T - n_t0) : 0; + const float* sk = kbuf + (ch & 1) * GCH * GKP; + // this token's T and P rows into registers now: they land while the first product runs + float tr[GCH], pr[GCH]; + { + const float4* T4 = reinterpret_cast(tm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH); + const float4* P4 = reinterpret_cast(pm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH); +#pragma unroll + for (int i = 0; i < GCH / 4; ++i) { + const float4 a = __ldg(T4 + i), b = __ldg(P4 + i); + tr[4 * i] = a.x; tr[4 * i + 1] = a.y; tr[4 * i + 2] = a.z; tr[4 * i + 3] = a.w; + pr[4 * i] = b.x; pr[4 * i + 1] = b.y; pr[4 * i + 2] = b.z; pr[4 * i + 3] = b.w; + } + } + float4 nv4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float ngam = 0.0f, nbet = 0.0f, nglast = 0.0f; + if (more) { // the next chunk's v, gamma and beta; the one after into L2 (its k and q: after barrier A) + load_vgb(ch + 1, n_t0, nn, nv4, ngam, nbet, nglast); + const int64_t f_t0 = n_t0 + GCH; + const int t = threadIdx.x >> 3, l = threadIdx.x & 7; + if (t < GCH && f_t0 + t < T) gdn_pf_l2(h + (f_t0 + t) * C + (l < 4 ? HK * S : 0) + qh * S + 32 * (l & 3)); + if (tid < GCH) { + gdn_pf_l2(tm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH); + gdn_pf_l2(pm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH); + } + } + // X = K S0 and Q S0 for token tt, then Y = beta (V - exp(gamma) X) + float x[4] = {0.f, 0.f, 0.f, 0.f}, qs[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll 4 + for (int r = 0; r < S; r += 4) { + const float4 k4 = *reinterpret_cast(&sk[tt * GKP + r]); + const float4 q4 = *reinterpret_cast(&sq[tt * GKP + r]); + const float kk[4] = {k4.x, k4.y, k4.z, k4.w}, qq[4] = {q4.x, q4.y, q4.z, q4.w}; +#pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const float4 s4 = *reinterpret_cast(&ss[(r + jj) * GDV + vv]); + x[0] = fmaf(kk[jj], s4.x, x[0]); x[1] = fmaf(kk[jj], s4.y, x[1]); + x[2] = fmaf(kk[jj], s4.z, x[2]); x[3] = fmaf(kk[jj], s4.w, x[3]); + qs[0] = fmaf(qq[jj], s4.x, qs[0]); qs[1] = fmaf(qq[jj], s4.y, qs[1]); + qs[2] = fmaf(qq[jj], s4.z, qs[2]); qs[3] = fmaf(qq[jj], s4.w, qs[3]); + } + } + const float e = expf(gam); + *reinterpret_cast(&sy[tt * GDV + vv]) = make_float4(bet * (v4.x - e * x[0]), bet * (v4.y - e * x[1]), + bet * (v4.z - e * x[2]), bet * (v4.w - e * x[3])); + __syncthreads(); // (A) Y complete; every read of q done + if (more) { // the next chunk's k into the other buffer, its q into the single q buffer + stage_kq(n_t0, nn, kbuf + ((ch + 1) & 1) * GCH * GKP, false); + stage_kq(n_t0, nn, sq, true); + gdn_cp_commit(); + } + // D = T Y (T is zero above its diagonal), and D decayed to the chunk's end for the update + float d[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int i = 0; i < GCH; ++i) { + const float4 y4 = *reinterpret_cast(&sy[i * GDV + vv]); + d[0] = fmaf(tr[i], y4.x, d[0]); d[1] = fmaf(tr[i], y4.y, d[1]); + d[2] = fmaf(tr[i], y4.z, d[2]); d[3] = fmaf(tr[i], y4.w, d[3]); + } + const float f = expf(glast - gam); + *reinterpret_cast(&sd[tt * GDV + vv]) = make_float4(d[0], d[1], d[2], d[3]); + *reinterpret_cast(&sdd[tt * GDV + vv]) = make_float4(f * d[0], f * d[1], f * d[2], f * d[3]); + __syncthreads(); // (B) D complete + // o = exp(gamma) Q S0 + P D (P is zero above its diagonal), the output + float o[4] = {e * qs[0], e * qs[1], e * qs[2], e * qs[3]}; +#pragma unroll + for (int i = 0; i < GCH; ++i) { + const float4 d4 = *reinterpret_cast(&sd[i * GDV + vv]); + o[0] = fmaf(pr[i], d4.x, o[0]); o[1] = fmaf(pr[i], d4.y, o[1]); + o[2] = fmaf(pr[i], d4.z, o[2]); o[3] = fmaf(pr[i], d4.w, o[3]); + } + if (tt < n) + *reinterpret_cast(oc_out + (c_t0 + tt) * HV * S + vh * S + c0 + vv) = + make_float4(o[0] * out_scale, o[1] * out_scale, o[2] * out_scale, o[3] * out_scale); + // S = exp(gamma_last) S0 + K^T (decayed D) + const float gL = expf(glast); +#pragma unroll + for (int xx = 0; xx < 4; ++xx) +#pragma unroll + for (int y = 0; y < 4; ++y) s[xx][y] *= gL; +#pragma unroll 4 + for (int t = 0; t < GCH; ++t) { + const float4 k4 = *reinterpret_cast(&sk[t * GKP + 4 * rq]); + const float4 d4 = *reinterpret_cast(&sdd[t * GDV + vv]); + const float kx[4] = {k4.x, k4.y, k4.z, k4.w}, dy[4] = {d4.x, d4.y, d4.z, d4.w}; +#pragma unroll + for (int xx = 0; xx < 4; ++xx) +#pragma unroll + for (int y = 0; y < 4; ++y) s[xx][y] = fmaf(kx[xx], dy[y], s[xx][y]); + } +#pragma unroll + for (int xx = 0; xx < 4; ++xx) + *reinterpret_cast(&ss[(4 * rq + xx) * GDV + vv]) = make_float4(s[xx][0], s[xx][1], s[xx][2], s[xx][3]); + v4 = nv4; gam = ngam; bet = nbet; glast = nglast; + gdn_cp_wait_all(); + __syncthreads(); // (C) the new ss, the next k and q landed; every read of sd, sdd and this k buffer done + } +#pragma unroll + for (int xx = 0; xx < 4; ++xx) +#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 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 +// keeps its memory, cost host time the GPU waited for (a 2K prompt's recurrence took 78 ms against 34 ms for +// gdn_rec_kh_kernel). +float* gdn_chunk_scratch() { + static float* bufs[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return nullptr; } + if (bufs[dev] == nullptr) { + const size_t n = (size_t) (GSB / GCH) * HV * (2 * GCH * GCH + GCH); + if (cudaMalloc((void**) &bufs[dev], n * sizeof(float)) != cudaSuccess) { + cudaGetLastError(); + bufs[dev] = nullptr; + } + } + return bufs[dev]; +} + +// The whole recurrence of T tokens in super-blocks of GSB: a prep and a scan launch each, the scratch (T, P and gamma +// of a super-block's chunks: up to GSB / GCH x 48 heads x (2 x 32 x 32 + 32) floats, 25.6 MB) from gdn_chunk_scratch. +// y: the [T][HV][S] output. An error return means nothing was launched (the caller takes another kernel): the scratch +// could not be had, or the card has fewer than 128 SMs (a second wave of the scan would double it) or too little +// shared memory for it (Turing). +cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, + cudaStream_t s) { + if (T <= 0) return cudaSuccess; + { // sm_80+ (cp.async), the scan's 128 blocks one an SM in one wave, and its 93.7 KB of shared memory (else: + // another kernel) + 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; + } + // as in kernels.cu: STRATA_GDN_CHUNKED=2 skips the SM-count test (to measure a card under 128 SMs) + static const bool any_sms = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) >= 2; }(); + if (major < 8 || (!any_sms && sms < HK * (S / GDV)) || (size_t) smem < kChunkScanSmem) + return cudaErrorNotSupported; + } + float* scratch = gdn_chunk_scratch(); + if (scratch == nullptr) return cudaErrorMemoryAllocation; + const int nb = (int) ((std::min(GSB, T) + GCH - 1) / GCH); + const size_t tsz = (size_t) nb * HV * GCH * GCH; + float *tm = scratch, *pm = tm + tsz, *gm = pm + tsz; + { // once a device + static bool attrs[64] = {}; + int dev = 0; + cudaGetDevice(&dev); + if (dev >= 0 && dev < 64 && !attrs[dev]) { + cudaFuncSetAttribute(gdn_chunk_prep_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkPrepSmem); + cudaFuncSetAttribute(gdn_chunk_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkScanSmem); + attrs[dev] = true; + } + } + for (int64_t t0 = 0; t0 < T; t0 += GSB) { + const int nch = (int) ((std::min(GSB, T - t0) + GCH - 1) / GCH); + gdn_chunk_prep_kernel<<>>(h, gate, beta, tm, pm, gm, t0, T); + gdn_chunk_scan_kernel<<>>(state, h, beta, tm, pm, gm, y, t0, nch, T); + } + return cudaSuccess; // launch errors surface at the caller's check; an error above means nothing ran +} // 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, @@ -458,6 +808,92 @@ int check_bits(int64_t T, uint64_t seed) { return fails; } +// The chunked recurrence against gdn_rec_kh_kernel (other bits: the largest |difference| over the largest |value|, the +// output and the state after the chunk); a failure above 1e-4 (FP32 sums in another order stay near 1e-6). +double max_rel(const float* a, const float* b, size_t n) { + std::vector x(n), y(n); + ck(cudaMemcpy(x.data(), a, n * 4, cudaMemcpyDeviceToHost), "copy"); + ck(cudaMemcpy(y.data(), b, n * 4, cudaMemcpyDeviceToHost), "copy"); + double md = 0.0, mv = 0.0; + for (size_t i = 0; i < n; ++i) { + md = std::max(md, (double) std::fabs(x[i] - y[i])); + mv = std::max(mv, (double) std::fabs(x[i])); + } + return mv > 0.0 ? md / mv : md; +} +// The recurrence in FP64 (a thread per value head and column, the state in local memory): the reference both FP32 +// recurrences are measured against +__global__ void gdn_rec_f64_kernel(double* __restrict__ state, const float* __restrict__ h, const float* __restrict__ gate, + const float* __restrict__ beta, double* __restrict__ out, int64_t T) { + const int head = blockIdx.x, col = threadIdx.x, qh = head % HK; + double s[S]; + for (int r = 0; r < S; ++r) s[r] = state[((size_t) r * HV + head) * S + col]; + for (int64_t t = 0; t < T; ++t) { + const float* ht = h + t * C; + const double g = exp((double) gate[t * HV + head]), b = beta[t * HV + head]; + double kv = 0.0; + for (int r = 0; r < S; ++r) kv += s[r] * ht[HK * S + qh * S + r]; + const double delta = (ht[2 * HK * S + head * S + col] - g * kv) * b; + double o = 0.0; + for (int r = 0; r < S; ++r) { + s[r] = g * s[r] + ht[HK * S + qh * S + r] * delta; + o += s[r] * ht[qh * S + r]; + } + out[(t * HV + head) * S + col] = o / sqrt((double) S); + } + for (int r = 0; r < S; ++r) state[((size_t) r * HV + head) * S + col] = s[r]; +} +__global__ void to_f64(const float* x, double* y, int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) y[i] = x[i]; +} +double max_rel_f64(const float* a, const double* ref, size_t n) { // max |a - ref| / max |ref| + std::vector x(n); + std::vector y(n); + ck(cudaMemcpy(x.data(), a, n * 4, cudaMemcpyDeviceToHost), "copy"); + ck(cudaMemcpy(y.data(), ref, n * 8, cudaMemcpyDeviceToHost), "copy"); + double md = 0.0, mv = 0.0; + for (size_t i = 0; i < n; ++i) { + md = std::max(md, std::fabs(x[i] - y[i])); + mv = std::max(mv, std::fabs(y[i])); + } + return mv > 0.0 ? md / mv : md; +} +int check_chunked(int64_t T, uint64_t seed) { + Inputs in(T, seed); + const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S; + float* s0 = dalloc(st); + float* s1 = dalloc(st); + float* o0 = dalloc(oc_n); + float* o1 = dalloc(oc_n); + ck(cudaMemcpy(s0, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy"); + ck(cudaMemcpy(s1, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy"); + gdn_rec_kh_kernel<<>>(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); + 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); + cudaFree(s0); cudaFree(s1); cudaFree(o0); cudaFree(o1); + return 0; + } + ck(e, "chunked"); + ck(cudaDeviceSynchronize(), "chunked run"); + 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); + if (T <= 8192) { // both against FP64 (its output: 8 bytes a value, so not at 32K) + double* sd = dalloc(st); + double* od = dalloc(oc_n); + to_f64<<<1024, 256>>>(in.state0, sd, (int64_t) st); + gdn_rec_f64_kernel<<>>(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", + 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; +} + float median(std::vector v) { std::sort(v.begin(), v.end()); return v.empty() ? 0.0f : v[v.size() / 2]; @@ -501,12 +937,29 @@ void bench(int64_t T) { if (i >= warm) t_norm[v].push_back(ms); } } + std::vector 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 && + cudaDeviceSynchronize() == cudaSuccess; + for (int i = 0; can_chunk && 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<<>>(state, in.h, in.gate, in.beta, oc, in.T); + else ck(gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0), "chunked"); + }); + if (i >= warm) t_kc[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); 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, 1000.0f * r1 / (float) T, r0 / r1); + if (can_chunk) { + const float kh = median(t_kc[0]), kc = median(t_kc[1]); + 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); + } 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", @@ -516,6 +969,46 @@ void bench(int64_t T) { cudaFree(state); cudaFree(oc); cudaFree(y16); } +// gdn_rec_kh_kernel against the chunked recurrence on short chunks (the chunked one's launches, host side included: +// the GPU is idle at each start), where kernels.cu's kGdnChunkedMin comes from +void chunked_sweep() { + std::printf(" short chunks, gdn_rec_kh_kernel -> chunked (medians of 21 alternating runs):\n"); + for (const int64_t T : {32, 64, 96, 128, 192, 256, 512, 1024}) { + Inputs in(T, 0xC5); + const size_t st = (size_t) S * HV * S; + float* state = dalloc(st); + float* oc = dalloc((size_t) T * HV * S); + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "event"); + ck(cudaEventCreate(&e1), "event"); + const bool can = gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0) == cudaSuccess && + cudaDeviceSynchronize() == cudaSuccess; + std::vector t[2]; + for (int i = 0; can && i < 5 + 21; ++i) + for (int j = 0; j < 2; ++j) { + const int v = (i + j) % 2; + ck(cudaMemcpy(state, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state"); + cudaEventRecord(e0); + if (v == 0) gdn_rec_kh_kernel<<>>(state, in.h, in.gate, in.beta, oc, in.T); + else ck(gdn_rec_chunked(state, in.h, in.gate, in.beta, oc, in.T, 0), "chunked"); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "timed"); + float ms = 0.0f; + cudaEventElapsedTime(&ms, e0, e1); + if (i >= 5) t[v].push_back(ms); + } + if (can) { + const float kh = median(t[0]), kc = median(t[1]); + std::printf(" T = %-5lld %8.1f us -> %8.1f us %.2fx\n", (long long) T, 1000.0f * kh, 1000.0f * kc, kh / kc); + } else { + std::printf(" chunked: not on this card\n"); + } + cudaEventDestroy(e0); cudaEventDestroy(e1); + cudaFree(state); cudaFree(oc); + if (!can) return; + } +} + // The two kernels at a given number of blocks per SM, as on cards with more or fewer SMs than this one: the kernel // before puts ceil(192 / SMs) of its blocks on an SM, gdn_rec_kh_kernel ceil(64 / SMs), and the busiest SM sets the // pace (every block walks the whole chunk). b blocks per SM here: b rounds of one block per SM, each round one launch @@ -874,10 +1367,14 @@ int main(int argc, char** argv) { 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++); if (do_bench) { std::printf("--bench: the prompt path's DeltaNet recurrence\n"); + bench(2048); bench(8192); bench(32768); + chunked_sweep(); scale(8192); fewer_sms(8192); } diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 3f14fb16..5314a5f1 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -3,6 +3,7 @@ #include "strata/kernels/mrope.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/kernels/router_top10.hpp" +#include "strata/core/emulate.hpp" #include #include @@ -710,6 +711,356 @@ bool gdn_keyhead_ok() { } return known[dev] == 1; } +// STRATA_GDN_CHUNKED=1 (opt-in): the recurrence in chunks of GCH tokens (the WY form of the gated delta rule, as +// flash-linear-attention computes it), all in FP32. Per value head, with g_t = exp(gate_t), gamma_t the gate's sum +// from the chunk's start to t (inclusive) and S0 the state before the chunk: +// A[t][i] = beta_t exp(gamma_t - gamma_i) k_t.k_i (i < t), T = (I + A)^-1 (unit lower triangular), +// Y_t = beta_t (v_t - exp(gamma_t) S0^T k_t), D = T Y (the delta rule's corrections, one per token), +// o_t = exp(gamma_t) S0^T q_t + sum_{i <= t} exp(gamma_t - gamma_i) (q_t.k_i) D_i, +// S = exp(gamma_last) S0 + sum_t exp(gamma_last - gamma_t) k_t D_t^T, +// the same state and outputs as the token-by-token kernels up to FP32 rounding (another order of the sums). +// gdn_chunk_prep_kernel builds T, P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) and gamma for every chunk of a +// super-block at once (a block per chunk and key head: its three value heads share k and q); gdn_chunk_scan_kernel then +// walks the super-block's chunks per (value head, 16 columns): the state slice in registers, the products as small +// register-tiled matmuls from shared memory. Every exponent is <= 0 (gates are negative), so nothing overflows. +// STRATA_GDN_CHUNKED=1 takes prompt chunks of this many tokens and more: on an RTX 5090 the two launches cost more +// 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 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 +constexpr int GKP = S + 4; // the scan's padded q / k rows (8 rows of a warp land on 8 banks) +constexpr int GTP = GCH + 1; // padded T / P rows +static_assert(GCH == 32, "gdn_chunk_prep_kernel: a lane per token of the chunk"); +constexpr size_t kChunkPrepSmem = sizeof(float) * (2 * GCH * (S + 1) + 2 * GCH * GTP); // A over k / q +static_assert(VPK * GCH * GTP <= 2 * GCH * (S + 1), "gdn_chunk_prep_kernel: A fits where k and q were"); +constexpr size_t kChunkScanSmem = sizeof(float) * (3 * GCH * GKP + VPK * (S * GDV + 3 * GCH * GDV)); + +__global__ void __launch_bounds__(256) gdn_chunk_prep_kernel(const float* __restrict__ h, const float* __restrict__ gate, + const float* __restrict__ beta, float* __restrict__ tm, + float* __restrict__ pm, float* __restrict__ gm, int64_t t0, + int64_t T) { + extern __shared__ __align__(16) float gsm[]; + float* sk = gsm; // [GCH][S + 1] + float* sq = sk + GCH * (S + 1); // [GCH][S + 1] + float* skk = sq + GCH * (S + 1); // [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 k and q: + // read by then, so two blocks share an SM) + 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); + { // k and q as float4, every load issued before the first store + 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(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(h + (tb + t) * C + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f); + } +#pragma unroll + for (int m = 0; m < NP; ++m) { + const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4; + float* dk = sk + t * (S + 1) + r; + float* dq = sq + t * (S + 1) + r; + dk[0] = kv[m].x; dk[1] = kv[m].y; dk[2] = kv[m].z; dk[3] = kv[m].w; + dq[0] = qv[m].x; dq[1] = qv[m].y; dq[2] = qv[m].z; dq[3] = qv[m].w; + } + } + __syncthreads(); + { // lane i, rows warp + 8m: k_t.k_i and q_t.k_i on eight independent sums (rows 129 apart: 32 banks) + constexpr int RW = GCH / 8; + float kk[RW] = {}, qk[RW] = {}; + for (int r = 0; r < S; ++r) { + const float ki = sk[lane * (S + 1) + r]; +#pragma unroll + for (int m = 0; m < RW; ++m) { + kk[m] = fmaf(sk[(warp + 8 * m) * (S + 1) + r], ki, kk[m]); + qk[m] = fmaf(sq[(warp + 8 * m) * (S + 1) + r], ki, qk[m]); + } + } +#pragma unroll + for (int m = 0; m < RW; ++m) { + const int t = warp + 8 * m; + skk[t * GTP + lane] = lane <= t ? kk[m] : 0.0f; + sqk[t * GTP + lane] = lane <= t ? qk[m] : 0.0f; + } + } + __syncthreads(); + if (warp >= VPK) return; + const int vh = qh + warp * HK, i = lane; // warp j: value head j of the key head; lane i: token i (column i) + float* a = sa + warp * GCH * GTP; + const float b = i < n ? beta[(tb + i) * HV + vh] : 0.0f; + float gam = i < n ? gate[(tb + i) * HV + vh] : 0.0f; // past the end: gate 0, beta 0 (no effect on S) +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const float u = __shfl_up_sync(0xffffffffu, gam, o); + if (lane >= o) gam += u; + } + 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 in place: 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) + // - a trip the whole warp shares, so the loads go ahead of the sums + for (int t = 1; t < GCH; ++t) { + float v = 0.0f; +#pragma unroll 8 + for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], a[k * GTP + i], v); + __syncwarp(); + if (i < t) a[t * GTP + i] = v; + __syncwarp(); + } + float* T_ = tm + ((int64_t) ch * HV + vh) * GCH * GCH; + float* P_ = pm + ((int64_t) ch * HV + vh) * GCH * GCH; + for (int t = 0; t < GCH; ++t) { + const float gt = __shfl_sync(0xffffffffu, gam, t); + T_[t * GCH + i] = a[t * GTP + i]; + P_[t * GCH + i] = i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f; + } + gm[((int64_t) ch * HV + vh) * GCH + i] = gam; +} + +__device__ __forceinline__ void gdn_pf_l2(const float* p) { asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); } +__device__ __forceinline__ void gdn_cp_wait_all() { +#if STRATA_GDN_CP_ASYNC + asm volatile("cp.async.wait_all;\n" ::); +#endif +} +// A block per (key head, 16 value columns): 128 threads for each of the key head's three value heads, which share the +// staged k and q rows. 128 blocks, one an SM, in one wave (each walks every chunk: a second wave would double the +// time). A thread owns one token's row of the products (4 columns) and holds that token's T and P rows in registers, +// loaded at the chunk's start so they land during the first product; the next chunk's k (a second buffer), q (after +// this chunk's last read of q), v, gamma and beta load while this chunk computes. Three barriers a chunk. +__global__ void __launch_bounds__(128 * VPK) gdn_chunk_scan_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ beta, const float* __restrict__ tm, + const float* __restrict__ pm, const float* __restrict__ gm, + float* __restrict__ oc_out, int64_t t0, int nch, int64_t T) { + extern __shared__ __align__(16) float gsm[]; + constexpr int NT = 128 * VPK, HEAD = S * GDV + 3 * GCH * GDV; // threads; a head's shared floats + float* kbuf = gsm; // [2][GCH][GKP] k, double-buffered + float* sq = kbuf + 2 * GCH * GKP; // [GCH][GKP] + const int qh = blockIdx.x, c0 = blockIdx.y * GDV, j = threadIdx.x / 128, tid = threadIdx.x % 128; + const int vh = qh + j * HK; + float* ss = sq + GCH * GKP + j * HEAD; // [S][GDV] the state slice at the chunk's start + float* sy = ss + S * GDV; // [GCH][GDV] Y + float* sd = sy + GCH * GDV; // [GCH][GDV] D + float* sdd = sd + GCH * GDV; // [GCH][GDV] exp(gamma_last - gamma_t) D + const int rq = tid >> 2, vq = tid & 3; // the update's tile: rows 4rq..4rq+3; both tiles: columns 4vq..4vq+3 + const int tt = tid >> 2, vv = 4 * vq; // the products' tile: token tt + const size_t rs = (size_t) HV * S; + auto stage_kq = [&](int64_t c_t0, int n, float* dst, bool isq) { // k or q rows of a chunk, cp.async + for (int p = threadIdx.x; p < GCH * (S / 4); p += NT) { + const int t = p / (S / 4), r = (p % (S / 4)) * 4; + if (t < n) gdn_cp16(dst + t * GKP + r, h + (c_t0 + t) * C + (isq ? 0 : HK * S) + qh * S + r); + else *reinterpret_cast(dst + t * GKP + r) = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + }; + // this tile's v, gamma, beta and the chunk's last gamma (registers) + auto load_vgb = [&](int ch, int64_t c_t0, int n, float4& v4, float& gam, float& bet, float& glast) { + v4 = tt < n ? __ldg(reinterpret_cast(h + (c_t0 + tt) * C + 2 * HK * S + vh * S + c0 + vv)) + : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + const float* g = gm + ((int64_t) ch * HV + vh) * GCH; + gam = __ldg(g + tt); + glast = __ldg(g + GCH - 1); + bet = tt < n ? __ldg(beta + (c_t0 + tt) * HV + vh) : 0.0f; + }; + float s[4][4]; +#pragma unroll + for (int x = 0; x < 4; ++x) { +#pragma unroll + for (int y = 0; y < 4; ++y) s[x][y] = state[(size_t) (4 * rq + x) * rs + (size_t) vh * S + c0 + vv + y]; + *reinterpret_cast(&ss[(4 * rq + x) * GDV + vv]) = make_float4(s[x][0], s[x][1], s[x][2], s[x][3]); + } + const float out_scale = rsqrtf((float) S); + float4 v4; + float gam, bet, glast; + { + const int n0 = (int) min((int64_t) GCH, T - t0); + stage_kq(t0, n0, kbuf, false); + stage_kq(t0, n0, sq, true); + gdn_cp_commit(); + load_vgb(0, t0, n0, v4, gam, bet, glast); + gdn_cp_wait_all(); + __syncthreads(); + } + for (int ch = 0; ch < nch; ++ch) { + const int64_t c_t0 = t0 + (int64_t) ch * GCH; + const int n = (int) min((int64_t) GCH, T - c_t0); + const bool more = ch + 1 < nch; + const int64_t n_t0 = c_t0 + GCH; + const int nn = more ? (int) min((int64_t) GCH, T - n_t0) : 0; + const float* sk = kbuf + (ch & 1) * GCH * GKP; + // this token's T and P rows into registers now: they land while the first product runs + float tr[GCH], pr[GCH]; + { + const float4* T4 = reinterpret_cast(tm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH); + const float4* P4 = reinterpret_cast(pm + (((int64_t) ch * HV + vh) * GCH + tt) * GCH); +#pragma unroll + for (int i = 0; i < GCH / 4; ++i) { + const float4 a = __ldg(T4 + i), b = __ldg(P4 + i); + tr[4 * i] = a.x; tr[4 * i + 1] = a.y; tr[4 * i + 2] = a.z; tr[4 * i + 3] = a.w; + pr[4 * i] = b.x; pr[4 * i + 1] = b.y; pr[4 * i + 2] = b.z; pr[4 * i + 3] = b.w; + } + } + float4 nv4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float ngam = 0.0f, nbet = 0.0f, nglast = 0.0f; + if (more) { // the next chunk's v, gamma and beta; the one after into L2 (its k and q: after barrier A) + load_vgb(ch + 1, n_t0, nn, nv4, ngam, nbet, nglast); + const int64_t f_t0 = n_t0 + GCH; + const int t = threadIdx.x >> 3, l = threadIdx.x & 7; + if (t < GCH && f_t0 + t < T) gdn_pf_l2(h + (f_t0 + t) * C + (l < 4 ? HK * S : 0) + qh * S + 32 * (l & 3)); + if (tid < GCH) { + gdn_pf_l2(tm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH); + gdn_pf_l2(pm + (((int64_t) (ch + 1) * HV + vh) * GCH + tid) * GCH); + } + } + // X = K S0 and Q S0 for token tt, then Y = beta (V - exp(gamma) X) + float x[4] = {0.f, 0.f, 0.f, 0.f}, qs[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll 4 + for (int r = 0; r < S; r += 4) { + const float4 k4 = *reinterpret_cast(&sk[tt * GKP + r]); + const float4 q4 = *reinterpret_cast(&sq[tt * GKP + r]); + const float kk[4] = {k4.x, k4.y, k4.z, k4.w}, qq[4] = {q4.x, q4.y, q4.z, q4.w}; +#pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const float4 s4 = *reinterpret_cast(&ss[(r + jj) * GDV + vv]); + x[0] = fmaf(kk[jj], s4.x, x[0]); x[1] = fmaf(kk[jj], s4.y, x[1]); + x[2] = fmaf(kk[jj], s4.z, x[2]); x[3] = fmaf(kk[jj], s4.w, x[3]); + qs[0] = fmaf(qq[jj], s4.x, qs[0]); qs[1] = fmaf(qq[jj], s4.y, qs[1]); + qs[2] = fmaf(qq[jj], s4.z, qs[2]); qs[3] = fmaf(qq[jj], s4.w, qs[3]); + } + } + const float e = expf(gam); + *reinterpret_cast(&sy[tt * GDV + vv]) = make_float4(bet * (v4.x - e * x[0]), bet * (v4.y - e * x[1]), + bet * (v4.z - e * x[2]), bet * (v4.w - e * x[3])); + __syncthreads(); // (A) Y complete; every read of q done + if (more) { // the next chunk's k into the other buffer, its q into the single q buffer + stage_kq(n_t0, nn, kbuf + ((ch + 1) & 1) * GCH * GKP, false); + stage_kq(n_t0, nn, sq, true); + gdn_cp_commit(); + } + // D = T Y (T is zero above its diagonal), and D decayed to the chunk's end for the update + float d[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int i = 0; i < GCH; ++i) { + const float4 y4 = *reinterpret_cast(&sy[i * GDV + vv]); + d[0] = fmaf(tr[i], y4.x, d[0]); d[1] = fmaf(tr[i], y4.y, d[1]); + d[2] = fmaf(tr[i], y4.z, d[2]); d[3] = fmaf(tr[i], y4.w, d[3]); + } + const float f = expf(glast - gam); + *reinterpret_cast(&sd[tt * GDV + vv]) = make_float4(d[0], d[1], d[2], d[3]); + *reinterpret_cast(&sdd[tt * GDV + vv]) = make_float4(f * d[0], f * d[1], f * d[2], f * d[3]); + __syncthreads(); // (B) D complete + // o = exp(gamma) Q S0 + P D (P is zero above its diagonal), the output + float o[4] = {e * qs[0], e * qs[1], e * qs[2], e * qs[3]}; +#pragma unroll + for (int i = 0; i < GCH; ++i) { + const float4 d4 = *reinterpret_cast(&sd[i * GDV + vv]); + o[0] = fmaf(pr[i], d4.x, o[0]); o[1] = fmaf(pr[i], d4.y, o[1]); + o[2] = fmaf(pr[i], d4.z, o[2]); o[3] = fmaf(pr[i], d4.w, o[3]); + } + if (tt < n) + *reinterpret_cast(oc_out + (c_t0 + tt) * HV * S + vh * S + c0 + vv) = + make_float4(o[0] * out_scale, o[1] * out_scale, o[2] * out_scale, o[3] * out_scale); + // S = exp(gamma_last) S0 + K^T (decayed D) + const float gL = expf(glast); +#pragma unroll + for (int xx = 0; xx < 4; ++xx) +#pragma unroll + for (int y = 0; y < 4; ++y) s[xx][y] *= gL; +#pragma unroll 4 + for (int t = 0; t < GCH; ++t) { + const float4 k4 = *reinterpret_cast(&sk[t * GKP + 4 * rq]); + const float4 d4 = *reinterpret_cast(&sdd[t * GDV + vv]); + const float kx[4] = {k4.x, k4.y, k4.z, k4.w}, dy[4] = {d4.x, d4.y, d4.z, d4.w}; +#pragma unroll + for (int xx = 0; xx < 4; ++xx) +#pragma unroll + for (int y = 0; y < 4; ++y) s[xx][y] = fmaf(kx[xx], dy[y], s[xx][y]); + } +#pragma unroll + for (int xx = 0; xx < 4; ++xx) + *reinterpret_cast(&ss[(4 * rq + xx) * GDV + vv]) = make_float4(s[xx][0], s[xx][1], s[xx][2], s[xx][3]); + v4 = nv4; gam = ngam; bet = nbet; glast = nglast; + gdn_cp_wait_all(); + __syncthreads(); // (C) the new ss, the next k and q landed; every read of sd, sdd and this k buffer done + } +#pragma unroll + for (int xx = 0; xx < 4; ++xx) +#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 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 +// keeps its memory, cost host time the GPU waited for (a 2K prompt's recurrence took 78 ms against 34 ms for +// gdn_rec_kh_kernel). +float* gdn_chunk_scratch() { + static float* bufs[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return nullptr; } + if (bufs[dev] == nullptr) { + const size_t n = (size_t) (GSB / GCH) * HV * (2 * GCH * GCH + GCH); + if (cudaMalloc((void**) &bufs[dev], n * sizeof(float)) != cudaSuccess) { + cudaGetLastError(); + bufs[dev] = nullptr; + } + } + return bufs[dev]; +} + +// The whole recurrence of T tokens in super-blocks of GSB: a prep and a scan launch each, the scratch (T, P and gamma +// of a super-block's chunks: up to GSB / GCH x 48 heads x (2 x 32 x 32 + 32) floats, 25.6 MB) from gdn_chunk_scratch. +// y: the [T][HV][S] output. An error return means nothing was launched (the caller takes another kernel): the scratch +// could not be had, or the card has fewer than 128 SMs (a second wave of the scan would double it) or too little +// shared memory for it (Turing). +cudaError_t gdn_rec_chunked(float* state, const float* h, const float* gate, const float* beta, float* y, int64_t T, + cudaStream_t s) { + if (T <= 0) return cudaSuccess; + { // sm_80+ (cp.async), the scan's 128 blocks one an SM in one wave, and its 93.7 KB of shared memory (else: + // another kernel) + 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; + } + // STRATA_GDN_CHUNKED=2 skips the SM-count test (measurement on a card under 128 SMs: the scan then runs in + // several waves and is expected to be slower than the default kernel; the architecture and shared-memory + // tests stay) + static const bool any_sms = [] { const char* v = std::getenv("STRATA_GDN_CHUNKED"); return v != nullptr && std::atoi(v) >= 2; }(); + if (strata::cc_major_of(major) < 8 || (!any_sms && sms < HK * (S / GDV)) || (size_t) strata::smem_optin_of(smem) < kChunkScanSmem) + return cudaErrorNotSupported; + } + float* scratch = gdn_chunk_scratch(); + if (scratch == nullptr) return cudaErrorMemoryAllocation; + const int nb = (int) ((std::min(GSB, T) + GCH - 1) / GCH); + const size_t tsz = (size_t) nb * HV * GCH * GCH; + float *tm = scratch, *pm = tm + tsz, *gm = pm + tsz; + { // once a device + static bool attrs[64] = {}; + int dev = 0; + cudaGetDevice(&dev); + if (dev >= 0 && dev < 64 && !attrs[dev]) { + cudaFuncSetAttribute(gdn_chunk_prep_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkPrepSmem); + cudaFuncSetAttribute(gdn_chunk_scan_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) kChunkScanSmem); + attrs[dev] = true; + } + } + for (int64_t t0 = 0; t0 < T; t0 += GSB) { + const int nch = (int) ((std::min(GSB, T - t0) + GCH - 1) / GCH); + gdn_chunk_prep_kernel<<>>(h, gate, beta, tm, pm, gm, t0, T); + gdn_chunk_scan_kernel<<>>(state, h, beta, tm, pm, gm, y, t0, nch, T); + } + return cudaSuccess; // launch errors surface at the caller's check; an error above means nothing ran +} #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 @@ -1626,7 +1977,11 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo } else { static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); #if !defined(__HIPCC__) - if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits) + // 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) { + } else if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits) gdn_rec_kh_kernel<<>>(state, h, gate, beta, y, T); else #endif diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 87ab6456..34d7813e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -25,6 +25,7 @@ #include "strata/core/conversation_memory.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" +#include "strata/core/foresight_swap.hpp" #include "strata/core/pinned.hpp" #include "strata/core/remote_experts.hpp" #include "strata/core/on_device.hpp" @@ -1147,6 +1148,18 @@ void pl_diag_print(std::FILE* f) { if (d.v[st][par] != nullptr) d.v[st][par]->diag_pipelined(f, names[st][par]); } +// #1341 #964: CUDA_LAUNCH_BLOCKING=1 in the environment. A verify window's graph waits on the GPU for flags the host +// raises once cudaGraphLaunch has returned, and a blocking launch returns only when the graph has finished, so the +// first window never ends (the batched prompt path has no such wait and runs). HIP's own switches are not checked. +bool launch_blocking() { +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) + return false; +#else + const char* v = std::getenv("CUDA_LAUNCH_BLOCKING"); + return v != nullptr && std::atoi(v) != 0; +#endif +} + void stall_report(std::FILE* f, uint64_t layers_during) { strata::core::Progress& p = strata::core::progress(); std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " @@ -1544,6 +1557,10 @@ int main(int argc, char** argv) { setenv("CUDA_MODULE_LOADING", "EAGER", 0); #endif } + if (launch_blocking()) + std::fprintf(stderr, "warning: CUDA_LAUNCH_BLOCKING=1: the verify windows cannot run with blocking launches, so " + "the first one after a prompt hangs until the watchdog ends the engine (#1341). Unset it; " + "STRATA_PF_STEP_SYNC=1 narrows down a failing prompt step without it\n"); // --gpu LIST pins the visible GPUs (nvidia-smi/PCI order) from the command line instead of the caller's // environment: CUDA_VISIBLE_DEVICES is read at the first CUDA call, so this has to happen here, before // anything else. The value itself is consumed again by the option loop below. @@ -4859,7 +4876,12 @@ int main(int argc, char** argv) { // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). strata::core::RouterLookahead lookahead; - if (srcp == &src && src.warms() && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { + // #1348, one prefetch design: with the Foresight swap space on (STRATA_FS_SLOTS) the look-ahead also runs on the pinned-RAM + // tiers, where there are no pages to warm, and feeds its predictions to the swap space (STRATA_FS_AHEAD=0: not) + const bool fs_ahead = srcp != nullptr && [] { const char* v = std::getenv("STRATA_FS_SLOTS"); return v != nullptr && std::atoi(v) > 0; }() && + [] { const char* v = std::getenv("STRATA_FS_AHEAD"); return v == nullptr || std::atoi(v) != 0; }(); + if (srcp != nullptr && ((srcp == &src && src.warms()) || fs_ahead) && + [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { std::vector> routers((size_t) g.n_layers); bool ok = true; for (int64_t l = 0; l < g.n_layers && ok; ++l) { @@ -4871,13 +4893,14 @@ int main(int argc, char** argv) { ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; } const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); - if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) { + if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, srcp, err, fs_ahead)) { drive.d.lookahead = &lookahead; if (const char* dv = std::getenv("STRATA_IO_PREFETCH_DEPTH"); dv != nullptr && std::atoi(dv) > 0) lookahead.set_depth(std::atoi(dv)); - else if (src.io_prefetch()) + else if (srcp == &src && src.io_prefetch()) lookahead.set_depth(2); - std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n"); + std::fprintf(stderr, "strata generate: routing-aware prefetch on (the next layer's router%s)\n", + fs_ahead ? ", feeding the Foresight swap space" : ", file tier"); } else { (void) cudaGetLastError(); std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n", @@ -7021,12 +7044,33 @@ int main(int argc, char** argv) { const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; const size_t retained = reuse.bytes() + stage_retained; const size_t additional = estimate > retained ? estimate - retained : 0; - if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), - additional, floor)) { - std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", - additional >> 20, (long long) o.conversation_cache_min_free_mib); + // The physical-RAM gate: the incoming snapshot has to fit beside the floor. make_room() + // above only balanced the cache's own budget, so a full cache leaves this one short even + // though every parked conversation could give its RAM back - and refusing here throws + // away the whole prompt read that produced this snapshot (measured: 270k tokens, 96 s). + // Evict the least recently active parked conversations until it fits, or until none are + // left. Each ConversationBuffer is a list of 16 MiB segments, each segment its own + // allocation, so an evicted entry is back with the kernel before the next check reads + // /proc/meminfo; no waiting is needed. slots() bounds the loop, and the two lines + // below say what it did either way. + size_t evicted = 0; + auto admit = [&] { + return strata::core::conversation_memory_admit( + strata::core::conversation_available_memory(), additional, floor); + }; + while (!admit() && conversations.size() > 0 && evicted < conversations.slots() && + conversations.evict_oldest()) + ++evicted; + if (!admit()) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor; evicted %zu, %zu still parked, or telemetry unavailable)\n", + additional >> 20, (long long) o.conversation_cache_min_free_mib, + evicted, conversations.size()); return true; } + if (evicted) + std::fprintf(stderr, "strata serve: conversation cache: evicted %zu parked conversation%s to admit this snapshot (%zu MiB plus %lld MiB floor)\n", + evicted, evicted == 1 ? "" : "s", additional >> 20, + (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, @@ -7231,6 +7275,24 @@ int main(int argc, char** argv) { } } drive.d.plan = ver.plan_sink(); + // Foresight swap space (STRATA_FS_SLOTS; unset = null and nothing changes) + std::unique_ptr fs_swap; + { + int main_dev = 0; + cudaGetDevice(&main_dev); + std::vector devs{main_dev}; + for (auto& st : stages) devs.push_back(st->dev); + std::vector card((size_t) g.n_layers, 0); + for (int64_t l = 0; l < g.n_layers; ++l) card[(size_t) l] = multi_gpu ? stage_of(l) : 0; + fs_swap.reset(strata::core::foresight_swap_from_env(g.n_layers, g.n_expert, card, devs)); + drive.d.fs = fs_swap.get(); + if (fs_swap && drive.d.lookahead != nullptr) lookahead.set_foresight(fs_swap.get()); + } + // the look-ahead thread must not touch the swap space once it is gone (declared after it: destroyed first) + struct FsDetach { + strata::core::RouterLookahead* la; + ~FsDetach() { la->set_foresight(nullptr); } + } fs_detach{&lookahead}; drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5))); const bool all_experts_resident = !host_res.empty() && std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; }); @@ -7936,8 +7998,10 @@ int main(int argc, char** argv) { // a blocking step's explicit allowance (session files): still within it, not yet stuck if (strata::core::progress_now_ms() < p.allow_until_ms.load()) continue; std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping " - "the engine so the server starts it again (issue #29)\n", - limit, stage_text().c_str()); + "the engine so the server starts it again (issue #29)%s\n", + limit, stage_text().c_str(), + launch_blocking() ? "; CUDA_LAUNCH_BLOCKING=1 is set, and no verify window can " + "finish with it (#1341)" : ""); stall_report(stderr, p.ticks.load() - ticks_at); strata::core::release_gpu_waits(stderr); // #267: no spin kernel outlives the process std::fflush(stderr); @@ -10301,6 +10365,7 @@ int main(int argc, char** argv) { draft_offered += A.T - 1; draft_accepted += a; ++rounds; + if (drive.d.fs) drive.d.fs->completed.fetch_add(1, std::memory_order_release); ++dec_windows; dec_T += A.T; bool eos = false; @@ -10551,6 +10616,7 @@ int main(int argc, char** argv) { } std::fflush(stdout); ++rounds; + if (drive.d.fs) drive.d.fs->completed.fetch_add(1, std::memory_order_release); const Clock::time_point tw2 = Clock::now(); // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will @@ -10609,6 +10675,7 @@ int main(int argc, char** argv) { else std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str()); } } + if (drive.d.fs) std::fprintf(stderr, "strata serve: %s\n", drive.d.fs->report().c_str()); if (!cancelled) { // a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from // (the checkpoints taken while reading it are still good) diff --git a/tools/ab_engine.py b/tools/ab_engine.py new file mode 100644 index 00000000..adb6dc28 --- /dev/null +++ b/tools/ab_engine.py @@ -0,0 +1,139 @@ +"""A/B two engine builds or environments on one config: restart the server per arm, alternate arms over rounds. + + python tools/ab_engine.py strata-q2_0.json A:exe=/path/a B:exe=/path/b,STRATA_EXP_MODE=0 [--rounds 3] + +An arm is NAME:key=value,...; `exe` replaces the config's engine, `xargs` appends ';'-separated engine arguments, +every other key is set in the engine's environment. Each round starts the server once per arm (the arms' order alternates), warms it up with one short +answer, then sends the same requests: greedy, fixed prompts, a short chat set and one long prompt. Prints the +server's own timings (llama.cpp's `timings`: decode and prompt tokens per second) per request and the per-arm +medians. Decode numbers move run to run (the adaptive expert tier, the OS), so compare medians over rounds. +""" +from __future__ import annotations + +import argparse +import json +import os +import random +import statistics +import subprocess +import sys +import tempfile +import time +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PROMPTS = ( + "Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.", + "Explain in two paragraphs how a refrigerator moves heat from inside to outside.", + "List ten practical tips for learning a new language as an adult, one sentence each.", +) + + +def long_prompt(words: int) -> str: + rng = random.Random(7) + vocab = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember " + "ledger quartz meadow anchor violet thunder").split() + body = " ".join(rng.choice(vocab) for _ in range(words)) + return f"Here is a list of words:\n{body}\n\nSummarize what kinds of words appear in the list, in five sentences." + + +def post(port: int, prompt: str, max_tokens: int) -> dict: + req = urllib.request.Request( + f"http://127.0.0.1:{port}/v1/chat/completions", + data=json.dumps({"messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, + "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}}).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=1800) as r: + return json.loads(r.read()) + + +def wait_ready(port: int, proc: subprocess.Popen, timeout: float = 1800) -> None: + t0 = time.time() + while time.time() - t0 < timeout: + if proc.poll() is not None: + raise RuntimeError(f"server exited with {proc.returncode}") + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=5) as r: + if r.status == 200: + post(port, "Say hi.", 8) + return + except Exception: + pass + time.sleep(3) + raise TimeoutError("server not ready") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("config") + ap.add_argument("arms", nargs="+") + ap.add_argument("--rounds", type=int, default=3) + ap.add_argument("--port", type=int, default=8090) + ap.add_argument("--max-new", type=int, default=256) + ap.add_argument("--long-words", type=int, default=6000) + ap.add_argument("--log", default="ab_engine.jsonl") + a = ap.parse_args() + base = json.loads(Path(a.config).read_text()) + arms = [] + for s in a.arms: + name, _, kv = s.partition(":") + env = dict(x.split("=", 1) for x in kv.split(",") if x) + arms.append((name, env)) + reqs = [(f"chat{i}", p) for i, p in enumerate(PROMPTS)] + [("long", long_prompt(a.long_words))] + out = open(a.log, "a") + res: dict = {n: {} for n, _ in arms} + for rnd in range(a.rounds): + order = arms if rnd % 2 == 0 else arms[::-1] + for name, env in order: + cfg = dict(base) + e = dict(env) + if "exe" in e: + cfg["exe"] = e.pop("exe") + if "xargs" in e: # extra engine arguments, ';'-separated + cfg["args"] = list(base["args"]) + e.pop("xargs").split(";") + cfg["port"] = a.port + cfg["log"] = str(Path(tempfile.gettempdir()) / f"ab_{name}_r{rnd}.log") + cpath = Path(tempfile.gettempdir()) / f"ab_{name}.json" + cpath.write_text(json.dumps(cfg, indent=1)) + penv = dict(os.environ, **e) + proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", + str(cpath), "--port", str(a.port)], cwd=str(ROOT), env=penv, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + t0 = time.time() + wait_ready(a.port, proc) + print(f"round {rnd} {name}: ready in {time.time() - t0:.0f} s", flush=True) + for tag, p in reqs: + r = post(a.port, p, a.max_new) + t = r.get("timings", {}) + row = {"round": rnd, "arm": name, "req": tag, "decode": t.get("predicted_per_second"), + "prompt": t.get("prompt_per_second"), "prompt_n": t.get("prompt_n"), + "n": r.get("usage", {}).get("completion_tokens"), + "text": r["choices"][0]["message"].get("content", "")[:80]} + out.write(json.dumps(row) + "\n") + out.flush() + res[name].setdefault(tag, []).append(row) + print(f" {tag:6s} decode {row['decode']} tok/s prompt {row['prompt']} tok/s ({row['prompt_n']}) " + f"n {row['n']}", flush=True) + finally: + proc.terminate() + try: + proc.wait(60) + except subprocess.TimeoutExpired: + proc.kill() + time.sleep(5) + print("\nmedians over rounds:") + for tag, _ in reqs: + cells = [] + for name, _ in arms: + rows = res[name].get(tag, []) + d = statistics.median([x["decode"] for x in rows if x["decode"]]) if rows else float("nan") + pr = statistics.median([x["prompt"] for x in rows if x["prompt"]]) if rows else float("nan") + cells.append(f"{name}: decode {d:6.1f} prompt {pr:7.1f}") + print(f" {tag:6s} | " + " | ".join(cells)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/calibrate.py b/tools/calibrate.py index 186604be..23894775 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -225,7 +225,10 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke by_workers = {} for w in worker_candidates(d_workers, extra_workers): say(f" Measuring with {w} CPU workers (restarts the engine) ...") - e = start_engine(with_arg(tuned, "--pool-workers", None if w == d_workers else str(w))) + 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: + continue try: sw = Session(e, ids_list) sw.warm_up(1) @@ -233,8 +236,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke say(f" {w} workers: {statistics.median(by_workers[w]):.1f} tok/s") finally: close(e) - w_best = pick(by_workers, d_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 if w_best != d_workers: settings["--pool-workers"] = str(w_best) base_rate = statistics.median(by_workers[w_best]) @@ -249,7 +252,9 @@ 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 = start_engine(args) + e = restart(start_engine, args, "the expert tier " + key, say, report) + if e is None: + continue try: sa = Session(e, ids_list) sa.warm_up(1) @@ -257,7 +262,7 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke say(f" {statistics.median(by_adapt[key]):.1f} tok/s") finally: close(e) - a_best = pick(by_adapt, "default") + a_best = pick(by_adapt, "default") if by_adapt else "default" report["adapt"] = by_adapt if a_best != "default": for flag, v in zip(ADAPT_FLAGS, a_best.split("/")): @@ -270,6 +275,20 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke return {"settings": settings, "report": report} +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 + noting it in report["failed_starts"]. (The first start, for steps 1-3, is not covered: with no engine there is + nothing measured.)""" + 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__ + 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 close(eng): proc = getattr(eng, "proc", None) if proc is None: diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index 6922d78b..7ce1bdd0 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -78,6 +78,32 @@ class Calibrate(unittest.TestCase): self.assertEqual(len(starts), 1 + len(CAL.worker_candidates(6)) + len(CAL.ADAPT_CANDIDATES)) self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5") # measured against the product default + def test_a_failed_restart_keeps_the_measurements_1337(self): + # the top PCIe share wins by far; every later restart (the worker counts, the expert tier) fails to start + n = {"starts": 0} + + def start(args): + n["starts"] += 1 + if n["starts"] > 1: + raise RuntimeError("the engine exited before it was ready: cudaMalloc failed (213 MiB free)") + return FakeEngine(args, lambda f, p, w: 80.0 if f == 0.75 else 50.0, 6) + said = [] + res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=said.append) + self.assertEqual(res["settings"].get("--pcie-frac"), "0.75") # steps 1-3 survived + self.assertGreater(len(res["report"]["failed_starts"]), 1) + self.assertTrue(any("did not start" in x and "cudaMalloc" in x for x in said)) + self.assertEqual(res["report"]["workers"], {}) + self.assertEqual(res["report"]["adapt"], {}) + + def test_one_failing_worker_count_only_drops_that_candidate_1337(self): + def start(args): + if CAL.arg_value(args, "--pool-workers") == "3": + raise RuntimeError("out of memory") + return FakeEngine(args, lambda f, p, w: 60.0 if w == 2 else 50.0, 6) + res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None) + self.assertEqual(res["settings"].get("--pool-workers"), "2") + self.assertEqual(list(res["report"]["failed_starts"]), ["3 workers"]) + def test_adaptive_tier(self): # a slow-RAM PC: swapping 160 experts per round is 10% faster, 80 is 2% (noise) res, starts = self.run_with(lambda f, p, w: 50.0, adapt={"160": 1.10, "80": 1.02})