diff --git a/CMakeLists.txt b/CMakeLists.txt index 9bbd8716..b6bd8503 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -443,6 +443,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/fused_gdn.cu src/kernels/cuda/dequant_bf16.cu src/kernels/cuda/qsa_select.cu + src/kernels/cuda/qsa_pattn.cu src/kernels/cuda/verify_kernels.cu src/kernels/cuda/dflash2.cu src/kernels/cuda/iq_kernels.cu @@ -472,6 +473,29 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) endif() + # PR #3943: STRATA_PATTN_SM60's score and value kernels against the decode kernels' output (the Daily's chunk kernel and + # the merge), bitwise, on random int8 K/V (GPU, synthetic, no model). Only in the experimental sm_60 build; it skips + # (77) on a build without the kernels. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_pattn_parity src/kernels/qsa_pattn_parity.cpp) + target_include_directories(qsa_pattn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_pattn_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_pattn_parity COMMAND qsa_pattn_parity) + set_tests_properties(qsa_pattn_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() + # PR #3820: STRATA_SELECT_LONG's multi-CTA top-k and shuffle-free decode scorer against qsa_block_topk and + # qsa_block_scores, bitwise, on random scores (GPU, synthetic, no model). The switches force the new kernels on any + # card; the "n3" case fixes three CTAs a query. Only in the experimental sm_60 build (skips with 77 otherwise). + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_select_long_parity src/kernels/qsa_select_long_parity.cpp) + target_include_directories(qsa_select_long_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_select_long_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_select_long_parity COMMAND qsa_select_long_parity) + add_test(NAME qsa_select_long_parity_n3 COMMAND qsa_select_long_parity) + set_tests_properties(qsa_select_long_parity qsa_select_long_parity_n3 PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(qsa_select_long_parity PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1") + set_tests_properties(qsa_select_long_parity_n3 PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1;STRATA_TOPK_MULTI_N=3") + endif() # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) @@ -1124,6 +1148,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + # sm_89's opt-in tables (#3453, STRATA_MMVQ_IL_89=1): the table check only (no case matches MMVQ_IL_ONLY) + add_test(NAME mmvq_il_parity_89table COMMAND mmvq_il_parity) + set_tests_properties(mmvq_il_parity_89table PROPERTIES ENVIRONMENT "STRATA_MMVQ_IL_89=1;MMVQ_IL_ONLY=no-such-case") # the wide dequant kernels (a thread per 8 values; sm_61's default), bitwise vs the per-group ones (GPU, synthetic, # no model; --bench adds old/new timings) add_executable(dequant_wide_parity src/kernels/dequant_wide_parity.cpp) @@ -1923,6 +1950,12 @@ if(STRATA_NATIVE_EXPERTS) add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu src/prefill/mmq_nvfp4_w4a8.cu src/prefill/ggml_cuda_host.cu ${_strata_quantize_cu}) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # GP100 (sm_60): a resident layer's experts weight-stationary, one launch per product (moe_ws.hpp; opt-in at + # run time, STRATA_MMQ_WS=1, and only where every visible GPU is cc 6.0) + target_sources(strata_mmq PRIVATE src/prefill/moe_ws.cu src/prefill/moe_ws_gu_iq2.cu src/prefill/moe_ws_gu_iq3.cu + src/prefill/moe_ws_down.cu) + endif() # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and # STRATA_MMQ_KQUANTS q4_k q5_k q5_1 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch # follows eddoursul/Strata 7706c1b). MODEL-UPDATE Phase 1: on CUDA they are a library of their own, strata_kq @@ -2061,6 +2094,10 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # the weight-stationary experts (moe_ws.hpp) are in strata_mmq: the prompt path may take them (STRATA_MMQ_WS=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_WS=1) + endif() if(STRATA_BUILD_TESTS) # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80) add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp) @@ -2082,6 +2119,19 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(prefill_mmq_scatter_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_mmq_scatter_test COMMAND prefill_mmq_scatter_test) set_tests_properties(prefill_mmq_scatter_test PROPERTIES TIMEOUT 120) + if(STRATA_EXPERIMENTAL_SM60) + # mmq::swiglu_quant: swiglu + the down product's q8_1 rows in one kernel against the two, byte for byte + add_executable(prefill_swiglu_quant_test tests/cuda/prefill_swiglu_quant_test.cpp) + target_link_libraries(prefill_swiglu_quant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_swiglu_quant_test COMMAND prefill_swiglu_quant_test) + set_tests_properties(prefill_swiglu_quant_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the weight-stationary experts (STRATA_MMQ_WS) against the per-group MMQ, byte for byte, on random experts; the + # verdict is given on a compute capability 6.0 card only (77 elsewhere) + add_executable(prefill_ws_parity_test tests/cuda/prefill_ws_parity_test.cpp) + target_link_libraries(prefill_ws_parity_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_ws_parity_test COMMAND prefill_ws_parity_test) + set_tests_properties(prefill_ws_parity_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() endif() if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) @@ -2218,6 +2268,20 @@ if(STRATA_NATIVE_EXPERTS) add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + # STRATA_EXPERT_NIBBLE (include/strata/core/expert_nibble.hpp): the 4-bit gate/up expert slots against the + # production kernels and the GGUF blobs, bit for bit, on a real model's layers (needs a GP100); --header: the + # contract's host half, no GPU + add_executable(iq_nibble_parity src/kernels/iq_nibble_parity.cpp) + target_include_directories(iq_nibble_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(iq_nibble_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ggml-base ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_nibble_parity_header COMMAND iq_nibble_parity --header) + # the synthetic experts of every gate/up x down format pair, no model (skips with 77 on a card that is not a GP100) + add_test(NAME iq_nibble_parity_synthetic COMMAND iq_nibble_parity --synthetic-only) + set_tests_properties(iq_nibble_parity_synthetic PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900) + endif() + endif() # MODEL-UPDATE: the dense Q8_0 GEMVs at the engine's shapes against the memory bandwidth (a benchmark, no test) add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp) target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories}) diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index 1f3bae10..8974c3be 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -15,18 +15,19 @@ Which table a card gets: |---|---| | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | -| sm_89 (Ada) and every other sm_80+ card | `kIlRowsShared` too. Nobody has measured sm_89 yet (we have no such card). | +| sm_89 (Ada) | the shared table (`kIlRowsShared`) unless `STRATA_MMVQ_IL_89=1`, which switches on `kIlRows_89`: the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. It is opt-in because no sm_89 card has run `mmvq_il_parity` on this code, and the issue saw no end-to-end decode change on a 4090 or a 4080 (issue 3453), so the gain is a microbenchmark one. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card. To flip the default, run `mmvq_il_parity` on an Ada card (it must end with `OK`) and an interleaved decode A/B with the switch on and off. | +| every other sm_80+ card | `kIlRowsShared` | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | -## Measuring sm_89 (or any other card) +## Measuring a card that has no table yet 1. Build with tests: `cmake -S . -B build -DSTRATA_BUILD_TESTS=ON` and `cmake --build build --target mmvq_il_parity`. 2. Close everything else on the GPU, then run `build/mmvq_il_parity --bench --emit-table` (a few minutes). It first checks bit-for-bit parity of every shape and every rows choice (it must end with `mmvq_il_parity: OK`), prints a `BENCH` line per shape and token count, and last a ready-to-paste block, one line per type. -3. Post the whole output on the issue. A maintainer pastes the block as `kIlRows_89[]` and adds - `{89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)}` to `kIlArch`. +3. Post the whole output on the issue. A maintainer pastes the block as `kIlRows_[]` and adds + `{, kIlRows_, sizeof(kIlRows_) / sizeof(IlRows)}` to `kIlArch`. 4. To try a table without rebuilding, set `STRATA_MMVQ_IL_ROWS="type:ncols:r0,r1,r2,r3,r4;..."`, for example `STRATA_MMVQ_IL_ROWS="23:3:0,0,2,4,4;12:2:0,1,1,1,1"` (the five numbers are the row classes below 2048, 4096, 8192, 12288 and above; each is 0, 1, 2 or 4). Then A/B the decode: same flags, `STRATA_MMVQ_IL_ROWS` set or unset, 10 diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 080d9ee7..ace14e22 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -147,7 +147,7 @@ in [DETAILS.md](DETAILS.md#rtx-30-series-sm_86-and-tesla-p100-sm_60-bitwise-deco ## Pascal GP100: a Q8_0 decode kernel (opt-in) GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projections read their weights at 40-80 GB/s of about -730, decoding K- and i-quant blocks one int at a time. Two opt-in changes, both measured on a PH402 only: +730, decoding K- and i-quant blocks one int at a time. Six opt-in changes, all measured on a PH402 only: - **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp per row, 16-byte weight loads, activations copied once per workgroup into shared memory, @@ -159,14 +159,91 @@ GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projectio - **`STRATA_IQ_STAGE_TABLES=1`** stages IQ3_XXS and IQ3_S codebooks in shared memory in the grouped expert kernels. Bitwise the same output. Interleaved A/Bs on a Tesla P100 showed no end-to-end change, so it is off by default. On an RTX 3090 Ti, forced on, the same layers took 3-13% longer. +- **`STRATA_DOWN_WS=1`** (compute capability 6.0 only, CUDA build with `STRATA_EXPERIMENTAL_SM60`): the verify window's IQ4_NL / Q2_0 + expert down rows (n_ff 640) take `native_down_ws_kernel`. It stages a block's rows in shared memory with 16-byte loads and then + runs expert mode 0's row dots on them, so the output is bit for bit mode 0's (and mode 8's, which equals it). The author's numbers + on one PH402 die, Swift 1.5 IQ3_S, one-token window: IQ4_NL 72.6 us (mode 8, the cc 6.0 default) and 54.5 us (mode 0) become + 42.3 us; Q2_0 53.5 / 65.4 us become 38.6 us. It replaces the down step in either expert mode. Not measured end to end on a + single card here. +- **`STRATA_PATTN_SM60=1`** (prompt reading with int8 K/V, CUDA build with `STRATA_EXPERIMENTAL_SM60`, compute capability 6.x): below + sm_70 the prompt reads each QSA layer's attention through the decode kernels, 32 queries a call, with 817 KB of partial results a + query and a merge kernel. The switch runs a score kernel and a value kernel that merges as it folds + (`src/kernels/cuda/qsa_pattn.cu`), in the same scratch and with the same arithmetic in the same order, so the output matches the + decode kernels bit for bit. If a launch fails or the shape does not fit, the usual loop runs. The author measured a 1,536-query + chunk's attention at 43.3 -> 30.8 ms per QSA layer at 26K context on one GP100 die, and 2-3% less time on 8K-150K token prompts + on four dies; we have not measured it here, and nobody has measured compute capability 6.1. `qsa_pattn_parity` (built with the + tests in this build) checks the bytes on random data. +- **`STRATA_SELECT_LONG=1`** (decode, CUDA build with `STRATA_EXPERIMENTAL_SM60`, compute capability 6.x by default): past + `STRATA_SELECT_LONG_AT` cells (default 65,536) a decode window's QSA select runs a top-k over several CTAs a query (six kernels) + and a decode block scorer without warp shuffles, in place of one CTA a query. They return the same ids and the same score bits + (`qsa_select_long_parity` checks this on random data). Each costs a few more kernels a call, which only a long context pays + back, so the verifier keeps a second set of window graphs for it: expect some more VRAM for graphs, and nothing changes below + the threshold. `STRATA_TOPK_MULTI=0` and `STRATA_SCORES_DX=0` turn one half off. The author measured, on four GP100 dies with + every expert resident and `--pipeline-windows 3`, 51.0 -> 52.5 tok/s (+2.9%) decoding 400 tokens at 115K context, and no change + below 64K; we have not measured it. A build without the sm_6x kernels ignores the switch with a warning. +- **`STRATA_MMQ_WS=1`** (prompt reading, CUDA build with `STRATA_EXPERIMENTAL_SM60`, every visible card compute capability 6.0): a + layer whose routed experts are all resident in VRAM, on this GPU alone (no peer, CPU or streamed share), runs its gate/up as one + weight-stationary launch over all its experts, one `swiglu_quant` over all its rows and its down as one launch, in place of a + gate/up, swiglu and down MMQ launch per 16-expert group. A CTA holds 128 or 256 weight rows of one expert and runs them against + up to 64 of that expert's rows, so each weight block is decoded once per pass. Gate/up for IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS and + IQ3_S, down for Q2_0 and IQ4_NL; the products keep MMQ's int8 values, scales and per-32-value epilogue order, so the results are + MMQ's bits. Every other layer keeps its path. `STRATA_WS_FAST=1` adds a down kernel for the IQ4_NL 32-token tier with fewer + instructions per pass (the same bits). The author measured, on four GP100 dies with every expert resident, prompt reads 31-37% + shorter (240 tokens 2,156 -> 1,364 ms; a fresh 26K read 41,231 -> 28,555 ms; one run per arm) and decode unchanged; we have not + measured it. A single 16 GB card that keeps experts in RAM takes the per-group path. `prefill_ws_parity_test` compares the + products with MMQ on random experts; its verdict needs a GP100. -Neither change is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default +None of these changes is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default application clock is 759 MHz and a layer split leaves each die idle most of a window, so lock the clocks (`nvidia-smi -i -ac 715,1050` as administrator). And a second engine pinned to the same logical CPUs halves this one's decode; keep two engines on different logical CPUs. `tools/q8_sm60_check.cu` checks the kernel against a CPU reference on these shapes (1-8 columns). +### Pascal GP100: 4-bit gate/up expert slots (opt-in, `STRATA_EXPERT_NIBBLE=1`) + +On a GP100 die the verify window's gate/up expert kernels wait on each block's serial chain (the weights, two codebook +lookups per four weights, the emulated dp4a, the reduction), not on memory bandwidth. IQ2_S, IQ3_XXS and IQ3_S have +only 3 or 8 magnitudes in their grids, so every weight is one of at most 16 signed values: `STRATA_EXPERT_NIBBLE=1` +keeps those layers' gate/up experts in VRAM as 16 bytes of 4-bit codes per 32 weights (one 16-byte load), with the +integer scale and the fp16 `d` of each block kept as they are, and decodes four weights in 1-4 integer instructions. The +down rows stay GGUF blocks. The host copy, the pack and its tools do not change: the conversion runs on the GPU while +the slots are filled. Only the CUDA build with `STRATA_EXPERIMENTAL_SM60` has the kernels. + +- **The answers are meant to be bit for bit the default's.** The 4-bit kernels run the production integer chain and float tail in + the production order (`native_gu_multi_kernel`'s sub-16 rows), and SwiGLU, the q8_1 step and the down projection are + the layout's own (mode 8 on a GP100). At every start each item is decoded with the production loader, encoded, + decoded from the written code and compared, and the GGUF blocks are rebuilt from every slot and compared with the + blob byte for byte; any difference refuses the start and names the layer. The prompt path's MMQ gathers the GGUF + blocks rebuilt from the slots (the copy it makes today, with the 4-bit codes read instead): the same bytes. The kernels that + existed before this change have the same SASS in the sm_60 build with and without it (446 kernels in `iq_kernels.cu` compared). + `iq_nibble_parity --synthetic-only` checks the codec, the rebuilt blocks and the expert step on random experts of every format + pair with no model file; `iq_nibble_parity ` does the same on a model's layers, against the GGUF blobs in mode 8 and + in the CUDA layout (`STRATA_SM60_TABLE=0`). Both need a GP100. +- **It needs every expert in VRAM** on the card that runs its layer: a profile that ranks every pair, room for the + larger slots (per layer of 512 experts: +175 MiB for IQ3_S, +250 MiB for IQ3_XXS, +350 MiB for IQ2_S), and a prompt + path with its own buffers, no loan of cache slots (`--no-prefill-borrow` on one GPU; a layer split's stages keep + their own when their cards have room, #340). `STRATA_EXPERT_NIBBLE_SKIP=` keeps layers in their GGUF slots; + `STRATA_EXPERT_NIBBLE_FMTS=22,18,21` picks the formats. +- **It does not start with what it cannot serve.** With the switch set, a build without `STRATA_EXPERIMENTAL_SM60`, a card other + than compute capability 6.0, `--peer-device`, `--expert-cache-device1..3`, `--kv-grow`, `--vram-elastic`, no `--expert-profile`, + `--expert-cache 0`, `STRATA_MMQ_DIRECT`, `STRATA_PREFILL_MMQ=0`, `STRATA_PF_FUSED=1`, `STRATA_FS_SLOTS`, `STRATA_EXPERT_V2=1` or + `STRATA_EXP_MODE` other than 0 or 8 make the engine say so in a warning and start with the usual GGUF slots. What is only known + later (a layer with an expert out of VRAM, a loan of cache slots, a prompt chunk other than the one the run without the switch + reads) still refuses the start with the reason. The adaptive tier is off with the switch. `STRATA_EXPERT_NIBBLE_RECHECK=1` (debug) + hashes every 4-bit slot again after each request. +- **Opt-in `STRATA_NIB_GU_PROTO=1`** (with `STRATA_EXPERT_NIBBLE=1`): the 4-bit gate/up runs `nibx_gu_kernel` + (`nib_gu_proto.cuh`), the same row dot with the group's activations staged once per two row blocks by 16-byte + loads. The author measured, on one GP100 die, a layer's gate/up at 54-57 us instead of 67-72 us at one token (x1.24-1.27) and + x1.22-1.39 at two to four tokens. +- The author measured the switch on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB each, clocks locked at 715 / + 1050 MHz), Windows 11, CUDA 12.9, engine 0.1.45.3, Swift 1.5 IQ3_S (abliterated) pack, layer split 12,24,36, + `--trim-stage-weights`, MTP with `--spec-min-p 0.85`, `--pipeline-windows 2`, 1M context, every expert resident: 47 of 48 layers + converted (+12.7 GiB of VRAM over the four dies, +3.1 s of start-up). Decode of eight prompts (8K, 26K and 88K-token contexts), + token-weighted: 47.3 -> 51.9 tok/s (+9.7%; each prompt +9.5..+10.9%). Prompt reading 2.3..3.0% slower (the gather rebuilds the + GGUF blocks). The replies of 15 requests, including a 260K-token read, matched the engine without the switch. We have not + measured it on this code. + ## Tesla P40 (sm_61): what was measured and changed Three things run differently on compute capability 6.1 by default and a fourth is opt-in. Each gives the same bits as what it diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 3f66f5ca..238c8594 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -219,6 +219,14 @@ public: /// Slots filled so far, for the startup report. int64_t fills() const { return fills_; } + /// STRATA_EXPERT_NIBBLE=1 (strata/core/expert_nibble.hpp): called once the startup fill has written every slot + /// (some of them as 4-bit codes, not GGUF blocks) and checked them. From then on no slot may be written through + /// this class: the fill_slot calls stop the engine (they would write GGUF bytes, possibly into a 4-bit slot, and a + /// wrong expert gives a plausible token, never an error), and `admit` claims nothing. Never called with the switch + /// off: an unsealed cache is the one above. + void seal() { sealed_ = true; } + bool sealed() const { return sealed_; } + /// The elastic K/V (--kv-grow): the arena in a VMM range (vmm.hpp) instead of one cudaMalloc, so the K/V can take /// single chunks of it and give them back. Applies to the next `open`; ignored where VMM is not available. static void set_vmm(bool enabled); @@ -268,6 +276,7 @@ private: std::vector layer_next_; ///< [n_layers] -> that layer's next free slot std::vector off_; ///< plan v0.3 P6: slot offsets (slots + 1 entries) when sized int64_t admitted_ = 0; + bool sealed_ = false; ///< STRATA_EXPERT_NIBBLE: `seal` was called (no slot is written after it) }; } // namespace strata::core diff --git a/include/strata/core/expert_nibble.hpp b/include/strata/core/expert_nibble.hpp new file mode 100644 index 00000000..92001956 --- /dev/null +++ b/include/strata/core/expert_nibble.hpp @@ -0,0 +1,457 @@ +// include/strata/core/expert_nibble.hpp - STRATA_EXPERT_NIBBLE=1 (opt-in, default off): the gate/up experts of +// IQ2_S / IQ3_XXS / IQ3_S layers kept as 4-bit codes in their VRAM slots, for Pascal GP100 (sm_60). +// +// **WHY.** On a GP100 the decode window's gate/up expert kernels are not held by memory bandwidth: they use a small +// part of it and wait on each block's serial chain (the weights, the codebook lookups, the emulated dp4a, the +// reduction). Re-encoding each 32-weight item of these three formats as sixteen bytes of 4-bit codes (one aligned +// 16-byte load) and keeping the integer scale and the fp16 d as they are makes the slot 1.25-1.68x the GGUF bytes and +// the decode of four weights 1-4 integer instructions instead of two codebook lookups. +// +// **WHY IT IS LOSSLESS.** Their grids have only 3 (IQ2_S) or 8 (IQ3_XXS, IQ3_S) magnitudes, so each int8 weight the +// production `Split::load` decodes is one of at most 16 signed values. At every start the transcoder decodes every +// item of every converted slot with the production load, encodes it, decodes the written code again and compares; and +// the GGUF blocks are rebuilt from every slot and compared with the blob byte for byte (`check_gguf`). The decode +// kernels run the production integer chain and float tail in the production order: every gate / up value is the +// production kernel's, bit for bit. The prompt path's MMQ reads the GGUF blocks rebuilt from the slot (`gather_gguf`, +// in place of the copy it does today): the same bytes, so the same bits. +// +// **OFF IS TODAY.** Unset or 0: no layer is converted, `slot_bytes(l)` is `expert_layout().blob_bytes(l)`, nothing is +// transcoded, sealed or hashed, and none of the new branches is entered. Only a CUDA build with +// STRATA_EXPERIMENTAL_SM60 has the kernels (STRATA_EXPERT_NIBBLE_BUILT); every other build refuses the switch at start. +#pragma once + +#include "strata/kernels/cpu/expert_layout.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \ + !defined(STRATA_GPU_METAL) +#define STRATA_EXPERT_NIBBLE_BUILT 1 +#else +#define STRATA_EXPERT_NIBBLE_BUILT 0 +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_NIB_HD __host__ __device__ +#else +#define STRATA_NIB_HD +#endif + +namespace strata::core::nibble { + +// ------------------------------------------------------------------------------------------------ the slot layout +// +// A converted layer's expert slot, in order (the host arena and the pack keep the GGUF blocks): +// +// codes kRows x kItems x 16 B row r, item k at (r * kItems + k) * 16; rows 0..kNFf-1 gate, kNFf..kRows-1 up +// scales kRows x kItems x 1 B row r, item k at kScOff + r * kItems + k (the production scale step's input) +// d kRows x kSuper x 2 B row r, superblock s at kDOff + (r * kSuper + s) * 2: the block's fp16 d, bit for bit +// ------ kGuBytes = 1,766,400 B (6900 x 256: the down part starts 256-aligned) +// down the GGUF down rows, copied verbatim from the raw blob's [down_off, bytes) +// ------ slot_bytes = round_up(kGuBytes + down bytes, kSlotAlign) +// +// One item = 32 weights of a row, one 16-byte code (four 32-bit words, see `encode_item`). Only the expert shape +// n_embd 2560, n_ff 640 is converted: every other layer keeps its GGUF blob and its kernels. + +inline constexpr int64_t kNEmbd = 2560; ///< the gate/up rows' width (the activation) +inline constexpr int64_t kNFf = 640; ///< gate rows = up rows = n_ff +inline constexpr int64_t kRows = 2 * kNFf; ///< 1280: gate, then up +inline constexpr int64_t kItems = kNEmbd / 32; ///< 80 items of 32 weights per row +inline constexpr int64_t kSuper = kNEmbd / 256; ///< 10 superblocks (one fp16 d each) per row +inline constexpr uint64_t kItemBytes = 16; ///< one item's code: four words, one 16-byte load + +inline constexpr uint64_t kCodesOff = 0; +inline constexpr uint64_t kUpCodesOff = (uint64_t) kNFf * kItems * kItemBytes; ///< 819,200: row kNFf +inline constexpr uint64_t kScOff = (uint64_t) kRows * kItems * kItemBytes; ///< 1,638,400 +inline constexpr uint64_t kDOff = kScOff + (uint64_t) kRows * kItems; ///< 1,740,800 +inline constexpr uint64_t kGuBytes = kDOff + (uint64_t) kRows * kSuper * 2; ///< 1,766,400 +inline constexpr uint64_t kDownOff = kGuBytes; ///< the down rows +inline constexpr uint64_t kSlotAlign = 256; ///< every slot's size + +static_assert(kGuBytes == 1766400, "the slot layout above"); +static_assert(kGuBytes % kSlotAlign == 0, "the down part starts 256-aligned"); +static_assert(kScOff % 16 == 0 && kDOff % 16 == 0, "each region starts 16-aligned"); + +/// Byte offset of row `row` (0..kRows-1; up rows are kNFf + r) item `k`'s code inside the slot. +STRATA_NIB_HD constexpr uint64_t code_off(int64_t row, int64_t k) { + return kCodesOff + ((uint64_t) row * kItems + (uint64_t) k) * kItemBytes; +} +/// Byte offset of row `row` item `k`'s scale byte. +STRATA_NIB_HD constexpr uint64_t scale_off(int64_t row, int64_t k) { return kScOff + (uint64_t) row * kItems + (uint64_t) k; } +/// Byte offset of row `row` superblock `s`'s fp16 d (s = k / 8 for item k). +STRATA_NIB_HD constexpr uint64_t d_off(int64_t row, int64_t s) { return kDOff + ((uint64_t) row * kSuper + (uint64_t) s) * 2; } +/// A converted slot's size for a raw blob whose down rows are `down_bytes` long. +STRATA_NIB_HD constexpr uint64_t slot_bytes_for(uint64_t down_bytes) { + return (kGuBytes + down_bytes + kSlotAlign - 1) / kSlotAlign * kSlotAlign; +} + +// ------------------------------------------------------------------------------------------------ the formats + +inline constexpr int kIQ3_XXS = 18; +inline constexpr int kIQ3_S = 21; +inline constexpr int kIQ2_S = 22; + +/// Whether `gu_type` is converted (the three formats whose weights take at most 16 values). +STRATA_NIB_HD constexpr bool fmt_built(int gu_type) { return gu_type == kIQ2_S || gu_type == kIQ3_XXS || gu_type == kIQ3_S; } +/// The GGUF gate/up row bytes of `gu_type` at kNEmbd (a converted layer's raw blob must agree; 0 = not a format here). +STRATA_NIB_HD constexpr uint64_t raw_gu_row(int gu_type) { + return gu_type == kIQ2_S ? 820 : gu_type == kIQ3_XXS ? 980 : gu_type == kIQ3_S ? 1100 : 0; +} +inline const char* fmt_name(int gu_type) { + switch (gu_type) { + case kIQ3_XXS: return "IQ3_XXS"; + case kIQ3_S: return "IQ3_S"; + case kIQ2_S: return "IQ2_S"; + default: return "?"; + } +} + +// ------------------------------------------------------------------------------------------------ the item code +// +// `g[32]` below is one item as the production `Split::load` leaves it: g[4 * j + b] is byte b of W.g[j] +// (j = 0..7, the dp4a order against the q8_1 block's qs words). Word m (0..3) of the 16-byte code holds W.g[2m] +// and W.g[2m + 1]: +// +// IQ2_S bits 4b..4b+3 = c(g[8m + b]), bits 16+4b.. = c(g[8m + 4 + b]), b = 0..3 +// c = magnitude index of {8, 25, 43} | sign << 2: the PRMT selector into {8,25,43,0} {-8,-25,-43,0} +// IQ3_XXS same nibble positions; c = index of {4, 12, 20, 28, 36, 44, 52, 62} | sign << 3 +// IQ3_S byte b = u(g[8m + b]) | u(g[8m + 4 + b]) << 4, u = (v + 15) / 2 (v odd, -15..15); v = 2u - 15 +// +// The scale byte keeps the production integer scale step's input: +// IQ2_S the block's scales byte for the item: ls0 | ls1 << 4 (W.ls0, W.ls1) +// IQ3_XXS aux32 >> 28 (0..15, W.ls) +// IQ3_S 1 + 2 * nibble (1..31, W.ls) + +/// Encodes one item; false when a weight is outside the format's code set (the conversion then refuses to start). +inline bool encode_item(int gu_type, const int8_t g[32], uint32_t q[4]) { + bool ok = true; + auto code = [&](int8_t v) -> uint32_t { + const int a = v < 0 ? -(int) v : (int) v; + if (gu_type == kIQ3_S) { + if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; } + return (uint32_t) (((int) v + 15) / 2); + } + if (gu_type == kIQ3_XXS) { + static constexpr int mag[8] = { 4, 12, 20, 28, 36, 44, 52, 62 }; + for (uint32_t i = 0; i < 8; ++i) + if (a == mag[i]) return i | (v < 0 ? 8u : 0u); + ok = false; + return 0; + } + const uint32_t m = a == 8 ? 0u : a == 25 ? 1u : a == 43 ? 2u : 3u; // IQ2_S + if (m == 3u) { ok = false; return 0; } + return m | (v < 0 ? 4u : 0u); + }; + for (int m = 0; m < 4; ++m) { + uint32_t w = 0; + for (int b = 0; b < 4; ++b) { + const uint32_t c0 = code(g[8 * m + b]), c1 = code(g[8 * m + 4 + b]); + if (gu_type == kIQ3_S) w |= (c0 | c1 << 4) << (8 * b); + else w |= c0 << (4 * b) | c1 << (16 + 4 * b); + } + q[m] = w; + } + return ok; +} + +/// Decodes one item's code back to the production W.g bytes (the host reference the parity program compares with; +/// the device decoders give the same bytes). Codes outside the set decode as the PRMT does: IQ2_S index 3 -> 0. +inline void decode_item(int gu_type, const uint32_t q[4], int8_t g[32]) { + static constexpr int8_t iq2[8] = { 8, 25, 43, 0, -8, -25, -43, 0 }; + static constexpr int8_t iq3[8] = { 4, 12, 20, 28, 36, 44, 52, 62 }; + for (int m = 0; m < 4; ++m) + for (int b = 0; b < 4; ++b) { + uint32_t c0, c1; + if (gu_type == kIQ3_S) { + c0 = q[m] >> (8 * b) & 15u; + c1 = q[m] >> (8 * b + 4) & 15u; + } else { + c0 = q[m] >> (4 * b) & 15u; + c1 = q[m] >> (16 + 4 * b) & 15u; + } + auto val = [&](uint32_t c) -> int8_t { + if (gu_type == kIQ3_S) return (int8_t) (2 * (int) c - 15); + if (gu_type == kIQ3_XXS) return (int8_t) ((c & 8u) ? -iq3[c & 7u] : iq3[c & 7u]); + return iq2[c & 7u]; + }; + g[8 * m + b] = val(c0); + g[8 * m + 4 + b] = val(c1); + } +} + +// ------------------------------------------------------------------------------------------------ the slot hash +// +// STRATA_EXPERT_NIBBLE_RECHECK's fingerprint of a slot: over the slot's first `hashed` bytes (kGuBytes plus the down +// rows; the alignment tail is not written and not hashed) as little-endian 32-bit words w_i, the last one +// zero-extended, H = sum_i (uint64) (w_i ^ i) * kHashMul mod 2^64. A sum, so the device's order of adding does not +// change it; the index term makes a moved word count. + +inline constexpr uint64_t kHashMul = 0x9E3779B97F4A7C15ull; + +/// The host reference of the slot hash (the device hash gives the same value for the same bytes). +inline uint64_t hash_host(const void* p, uint64_t bytes) { + const uint8_t* s = (const uint8_t*) p; + uint64_t h = 0; + const uint64_t n = (bytes + 3) / 4; + for (uint64_t i = 0; i < n; ++i) { + uint32_t w = 0; + const uint64_t at = 4 * i, take = bytes - at < 4 ? bytes - at : 4; + std::memcpy(&w, s + at, (size_t) take); // little-endian hosts only + h += (uint64_t) (w ^ (uint32_t) i) * kHashMul; + } + return h; +} + +// ------------------------------------------------------------------------------------------------ the switches + +struct Config { + bool on = false; ///< STRATA_EXPERT_NIBBLE=1 + bool recheck = false; ///< STRATA_EXPERT_NIBBLE_RECHECK=1 (debug: every slot's hash per request) + std::vector fmts{ kIQ2_S, kIQ3_XXS, kIQ3_S }; ///< STRATA_EXPERT_NIBBLE_FMTS (default 22,18,21) + std::vector skip; ///< STRATA_EXPERT_NIBBLE_SKIP: layers kept in their GGUF blocks + std::string error; ///< non-empty: a malformed value - the start is refused +}; + +namespace detail { +/// "a,b,c" -> integers; false on anything else (empty = an empty list). +inline bool parse_list(const char* s, std::vector& out) { + out.clear(); + while (s != nullptr && *s != '\0') { + char* end = nullptr; + const long long v = std::strtoll(s, &end, 10); + if (end == s) return false; + out.push_back((int64_t) v); + s = end; + if (*s == ',') ++s; + else if (*s != '\0') return false; + } + return true; +} +} // namespace detail + +/// The switches, read once (generate.cpp reads them before anything is allocated). +inline const Config& config() { + static const Config c = [] { + Config r; + const char* e = std::getenv("STRATA_EXPERT_NIBBLE"); + if (e != nullptr && e[0] != '\0' && std::strcmp(e, "0") != 0) { + if (std::strcmp(e, "1") == 0) r.on = true; + else r.error = std::string("STRATA_EXPERT_NIBBLE=") + e + ": expected 0 or 1"; + } + const char* rc = std::getenv("STRATA_EXPERT_NIBBLE_RECHECK"); + r.recheck = rc != nullptr && std::strcmp(rc, "1") == 0; + std::vector v; + if (const char* f = std::getenv("STRATA_EXPERT_NIBBLE_FMTS"); f != nullptr && f[0] != '\0') { + if (!detail::parse_list(f, v)) { + if (r.error.empty()) r.error = std::string("STRATA_EXPERT_NIBBLE_FMTS=") + f + ": expected ggml types, e.g. 22,18,21"; + } else { + r.fmts.clear(); + for (const int64_t t : v) { + if (!fmt_built((int) t) && r.error.empty()) + r.error = "STRATA_EXPERT_NIBBLE_FMTS: type " + std::to_string(t) + + " is not converted (22 IQ2_S, 18 IQ3_XXS, 21 IQ3_S)"; + r.fmts.push_back((int) t); + } + } + } + if (const char* k = std::getenv("STRATA_EXPERT_NIBBLE_SKIP"); k != nullptr && k[0] != '\0') { + if (!detail::parse_list(k, r.skip) && r.error.empty()) + r.error = std::string("STRATA_EXPERT_NIBBLE_SKIP=") + k + ": expected layer numbers, e.g. 40,44"; + } + return r; + }(); + return c; +} + +/// With the switch on, the first environment setting it refuses, as a message (empty = none): the paths that would +/// read a converted slot as GGUF blocks, write GGUF bytes into one, or run other kernels for the converted layers +/// than the ones the 4-bit kernels are bit for bit. The command-line half (--peer-device, remote expert caches, +/// --kv-grow, --vram-elastic), the cc 6.0 check, full residency and no loan are generate.cpp's checks; the prompt +/// path's own (MMQ on every converted layer) is Prefill::nibble_prompt_check. +inline std::string env_conflicts() { + auto set = [](const char* n) -> const char* { + const char* v = std::getenv(n); + return v != nullptr && v[0] != '\0' ? v : nullptr; + }; + const char* v = set("STRATA_MMQ_DIRECT"); + if (v != nullptr && std::atoi(v) != 0) + return "STRATA_MMQ_DIRECT (the prompt MMQ would read a converted slot in place as GGUF blocks)"; + v = set("STRATA_PREFILL_MMQ"); + if (v != nullptr && std::atoi(v) == 0) return "STRATA_PREFILL_MMQ=0 (the FP16 prompt path reads GGUF blocks)"; + v = set("STRATA_PF_FUSED"); + if (v != nullptr && v[0] == '1') return "STRATA_PF_FUSED=1 (the fused prompt kernels read GGUF blocks)"; + v = set("STRATA_FS_SLOTS"); + if (v != nullptr && std::atoi(v) > 0) return "STRATA_FS_SLOTS (Foresight swaps GGUF blobs into slots)"; + v = set("STRATA_EXPERT_V2"); + if (v != nullptr && v[0] == '1') return "STRATA_EXPERT_V2=1 (the S26 kernels, not the CUDA layout, on IQ3_S)"; + v = set("STRATA_KV_GROW"); + if (v != nullptr && v[0] != '0') return "STRATA_KV_GROW (the elastic K/V moves slots at their GGUF size)"; + v = set("STRATA_EXP_MODE"); + if (v != nullptr && std::atoi(v) != 0 && std::atoi(v) != 8) + return "STRATA_EXP_MODE other than 0 or 8 (another layout's gate/up kernels)"; + return {}; +} + +// ------------------------------------------------------------------------------------------------ the VRAM table + +/// One layer's slots. `on` false: the GGUF blob, `slot_bytes == raw_bytes`, the production kernels. +struct LayerVram { + bool on = false; + int gu_type = -1, d_type = -1; + uint64_t down_off = 0; ///< in the slot: kDownOff when on, else the raw blob's down_off + uint64_t down_bytes = 0; ///< the down rows (raw_bytes - raw_down_off) + uint64_t hashed = 0; ///< bytes the slot hash covers: kGuBytes + down_bytes when on, else 0 + uint64_t slot_bytes = 0; ///< what the expert cache allocates per slot (`open_sized`, every estimate) + // the raw blob as the arena and the pack hold it (expert_layout().fmt[l]); the transcoder reads these + uint64_t raw_bytes = 0, raw_gu_row = 0, raw_up_off = 0, raw_down_off = 0; +}; + +/// One layer's entry from its GGUF format and the switches (pure; `plan_layers` calls it per layer). +inline LayerVram plan_layer(int64_t l, const strata::kernels::cpu::NativeFmt& f, const Config& c) { + LayerVram v; + v.gu_type = f.gu_type; + v.d_type = f.d_type; + v.raw_bytes = f.bytes; + v.raw_gu_row = f.gu_row; + v.raw_up_off = f.up_off; + v.raw_down_off = f.down_off; + v.down_bytes = f.bytes - f.down_off; + v.down_off = f.down_off; + v.slot_bytes = f.bytes; + bool listed = false, skipped = false; + for (const int t : c.fmts) listed = listed || t == f.gu_type; + for (const int64_t s : c.skip) skipped = skipped || s == l; + // [gate | up | down] exactly, no NVFP4 tail, the down rows a whole number of 16-byte words (the gathers copy them so) + const bool shape = f.n_embd == kNEmbd && f.n_ff == kNFf && f.gu_row == raw_gu_row(f.gu_type) && + f.up_off == (uint64_t) kNFf * f.gu_row && f.down_off == 2 * f.up_off && f.bytes > f.down_off && + f.tail_off == 0 && (f.bytes - f.down_off) % 16 == 0; + if (c.on && c.error.empty() && listed && !skipped && fmt_built(f.gu_type) && shape) { + v.on = true; + v.down_off = kDownOff; + v.hashed = kGuBytes + v.down_bytes; + v.slot_bytes = slot_bytes_for(v.down_bytes); + } + return v; +} + +/// Every layer's entry for this pack (all off for a Q2_0 pack or with the switch off). `err`: a SKIP layer out of +/// range, or the switch on with a Q2_0 pack. +inline std::vector plan_layers(const strata::kernels::cpu::ExpertLayout& lay, std::string& err) { + const Config& c = config(); + std::vector out((size_t) (lay.n_layers > 0 ? lay.n_layers : 0)); + for (int64_t l = 0; l < (int64_t) out.size(); ++l) { + if (lay.native && (size_t) l < lay.fmt.size()) out[(size_t) l] = plan_layer(l, lay.fmt[(size_t) l], c); + else out[(size_t) l].slot_bytes = out[(size_t) l].raw_bytes = lay.blob_bytes(l); + } + if (c.on && !lay.native) err = "STRATA_EXPERT_NIBBLE needs a native pack (native_experts.txt)"; + for (const int64_t s : c.skip) + if (c.on && (s < 0 || s >= lay.n_layers) && err.empty()) + err = "STRATA_EXPERT_NIBBLE_SKIP: layer " + std::to_string(s) + " is not in the model"; + return out; +} + +namespace detail { +inline std::vector& table() { + static std::vector t; + return t; +} +} // namespace detail + +/// generate.cpp only: the table, once, after `expert_layout_load` and BEFORE the first slot estimate (placement +/// search, can_start, the cache's auto size, every `open_sized`). Not thread-safe: set before any other thread. +inline void set_layers(std::vector v) { detail::table() = std::move(v); } + +/// Layer `l`'s entry (an off entry when the table is not set or `l` is outside it). Read-only after `set_layers`. +inline const LayerVram& layer(int64_t l) { + static const LayerVram off; + const auto& t = detail::table(); + return l >= 0 && (size_t) l < t.size() ? t[(size_t) l] : off; +} + +/// Whether any layer is converted (the switch on and the table set). +inline bool any_on() { + for (const LayerVram& v : detail::table()) + if (v.on) return true; + return false; +} + +/// Bytes of one of layer `l`'s VRAM slots: the converted size for a converted layer, else the layout's blob bytes +/// (exactly `expert_layout().blob_bytes(l)`: with the switch off every caller sizes what it sized before). +inline uint64_t slot_bytes(int64_t l) { + const auto& t = detail::table(); + if (l >= 0 && (size_t) l < t.size()) return t[(size_t) l].slot_bytes; + return strata::kernels::cpu::expert_layout().blob_bytes(l); +} + +// ------------------------------------------------------------------------------------------------ fatal paths + +/// A converted layer reached a path that would compute or copy it as GGUF blocks: say where and stop. Never a +/// silent wrong answer. +[[noreturn]] inline void fatal(int64_t l, const char* where, const char* why) { + std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: layer %lld (%s, 4-bit slots) reached %s: %s - stopping\n", + (long long) l, fmt_name(layer(l).gu_type), where != nullptr ? where : "?", why != nullptr ? why : ""); + std::fflush(stderr); + std::abort(); +} + +/// Before each raw slot copy that bypasses the ExpertCache API (the adaptive tier's copies, the elastic K/V's slot +/// moves): fatal when `l` is a converted layer. The startup refusals keep these paths off; this is the backstop +/// (with `ExpertCache::seal()` for the API's own fills). +inline void guard_raw(int64_t l, const char* where) { + if (layer(l).on) fatal(l, where, "a raw slot copy at the GGUF size"); +} + +// ------------------------------------------------------------------------------------------------ the decode kernels +// +// Two skeletons in the shape of native_gu_multi_kernel (16 lanes a row, a group's entries GRP_NC at a time), both bit +// for bit the production gate/up: S stages the entries' q8_1 blocks in shared memory and decodes each item where it +// is used (IQ3_S: v = 2u - 15 restored per byte, then the production apply); P loads the lane's codes, scales and d +// before staging the qs words as 16-byte rows (IQ3_S: sum = 2 dot(u, x) - 15 sum(x), the same int32). Per format the +// faster one on 4x GP100 at T = 1..6 (native_expert_bench --nibble): IQ2_S P, IQ3_XXS S, IQ3_S S. + +inline constexpr int kSkelS = 0, kSkelP = 1; +STRATA_NIB_HD constexpr int gu_skeleton(int gu_type) { return gu_type == kIQ2_S ? kSkelP : kSkelS; } + +// ------------------------------------------------------------------------------------------------ iq_kernels.cu +// +// Device addresses are `unsigned long long` (as native_expert_grouped's grp_ptr), streams `void*`; each returns the +// CUDA error code (0 = success) so the caller can name the layer. A build without STRATA_EXPERT_NIBBLE_BUILT +// returns cudaErrorInvalidValue (1) from each. + +/// The reverse codebooks (grid magnitudes -> GGUF grid index) `check_gguf` and `gather_gguf` use, built on the CURRENT +/// device (once per device; call it at load, before any capture). Non-zero also when a grid entry is not unique. +int prepare(void* stream); + +/// Converts `n` raw blobs of layer `L` (device `staging`, `L.raw_bytes` apart, as the host arena holds them) into +/// the converted slots at `slot_ptrs[0..n)` (a device array): codes, scales, d. The down rows are not touched (the +/// caller copies them to `slot + kDownOff`). Every item is decoded with the production `Split::load`, encoded, +/// decoded from the written code again and compared with W.g[0..7], the scale and d; each item that differs or holds +/// a weight outside the code set adds 1 to `*bad` (device). L.on must be true. +int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream); + +/// The GGUF gate/up blocks rebuilt from each of the `n` (<= 64) converted slots at `slot_ptrs` and its down rows, +/// compared with the raw blobs in `staging` (`L.raw_bytes` apart) byte for byte: each 32-bit word that differs adds 1 +/// to `*bad`. `prepare` first. +int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream); + +/// The prompt path's gather of a converted layer's experts (prefill.cpp, MMQ): for q in [first, n) (n <= 16), the +/// GGUF [gate | up] blocks rebuilt from slot `slots[q]` (host array of device addresses) into gu_dst + q * gu_stride - +/// the bytes the raw blob holds, byte for byte - and its down rows copied to d_dst + q * d_stride; `zero_bytes` zeroed +/// after expert n - 1's gate/up and down (MMQ's tail). Every address, stride and size 16-byte aligned. `prepare` +/// on this device first. +int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride, + void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream); + +/// The slot hash (`hash_host`'s value) of the `L.hashed` bytes at each `slot_ptrs[i]`, into device `out[0..n)`. +int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out, + void* stream); + +} // namespace strata::core::nibble diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 2b2d9a0e..dec01c42 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -550,9 +550,12 @@ private: cudaStream_t df_side_[2] = {}; cudaEvent_t df_fork_ = nullptr; cudaEvent_t df_join_[2] = {}; - cudaGraphExec_t exec_[9] = {}; - cudaGraphExec_t exec_nr_[9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise - bool launched_[9] = {}, launched_nr_[9] = {}; ///< this graph has been launched once (early_ple_flag: a cold first launch raises the PLE flag first) + // [sel_long_][T]: 1 is the long-context QSA select (STRATA_SELECT_LONG=1: multi-CTA top-k, shuffle-free decode + // scores; see run()); without it only [0] is ever captured + cudaGraphExec_t exec_[2][9] = {}; + cudaGraphExec_t exec_nr_[2][9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise + bool launched_[2][9] = {}, launched_nr_[2][9] = {}; ///< this graph has been launched once (early_ple_flag: a cold first launch raises the PLE flag first) + int sel_long_ = 0; // fork 34a35db (STRATA_SIDE_MIXER=1): the GDN gates and the QSA indexer on a branch of the window's graph beside the // mixer's projections, joined before the recurrence / the attention cudaStream_t side_ = nullptr; @@ -636,6 +639,7 @@ private: float *qidx_ = nullptr, *scores_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr, *attn_scratch_ = nullptr; float* tail_snap_ = nullptr; // per QSA layer int32_t* sel_ = nullptr; + int32_t* topk_scratch_ = nullptr; // qsa_block_topk_long's multi-CTA exchange (STRATA_SELECT_LONG=1 only) float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *hit_out_ = nullptr; int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr; int32_t* plan_ = nullptr; // device copy of the plan block diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index ce06a9fe..b1f5ae5a 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -51,9 +51,16 @@ struct NativeExpertLayout { // APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before // quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr. int had_block = 0; + bool gu_nib = false; // STRATA_EXPERT_NIBBLE: gate/up as 4-bit codes (strata/core/expert_nibble.hpp's + // slot); set only by native_expert_layout_nib const float* d_signs = nullptr; }; NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +/// STRATA_EXPERT_NIBBLE: a converted VRAM slot - gate/up as 4-bit codes, scales and d (expert_nibble.hpp's layout: +/// up_off = the up rows' codes, down_off = kGuBytes, bytes = the slot), the GGUF down rows after them. IQ2_S / +/// IQ3_XXS / IQ3_S at n_embd 2560, n_ff 640 only, and only in a build with the kernels (`native_expert_nib_supported`). +NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; /// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the /// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated). bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; @@ -83,9 +90,15 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long /// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results /// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs. void native_grouped_set_v1(bool v1); +/// The bench / parity only: the 4-bit gate/up kernel of every format (-1 = expert_nibble.hpp's gu_skeleton, the +/// default; 0 = the S skeleton; 1 = the P skeleton). Bitwise the same results; set before graph capture. +void native_expert_nib_set_variant(int v); +/// gu-proto (nib_gu_proto.cuh): variant v's registers, local bytes and resident 256-thread blocks per SM for gu_type; +/// false when v is not a gu-proto id (>= 10) or the type has none. +bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm); /// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase -/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down). +/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down, 3 gate/up only). void native_expert_set_mode(int mode, int phase); /// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width` diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index ce11095c..c809e74e 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -110,8 +110,15 @@ void native_q8_0_packed_register(const void* gguf_weights, const void* packed, i void native_q8_0_packed_unregister(const void* gguf_weights); /// STRATA_Q8_SM60=1 (opt-in, Pascal GP100): every Q8_0 dense matrix is packed as above whatever its shape, and the /// Q8_0 decode GEMVs run a kernel written for compute capability 6.0 (q8_sm60.cuh; not bitwise the exact kernels). -/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release. +/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release; +/// native_q8_0_sm60_pack_quiet is the same with no line for a success (the caller sums several up). bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what); +bool native_q8_0_sm60_pack_quiet(const void* weights, int n_in, int n_out, const char* what); +/// The same for a matrix that nothing but native_mmvq reads (the MTP drafter's draft head subset): where every column +/// count takes the Pascal kernel and the planes stay 16-byte aligned, they replace the GGUF blocks in the matrix's own +/// allocation (the same byte count, staged through the host: no second copy); otherwise a packed copy as +/// native_q8_0_sm60_pack makes. Either way native_q8_0_sm60_release must run before the caller frees the matrix. +bool native_q8_0_sm60_pack_in_place(void* weights, int n_in, int n_out, const char* what); void native_q8_0_sm60_release(const void* weights); /// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh / diff --git a/include/strata/kernels/qsa_pattn.hpp b/include/strata/kernels/qsa_pattn.hpp new file mode 100644 index 00000000..3fd8de0b --- /dev/null +++ b/include/strata/kernels/qsa_pattn.hpp @@ -0,0 +1,46 @@ +// include/strata/kernels/qsa_pattn.hpp - STRATA_PATTN_SM60: the prompt path's QSA attention on sm_6x, bit for bit +// what prefill.cpp gets today from qsa_decode_attn_batch (attn_chunk_kernel_pre75<1, 2> + attn_merge_kernel or +// attn_merge_v2_kernel, 32 queries a call) with int8 K/V. +// +// On sm_6x qsa_prompt_attn_batch returns false (no tensor cores) and the prompt reads every QSA layer's attention +// through the decode kernels: one CTA per (64-cell chunk, KV head, query), the partials of all 33 chunks written to +// scratch (817 KB a query) and merged by a second kernel. The kernels here keep every operation of that path in its +// order - each lane's 8-dimension products, warp_sum's tree over the 32 lanes, the chunk softmax (warp_max / __expf / +// warp_sum pairs), the ascending fmaf value fold, the merge's chunk order (fmaxf, __expf(m - M), fmaf(l, w, L), +// fmaf(acc, w, acc), acc / L) - and change only where operands live and which thread does what: +// - ps_score_x_kernel, one CTA per (chunk, KV head, query): q in registers (loaded once in a per-lane slot order), +// the chunk's K staged with 16-byte loads, two cells at a time through one reduce-scatter whose 24 sums are +// warp_sum's tree without reduce12's selects; writes the chunk's probabilities, rows, m and l to the scratch; +// - ps_value_d4_kernel, one CTA per (KV head, query): four dims x 12 heads a thread, V four bytes a load, the chunks +// in ascending order, each merged into the output as the merge kernel does (no partial accumulators, no merge +// kernel). +// The caller's attention scratch holds the blocks of ~100 queries; a prompt chunk runs in batches of that size. +// +// Off unless STRATA_PATTN_SM60=1, and compiled only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (every other build +// links stubs that answer false, so the usual attention runs). +#pragma once + +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +namespace strata::kernels { + +/// STRATA_PATTN_SM60: 0 off (default, and in a build without the sm_6x kernels); 1 on. +int pattn_mode(); + +/// qsa_decode_attn_batch for all `n_q` queries of a prompt chunk in one call (int8 K/V, sm_6x, experimental build). +/// `scratch` / `scratch_floats`: the caller's attention scratch (prefill.cpp: attn_batch x qsa_decode_attn_scratch_floats). +/// False: not applicable or a launch failed (nothing the caller can rely on was written; it runs the usual loop). +bool qsa_pattn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, + void* stream); + +/// The same without the compute-capability test, for src/kernels/qsa_pattn_parity.cpp (it runs the kernels on any card +/// to compare them with the decode kernels' output). False in a build without the sm_6x kernels. +bool qsa_pattn_batch_any_arch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, + int64_t n_q, void* stream); + +} // namespace strata::kernels diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index e8beacce..35ee7a58 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -78,4 +78,20 @@ bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t n void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, const QsaShapes& s, int32_t* ids, void* stream); +/// The long-context decode select (the verifier's STRATA_SELECT_LONG=1 windows; CUDA builds with +/// STRATA_EXPERIMENTAL_SM60, elsewhere the plain calls). qsa_block_topk_long: qsa_block_topk's ids; a call with +/// `multi_scratch` (qsa_topk_multi_scratch_ints(nq) device ints, one call at a time per scratch, no initial value), no +/// active count and <= 16 queries runs several CTAs per query (block_topk_multi_*: STRATA_TOPK_MULTI=0 off, =1 on any +/// card, default compute capability 6.x past the register kernel's reach); otherwise it is qsa_block_topk. +/// qsa_block_scores_long: qsa_block_scores's bits; a call of <= 8 queries with no active count runs +/// block_scores_dx_kernel (STRATA_SCORES_DX=0 off, =1 on any card, default compute capability 6.x); otherwise it is +/// qsa_block_scores. +void qsa_block_topk_long(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks, int32_t* multi_scratch); +void qsa_block_scores_long(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks); +/// Device ints a qsa_block_topk_long call of `nq` queries may use as multi_scratch (0 on a build without the multi-CTA +/// path: pass null). +int64_t qsa_topk_multi_scratch_ints(int64_t nq); + } // namespace strata::kernels diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index fee662fc..6fba093e 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -122,6 +122,11 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre /// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split /// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats). void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream); +/// swiglu (n_ff 640), then quantize() of its rows for a down product of `ggml_type`, in one pass: H never stored, +/// the same bytes in hq. Only where swiglu_quant_ok (a q8_1 D4 down type; gu 16-byte aligned): CUDA, the +/// STRATA_EXPERIMENTAL_SM60 build. +bool swiglu_quant_ok(int ggml_type); +void swiglu_quant(const float* gu, void* hq, int64_t rows, bool interleaved, void* stream); /// swiglu of an NVFP4 group's gate/up rows (split halves) with scale_gu_rows' scales applied as they are read. void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n, const float* tails, int64_t row0, void* stream); diff --git a/include/strata/prefill/moe_ws.hpp b/include/strata/prefill/moe_ws.hpp new file mode 100644 index 00000000..d5a42eff --- /dev/null +++ b/include/strata/prefill/moe_ws.hpp @@ -0,0 +1,72 @@ +// include/strata/prefill/moe_ws.hpp - GP100 (sm_60, the STRATA_EXPERIMENTAL_SM60 build): the prompt path's expert +// products of a layer whose experts are all resident in VRAM, read in place there and weight-stationary: ONE launch +// for the layer's gate/up and ONE for its down instead of a gate/up, swiglu and down MMQ launch per 16-expert group. +// A CTA holds 128 (or 256) weight rows of one expert and runs them against up to 64 of the expert's activation rows, a +// thread per weight row: each weight block is decoded once per pass instead of once per MMQ tile, and an expert's +// rows are its own count, not the group's largest. Every product keeps MMQ's int8 values, scales and per-32-value +// epilogue in its K order (the down K loop stops at 640), so GU, H and Dm are the per-group MMQ's bits. Swift +// Flash's shapes and formats only: gate/up [1280 x 2560] IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS or IQ3_S, down [2560 x 640] +// Q2_0 or IQ4_NL. +#pragma once + +#include +#include + +namespace strata::prefill::ws { + +/// The products of a layer: 1 with STRATA_MMQ_WS=1 (opt-in) gate/up and down, else 0 (the per-group MMQ). 0 also where +/// the build has no kernels (HIP, no ggml sources, not the STRATA_EXPERIMENTAL_SM60 build) or a visible GPU is not +/// cc 6.0 (the kernels were tuned and checked on GP100 only). +int mode(); +/// mode() != 0 and both formats have kernels. +bool supported(int gu_type, int d_type); +/// STRATA_WS_FAST=1 (opt-in, read once): the IQ4_NL down's 32-token tier (u >= 20 rows per routed expert) runs a +/// kernel that issues fewer instructions per pass - a switch into the unrolled token pairs, dy transposed - with every +/// token's operations and their order unchanged, so Dm is the same bits. 0 (unset): the kernels as before. +int fast(); +/// Benches and tests: 0 / 1 overrides fast(), -1 goes back to the environment. +void set_fast(int v); +/// Tests: 0 / 1 overrides mode() (1 runs the kernels on a card that is not cc 6.0), -1 goes back to the environment. +void set_mode(int v); +/// The weight-stationary product of `ggml_type` beats the per-group MMQ at u rows per routed expert (the measured +/// ratios, moe_ws.cu; u is clamped to the measured 2.5 .. 160). +bool faster(int ggml_type, double u); +/// Every gate/up and down matrix starts this aligned (the IQ4_NL down reads 8-byte pieces; the expert cache's slots are +/// 256-byte aligned and the Swift gate/up sizes multiples of 8). +constexpr uint64_t kAlign = 8; + +/// The CTAs' work: rows [row0, row0 + rows) of Xq / GU / Hq / Dm, all of the expert at position j of the layer's order +/// (MMQ's: its xoff entry), at most kChunkRows. A CTA takes one chunk and one 128- or 256-row piece of the weights. +struct alignas(16) Chunk { + int32_t j, row0, rows, pad; +}; +constexpr int kChunkRows = 64; +/// The most chunks a layer of `rows` routed rows over at most `n_expert` experts makes. +inline size_t max_chunks(int64_t rows, int64_t n_expert) { return (size_t) (rows / kChunkRows + n_expert); } +/// The chunks of the n experts of `order` (expert e has cnt[e] rows from bounds[j], j its position), the largest +/// expert first (the long CTAs start first); returns their number (<= max_chunks). +size_t chunks(const int32_t* order, size_t n, const int32_t* cnt, const int32_t* bounds, Chunk* out); + +/// One layer: its n routed experts' matrices at w + xoff[j] (gate/up, rows 0-639 gate then up) and w + xoff[j] + +/// down_off (down), xoff on the device in the layer's order (Product::xoff's table, all n entries); `rows` = T*K. +struct Layer { + int gu_type = -1, d_type = -1; + const void* w = nullptr; + const int64_t* xoff = nullptr; + int64_t down_off = 0; + const Chunk* chunks = nullptr; ///< on the device + int64_t nchunks = 0; + int64_t rows = 0; + int n = 0; + const void* xq = nullptr; ///< the gate/up's q8_1 rows (mmq::quantize_scatter's, rows of them) + float* gu = nullptr; ///< [rows][1280], the rows MMQ writes through identity ids + const void* hq = nullptr; ///< H's q8_1 rows: ONE mmq::swiglu_quant over all `rows` rows of gu + float* dm = nullptr; ///< [rows][2560] +}; +/// The layer's gate/up into gu, one launch; false (nothing launched) where the per-group MMQ is to run instead (mode 0, +/// or not faster at this u) - the same GU rows either way. +bool gate_up(const Layer& L, void* stream); +/// The layer's down from hq into dm, one launch. +void down(const Layer& L, void* stream); + +} // namespace strata::prefill::ws diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 39ed8557..fa75c31d 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -169,6 +169,11 @@ public: /// build with the pointer-table MMQ (STRATA_MMQ_TAB). static size_t slot_guard_bytes(); + /// STRATA_EXPERT_NIBBLE=1: whether every converted layer's experts reach the prompt path's MMQ gather only (the + /// GGUF blocks rebuilt from the 4-bit slots); false with the first layer and the reason in `why`. Pure: the + /// layers' formats, the environment and the visible GPUs (generate.cpp asks once, before anything is allocated). + static bool nibble_prompt_check(std::string& why); + /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest /// first, -1 for none) and is advanced to the last two of these. bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); diff --git a/metal/src/engine/stubs_0145.cpp b/metal/src/engine/stubs_0145.cpp index 0c1976f6..8aa89f3d 100644 --- a/metal/src/engine/stubs_0145.cpp +++ b/metal/src/engine/stubs_0145.cpp @@ -147,5 +147,12 @@ namespace strata::kernels { bool gemm_iq_f16_grouped(int p0, void const* p1, uns // STRATA_Q8_SM60 (Pascal GP100, opt-in): a no-op on Metal; NativeHead::load()/unload() call these for a Q8_0 head, so they must exist and answer "nothing packed". namespace strata::kernels { bool native_q8_0_sm60_pack(void const* p0, int p1, int p2, char const* p3) { return false; } } namespace strata::kernels { void native_q8_0_sm60_release(void const* p0) { } } +// the MTP drafter's STRATA_MTP_Q8_SM60 packing (mtp.cpp): nothing packed on Metal +namespace strata::kernels { bool native_q8_0_sm60_pack_quiet(void const* p0, int p1, int p2, char const* p3) { return false; } } +namespace strata::kernels { bool native_q8_0_sm60_pack_in_place(void* p0, int p1, int p2, char const* p3) { return false; } } +// STRATA_SELECT_LONG (verify.cpp's long-context decode select): CUDA only; never reached on Metal (no scratch asked for) +namespace strata::kernels { long long qsa_topk_multi_scratch_ints(long long p0) { return 0; } } +namespace strata::kernels { void qsa_block_topk_long(float const* p0, int const* p1, long long p2, long long p3, long long p4, strata::kernels::QsaShapes const& p5, int* p6, void* p7, long long p8, int* p9) { strata::metal_engine::missing("strata::kernels::qsa_block_topk_long"); } } +namespace strata::kernels { void qsa_block_scores_long(float const* p0, float const* p1, float const* p2, int const* p3, long long p4, long long p5, strata::kernels::QsaShapes const& p6, float* p7, void* p8, long long p9) { strata::metal_engine::missing("strata::kernels::qsa_block_scores_long"); } } // only reached with pf_wmma (off on Metal) namespace strata::prefill { void swiglu_split_f16(float const* p0, unsigned short* p1, long long p2, int p3, bool p4, void* p5) { } } diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index f499378c..d670c8da 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -81,6 +81,17 @@ bool nvml_device_free(size_t& out) { } // namespace #endif +namespace { +// STRATA_EXPERT_NIBBLE: a write into a sealed cache (see ExpertCache::seal). Says which call and stops: the slots hold +// 4-bit codes the GGUF bytes would overwrite, or a GGUF expert where a 4-bit one is expected - a wrong reply, not an error. +[[noreturn]] void sealed_write(const char* call, int32_t slot) { + std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: ExpertCache::%s(slot %d) after the cache was sealed - a GGUF " + "blob would be written into the 4-bit expert slots: stopping\n", call, (int) slot); + std::fflush(stderr); + std::abort(); +} +} // namespace + // See the header. NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same: // not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim. Swap is not counted here (unlike // NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one. @@ -699,6 +710,7 @@ void ExpertCache::close() { next_free_ = 0; fills_ = 0; admitted_ = 0; + sealed_ = false; layer_next_.clear(); } @@ -719,6 +731,7 @@ int32_t ExpertCache::slot_of(int64_t layer, int64_t expert) const { } int32_t ExpertCache::admit(int64_t layer, int64_t expert) { + if (sealed_) return kNotResident; // STRATA_EXPERT_NIBBLE: nothing is admitted (and so filled) after the startup fill if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident; const size_t at = (size_t) (layer * n_expert_ + expert); if (residency_[at] != kNotResident) return residency_[at]; @@ -751,6 +764,7 @@ const uint8_t* ExpertCache::device_slot(int32_t slot) const { } bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes) { + if (sealed_) sealed_write("fill_slot", slot); const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); uint8_t* dst = device_slot(slot); if (dst == nullptr) { @@ -773,6 +787,7 @@ bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream } bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + if (sealed_) sealed_write("fill_slot_blocking", slot); const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); uint8_t* dst = device_slot(slot); if (dst == nullptr) { @@ -804,6 +819,7 @@ bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std } bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + if (sealed_) sealed_write("fill_slot_queued", slot); const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); uint8_t* dst = device_slot(slot); if (dst == nullptr || host_blob == nullptr) { @@ -821,6 +837,7 @@ bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std:: } bool ExpertCache::fill_slot_queued_parts(int32_t slot, const BlobPart* parts, int n, std::string& err) { + if (sealed_) sealed_write("fill_slot_queued_parts", slot); uint8_t* dst = device_slot(slot); if (dst == nullptr || parts == nullptr || n <= 0) { err = "ExpertCache::fill_slot_queued_parts: slot outside the arena or no pieces"; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index d0ce8bbb..80c15dee 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1,5 +1,6 @@ // src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract. #include "strata/core/expert_source.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/foresight_swap.hpp" #include "strata/core/on_device.hpp" #include "strata/platform/aux_cpus.hpp" @@ -5248,6 +5249,14 @@ void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids d.hit_pending = false; if (!d.hits_ready() || ids == nullptr || k <= 0) return; if ((int64_t) d.is_hit.size() < k) d.is_hit.resize((size_t) k); + // STRATA_EXPERT_NIBBLE=1: this split computes a resident expert with the GGUF-block kernels and admits + fills + // a missed one with its GGUF blob - neither may meet a layer whose slots hold 4-bit codes (a native pack's + // experts run in the verify windows, so this is the backstop, never the path) +#if STRATA_EXPERT_NIBBLE_BUILT // compiled out of every other build: nothing is added to the hit split there + if (strata::core::nibble::layer(d.layers).on) + strata::core::nibble::fatal(d.layers, "the expert source's hit split (expert_hit_run)", + "it computes resident experts as GGUF blocks and fills slots with GGUF blobs"); +#endif // ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================ // diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 292a5d2b..99ad68f2 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -78,6 +78,16 @@ bool mtp_catchup_all() { }(); return on; } +// STRATA_MTP_Q8_SM60=1 (opt-in, with STRATA_Q8_SM60=1): the drafter's own Q8_0 matrices (the draft head's subset, +// the projections) run on the Pascal GEMV too (the drafts differ in rounding only: the Pascal kernel sums in another +// order; the replies do not depend on the drafts) +bool mtp_q8_sm60() { + static const bool on = [] { + const char* v = std::getenv("STRATA_MTP_Q8_SM60"); + return v != nullptr && v[0] == '1'; + }(); + return on; +} constexpr int GGML_Q8_0 = 8; constexpr int GGML_Q4_0 = 2; using Clock = std::chrono::steady_clock; @@ -154,12 +164,20 @@ MtpDrafter::~MtpDrafter() { if (side_) cudaStreamDestroy(side_); if (sh_fork_) cudaEventDestroy(sh_fork_); if (sh_join_) cudaEventDestroy(sh_join_); - if (owns_weights_ && dense_) cudaFree(dense_); + if (owns_weights_ && dense_) { + for (const auto& t : tensors_) // the STRATA_MTP_Q8_SM60 registrations first (a no-op for the rest) + if (t.kind == "q8_0") strata::kernels::native_q8_0_sm60_release(dense_ + t.off); + cudaFree(dense_); + } if (owns_weights_ && experts_) cudaFree(experts_); if (state_arena_) cudaFree(state_arena_); if (arena_) cudaFree(arena_); if (head_logits_) cudaFree(head_logits_); - if (owns_draft_head_ && dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); } + if (owns_draft_head_ && dhead_) { + strata::kernels::native_q6_k_unpack(dhead_); + strata::kernels::native_q8_0_sm60_release(dhead_); + cudaFree(dhead_); + } if (owns_draft_head_ && dvocab_) cudaFree(dvocab_); if (ev_chain_) cudaEventDestroy(ev_chain_); for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e); @@ -335,6 +353,26 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session "self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"}; for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; } + // STRATA_MTP_Q8_SM60=1: the projections on the Pascal GEMV (--batch's shared drafters read the same pointers), as + // packed copies like the main model's: the prompt path's draft_kv reads four of them in the GGUF layout (MMQ); + // --mtp-q4 reads its Q4_0 copies instead + if (shared == nullptr && dense4_ == nullptr && mtp_q8_sm60()) { + int packed = 0; + uint64_t packed_bytes = 0; + for (const char* n : required) + for (const auto& t : tensors_) + if (t.name == n && t.kind == "q8_0" && + strata::kernels::native_q8_0_sm60_pack_quiet(dense_ + t.off, (int) t.cols, (int) t.rows, + ("MTP " + t.name).c_str())) { + ++packed; + packed_bytes += t.bytes; // a copy is the same 34 bytes per 32 values + } + vram_ += packed_bytes; + if (packed > 0) + std::fprintf(stderr, "strata mtp: %d of %zu projections on the Pascal Q8_0 GEMV (STRATA_MTP_Q8_SM60=1, %.1f " + "MiB more VRAM)\n", packed, sizeof(required) / sizeof(required[0]), + (double) packed_bytes / 1048576.0); + } // ---- the layer's own K/V (dense attention: no indexer state is read) const strata::kernels::QsaShapes s = shapes_of(g); @@ -742,6 +780,12 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1 strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_, "MTP draft head"); + // STRATA_MTP_Q8_SM60=1: the subset on the Pascal GEMV like the main head, but packed in place - nothing but + // record_rest's native_mmvq reads it (the prompt path never does), and a copy would cost its size again + if (dhead_type_ == GGML_Q8_0 && owns_draft_head_ && mtp_q8_sm60() && row_bytes == g_->n_embd / 32 * 34 && + strata::kernels::native_q8_0_sm60_pack_in_place(dhead_, (int) g_->n_embd, (int) n_dvocab_, + "MTP draft head")) + std::fprintf(stderr, "strata mtp: the draft head on the Pascal Q8_0 GEMV (STRATA_MTP_Q8_SM60=1)\n"); } } if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a87e995d..79b3b89b 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -5,6 +5,7 @@ #include "strata/kernels/gfx_arch.hpp" #include "strata/core/verify.hpp" #include "strata/core/window_evict.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/pin_budget.hpp" #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) #include "strata/core/host_graph_launch.hpp" @@ -167,6 +168,32 @@ inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv // fork F4 (Eddoursul): 2-4 token dense projections read an interleaved copy of the q8_1 activations (bitwise the same // outputs); STRATA_MMVQ_IL=0 keeps native_mmvq's multi-column kernels inline bool g_mmvq_il() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL"); return v == nullptr || v[0] != '0'; }(); return on; } +// STRATA_SELECT_LONG=1 (opt-in): a window graph past select_long_at() cells takes the long-context QSA select +// (qsa_block_topk_long's multi-CTA top-k through topk_scratch_, qsa_block_scores_long's shuffle-free decode scorer; +// both compute capability 6.x by default, the same ids and score bits). Each costs ~6 more kernels a call, which only +// a longer context pays back (4x GP100: 0.5 ms a window more at 1K, even at 30K, 4.0-4.7 ms less at 300K), so the +// verifier keeps a second set of window graphs for it. Off: no scratch, no second graphs. +inline bool select_long_on() { + static const bool on = [] { + const char* v = std::getenv("STRATA_SELECT_LONG"); + if (v == nullptr || v[0] != '1') return false; + if (strata::kernels::qsa_topk_multi_scratch_ints(1) <= 0) { // a build without the multi-CTA kernels: no second graphs + std::fprintf(stderr, "strata verify: STRATA_SELECT_LONG=1 needs the CUDA build with STRATA_EXPERIMENTAL_SM60; " + "ignored\n"); + return false; + } + return true; + }(); + return on; +} +// STRATA_SELECT_LONG_AT: the threshold in cells (default 65536; 0: always) +inline int64_t select_long_at() { + static const int64_t at = [] { + const char* v = std::getenv("STRATA_SELECT_LONG_AT"); + return v != nullptr && v[0] != 0 ? (int64_t) std::atoll(v) : (int64_t) 65536; + }(); + return at; +} // 143-amdk: STRATA_QFUSE_HC - only the hyper-connection read writes its consumer's q8_1 image (not the GDN recurrence): gfx12 default (=0 / 1 forces off / on) inline bool g_qfuse_hc() { #if defined(STRATA_USE_HIP) @@ -618,10 +645,12 @@ Verifier::~Verifier() { } if (cs_) cudaStreamSynchronize(cs_); if (sh_cs_) cudaStreamSynchronize(sh_cs_); - for (auto& e : exec_) - if (e) cudaGraphExecDestroy(e); - for (auto& e : exec_nr_) - if (e) cudaGraphExecDestroy(e); + for (auto& row : exec_) + for (auto& e : row) + if (e) cudaGraphExecDestroy(e); + for (auto& row : exec_nr_) + for (auto& e : row) + if (e) cudaGraphExecDestroy(e); if (commit_exec_) cudaGraphExecDestroy(commit_exec_); for (auto& kv : exec_bm_) if (kv.second) cudaGraphExecDestroy(kv.second); @@ -879,6 +908,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& kcur_ = b.take(T * NKV * HD); vcur_ = b.take(T * NKV * HD); idx_raw_L_ = b.take(nQ * T * ID); qidx_ = b.take(T * IQ * ID); scores_ = b.take(T * (uint64_t) max_blocks_); sel_ = b.take(T * (uint64_t) cap_); + if (select_long_on() && strata::kernels::qsa_topk_multi_scratch_ints(T) > 0) // STRATA_SELECT_LONG only + topk_scratch_ = b.take((uint64_t) strata::kernels::qsa_topk_multi_scratch_ints(T)); attn_ = b.take(T * NH * HD); attn32_ = b.take(T * NH * HD); attn_scratch_ = b.take(T * (uint64_t) attn_scratch_floats_); tail_snap_ = b.take(nQ * TS); @@ -1663,6 +1694,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } }; auto idx_select = [&](cudaStream_t ns) { + if (sel_long_) { // STRATA_SELECT_LONG: the long-context window graphs (the same ids) + qsa_block_scores_long(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, + max_blocks_, s, scores_ + (size_t) tb * max_blocks_, ns, -1); + qsa_block_topk_long(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, + cap_, s, sel_ + (size_t) tb * cap_, ns, -1, topk_scratch_); + return; + } qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_, s, scores_ + (size_t) tb * max_blocks_, ns); qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s, @@ -2091,11 +2129,21 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const auto& lay = strata::kernels::cpu::expert_layout(); // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging. // `gy`: the native launch's groups side by side (0: cap, one block row per possible group). - auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf) { + // `vram`: the groups point into this GPU's expert slots - a layer STRATA_EXPERT_NIBBLE converted holds its + // gate/up there as 4-bit codes (expert_nibble.hpp); the PCIe share's blobs (host memory, staging) never do. + auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf, + bool vram) { if (lay.native) { // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) const auto& f = lay.fmt[(size_t) l]; +#if STRATA_EXPERT_NIBBLE_BUILT + NativeExpertLayout L = vram && strata::core::nibble::layer(l).on + ? native_expert_layout_nib(f.gu_type, f.d_type, f.n_embd, f.n_ff) + : native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); +#else + (void) vram; NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); +#endif if (f.had_d) { L.had_block = f.had_block; L.d_signs = had_sh_; } // APR: h is rotated in there native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap, nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy); @@ -2107,7 +2155,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { bool hits_in_combine = false; if (ar_on()) { stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, parts_out); + grouped(p_ptr, p_start, p_counts, 0, parts_out, true); stamp(l, 20, grp); } else { if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) @@ -2125,7 +2173,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, hit_out); + grouped(p_ptr, p_start, p_counts, 0, hit_out, true); stamp(l, 20, grp); if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); else if (m_bal_ != nullptr) // set_pcie_balance: the PCIe part starts @@ -2140,7 +2188,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { stamp(l, 21, grp); // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them - grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out); + grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out, false); stamp(l, 22, grp); if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs); @@ -2453,7 +2501,7 @@ void Verifier::refresh_ar() { } bool Verifier::capture(int T, std::string& err) { - cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; + cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T]; if (exec_t != nullptr) return true; { // said before the capture: a process that exits inside it (#1275: Windows, 313 MiB free) leaves this line as the trace size_t free_b = 0, total_b = 0; @@ -2858,7 +2906,8 @@ bool Verifier::chain_overlap() const { bool Verifier::prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string& err) { const OnDevice on_device(device_); prelaunched_ = 0; - cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; // #871: the variant the previous stage refreshed + sel_long_ = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0; // the variant the previous stage captured + cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T]; // #871: the variant the previous stage refreshed if (T < 1 || T > max_t_ || exec_t == nullptr) { err = "verify: prelaunch before the window was captured"; return false; } if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } if (pos0 + T > ss_->qsa_states[ss_->qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } @@ -2902,11 +2951,14 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, prelaunched_ = 0; if (!pre && pre_launch_ && !pre_launch_(cs_, err)) return false; // (a prelaunched window's was served with the first stage's) if (!pre) refresh_ar(); + // STRATA_SELECT_LONG: the select kernels this window's context pays off with (the same on every stage) + sel_long_ = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0; if (!capture(T, err) || !capture_commit(err)) return false; const bool chain = chain_overlap(); if (chain) { // capture the next stage's window here, on this thread, so the helper only stages and launches const OnDevice on_next(next_->device_); next_->refresh_ar(); // #871: the variant its prelaunch and its run() will both use + next_->sel_long_ = sel_long_; if (!next_->capture(T, err) || !next_->capture_commit(err)) return false; } VDBG("captured; staging\n"); @@ -2929,7 +2981,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, #endif const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) bool flag_raised = false; // the PLE flag went up before the launch (early_ple_flag_mode) - bool& graph_launched = ar_off_ ? launched_nr_[T] : launched_[T]; + bool& graph_launched = ar_off_ ? launched_nr_[sel_long_][T] : launched_[sel_long_][T]; if (!pre && ar_on() && !test_stall && (early_ple_flag_mode() == 1 || (early_ple_flag_mode() == 2 && !graph_launched))) { if (do_ple) { const Clock::time_point tp = Clock::now(); @@ -2958,11 +3010,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH"); return value != nullptr && value[0] == '1'; }(); - launch_o.emplace(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch, + launch_o.emplace(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_, device_, threaded_launch, [this] { (void) release_gpu_waits(5000); }); const cudaError_t le = launch_o->status(); #else - const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); + const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_); #endif trace_ev("LAUNCHED", -1, -1, (int64_t) le); graph_launched = true; @@ -3550,6 +3602,7 @@ bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err row_base_ = hbase; for (int t = 0; t < S; ++t) brow_[t] = rows[t]; std::string rerr; + sel_long_ = 0; // batch rows: the one-CTA select const bool ok = record_window(S, cs_, rerr); batch_rec_ = false; row_base_ = 0; @@ -3718,17 +3771,17 @@ bool Verifier::evict_window_graph(int keep_t, bool& evicted, std::string& err) { evicted = false; if (no_window_eviction_ || keep_t < 1) return true; bool have[9] = {}; - for (int t = 1; t <= max_t_ && t < 9; ++t) have[t] = (ar_off_ ? exec_nr_[t] : exec_[t]) != nullptr; + for (int t = 1; t <= max_t_ && t < 9; ++t) have[t] = (ar_off_ ? exec_nr_[sel_long_][t] : exec_[sel_long_][t]) != nullptr; const int victim = strata::core::pick_window_victim(have, std::min(max_t_, 8), keep_t, prelaunched_); if (victim == 0) return true; if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = "verify: synchronizing before window graph eviction failed"; return false; } - cudaGraphExec_t& e = ar_off_ ? exec_nr_[victim] : exec_[victim]; + cudaGraphExec_t& e = ar_off_ ? exec_nr_[sel_long_][victim] : exec_[sel_long_][victim]; cudaGraphExecDestroy(e); e = nullptr; - (ar_off_ ? launched_nr_ : launched_)[victim] = false; // the next graph of that size is a cold first launch again + (ar_off_ ? launched_nr_ : launched_)[sel_long_][victim] = false; // the next graph of that size is a cold first launch again evicted = true; return true; } @@ -4261,8 +4314,14 @@ bool Verifier::capture_all(std::string& err) { explicit NoEvict(bool& flag) : f(flag) { f = true; } ~NoEvict() { f = false; } } no_evict(no_window_eviction_); - for (int T = 1; T <= max_t_; ++T) - if (!capture(T, err)) return false; + // STRATA_SELECT_LONG: both select variants (see select_long_at): pl_launch takes the one its window's context + // needs, and nothing can be captured once pipelined windows are in flight. Without it only [0] + for (int sl = 0; sl < (select_long_on() ? 2 : 1); ++sl) { + sel_long_ = sl; + for (int T = 1; T <= max_t_; ++T) + if (!capture(T, err)) return false; + } + sel_long_ = 0; if (!capture_commit(err)) return false; if ((ev_done_ == nullptr && cudaEventCreateWithFlags(&ev_done_, cudaEventDisableTiming) != cudaSuccess) || (ev_commit_ == nullptr && cudaEventCreateWithFlags(&ev_commit_, cudaEventDisableTiming) != cudaSuccess)) { @@ -4317,7 +4376,8 @@ bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } SessionState& ss = *ss_; if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } - if (exec_[T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) { + const int sl = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0; // the variant this window's context pays off with + if (exec_[sl][T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; } @@ -4339,7 +4399,7 @@ bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string std::atomic_thread_fence(std::memory_order_seq_cst); trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); - const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + const cudaError_t le = cudaGraphLaunch(exec_[sl][T], cs_); trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } if (fl_prof_) cudaMemcpyAsync(prof_pin_, prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost, cs_); diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index d2f2e34e..50f0a839 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -5,6 +5,7 @@ // MIT license, third_party/ggml/LICENSE). The block structs and codebook grids come from its ggml-common.h, // included unchanged. #include "strata/kernels/iq_kernels.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/sm75_series.hpp" #include "strata/core/sm120_series.hpp" #include "strata/kernels/gfx_arch.hpp" @@ -4167,6 +4168,1012 @@ void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, c else if (g_no_sub16_gu) native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); else native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); } +// ---------------------------------------------------------------- STRATA_DOWN_WS: the decode down projection, staged +// (opt-in, default off; cc 6.0 only). native_down_multi_kernel's IQ4_NL (K 40, n_ff 640) and Q2_0 (K 20) rows read each +// weight as 2-byte loads, an item at a time, straight from global memory, and a block (32 / 16 rows) waits on that. +// Here a block copies its rows (IQ4_NL 32, Q2_0 64: 11,520 bytes) into shared memory with 16-byte loads - one round +// trip, all in flight - reads the plan words before the group test and the entries' destination rows before the weights +// land, and then runs the production row dots on the copy: the same 8 / 16-lane sub-warp, lane t, items, float +// expressions and order (row_dot_40_sub8 / row_dot_20_sub16: s += item t (+ t + 32), s16, s8, s24, the __fadd_rn's, +// xor 4..1 / 8..1, * sd). Two integer-only changes inside an item: the dp4a emulation's byte products are taken from +// the table lookup's bytes with vmad byte selectors (no interleaving byte_perm), and IQ4_NL's lookup uses raw prmt +// selectors (bit 3, sign replicate, only touches the bytes the low/high merge drops; lhsi's nibbles are 0..7, so no +// 0x7777 masks). An item's int32 sum is the sum of the same int8 x int8 products, so every output is bit for bit +// native_down_multi_kernel's (memcmp equal on all 48 layers of the Swift 1.5 IQ3_S pack, all 512 experts, 1-6 +// entries a group and T = 1..4 plans; native_expert_bench checks it against mode 0 and mode 8 by output hash). +#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \ + !defined(STRATA_GPU_METAL) +#define STRATA_DOWN_WS_BUILT 1 // the CUDA build with STRATA_EXPERIMENTAL_SM60 only +#else +#define STRATA_DOWN_WS_BUILT 0 +#endif +#if STRATA_DOWN_WS_BUILT +#define STRATA_DWS_VMAD(r, a, sa, b, sb) asm("vmad.s32.s32.s32 %0, %1.b" #sa ", %2.b" #sb ", %0;" : "+r"(r) : "r"(a), "r"(b)) + +__device__ __forceinline__ uint32_t dws_prmt(uint32_t a, uint32_t b, uint32_t c) { + uint32_t d; + asm("prmt.b32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); + return d; +} + +// get_int_from_table_16(q4, kvalues_iq4nl) before its 0x6420 / 0x7531 interleave: t0 = T(v0) T(v16) T(v1) T(v17), +// t1 = T(v2) T(v18) T(v3) T(v19). low = prmt(T0..7, q) is right for codes < 8, high = prmt(T8..15, q ^ 0x8..) for +// codes >= 8, and the merge with lhsi (nibbles 0..7) takes exactly those bytes - the same bytes as __byte_perm's masked +// selectors give. +__device__ __forceinline__ void dws_iq4_tab(uint32_t q4, int& t0, int& t1) { + const uint32_t* table32 = (const uint32_t*) kvalues_iq4nl; + const uint32_t lhsi = 0x32103210u | ((q4 & 0x88888888u) >> 1); + const uint32_t qx = q4 ^ 0x88888888u; + t0 = (int) dws_prmt(dws_prmt(table32[0], table32[1], q4), dws_prmt(table32[2], table32[3], qx), lhsi); + t1 = (int) dws_prmt(dws_prmt(table32[0], table32[1], q4 >> 16), dws_prmt(table32[2], table32[3], qx >> 16), lhsi >> 16); +} + +struct DwsIq4W { int t0[2], t1[2]; float dw; }; + +__device__ __forceinline__ DwsIq4W dws_iq4_load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; + DwsIq4W r; +#pragma unroll + for (int l = 0; l < 2; ++l) dws_iq4_tab((uint32_t) get_int_b2(bq4->qs, iqs + l), r.t0[l], r.t1[l]); + r.dw = __half2float(bq4->d); + return r; +} + +// = Split<20>::apply(Split<20>::load(...)): x_l = (t0.b0 t0.b2 t1.b0 t1.b2) . q8[l], y_l = (t0.b1 t0.b3 t1.b1 t1.b3) . q8[l + 4] +__device__ __forceinline__ float dws_iq4_apply(const DwsIq4W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int* q8 = (const int*) bq8_1->qs + iqs; + int sumi = 0; +#pragma unroll + for (int l = 0; l < 2; ++l) { + const int A = q8[l + 0], B = q8[l + 4]; + STRATA_DWS_VMAD(sumi, r.t0[l], 0, A, 0); + STRATA_DWS_VMAD(sumi, r.t0[l], 2, A, 1); + STRATA_DWS_VMAD(sumi, r.t1[l], 0, A, 2); + STRATA_DWS_VMAD(sumi, r.t1[l], 2, A, 3); + STRATA_DWS_VMAD(sumi, r.t0[l], 1, B, 0); + STRATA_DWS_VMAD(sumi, r.t0[l], 3, B, 1); + STRATA_DWS_VMAD(sumi, r.t1[l], 1, B, 2); + STRATA_DWS_VMAD(sumi, r.t1[l], 3, B, 3); + } + const float d = r.dw * __low2float(bq8_1->ds); + return d * sumi; +} + +// row_dot_40_sub8<20, NC, true> (t < 8: its k loop is k = t, t + 32), the five items' words loaded first +template +__device__ __forceinline__ void dws_row40(const uint8_t* row, const block_q8_1* x, int t, float (&s)[NC]) { + const int k0 = t, k1 = t + 32, k2 = t + 16, k3 = t + 8, k4 = t + 24; + const DwsIq4W w0 = dws_iq4_load(row, k0 / 2, 2 * (k0 % 2)); + const DwsIq4W w1 = dws_iq4_load(row, k1 / 2, 2 * (k1 % 2)); + const DwsIq4W w2 = dws_iq4_load(row, k2 / 2, 2 * (k2 % 2)); + const DwsIq4W w3 = dws_iq4_load(row, k3 / 2, 2 * (k3 % 2)); + const DwsIq4W w4 = dws_iq4_load(row, k4 / 2, 2 * (k4 % 2)); +#pragma unroll + for (int c = 0; c < NC; ++c) { + const block_q8_1* xc = x + 20 * c; + s[c] = 0.0f; + s[c] += dws_iq4_apply(w0, xc + k0 / 2, 2 * (k0 % 2)); + s[c] += dws_iq4_apply(w1, xc + k1 / 2, 2 * (k1 % 2)); + { + float s16 = 0.0f; + s16 += dws_iq4_apply(w2, xc + k2 / 2, 2 * (k2 % 2)); + s[c] = __fadd_rn(s[c], s16); + } + float s8 = 0.0f; + s8 += dws_iq4_apply(w3, xc + k3 / 2, 2 * (k3 % 2)); + { + float s24 = 0.0f; + s24 += dws_iq4_apply(w4, xc + k4 / 2, 2 * (k4 % 2)); + s[c] = __fadd_rn(s[c], __fadd_rn(s8, s24)); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) { +#pragma unroll + for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// Split<42>::load before its 0x5140 / 0x7362 interleave (qx = qe.b0 qo.b0 qe.b1 qo.b1, qy = qe.b2 qo.b2 qe.b3 qo.b3) +struct DwsQ2W { int qe[4], qo[4]; float d2; }; + +__device__ __forceinline__ DwsQ2W dws_q2_load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx; + DwsQ2W r; + r.d2 = bq2_0->d; + const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int q = qs[j]; + r.qe[j] = __byte_perm(0x020100FF, 0x020100FF, q >> 0); + r.qo[j] = __byte_perm(0x020100FF, 0x020100FF, q >> 2); + } + return r; +} + +// = Split<42>::apply, the 32 products summed in two int32 chains +__device__ __forceinline__ float dws_q2_apply(const DwsQ2W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const block_q8_1* bq8_1_chunk = bq8_1 + iqs; + int a[2] = { 0, 0 }; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0); + const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1); + int& x = a[j & 1]; + STRATA_DWS_VMAD(x, u, 0, r.qe[j], 0); + STRATA_DWS_VMAD(x, u, 1, r.qo[j], 0); + STRATA_DWS_VMAD(x, u, 2, r.qe[j], 1); + STRATA_DWS_VMAD(x, u, 3, r.qo[j], 1); + STRATA_DWS_VMAD(x, v, 0, r.qe[j], 2); + STRATA_DWS_VMAD(x, v, 1, r.qo[j], 2); + STRATA_DWS_VMAD(x, v, 2, r.qe[j], 3); + STRATA_DWS_VMAD(x, v, 3, r.qo[j], 3); + } + const int sumi = a[0] + a[1]; + const float d8 = __low2float(bq8_1_chunk->ds); + return r.d2 * d8 * sumi; +} + +// row_dot_20_sub16<42, NC, true> +template +__device__ __forceinline__ void dws_row20(const uint8_t* row, const block_q8_1* x, int t, float (&s)[NC]) { + const DwsQ2W w = dws_q2_load(row, t / 2, t % 2); +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = 0.0f; + s[c] += dws_q2_apply(w, x + 20 * c + (t / 2) * 2, t % 2); + } + float s16[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; + if (t < 4) { + const int k = t + 16; + const DwsQ2W w2 = dws_q2_load(row, k / 2, k % 2); +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] += dws_q2_apply(w2, x + 20 * c + (k / 2) * 2, k % 2); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = __fadd_rn(s[c], s16[c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// NC entries of one row; every lane of the sub-warp holds the same sum (butterfly), lane c stores entry c +template +__device__ __forceinline__ void dws_rows(const uint8_t* wr, const block_q8_1* s_hq, int t, float sd, float* __restrict__ out, + const int (&dst)[NC], int64_t n_embd, int r) { + float s[NC]; + if constexpr (TD == 20) dws_row40(wr, s_hq, t, s); + else dws_row20(wr, s_hq, t, s); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (t == c) out[(size_t) dst[c] * n_embd + r] = s[c] * sd; +} + +// grid (n_embd / RB, gy), 256 threads: RB = 32 IQ4_NL rows (one pass of 8-lane rows) or 64 Q2_0 rows (four passes of +// 16-lane rows); entries NCMAX at a time (1: a T = 1 window, every group one entry; 4: as GRP_NC) +template +__global__ void __launch_bounds__(256, 4) native_down_ws_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + constexpr int LPR = TD == 20 ? 8 : 16, RPP = 256 / LPR, P = TD == 20 ? 1 : 4, RB = RPP * P; + constexpr int DROW = TD == 20 ? 360 : 180, WB = RB * DROW, NV = (WB / 16 + 255) / 256; + static_assert(WB % 16 == 0, "16-byte copies"); + STRATA_SHARED_ALIGN16_U32(s_w, WB / 4); + STRATA_SHARED_ALIGN16_U32(s_hq_buf, NCMAX * 20 * 9); + const int tid = threadIdx.x, t = tid % LPR, sub = tid / LPR; + const int r0 = blockIdx.x * RB; + const int nrow = min(RB, (int) L.n_embd - r0); + const block_q8_1* s_hq = reinterpret_cast(s_hq_buf); + // the plan words of this block row's first group before the test (gridDim.y <= cap_groups: in bounds) + int g = blockIdx.y; + unsigned long long gpu = grp_ptr[g]; + int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int ng = *n_groups; + for (; g < ng; g += gridDim.y) { // the group stride, as native_down_multi_kernel + if (g != (int) blockIdx.y) { + __syncthreads(); + gpu = grp_ptr[g]; + e0 = grp_start[g]; + e1 = grp_start[g + 1]; + } + const uint8_t* gp = (const uint8_t*) gpu + L.down_off + (size_t) r0 * DROW; + const float sd = L.tail_off ? ((const float*) (gpu + L.tail_off))[2] : 1.0f; + int dst[NCMAX]; +#pragma unroll + for (int c = 0; c < NCMAX; ++c) dst[c] = ent_dst[min(e0 + c, e1 - 1)]; + const int nbytes = nrow * DROW; + if ((((uintptr_t) gp) & 15) == 0 && (nbytes & 15) == 0) { + const uint4* src = reinterpret_cast(gp); + uint4* dw = reinterpret_cast(s_w); + uint4 v[NV]; +#pragma unroll + for (int k = 0; k < NV; ++k) + if (tid + 256 * k < (nbytes >> 4)) v[k] = __ldg(src + tid + 256 * k); +#pragma unroll + for (int k = 0; k < NV; ++k) + if (tid + 256 * k < (nbytes >> 4)) dw[tid + 256 * k] = v[k]; + } else { + const uint16_t* s2 = reinterpret_cast(gp); + uint16_t* d2 = reinterpret_cast(s_w); + for (int i = tid; i < (nbytes >> 1); i += 256) d2[i] = s2[i]; + } + for (int e = e0; e < e1; e += NCMAX) { + const int n = min(NCMAX, e1 - e); + if (e != e0) { + __syncthreads(); +#pragma unroll + for (int c = 0; c < NCMAX; ++c) dst[c] = ent_dst[min(e + c, e1 - 1)]; + } + const uint32_t* src = reinterpret_cast(hq + (size_t) e * 20); + for (int i = tid; i < n * 180; i += 256) s_hq_buf[i] = src[i]; + __syncthreads(); +#pragma unroll + for (int p = 0; p < P; ++p) { + const int rl = p * RPP + sub; + if (rl >= nrow) continue; + const uint8_t* wr = reinterpret_cast(s_w) + rl * DROW; + const int r = r0 + rl; + if constexpr (NCMAX == 1) { + const int d1[1] = { dst[0] }; + dws_rows(wr, s_hq, t, sd, out, d1, L.n_embd, r); + } else { + static_assert(NCMAX == 4, "NCMAX 1 or 4"); + if (n == 1) { + const int d1[1] = { dst[0] }; + dws_rows(wr, s_hq, t, sd, out, d1, L.n_embd, r); + } else if (n == 2) { + const int d2[2] = { dst[0], dst[1] }; + dws_rows(wr, s_hq, t, sd, out, d2, L.n_embd, r); + } else if (n == 3) { + const int d3[3] = { dst[0], dst[1], dst[2] }; + dws_rows(wr, s_hq, t, sd, out, d3, L.n_embd, r); + } else { + const int d4[4] = { dst[0], dst[1], dst[2], dst[3] }; + dws_rows(wr, s_hq, t, sd, out, d4, L.n_embd, r); + } + } + } + } + } +} +#undef STRATA_DWS_VMAD + +// STRATA_DOWN_WS=1 on a compute capability 6.0 device: the IQ4_NL / Q2_0 down rows at n_ff 640 take +// native_down_ws_kernel (whatever the expert mode: it is bitwise mode 0's, and mode 8's matches mode 0) +bool down_ws_on(const NativeExpertLayout& L) { + static const bool env = env_on("STRATA_DOWN_WS"); + if (!env || g_old_kernels || g_no_sub16_gu || L.n_ff != 640 || (L.d_type != 20 && L.d_type != 42)) return false; + static int per_dev[64]; // 0 unknown, 1 no, 2 yes + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; + if (!per_dev[dev]) { + int major = 0, minor = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + per_dev[dev] = major == 6 && minor == 0 ? 2 : 1; + } + return per_dev[dev] == 2; +} + +void launch_down_ws(const NativeExpertLayout& L, int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, float* out) { + const int rb = L.d_type == 20 ? 32 : 64; + const dim3 grid((unsigned) ((L.n_embd + rb - 1) / rb), (unsigned) gy); + const bool one = cap_groups <= 10; // a T = 1 window: ten groups of one entry + if (L.d_type == 20) { + if (one) native_down_ws_kernel<20, 1><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else native_down_ws_kernel<20, 4><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + } else { + if (one) native_down_ws_kernel<42, 1><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else native_down_ws_kernel<42, 4><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + } +} +#endif // STRATA_DOWN_WS_BUILT + + +// ---------------------------------------------------------------- STRATA_EXPERT_NIBBLE: gate/up on 4-bit slots +// (opt-in, default off; strata/core/expert_nibble.hpp has the slot layout and the item code). A converted layer's +// VRAM slot holds each 32-weight item of a gate/up row as 16 bytes of 4-bit codes (one 16-byte load), its integer +// scale byte and the superblock's fp16 d bit for bit; the kernels below decode an item into the production +// Split::W (or IQ3_S's offset form) with 1-4 instructions per four weights instead of the codebook lookups, then +// run the production integer chain and float tail in the production lane / item / addition order (row_dot_80_sub16: +// k = t, t+32, t+64 into s, t+16, t+48 into s16, __fadd_rn, xor 8, 4, 2, 1), so every gate / up value is bit for bit +// native_gu_multi_kernel's. Two skeletons in the shape of native_gu_multi_kernel (grid (80, gy), 256 +// threads, 16 lanes a row, a group's entries GRP_NC at a time, the group stride): +// S the entries' q8_1 blocks staged in shared memory, each item's code loaded and decoded where it is used, the +// production apply on it (IQ3_S: v = 2u - 15 restored per byte - no sum of x) +// P the lane's five items' codes, scales and d loaded before the staging (in flight during it), the entries' qs +// words staged as 16-byte rows and ds as a float, the production chain written out on the registers (IQ3_S: +// sumi = 2 dot(u, x) - 15 sum(x) with sum(x) from the staged words: the same int32) +// Then the load-time transcoder, the GGUF rebuild (the start-up check and the prompt path's gather) and the slot hash. +// Built only with STRATA_EXPERT_NIBBLE_BUILT (a CUDA build with STRATA_EXPERIMENTAL_SM60); elsewhere a gu_nib layout +// stops in native_expert_grouped, and the switch is refused at start. +#if STRATA_EXPERT_NIBBLE_BUILT +namespace nibk = strata::core::nibble; + +__device__ __forceinline__ uint32_t nib_prmt(uint32_t a, uint32_t b, uint32_t sel) { + uint32_t r; + asm("prmt.b32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(sel)); // the sign-replicate modes too + return r; +} + +// One item's code -> the production W (what Split::load gives for the same GGUF item, byte for byte). +template struct NibLoad; +template<> struct NibLoad<22> { // IQ2_S: the nibble is the PRMT selector into {8,25,43,0} {-8,-25,-43,0} + using W = Split<22>::W; + __device__ static W load(uint4 q, uint32_t sc, __half d) { + constexpr uint32_t T0 = 0x002B1908u, T1 = 0x00D5E7F8u; + W r; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + r.g[2 * m + 0] = (int) nib_prmt(T0, T1, qw[m]); + r.g[2 * m + 1] = (int) nib_prmt(T0, T1, qw[m] >> 16); + } + r.ls0 = sc & 0x0F; + r.ls1 = sc >> 4; + r.dw = __half2float(d); + return r; + } +}; +template<> struct NibLoad<18> { // IQ3_XXS: magnitude PRMT into {4..62}, sign-replicated byte masks, (g ^ m) + (m & 1s) + using W = Split<18>::W; + __device__ static W load(uint4 q, uint32_t sc, __half d) { + constexpr uint32_t T0 = 0x1C140C04u, T1 = 0x3E342C24u; // {4,12,20,28} {36,44,52,62} + W r; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t w = qw[m], ms = w & 0x77777777u, a = w << 4; + const uint32_t m0 = nib_prmt(a, w, 0xD9C8u), m1 = nib_prmt(a, w, 0xFBEAu); + const uint32_t g0 = nib_prmt(T0, T1, ms), g1 = nib_prmt(T0, T1, ms >> 16); + r.g[2 * m + 0] = (int) ((g0 ^ m0) + (m0 & 0x01010101u)); + r.g[2 * m + 1] = (int) ((g1 ^ m1) + (m1 & 0x01010101u)); + } + r.ls = (int) sc; + r.dw = __half2float(d); + return r; + } +}; +template<> struct NibLoad<21> { // IQ3_S: v = 2u - 15 per byte, ((2u | 0x80) - 0x0F) ^ 0x80 (every byte >= 0x80: no borrow) + using W = Split<21>::W; + __device__ static W load(uint4 q, uint32_t sc, __half d) { + W r; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t lo2 = (qw[m] << 1) & 0x1E1E1E1Eu, hi2 = (qw[m] >> 3) & 0x1E1E1E1Eu; // 2u per byte + r.g[2 * m + 0] = (int) (((lo2 | 0x80808080u) - 0x0F0F0F0Fu) ^ 0x80808080u); + r.g[2 * m + 1] = (int) (((hi2 | 0x80808080u) - 0x0F0F0F0Fu) ^ 0x80808080u); + } + r.ls = (int) sc; + r.dw = __half2float(d); + return r; + } +}; + +// S skeleton row dot over one converted row (codes, scales, d of row `row`), x the staged blocks +template +__device__ __forceinline__ void nib_row_dot_s(const uint4* __restrict__ crow, const uint8_t* __restrict__ srow, + const __half* __restrict__ drow, const block_q8_1* x, const int (&off)[NC], + int t, float (&s)[NC]) { + using Q = NibLoad; + const int iqs = 2 * (t & 7), kb = t >> 3; + const block_q8_1* xb[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) { s[c] = 0.0f; xb[c] = x + off[c] + kb * 8; } +#pragma unroll + for (int i = 0; i < 3; ++i) { + const typename Q::W w = Q::load(crow[t + 32 * i], srow[t + 32 * i], drow[kb + 4 * i]); +#pragma unroll + for (int c = 0; c < NC; ++c) s[c] += Split::apply(w, xb[c] + 32 * i, iqs); + } + float s16[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const typename Q::W w = Q::load(crow[t + 16 + 32 * i], srow[t + 16 + 32 * i], drow[kb + 2 + 4 * i]); +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] += Split::apply(w, xb[c] + 16 + 32 * i, iqs); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = __fadd_rn(s[c], s16[c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// One pass of the S skeleton: the n (1..GRP_NC) entries from e staged, then this thread's row against them. +// Block-uniform (e, n): every thread reaches both barriers. +template +__device__ __forceinline__ void nib_pass_s(block_q8_1* s_x, const uint4* crow, const uint8_t* srow, const __half* drow, + const int32_t* __restrict__ ent_tok, const block_q8_1* __restrict__ xq, + int e, int n, int t, float* dst, int r) { + int tok[GRP_NC]; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) tok[c] = ent_tok[e + min(c, n - 1)]; + __syncthreads(); + for (int i = threadIdx.x; i < n * 80 * 9; i += 256) { // 80 blocks x 36 B an entry, as 9 words a block + const int c = i / 720, rem = i % 720; + ((int*) s_x)[c * 720 + rem] = ((const int*) (xq + (size_t) tok[c] * 80))[rem]; + } + __syncthreads(); + if (n == 1) { + const int o[1] = { 0 }; float s[1]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0]; + } else if (n == 2) { + const int o[2] = { 0, 80 }; float s[2]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else if (n == 3) { + const int o[3] = { 0, 80, 160 }; float s[3]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else { + const int o[4] = { 0, 80, 160, 240 }; float s[4]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } +} + +// P skeleton: x as two LDS.128 per item and entry, ds as the float __low2float gives +struct NibXQ { int4 a, b; }; + +template +__device__ __forceinline__ float nib_p_apply(const uint4& q, uint32_t sc, __half dh, const NibXQ& x, float dx, int xsum) { + if constexpr (TG == 22) { // SplitLs2::apply on the registers + const typename NibLoad<22>::W w = NibLoad<22>::load(q, sc, dh); + int sumi0 = 0, sumi1 = 0; + sumi0 = ggml_cuda_dp4a(w.g[0], x.a.x, sumi0); sumi0 = ggml_cuda_dp4a(w.g[1], x.a.y, sumi0); + sumi0 = ggml_cuda_dp4a(w.g[2], x.a.z, sumi0); sumi0 = ggml_cuda_dp4a(w.g[3], x.a.w, sumi0); + sumi1 = ggml_cuda_dp4a(w.g[4], x.b.x, sumi1); sumi1 = ggml_cuda_dp4a(w.g[5], x.b.y, sumi1); + sumi1 = ggml_cuda_dp4a(w.g[6], x.b.z, sumi1); sumi1 = ggml_cuda_dp4a(w.g[7], x.b.w, sumi1); + const int sumi = (sumi0 * w.ls0 + sumi1 * w.ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = w.dw * dx; + return d * sumi; + } else if constexpr (TG == 18) { // Split<18>::apply on the registers + const typename NibLoad<18>::W w = NibLoad<18>::load(q, sc, dh); + int sumi = 0; + sumi = ggml_cuda_dp4a(w.g[0], x.a.x, sumi); sumi = ggml_cuda_dp4a(w.g[1], x.a.y, sumi); + sumi = ggml_cuda_dp4a(w.g[2], x.a.z, sumi); sumi = ggml_cuda_dp4a(w.g[3], x.a.w, sumi); + sumi = ggml_cuda_dp4a(w.g[4], x.b.x, sumi); sumi = ggml_cuda_dp4a(w.g[5], x.b.y, sumi); + sumi = ggml_cuda_dp4a(w.g[6], x.b.z, sumi); sumi = ggml_cuda_dp4a(w.g[7], x.b.w, sumi); + sumi = (w.ls * sumi + sumi / 2) / 2; + const float d = w.dw * dx; + return d * sumi; + } else { // IQ3_S, offset form: dot(v, x) = 2 dot(u, x) - 15 sum(x), exact (|2 dot(u, x)| < 2^17); then Split<21>'s + int u[8]; + const uint32_t qw[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + u[2 * m + 0] = (int) (qw[m] & 0x0F0F0F0Fu); + u[2 * m + 1] = (int) ((qw[m] >> 4) & 0x0F0F0F0Fu); + } + int sumu = 0; + sumu = ggml_cuda_dp4a(u[0], x.a.x, sumu); sumu = ggml_cuda_dp4a(u[1], x.a.y, sumu); + sumu = ggml_cuda_dp4a(u[2], x.a.z, sumu); sumu = ggml_cuda_dp4a(u[3], x.a.w, sumu); + sumu = ggml_cuda_dp4a(u[4], x.b.x, sumu); sumu = ggml_cuda_dp4a(u[5], x.b.y, sumu); + sumu = ggml_cuda_dp4a(u[6], x.b.z, sumu); sumu = ggml_cuda_dp4a(u[7], x.b.w, sumu); + int sumi = 2 * sumu - 15 * xsum; + sumi *= (int) sc; + const float d = __half2float(dh) * dx; + return d * sumi; + } +} + +// the lane's items in the production order: k = t, t+32, t+64 (sum s), then t+16, t+48 (sum s16) +template +__device__ __forceinline__ void nib_row_dot_p(const uint4 (&q)[5], const uint32_t (&sc)[5], const __half (&dh)[5], + const NibXQ* __restrict__ sx, const float* __restrict__ sd, + const int* __restrict__ sxs, int t, float (&s)[NC]) { + constexpr int K[5] = { 0, 32, 64, 16, 48 }; +#pragma unroll + for (int c = 0; c < NC; ++c) s[c] = 0.0f; +#pragma unroll + for (int i = 0; i < 3; ++i) { + const int k = t + K[i]; +#pragma unroll + for (int c = 0; c < NC; ++c) + s[c] += nib_p_apply(q[i], sc[i], dh[i], sx[c * 80 + k], sd[c * 80 + k], TG == 21 ? sxs[c * 80 + k] : 0); + } + float s16[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; +#pragma unroll + for (int i = 3; i < 5; ++i) { + const int k = t + K[i]; +#pragma unroll + for (int c = 0; c < NC; ++c) + s16[c] += nib_p_apply(q[i], sc[i], dh[i], sx[c * 80 + k], sd[c * 80 + k], TG == 21 ? sxs[c * 80 + k] : 0); + } +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[c] = __fadd_rn(s[c], s16[c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o); + } +} + +// The P skeleton's work on one group: this lane's five items into registers, then the passes. Block-uniform. +template +__device__ __forceinline__ void nib_group_p(NibXQ* s_x, float* s_d, int* s_xs, const uint4* crow, const uint8_t* srow, + const __half* drow, const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, int e0, int e1, int t, float* dst, int r) { + const int kb = t >> 3; + uint4 q[5]; uint32_t sc[5]; __half dh[5]; + q[0] = crow[t]; q[1] = crow[t + 32]; q[2] = crow[t + 64]; q[3] = crow[t + 16]; q[4] = crow[t + 48]; + sc[0] = srow[t]; sc[1] = srow[t + 32]; sc[2] = srow[t + 64]; sc[3] = srow[t + 16]; sc[4] = srow[t + 48]; + dh[0] = drow[kb]; dh[1] = drow[kb + 4]; dh[2] = drow[kb + 8]; dh[3] = drow[kb + 2]; dh[4] = drow[kb + 6]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + __syncthreads(); + for (int i = threadIdx.x; i < n * 80; i += 256) { + const int c = i >= 240 ? 3 : i >= 160 ? 2 : i >= 80 ? 1 : 0, kk = i - 80 * c; + const int tok = ent_tok[e + c]; + const int* src = (const int*) (xq + (size_t) tok * 80 + kk); + NibXQ v; + v.a = make_int4(src[1], src[2], src[3], src[4]); + v.b = make_int4(src[5], src[6], src[7], src[8]); + s_x[i] = v; + s_d[i] = __low2float(xq[(size_t) tok * 80 + kk].ds); + if constexpr (TG == 21) { // sum(x): the production dp4a against 0x01010101 over the 8 qs words + int xs = 0; + xs = ggml_cuda_dp4a(v.a.x, 0x01010101, xs); xs = ggml_cuda_dp4a(v.a.y, 0x01010101, xs); + xs = ggml_cuda_dp4a(v.a.z, 0x01010101, xs); xs = ggml_cuda_dp4a(v.a.w, 0x01010101, xs); + xs = ggml_cuda_dp4a(v.b.x, 0x01010101, xs); xs = ggml_cuda_dp4a(v.b.y, 0x01010101, xs); + xs = ggml_cuda_dp4a(v.b.z, 0x01010101, xs); xs = ggml_cuda_dp4a(v.b.w, 0x01010101, xs); + s_xs[i] = xs; + } + } + __syncthreads(); + if (n == 1) { + float s[1]; nib_row_dot_p(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0]; + } else if (n == 2) { + float s[2]; nib_row_dot_p(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else if (n == 3) { + float s[3]; nib_row_dot_p(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } else { + float s[4]; nib_row_dot_p(q, sc, dh, s_x, s_d, s_xs, t, s); + if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t]; + } + } +} + +// SKEL kSkelS or kSkelP for every group. grid (80, gy): 2 x 640 rows = 80 x 16, so every thread has a row and +// reaches every barrier. +constexpr int kNibSWords = GRP_NC * 80 * (int) (sizeof(block_q8_1) / 4); // S: the blocks +constexpr int kNibXqWords = GRP_NC * 80 * (int) (sizeof(NibXQ) / 4); // P: the qs rows, then ds, then sum(x) +template +inline constexpr int kNibSmemWords = SKEL == nibk::kSkelS ? kNibSWords : kNibXqWords + GRP_NC * 80 + (TG == 21 ? GRP_NC * 80 : 0); +template +__global__ void __launch_bounds__(256) nib_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, float* __restrict__ gate, + float* __restrict__ up) { + const int ng = *n_groups; + if (blockIdx.y >= (unsigned) ng) return; + STRATA_SHARED_ALIGN16_U32(s_buf, kNibSmemWords); + const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15; + const int row = blockIdx.x * 16 + subwarp; // 0 .. 2 n_ff + const bool is_up = row >= nibk::kNFf; + const int r = is_up ? row - (int) nibk::kNFf : row; + float* dst = is_up ? up : gate; + for (int g = blockIdx.y; g < ng; g += gridDim.y) { + const uint8_t* slot = (const uint8_t*) grp_ptr[g]; + const uint4* crow = (const uint4*) (slot + nibk::kCodesOff) + (size_t) row * nibk::kItems; + const uint8_t* srow = slot + nibk::kScOff + (size_t) row * nibk::kItems; + const __half* drow = (const __half*) (slot + nibk::kDOff) + (size_t) row * nibk::kSuper; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + if constexpr (SKEL == nibk::kSkelP) { + nib_group_p((NibXQ*) s_buf, (float*) (s_buf + kNibXqWords), (int*) (s_buf + kNibXqWords + GRP_NC * 80), + crow, srow, drow, ent_tok, xq, e0, e1, t, dst, r); + } else { + for (int e = e0; e < e1; e += GRP_NC) + nib_pass_s((block_q8_1*) s_buf, crow, srow, drow, ent_tok, xq, e, min(GRP_NC, e1 - e), t, dst, r); + } + } +} + +#include "nib_gu_proto.cuh" // STRATA_NIB_GU_PROTO: the staged-once 4-bit gate/up kernel (id 31) + +int g_nib_variant = -1; // native_expert_nib_set_variant (the bench / parity); -1 = expert_nibble.hpp's gu_skeleton + +// STRATA_NIB_GU_PROTO: unset / 0 = off (the S / P skeleton per format); 1 (or 31) = gu-proto 31 (the activations staged +// once per two row blocks with 16-byte loads, the production row dot). Read once. +int nib_gu_proto_env() { + static const int v = [] { + const char* e = std::getenv("STRATA_NIB_GU_PROTO"); + int id = e != nullptr ? std::atoi(e) : 0; + if (id == 1) id = 31; + if (id != 31) id = 0; + if (id != 0) std::fprintf(stderr, "native_expert_grouped: STRATA_NIB_GU_PROTO: 4-bit gate/up kernel gu-proto %d\n", id); + return id; + }(); + return v; +} + +// The gate/up of a converted layer's VRAM groups: native_gu_multi_kernel's grid and outputs. +void launch_gu_nib(const NativeExpertLayout& L, dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, + float* gate, float* up) { + if (g_nib_variant >= 10) { // gu-proto (nib_gu_proto.cuh), forced by the bench / parity + if (((uintptr_t) X & 15) != 0 || + !nibx_launch(L.gu_type, g_nib_variant, grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) { + std::fprintf(stderr, "native_expert_grouped: gu-proto variant %d for type %d is not built (or x is not 16-aligned)\n", + g_nib_variant, L.gu_type); + std::exit(1); + } + return; + } + // STRATA_NIB_GU_PROTO (opt-in, default off): the gu-proto kernel in place of the S / P skeleton - bitwise the + // same gate / up (iq_nibble_parity (7), native_expert_bench --nibble --vs). The 16-byte staging needs x 16-aligned + // (verify's nat_xq_ rows are: a 256-aligned buffer, 2,880 B a token); otherwise the production kernel runs. + if (g_nib_variant < 0) { + const int pv = nib_gu_proto_env(); + if (pv != 0 && ((uintptr_t) X & 15) == 0 && + nibx_launch(L.gu_type, pv, grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) + return; + } + const int skel = g_nib_variant >= 0 ? (g_nib_variant == 1 ? nibk::kSkelP : nibk::kSkelS) : nibk::gu_skeleton(L.gu_type); +#define STRATA_NIB_GU(TG, S) \ + case TG * 2 + S: nib_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, gate, up); break; + switch (L.gu_type * 2 + skel) { + STRATA_NIB_GU(22, 0) STRATA_NIB_GU(22, 1) + STRATA_NIB_GU(18, 0) STRATA_NIB_GU(18, 1) + STRATA_NIB_GU(21, 0) STRATA_NIB_GU(21, 1) + default: + std::fprintf(stderr, "native_expert_grouped: 4-bit gate/up type %d at %lld x %lld is not built\n", L.gu_type, + (long long) L.n_embd, (long long) L.n_ff); + std::exit(1); + } +#undef STRATA_NIB_GU +} + +// ---- the load-time transcoder (expert_nibble.hpp's transcode) +template +__device__ __forceinline__ uint32_t nib_code(int v, bool& ok) { + if constexpr (TG == 21) { // v odd in -15..15 -> u = (v + 15) / 2 + if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; } + return (uint32_t) ((v + 15) >> 1); + } else if constexpr (TG == 18) { // index of {4, 12, ..., 52, 62} | sign << 3 + const int a = v < 0 ? -v : v; + const int i = a == 62 ? 7 : ((a & 7) == 4 && a <= 52) ? (a - 4) >> 3 : -1; + if (i < 0) { ok = false; return 0; } + return (uint32_t) i | (v < 0 ? 8u : 0u); + } else { // IQ2_S: index of {8, 25, 43} | sign << 2 + const int a = v < 0 ? -v : v; + const int i = a == 8 ? 0 : a == 25 ? 1 : a == 43 ? 2 : -1; + if (i < 0) { ok = false; return 0; } + return (uint32_t) i | (v < 0 ? 4u : 0u); + } +} + +// The GGUF blocks (ggml-common.h): their size and the fp16 d at their start +template struct NibBlk; +template<> struct NibBlk<22> { using B = block_iq2_s; }; +template<> struct NibBlk<18> { using B = block_iq3_xxs; }; +template<> struct NibBlk<21> { using B = block_iq3_s; }; + +// One thread per (expert, row, item): the production load, the code, scale and d written, read back from memory and +// decoded with the kernels' own decoders, compared with the load's W (and, for IQ3_S, the P skeleton's u against v); +// `bad` counts the items that differ or hold a weight outside the code set. +template +__global__ void __launch_bounds__(256) nib_transcode_kernel(const uint8_t* __restrict__ src, uint64_t raw_bytes, + uint64_t gu_row, uint64_t up_off, + const unsigned long long* __restrict__ slots, long long n, + unsigned long long* __restrict__ bad) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * nibk::kRows * nibk::kItems) return; + const int k = (int) (i % nibk::kItems); + const int row = (int) ((i / nibk::kItems) % nibk::kRows); + const long long ex = i / (nibk::kItems * nibk::kRows); + const bool is_up = row >= nibk::kNFf; + const int r = is_up ? row - (int) nibk::kNFf : row; + const uint8_t* wr = src + (size_t) ex * raw_bytes + (is_up ? up_off : 0) + (size_t) r * gu_row; + const int kbx = k / Fmt::ipb, iqs = Fmt::step * (k % Fmt::ipb); + using S = Split; + const typename S::W w = S::template load(wr, kbx, iqs, nullptr); + bool ok = true; + uint32_t words[4]; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t g0 = (uint32_t) w.g[2 * m], g1 = (uint32_t) w.g[2 * m + 1]; + uint32_t word = 0; +#pragma unroll + for (int b = 0; b < 4; ++b) { + const uint32_t c0 = nib_code((int) (int8_t) (g0 >> (8 * b)), ok); + const uint32_t c1 = nib_code((int) (int8_t) (g1 >> (8 * b)), ok); + if constexpr (TG == 21) word |= (c0 | c1 << 4) << (8 * b); + else word |= c0 << (4 * b) | c1 << (16 + 4 * b); + } + words[m] = word; + } + uint32_t sc; + if constexpr (TG == 22) sc = (uint32_t) (w.ls0 | w.ls1 << 4); + else sc = (uint32_t) w.ls; + ok = ok && sc < 256u; + uint8_t* slot = (uint8_t*) slots[ex]; + uint4* cp = (uint4*) (slot + nibk::code_off(row, k)); + uint8_t* sp = slot + nibk::scale_off(row, k); + *cp = make_uint4(words[0], words[1], words[2], words[3]); + *sp = (uint8_t) sc; + const __half dsrc = ((const typename NibBlk::B*) wr + kbx)->d; // the block's d, bit for bit + __half dread = dsrc; + if (k % Fmt::ipb == 0) { // the superblock's first item writes its d + __half* dp = (__half*) (slot + nibk::d_off(row, kbx)); + *dp = dsrc; + dread = __ushort_as_half(*(volatile const unsigned short*) dp); + ok = ok && __half_as_ushort(dread) == __half_as_ushort(dsrc); + } + // the code and the scale read back from memory and decoded as the kernels do + const uint4 qb = __ldcv(cp); + const uint32_t sb = *(volatile const uint8_t*) sp; + const typename NibLoad::W v = NibLoad::load(qb, sb, dread); +#pragma unroll + for (int j = 0; j < 8; ++j) ok = ok && v.g[j] == w.g[j]; + if constexpr (TG == 22) ok = ok && v.ls0 == w.ls0 && v.ls1 == w.ls1; + else ok = ok && v.ls == w.ls; + ok = ok && __float_as_uint(v.dw) == __float_as_uint(w.dw); + if constexpr (TG == 21) { // the P skeleton's u: 2u - 15 per byte is v + const uint32_t qw[4] = { qb.x, qb.y, qb.z, qb.w }; +#pragma unroll + for (int m = 0; m < 4; ++m) { + const uint32_t u0 = qw[m] & 0x0F0F0F0Fu, u1 = (qw[m] >> 4) & 0x0F0F0F0Fu; + ok = ok && __vsub4(__vadd4(u0, u0), 0x0F0F0F0Fu) == (uint32_t) w.g[2 * m] && + __vsub4(__vadd4(u1, u1), 0x0F0F0F0Fu) == (uint32_t) w.g[2 * m + 1]; + } + } + if (!ok) atomicAdd(bad, 1ull); +} + +// ---- the GGUF rebuild (expert_nibble.hpp's check_gguf and gather_gguf) +// The reverse codebooks: a group's magnitude pattern -> its grid index (0xFFFFFFFF: not in the grid). 32-bit +// entries for atomicCAS, which also counts a pattern two grid entries share (none in ggml's grids; then refused). +constexpr int kNibRev22 = 6561, kNibRev18 = 4096, kNibRev21 = 4096; // 3^8 (IQ2_S: 8 weights), 8^4, 8^4 (4 weights) +__device__ uint32_t g_nib_rev22[kNibRev22]; +__device__ uint32_t g_nib_rev18[kNibRev18]; +__device__ uint32_t g_nib_rev21[kNibRev21]; +__device__ unsigned long long g_nib_rev_bad; + +__device__ __forceinline__ int nib_mag22(uint32_t b) { return b == 8 ? 0 : b == 25 ? 1 : b == 43 ? 2 : -1; } +__device__ __forceinline__ int nib_mag18(uint32_t b) { return b == 62 ? 7 : ((b & 7) == 4 && b <= 52) ? (int) (b - 4) >> 3 : -1; } +__device__ __forceinline__ int nib_mag21(uint32_t b) { return (b & 1) && b <= 15 ? (int) (b - 1) >> 1 : -1; } + +__global__ void nib_rev_clear_kernel() { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < kNibRev22) g_nib_rev22[i] = 0xFFFFFFFFu; + if (i < kNibRev18) g_nib_rev18[i] = 0xFFFFFFFFu; + if (i < kNibRev21) g_nib_rev21[i] = 0xFFFFFFFFu; + if (i == 0) g_nib_rev_bad = 0; +} +__global__ void nib_rev_fill_kernel() { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + uint32_t* tab = nullptr; + int key = 0; + bool ok = true; + uint32_t idx = 0; + if (i < 1024) { // iq2s_grid: 8 bytes of {8, 25, 43} + const uint64_t g = iq2s_grid[i]; + for (int j = 7; j >= 0; --j) { const int m = nib_mag22((uint32_t) (g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 3 + (m < 0 ? 0 : m); } + tab = g_nib_rev22; idx = (uint32_t) i; + } else if (i < 1024 + 256) { // iq3xxs_grid: 4 bytes of {4, ..., 62} + const uint32_t g = iq3xxs_grid[i - 1024]; + for (int j = 3; j >= 0; --j) { const int m = nib_mag18((g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 8 + (m < 0 ? 0 : m); } + tab = g_nib_rev18; idx = (uint32_t) (i - 1024); + } else if (i < 1024 + 256 + 512) { // iq3s_grid: 4 bytes of {1, 3, ..., 15} + const uint32_t g = iq3s_grid[i - 1280]; + for (int j = 3; j >= 0; --j) { const int m = nib_mag21((g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 8 + (m < 0 ? 0 : m); } + tab = g_nib_rev21; idx = (uint32_t) (i - 1280); + } else { + return; + } + if (!ok || atomicCAS(tab + key, 0xFFFFFFFFu, idx) != 0xFFFFFFFFu) atomicAdd(&g_nib_rev_bad, 1ull); +} + +// The bytes of GGUF block `s` of row `row`'s item `ib` (0..7) rebuilt from the slot into `blk` (shared memory, the +// block's first byte): the codes give each weight's magnitude index and sign, the reverse codebook the grid index, +// the scale byte and d are the block's own. Disjoint bytes per item (IQ3_S: the even item writes the shared scale +// byte); item 0 writes d. +template +__device__ __forceinline__ void nib_gguf_item(uint8_t* blk, int ib, const uint8_t* __restrict__ slot, int row, int k) { + const uint4 q4 = *(const uint4*) (slot + nibk::code_off(row, k)); + const uint32_t w[4] = { q4.x, q4.y, q4.z, q4.w }; + const uint32_t sc = slot[nibk::scale_off(row, k)]; + if (ib == 0) { + const uint8_t* dp = slot + nibk::d_off(row, k / 8); + blk[0] = dp[0]; + blk[1] = dp[1]; + } + if constexpr (TG == 22) { // block_iq2_s: d, qs[32] grid low bits, qs[32] signs, qh[8], scales[8] + uint32_t qh = 0; +#pragma unroll + for (int l = 0; l < 4; ++l) { + int key = 0; + uint32_t sg = 0; +#pragma unroll + for (int j = 7; j >= 0; --j) { + const uint32_t c = j < 4 ? (w[l] >> (4 * j)) & 15u : (w[l] >> (16 + 4 * (j - 4))) & 15u; + key = key * 3 + (int) (c & 3u); + sg |= ((c >> 2) & 1u) << j; + } + const uint32_t idx = key < kNibRev22 ? g_nib_rev22[key] : 0xFFFFFFFFu; + blk[2 + 4 * ib + l] = (uint8_t) idx; + blk[2 + 32 + 4 * ib + l] = (uint8_t) sg; + qh |= ((idx >> 8) & 3u) << (2 * l); + } + blk[66 + ib] = (uint8_t) qh; + blk[74 + ib] = (uint8_t) sc; + } else if constexpr (TG == 18) { // block_iq3_xxs: d, qs[64] grid indices, 8 x aux32 (4 x 7 sign bits | scale << 28) + uint32_t aux = sc << 28; +#pragma unroll + for (int l = 0; l < 4; ++l) { + uint32_t sg = 0; +#pragma unroll + for (int h = 0; h < 2; ++h) { + int key = 0; +#pragma unroll + for (int j = 3; j >= 0; --j) { + const uint32_t c = (w[l] >> (16 * h + 4 * j)) & 15u; + key = key * 8 + (int) (c & 7u); + sg |= ((c >> 3) & 1u) << (4 * h + j); + } + blk[2 + 8 * ib + 2 * l + h] = (uint8_t) g_nib_rev18[key]; + } + aux |= (sg & 0x7Fu) << (7 * l); // the 8th sign is the parity of the other 7 (ksigns_iq2xs) + } + blk[2 + 64 + 4 * ib + 0] = (uint8_t) aux; + blk[2 + 64 + 4 * ib + 1] = (uint8_t) (aux >> 8); + blk[2 + 64 + 4 * ib + 2] = (uint8_t) (aux >> 16); + blk[2 + 64 + 4 * ib + 3] = (uint8_t) (aux >> 24); + } else { // block_iq3_s: d, qs[64] grid low bits, qh[8], signs[32], scales[4] (two items' nibbles each) + uint32_t qh = 0; +#pragma unroll + for (int l = 0; l < 4; ++l) { + uint32_t sg = 0; +#pragma unroll + for (int h = 0; h < 2; ++h) { + int key = 0; +#pragma unroll + for (int j = 3; j >= 0; --j) { + const uint32_t u = (w[l] >> (8 * j + 4 * h)) & 15u; // v = 2u - 15: negative for u <= 7 + key = key * 8 + (int) (u <= 7u ? 7u - u : u - 8u); + sg |= (u <= 7u ? 1u : 0u) << (4 * h + j); + } + const uint32_t idx = g_nib_rev21[key]; + blk[2 + 8 * ib + 2 * l + h] = (uint8_t) idx; + qh |= ((idx >> 8) & 1u) << (2 * l + h); + } + blk[74 + 4 * ib + l] = (uint8_t) sg; + } + blk[66 + ib] = (uint8_t) qh; + if ((ib & 1) == 0) { + const uint32_t sc1 = slot[nibk::scale_off(row, k + 1)]; + blk[106 + ib / 2] = (uint8_t) (((sc - 1u) >> 1) | (((sc1 - 1u) >> 1) << 4)); + } + } +} + +constexpr int kNibGgufRows = 8; // gate/up rows a block rebuilds (in shared memory, then one coalesced pass) +constexpr int kNibGgufThreads = 128; +constexpr int kNibGgufWords = 8; // uint4 per thread in the down / tail part +struct NibGgufArgs { + const unsigned long long* dev; // the slots' device addresses (check), or nullptr: `p` + const uint8_t* p[16]; // the slots (gather: an MMQ group, at most mmq::kGatherGroupMax) + int first, n; + uint8_t* gu; // gather: the rebuilt [gate | up]; check: the raw blobs' first byte + uint64_t gu_stride; + uint8_t* d; // gather: the down rows; check: the raw blobs' down rows + uint64_t d_stride; + uint64_t gu_row, down16, zero16; // GGUF row bytes; down rows and MMQ tail in uint4 + unsigned long long* bad; // check: 32-bit words / uint4 that differ +}; +// blockIdx.y: expert first + y. blockIdx.x < kRows / kNibGgufRows: rows [8x, 8x + 8) rebuilt into shared memory, +// then written (gather) or compared (check) as 32-bit words; the rest: the down rows as uint4, and (gather, the last +// expert) the zeroed tails after gate/up and down. +template +__global__ void __launch_bounds__(kNibGgufThreads) nib_gguf_kernel(NibGgufArgs a) { + constexpr int BB = (int) sizeof(typename NibBlk::B); + __shared__ uint32_t s_rows[kNibGgufRows * 1100 / 4]; + const int q = a.first + (int) blockIdx.y; + const uint8_t* slot = a.dev != nullptr ? (const uint8_t*) a.dev[q] : a.p[q]; + constexpr int kRowBlocks = (int) (nibk::kRows / kNibGgufRows); + unsigned long long nbad = 0; + if ((int) blockIdx.x < kRowBlocks) { + const int r0 = (int) blockIdx.x * kNibGgufRows; + uint8_t* sb = (uint8_t*) s_rows; + for (int u = threadIdx.x; u < kNibGgufRows * (int) nibk::kItems; u += kNibGgufThreads) { + const int rr = u / (int) nibk::kItems, k = u % (int) nibk::kItems; + nib_gguf_item(sb + (size_t) rr * a.gu_row + (size_t) (k >> 3) * BB, k & 7, slot, r0 + rr, k); + } + __syncthreads(); + const int nw = (int) (kNibGgufRows * a.gu_row / 4); + uint32_t* dst = (uint32_t*) (a.gu + (size_t) q * a.gu_stride + (size_t) r0 * a.gu_row); + for (int i = threadIdx.x; i < nw; i += kNibGgufThreads) { + if constexpr (CHECK) nbad += dst[i] != s_rows[i]; + else dst[i] = s_rows[i]; + } + } else { + const uint4* src = (const uint4*) (slot + nibk::kDownOff); + uint4* dd = (uint4*) (a.d + (size_t) q * a.d_stride); + const int64_t base = ((int64_t) blockIdx.x - kRowBlocks) * (kNibGgufThreads * kNibGgufWords); +#pragma unroll + for (int w = 0; w < kNibGgufWords; ++w) { + const int64_t i = base + (int64_t) w * kNibGgufThreads + threadIdx.x; + if (i < (int64_t) a.down16) { + if constexpr (CHECK) { + const uint4 x = src[i], y = dd[i]; + nbad += x.x != y.x || x.y != y.y || x.z != y.z || x.w != y.w; + } else { + dd[i] = src[i]; + } + } else if (!CHECK && q == a.n - 1 && i < (int64_t) (a.down16 + 2 * a.zero16)) { + const int64_t z = i - (int64_t) a.down16; + if (z < (int64_t) a.zero16) ((uint4*) (a.gu + (size_t) a.n * a.gu_stride))[z] = make_uint4(0, 0, 0, 0); + else ((uint4*) (a.d + (size_t) a.n * a.d_stride))[z - (int64_t) a.zero16] = make_uint4(0, 0, 0, 0); + } + } + } + if constexpr (CHECK) { + if (nbad) atomicAdd(a.bad, nbad); + } +} + +// sum_i (w_i ^ i) * kHashMul mod 2^64 over the first `bytes` bytes of each slot (little-endian words, the last one +// zero-extended): expert_nibble.hpp's hash_host. A sum, so the blocks' order of adding does not change it. +__global__ void __launch_bounds__(256) nib_hash_kernel(const unsigned long long* __restrict__ slots, uint64_t bytes, + unsigned long long* __restrict__ out) { + const uint8_t* p = (const uint8_t*) slots[blockIdx.y]; + const uint64_t n16 = bytes / 16, nw = (bytes + 3) / 4; + uint64_t h = 0; + for (uint64_t q = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; q < n16; q += (uint64_t) gridDim.x * blockDim.x) { + const uint4 v = ((const uint4*) p)[q]; + const uint32_t i = (uint32_t) (4 * q); + h += (uint64_t) (v.x ^ i) * nibk::kHashMul + (uint64_t) (v.y ^ (i + 1)) * nibk::kHashMul + + (uint64_t) (v.z ^ (i + 2)) * nibk::kHashMul + (uint64_t) (v.w ^ (i + 3)) * nibk::kHashMul; + } + if (blockIdx.x == 0) + for (uint64_t i = 4 * n16 + threadIdx.x; i < nw; i += blockDim.x) { + uint32_t w = 0; + for (uint64_t b = 4 * i; b < 4 * i + 4 && b < bytes; ++b) w |= (uint32_t) p[b] << (8 * (b - 4 * i)); + h += (uint64_t) (w ^ (uint32_t) i) * nibk::kHashMul; + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) h += __shfl_xor_sync(0xffffffffu, h, o); + __shared__ uint64_t s_h[8]; + if ((threadIdx.x & 31) == 0) s_h[threadIdx.x >> 5] = h; + __syncthreads(); + if (threadIdx.x == 0) { + uint64_t t = 0; + for (int w = 0; w < (int) (blockDim.x >> 5); ++w) t += s_h[w]; + atomicAdd(out + blockIdx.y, (unsigned long long) t); + } +} +#endif // STRATA_EXPERT_NIBBLE_BUILT + +// STRATA_EXPERT_NIBBLE: whether a layout's gate/up is a converted slot's 4-bit codes (constant false in a build +// without the kernels, so its dispatch below is today's code) +constexpr bool nib_layout(const NativeExpertLayout& L) { +#if STRATA_EXPERT_NIBBLE_BUILT + return L.gu_nib; +#else + static_cast(L); + return false; +#endif +} } // namespace @@ -4352,6 +5359,50 @@ NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, return L; } +NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) { + namespace nb = strata::core::nibble; + NativeExpertLayout L = native_expert_layout(gu_type, d_type, n_embd, n_ff); + L.gu_nib = true; + L.gu_row = (size_t) (nb::kItems * nb::kItemBytes); // a row's codes (the scales and d follow all the codes) + L.up_off = nb::kUpCodesOff; + L.down_off = nb::kDownOff; + L.bytes = nb::slot_bytes_for((uint64_t) n_embd * L.d_row); + return L; +} + +bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { +#if STRATA_EXPERT_NIBBLE_BUILT + namespace nb = strata::core::nibble; + return nb::fmt_built(gu_type) && n_embd == nb::kNEmbd && n_ff == nb::kNFf && d_type != 40 && + native_expert_supported(gu_type, d_type, n_embd, n_ff); +#else + (void) gu_type; (void) d_type; (void) n_embd; (void) n_ff; + return false; +#endif +} + +void native_expert_nib_set_variant(int v) { +#if STRATA_EXPERT_NIBBLE_BUILT + g_nib_variant = v; +#else + (void) v; +#endif +} + +bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm) { +#if STRATA_EXPERT_NIBBLE_BUILT + cudaFuncAttributes a{}; + if (!nibx_launch(gu_type, v, dim3(80, 1), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &a)) return false; + *regs = a.numRegs; + *local_bytes = (int) a.localSizeBytes; + *blocks_per_sm = g_nibx_occ; + return true; +#else + (void) v; (void) gu_type; (void) regs; (void) local_bytes; (void) blocks_per_sm; + return false; +#endif +} + size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float); return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255); @@ -5007,7 +6058,7 @@ int exp_mode() { #endif } #endif -int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only +int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only, 3 gate/up only #if STRATA_EXP_LAYOUTS && !defined(__HIPCC__) // The down projection's mode on Turing's default: mode 4 is slower than the CUDA layout once groups have 3+ entries // (12 x 3: 36.5 -> 40.8 us, 16 x 4: 56.9 -> 68.9) - windows of 4+ tokens (cap_groups > 30) keep mode 0 there. @@ -5081,8 +6132,16 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long float* h = (float*) ((uint8_t*) scratch + 2 * fa); block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa); const auto* X = (const block_q8_1*) x_q8_1; +#if !STRATA_EXPERT_NIBBLE_BUILT + if (L.gu_nib) { // STRATA_EXPERT_NIBBLE's slots: the switch is refused at start in a build without the kernels + std::fprintf(stderr, "native_expert_grouped: 4-bit gate/up slots are not built into this engine\n"); + std::exit(1); + } +#endif + // STRATA_EXPERT_NIBBLE (nib_layout): only the gate/up step below takes another kernel (launch_gu_nib, in place of + // launch_gu); SwiGLU, the q8_1 quantization and the down rows (GGUF, at L.down_off) are the layout's own static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }(); - if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel + if (v2 && !nib_layout(L) && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values) static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); // (+ down rows' items spread evenly over the lanes, one load group: bitwise, harness 1.09-1.12x vs 1.03-1.06x; @@ -5152,7 +6211,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #endif #endif #if STRATA_EXP_LAYOUTS - const bool fused_gu = em0 == 8 && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && + const bool fused_gu = !nib_layout(L) && em0 == 8 && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && L.n_ff % 32 == 0; if (fused_gu && g_exp_phase != 2) { const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups); @@ -5174,7 +6233,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long #else const bool gs_layout = true; #endif - if (gs_layout && g_exp_phase == 0 && !v1 && gu_swiglu_on() && !(expdec_mode() && !g_old_kernels && expdec_gu_ok(L))) { + if (gs_layout && !nib_layout(L) && g_exp_phase == 0 && !v1 && gu_swiglu_on() && !(expdec_mode() && !g_old_kernels && expdec_gu_ok(L))) { switch (L.gu_type) { #define STRATA_GS(T) case T: gs_done = launch_gu_swiglu(L, gy, s, grp_ptr, grp_start, n_groups, ent_tok, X, hq); break; STRATA_GU_FMTS(STRATA_GS) @@ -5189,7 +6248,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long if (g_exp_phase != 2 && !gs_done) { #endif #if STRATA_EXP_LAYOUTS - const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); + const bool lds_gu = !nib_layout(L) && (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); if (lds_gu) { const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); @@ -5210,13 +6269,19 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42; - if ((em == 1 || em == 2 || em == 4) && amd_gu) { + if ((em == 1 || em == 2 || em == 4) && amd_gu && !nib_layout(L)) { switch (L.gu_type) { STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23) STRATA_GU_AMD(29) STRATA_GU_AMD(42) } } else #undef STRATA_GU_AMD +#endif +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_layout(L)) // STRATA_EXPERT_NIBBLE: a converted layer's VRAM slots, native_gu_multi_kernel's grid and bits + launch_gu_nib(L, dim3((unsigned) (strata::core::nibble::kRows / 16), (unsigned) gy), s, grp_ptr, grp_start, + n_groups, ent_tok, X, gate, up); + else #endif if (!expdec_gu(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) // STRATA_EXPDEC=1 switch (L.gu_type) { @@ -5229,6 +6294,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } #endif check("native_expert_grouped/gu"); + if (g_exp_phase == 3) return; // the bench: gate/up only const long long nh = (long long) cap_entries * L.n_ff; #if defined(STRATA_HIP_GFX906) // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass @@ -5255,6 +6321,13 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 || L.d_type == 40 || tq_sub8 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8; const int tq_ch = tq_sub8 ? tq_row_chunks() : 1; // the staged trellis down kernel takes this many 32-row chunks a block const dim3 gd((unsigned) (((L.n_embd + d_rows - 1) / d_rows + tq_ch - 1) / tq_ch), (unsigned) gy); +#if STRATA_DOWN_WS_BUILT + if (down_ws_on(L)) { // STRATA_DOWN_WS=1 (cc 6.0): the staged down rows, bitwise native_down_multi_kernel's + launch_down_ws(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, out); + check("native_expert_grouped/down ws"); + return; + } +#endif #if STRATA_EXP_LAYOUTS const int em0d = sm75_down_em(em0, cap_groups); int dev_d = 0; @@ -5296,6 +6369,164 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } // namespace strata::kernels +// ---------------------------------------------------------------- STRATA_EXPERT_NIBBLE: expert_nibble.hpp's functions +namespace strata::core::nibble { + +#if STRATA_EXPERT_NIBBLE_BUILT +namespace { +int g_rev_ready[64]; // per device: 0 not built, 1 built, 2 a grid entry not unique (refused) + +bool rev_ready() { + int dev = 0; + return cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < 64 && g_rev_ready[dev] == 1; +} +} // namespace +#endif + +int prepare(void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return (int) cudaErrorInvalidDevice; + if (g_rev_ready[dev] == 1) return 0; + if (g_rev_ready[dev] == 2) return (int) cudaErrorInvalidValue; + cudaStream_t s = (cudaStream_t) stream; + strata::kernels::nib_rev_clear_kernel<<<(strata::kernels::kNibRev22 + 255) / 256, 256, 0, s>>>(); + strata::kernels::nib_rev_fill_kernel<<<(1024 + 256 + 512 + 255) / 256, 256, 0, s>>>(); + cudaError_t e = cudaGetLastError(); + unsigned long long bad = 0; + if (e == cudaSuccess) e = cudaStreamSynchronize(s); + if (e == cudaSuccess) e = cudaMemcpyFromSymbol(&bad, strata::kernels::g_nib_rev_bad, sizeof bad); + if (e != cudaSuccess) return (int) e; + g_rev_ready[dev] = bad == 0 ? 1 : 2; + return bad == 0 ? 0 : (int) cudaErrorInvalidValue; +#else + (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (n <= 0) return 0; + if (!L.on || !fmt_built(L.gu_type) || L.raw_gu_row != raw_gu_row(L.gu_type) || + L.raw_up_off != (uint64_t) kNFf * L.raw_gu_row || L.raw_bytes < 2 * L.raw_up_off) + return (int) cudaErrorInvalidValue; + const long long nthr = (long long) n * kRows * kItems; + const dim3 grid((unsigned) ((nthr + 255) / 256)); + cudaStream_t s = (cudaStream_t) stream; + const uint8_t* src = (const uint8_t*) staging; +#define STRATA_NIB_TC(TG) \ + strata::kernels::nib_transcode_kernel<<>>(src, L.raw_bytes, L.raw_gu_row, L.raw_up_off, slot_ptrs, n, bad) + switch (L.gu_type) { + case kIQ2_S: STRATA_NIB_TC(22); break; + case kIQ3_XXS: STRATA_NIB_TC(18); break; + case kIQ3_S: STRATA_NIB_TC(21); break; + default: return (int) cudaErrorInvalidValue; + } +#undef STRATA_NIB_TC + return (int) cudaGetLastError(); +#else + (void) L; (void) staging; (void) n; (void) slot_ptrs; (void) bad; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +#if STRATA_EXPERT_NIBBLE_BUILT +namespace { +int launch_gguf(const LayerVram& L, strata::kernels::NibGgufArgs& a, bool check, cudaStream_t s) { + namespace K = strata::kernels; + if (!L.on || !fmt_built(L.gu_type) || L.raw_gu_row != raw_gu_row(L.gu_type) || L.down_bytes % 16 != 0 || + L.raw_up_off != (uint64_t) kNFf * L.raw_gu_row || L.raw_down_off != 2 * L.raw_up_off) + return (int) cudaErrorInvalidValue; + if (!rev_ready()) return (int) cudaErrorNotReady; // prepare() was not run on this device + a.gu_row = L.raw_gu_row; + a.down16 = L.down_bytes / 16; + const int64_t tail = (int64_t) (a.down16 + 2 * a.zero16); + const int64_t per = (int64_t) K::kNibGgufThreads * K::kNibGgufWords; + const dim3 grid((unsigned) (kRows / K::kNibGgufRows + (tail + per - 1) / per), (unsigned) (a.n - a.first)); +#define STRATA_NIB_GG(TG) \ + (check ? K::nib_gguf_kernel<<>>(a) \ + : K::nib_gguf_kernel<<>>(a)) + switch (L.gu_type) { + case kIQ2_S: STRATA_NIB_GG(22); break; + case kIQ3_XXS: STRATA_NIB_GG(18); break; + case kIQ3_S: STRATA_NIB_GG(21); break; + default: return (int) cudaErrorInvalidValue; + } +#undef STRATA_NIB_GG + return (int) cudaGetLastError(); +} +} // namespace +#endif + +int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (n <= 0) return 0; + if (n > 65535) return (int) cudaErrorInvalidValue; + strata::kernels::NibGgufArgs a{}; + a.dev = slot_ptrs; + a.first = 0; + a.n = (int) n; + a.gu = (uint8_t*) staging; + a.gu_stride = L.raw_bytes; + a.d = (uint8_t*) staging + L.raw_down_off; + a.d_stride = L.raw_bytes; + a.zero16 = 0; + a.bad = bad; + if (((uintptr_t) staging | L.raw_bytes) % 16 != 0) return (int) cudaErrorInvalidValue; + return launch_gguf(L, a, true, (cudaStream_t) stream); +#else + (void) L; (void) staging; (void) n; (void) slot_ptrs; (void) bad; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride, + void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (first < 0 || n <= first || n > 16) return (int) cudaErrorInvalidValue; + uintptr_t al = (uintptr_t) gu_dst | (uintptr_t) d_dst | gu_stride | d_stride | zero_bytes; + for (int q = first; q < n; ++q) al |= (uintptr_t) slots[q]; + if (al % 16 != 0 || gu_stride < (uint64_t) kRows * L.raw_gu_row || d_stride < L.down_bytes) return (int) cudaErrorInvalidValue; + strata::kernels::NibGgufArgs a{}; + a.dev = nullptr; + for (int q = first; q < n; ++q) a.p[q] = slots[q]; + a.first = first; + a.n = n; + a.gu = (uint8_t*) gu_dst; + a.gu_stride = gu_stride; + a.d = (uint8_t*) d_dst; + a.d_stride = d_stride; + a.zero16 = zero_bytes / 16; + a.bad = nullptr; + return launch_gguf(L, a, false, (cudaStream_t) stream); +#else + (void) L; (void) slots; (void) first; (void) n; (void) gu_dst; (void) gu_stride; (void) d_dst; (void) d_stride; + (void) zero_bytes; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out, void* stream) { +#if STRATA_EXPERT_NIBBLE_BUILT + if (n <= 0) return 0; + if (L.hashed == 0) return (int) cudaErrorInvalidValue; + cudaStream_t s = (cudaStream_t) stream; + const cudaError_t e = cudaMemsetAsync(out, 0, (size_t) n * sizeof(unsigned long long), s); + if (e != cudaSuccess) return (int) e; + // ~2.7 MB a slot: 32 blocks of 256 threads each, ~21 16-byte loads a thread + strata::kernels::nib_hash_kernel<<>>(slot_ptrs, L.hashed, out); + return (int) cudaGetLastError(); +#else + (void) L; (void) slot_ptrs; (void) n; (void) out; (void) stream; + return 1; // cudaErrorInvalidValue: not in this build +#endif +} + +} // namespace strata::core::nibble + // ---- Volta prompt experts (STRATA_PF_WMMA): a group's experts as one launch of FP16 tensor-core tiles, the weights // dequantized into shared memory by dq_dispatch (the FP16 path's own formulas), the activations FP16, FP32 sums. // Replaces MMQ's dp4a products on sm_70, and the FP16 path's dequantize-to-global + one cuBLAS call per expert. diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 05f9b42d..f0c3913e 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -2243,15 +2243,25 @@ bool native_q8_0_packed_eligible(int n_in, int n_out) { } namespace { -std::unordered_map& q8_sm60_owned() { // packed copies made here (the head), freed by release +// packed copies made here (the head), freed by release; null: packed in place (release only unregisters it) +std::unordered_map& q8_sm60_owned() { static std::unordered_map owned; return owned; } +bool q8_sm60_pack_impl(const void* weights, int n_in, int n_out, const char* what, bool quiet); } // namespace bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what) { + return q8_sm60_pack_impl(weights, n_in, n_out, what, false); +} +bool native_q8_0_sm60_pack_quiet(const void* weights, int n_in, int n_out, const char* what) { + return q8_sm60_pack_impl(weights, n_in, n_out, what, true); +} + +namespace { +bool q8_sm60_pack_impl(const void* weights, int n_in, int n_out, const char* what, bool quiet) { #if defined(__HIPCC__) - (void) weights; (void) n_in; (void) n_out; (void) what; + (void) weights; (void) n_in; (void) n_out; (void) what; (void) quiet; return false; #else if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false; @@ -2276,18 +2286,20 @@ bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* } q8_packed_registry()[weights] = Q8Packed{qs, d, n_in, n_out}; q8_sm60_owned()[weights] = packed; - std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in, - double(bytes) / 1048576.0); + if (!quiet) + std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in, + double(bytes) / 1048576.0); return true; #endif } +} // namespace void native_q8_0_sm60_release(const void* weights) { auto& owned = q8_sm60_owned(); const auto it = owned.find(weights); if (it == owned.end()) return; q8_packed_registry().erase(weights); - cudaFree(it->second); + if (it->second) cudaFree(it->second); owned.erase(it); } @@ -2313,6 +2325,40 @@ void native_q8_0_packed_register(const void* gguf_weights, const void* packed, i void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); } +bool native_q8_0_sm60_pack_in_place(void* weights, int n_in, int n_out, const char* what) { +#if defined(__HIPCC__) + (void) weights; (void) n_in; (void) n_out; (void) what; + return false; +#else + if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false; + if (q8_packed_registry().count(weights)) return true; + // The GGUF blocks are gone afterwards, so only where q8_packed_mmvq can never fall back to the GGUF-layout kernels + // (every column count fits the kernel's shared-memory planes) and its 16-byte weight loads stay aligned + if (q8sm60::smem_bytes(MAX_NCOLS, n_in) > q8sm60::MAX_SMEM || reinterpret_cast(weights) % 16 != 0) + return native_q8_0_sm60_pack(weights, n_in, n_out, what); + const std::size_t bytes = std::size_t(n_in / 32) * std::size_t(n_out) * 34; // both layouts: 34 bytes per 32 + std::vector blocks(bytes), planes(bytes); + if (cudaMemcpy(blocks.data(), weights, bytes, cudaMemcpyDeviceToHost) != cudaSuccess) { + cudaGetLastError(); + std::fprintf(stderr, "strata q8 sm60: reading the %s failed; it keeps the GGUF layout\n", what); + return false; + } + native_q8_0_pack_host(blocks.data(), planes.data(), n_in, n_out); + if (cudaMemcpy(weights, planes.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) { + cudaGetLastError(); + // a partial write leaves neither layout: put the blocks back + const bool restored = cudaMemcpy(weights, blocks.data(), bytes, cudaMemcpyHostToDevice) == cudaSuccess; + cudaGetLastError(); + std::fprintf(stderr, "strata q8 sm60: writing the packed %s failed; %s\n", what, + restored ? "it keeps the GGUF layout" : "its GGUF blocks could not be restored either"); + return false; + } + native_q8_0_packed_register(weights, weights, n_in, n_out); + q8_sm60_owned()[weights] = nullptr; + return true; // the caller says what it packed +#endif +} + bool native_q6_k_packed_enabled() { static const bool enabled = [] { const char* v = std::getenv("STRATA_Q6_PACKED"); @@ -2991,10 +3037,9 @@ constexpr IlRows kIlRowsShared[] = { // sm_86 + sm_120, and the fallback for e {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}}, // Q6_K }; // Per-architecture tables (P10). A card whose compute capability (major * 10 + minor) is listed here uses its own table; -// every other sm_80+ card uses kIlRowsShared. sm_89 (Ada) has none yet: nobody measured it (we have no such card), so -// it takes the shared table, which sits between the measured sm_86 and sm_120. To add one, run +// every other sm_80+ card uses kIlRowsShared. sm_89 (Ada) has an opt-in table (kIlRows_89, below; STRATA_MMVQ_IL_89=1). To add one, run // `mmvq_il_parity --bench --emit-table` on the card (docs/MMVQ_IL_TABLE.md), paste the printed block as a -// `constexpr IlRows kIlRows_89[]` and add {89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)} below. Each choice +// `constexpr IlRows kIlRows_[]` and add {, kIlRows_, sizeof(kIlRows_) / sizeof(IlRows)} below. Each choice // is bitwise the same output, so a table is only speed. Without a rebuild: STRATA_MMVQ_IL_ROWS (see il_env_rows). // Volta (sm_70): read off mmvq_il_parity --bench on a V100-SXM2-32GB (two runs, mean), the same rule - per cell the // rows count whose every measured shape takes at least 3% off native_mmvq's time (e.g. the Q5_K head at 3 columns @@ -3045,6 +3090,19 @@ constexpr IlRows kIlRows_120[] = { {14, {{0, 0, 2, 1, 1}, {0, 0, 4, 2, 4}, {0, 2, 2, 2, 2}}}, // Q6_K {11, {{0, 1, 2, 2, 2}, {0, 2, 4, 2, 2}, {0, 2, 2, 2, 2}}}, // Q3_K }; +// Ada (sm_89): the cells where two cards agree. mmvq_il_parity --bench --emit-table was run on an RTX 4070 (46 SMs, +// #3453) and on an RTX 4080 (48 SMs, same issue); a cell is kept only where both runs give the same rows count, else 0 +// (the plain kernel), so a card that disagrees never gets a split it did not measure. The 5-8 column table of that +// issue is not taken: the 4080 reproduced the 2-4 column table byte for byte in four runs, and the 5-8 column table +// changed in 10-14 of 20 entries between runs. Bitwise equal to native_mmvq, so the table is only speed. +// mmvq_il_parity's check_tables rebuilds the table from the two source runs and compares. +constexpr IlRows kIlRows_89[] = { + {23, {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}}, // IQ4_XS + {12, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}}, // Q4_K + {13, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}, {0, 0, 1, 0, 0}}}, // Q5_K + {14, {{0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}}}, // Q6_K + {11, {{0, 0, 1, 0, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}, // Q3_K +}; // Turing (sm_75): read off mmvq_il_parity --bench --emit-table on an RTX 2080 Ti 22 GB (SM 1650 MHz), the same 3% rule. // The plain multi-column kernels are bound by dp4a throughput on Turing from 2 columns on (IQ4_XS 2560x10240 at 4 // columns 81.1 -> 37.4 us, the Q5_K head 1671 -> 1045 us); bitwise equal to native_mmvq. No one-column table here: @@ -3078,6 +3136,10 @@ struct Il1Rows { int type; uint8_t r[5]; }; constexpr Il1Rows kIl1Rows_86[] = { {11, {0, 1, 1, 1, 1}}, // Q3_K: 2560x10240 60 -> 43 us, 6144x2560 30 -> 26 us on the A4000 }; +// Ada (sm_89): the RTX 4070 and the RTX 4080 runs gave the same one-column row (only Q3_K takes the interleaved kernel) +constexpr Il1Rows kIl1Rows_89[] = { + {11, {0, 0, 1, 1, 1}}, // Q3_K +}; // Tesla P40 (sm_61), the same three runs: IQ4_XS 2560x10240 102 -> 58 us, the Q5_K head 1754 -> 1507 us constexpr Il1Rows kIl1Rows_61[] = { {23, {2, 2, 4, 4, 4}}, // IQ4_XS @@ -3088,6 +3150,7 @@ struct Il1Arch { int cc; const Il1Rows* t; size_t n; }; constexpr Il1Arch kIl1Arch[] = { {61, kIl1Rows_61, sizeof(kIl1Rows_61) / sizeof(Il1Rows)}, {86, kIl1Rows_86, sizeof(kIl1Rows_86) / sizeof(Il1Rows)}, + {89, kIl1Rows_89, sizeof(kIl1Rows_89) / sizeof(Il1Rows)}, // Ada: the RTX 4070 and 4080 agree }; bool il_env_on(const char* name) { const char* v = std::getenv(name); @@ -3095,6 +3158,10 @@ bool il_env_on(const char* name) { } bool il_t1_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_T1"); return on; } bool il_q3k_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_Q3K"); return on; } +// #3453: sm_89's own tables (kIlRows_89 / kIl1Rows_89) are opt-in with STRATA_MMVQ_IL_89=1 until an sm_89 card has run +// mmvq_il_parity and an end-to-end A/B (docs/MMVQ_IL_TABLE.md). Unset, an Ada card answers what it answered before: the +// shared table, no one-column row. Cached once; the lookup runs on the host once a launch. +bool il_89_opt_in() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL_89"); return v != nullptr && v[0] == '1'; }(); return on; } struct IlArch { int cc; const IlRows* t; size_t n; }; constexpr IlArch kIlArch[] = { {60, kIlRows_60, sizeof(kIlRows_60) / sizeof(IlRows)}, // Pascal GP100: measured on a Tesla P100 @@ -3102,6 +3169,7 @@ constexpr IlArch kIlArch[] = { {75, kIlRows_75, sizeof(kIlRows_75) / sizeof(IlRows)}, // Turing: measured on an RTX 2080 Ti {70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)}, // Volta: PR 1401, measured on a V100-SXM2 {86, kIlRows_86, sizeof(kIlRows_86) / sizeof(IlRows)}, // 143-dense: RTX A4000 with the real shapes (Q3_K added) + {89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)}, // Ada: the cells where an RTX 4070 and an RTX 4080 agree // 147-verify: RTX PRO 5000 Blackwell (110 SMs). Only 12.0 cards with 80+ SMs (il_cc's 1201) take it: the shared table // was measured on an RTX 5070 (48 SMs) and stays that card's {1201, kIlRows_120, sizeof(kIlRows_120) / sizeof(IlRows)}, @@ -3158,7 +3226,7 @@ int native_mmvq_il_rows_for(int cc, int type, int ncols, int n_out) { if (ncols == 1) { // 143-dense: one column (the plain q8_1 blocks, no interleaved copy); STRATA_MMVQ_IL_T1=0 turns it off if (!il_t1_on()) return 0; for (const Il1Arch& a : kIl1Arch) - if (a.cc == cc) + if (a.cc == cc && (cc != 89 || il_89_opt_in())) for (size_t i = 0; i < a.n; ++i) if (a.t[i].type == type) return a.t[i].r[cls]; return 0; @@ -3168,7 +3236,7 @@ int native_mmvq_il_rows_for(int cc, int type, int ncols, int n_out) { size_t n = sizeof(kIlRowsShared) / sizeof(IlRows); static const bool own120 = il_env_on("STRATA_MMVQ_IL_120"); // 147-verify: =0 gives a big 12.0 card the shared table again for (const IlArch& a : kIlArch) - if (a.cc == cc && a.t != nullptr && (cc != 1201 || own120)) { t = a.t; n = a.n; } + if (a.cc == cc && a.t != nullptr && (cc != 1201 || own120) && (cc != 89 || il_89_opt_in())) { t = a.t; n = a.n; } for (size_t i = 0; i < n; ++i) if (t[i].type == type) return t[i].r[ncols - 2][cls]; return 0; diff --git a/src/kernels/cuda/nib_gu_proto.cuh b/src/kernels/cuda/nib_gu_proto.cuh new file mode 100644 index 00000000..368eeb33 --- /dev/null +++ b/src/kernels/cuda/nib_gu_proto.cuh @@ -0,0 +1,137 @@ +// src/kernels/cuda/nib_gu_proto.cuh - STRATA_NIB_GU_PROTO: a staging variant of nib_gu_kernel (STRATA_EXPERT_NIBBLE's +// 4-bit gate/up), included by iq_kernels.cu inside its anonymous namespace after nib_gu_kernel. +// +// The kernel keeps the S skeleton's per-row arithmetic by calling nib_row_dot_s itself (16 lanes a row, lane t's items +// k = t, t+32, t+64 into s and t+16, t+48 into s16, NibLoad::load then Split::apply on the staged block_q8_1, +// __fadd_rn(s, s16), xor 8, 4, 2, 1). Only the staging and the block -> (group, rows) mapping change: +// - a block takes RB row blocks (16 rows each) of one group: grid (80 / RB, gy). The group's entries are staged +// once and the RB row blocks run one after another on them; +// - the staging reads the entries' q8_1 rows (2,880 B = 180 x 16 B each, 16-aligned when xq is) as 16-byte loads, +// every load issued before the first store, so only the stores sit between the two barriers. The S skeleton's +// word loop (nib_pass_s) has a serial load -> store chain there that stalls all eight warps of the block. +// The outputs are written without nib_pass_s's dynamically indexed s[t] (a select on t), the same values. +// Id 31 = RB 2, the one STRATA_NIB_GU_PROTO=1 selects: one GP100 die (PH402), T=1, gate/up alone, IQ2_S / IQ3_XXS / +// IQ3_S x1.25-1.27 against the S / P skeleton, every gate and up row bitwise equal (iq_nibble_parity (7), +// native_expert_bench --nibble --vs 31). +#pragma once + +// The n (1..GRP_NC) entries from e into s_x (block_q8_1 rows of 80). Block-uniform (e, n): every thread reaches both +// barriers. 16-byte loads, all in flight before the first store. +__device__ __forceinline__ void nibx_stage(block_q8_1* s_x, const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, int e, int n) { + constexpr int kV = (GRP_NC * 180 + 255) / 256; // 3 + const int nv = n * 180; + uint4 v[kV]; +#pragma unroll + for (int j = 0; j < kV; ++j) { + const int i = threadIdx.x + 256 * j; + if (i < nv) { + const int c = i >= 540 ? 3 : i >= 360 ? 2 : i >= 180 ? 1 : 0; + v[j] = ((const uint4*) (xq + (size_t) ent_tok[e + c] * 80))[i - 180 * c]; + } + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < kV; ++j) { + const int i = threadIdx.x + 256 * j; + if (i < nv) ((uint4*) s_x)[i] = v[j]; + } + __syncthreads(); +} + +// nib_pass_s's compute on the staged entries (nib_row_dot_s, the production function), stored without the dynamically +// indexed s[t] +template +__device__ __forceinline__ void nibx_run(const uint8_t* slot, int row, const block_q8_1* s_x, int e, int n, int t, + float* dst, int r) { + const uint4* crow = (const uint4*) (slot + nibk::kCodesOff) + (size_t) row * nibk::kItems; + const uint8_t* srow = slot + nibk::kScOff + (size_t) row * nibk::kItems; + const __half* drow = (const __half*) (slot + nibk::kDOff) + (size_t) row * nibk::kSuper; + if (n == 1) { + const int o[1] = { 0 }; float s[1]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0]; + } else if (n == 2) { + const int o[2] = { 0, 80 }; float s[2]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = t == 0 ? s[0] : s[1]; + } else if (n == 3) { + const int o[3] = { 0, 80, 160 }; float s[3]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = t == 0 ? s[0] : t == 1 ? s[1] : s[2]; + } else { + const int o[4] = { 0, 80, 160, 240 }; float s[4]; + nib_row_dot_s(crow, srow, drow, s_x, o, t, s); + if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = t == 0 ? s[0] : t == 1 ? s[1] : t == 2 ? s[2] : s[3]; + } +} + +template +__global__ void __launch_bounds__(256) nibx_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, float* __restrict__ gate, + float* __restrict__ up) { + static_assert(80 % RB == 0, "row blocks per block divide 80"); + const int ng = *n_groups; + if (blockIdx.y >= (unsigned) ng) return; + STRATA_SHARED_ALIGN16_U32(s_buf, kNibSWords); + block_q8_1* s_x = (block_q8_1*) s_buf; + const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15; + const int rb0 = blockIdx.x * RB; + for (int g = blockIdx.y; g < ng; g += gridDim.y) { + const uint8_t* slot = (const uint8_t*) grp_ptr[g]; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int nt = e1 - e0; + if (nt <= 0) continue; // an empty group: nothing to write (block-uniform, no barrier skipped unevenly) + if (nt <= GRP_NC) { + nibx_stage(s_x, ent_tok, xq, e0, nt); +#pragma unroll 1 + for (int j = 0; j < RB; ++j) { + const int row = (rb0 + j) * 16 + subwarp; + const bool is_up = row >= nibk::kNFf; + nibx_run(slot, row, s_x, e0, nt, t, is_up ? up : gate, is_up ? row - (int) nibk::kNFf : row); + } + } else { // more entries than one pass holds: per row block, the passes as nib_pass_s runs them +#pragma unroll 1 + for (int j = 0; j < RB; ++j) { + const int row = (rb0 + j) * 16 + subwarp; + const bool is_up = row >= nibk::kNFf; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + nibx_stage(s_x, ent_tok, xq, e, n); + nibx_run(slot, row, s_x, e, n, t, is_up ? up : gate, is_up ? row - (int) nibk::kNFf : row); + } + } + } + } +} + +int g_nibx_occ = 0; // the last attribute query's resident blocks per SM + +template +void nibx_launch_one(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, + const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, + cudaFuncAttributes* attr) { + if (attr) { + cudaFuncGetAttributes(attr, nibx_gu_kernel); + cudaOccupancyMaxActiveBlocksPerMultiprocessor(&g_nibx_occ, nibx_gu_kernel, 256, 0); + return; + } + nibx_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, gate, up); +} + +// false: not the gu-proto id (31) or not a converted format. attr != nullptr: only the kernel's attributes, nothing +// launched. +bool nibx_launch(int gu_type, int id, dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, + float* gate, float* up, cudaFuncAttributes* attr = nullptr) { + if (id != 31) return false; + switch (gu_type) { + case 22: nibx_launch_one<22, 2>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up, attr); return true; + case 18: nibx_launch_one<18, 2>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up, attr); return true; + case 21: nibx_launch_one<21, 2>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up, attr); return true; + default: return false; + } +} diff --git a/src/kernels/cuda/qsa_pattn.cu b/src/kernels/cuda/qsa_pattn.cu new file mode 100644 index 00000000..0b1174a7 --- /dev/null +++ b/src/kernels/cuda/qsa_pattn.cu @@ -0,0 +1,458 @@ +// src/kernels/cuda/qsa_pattn.cu - see include/strata/kernels/qsa_pattn.hpp. +// +// Every value below is computed by the operation the production path uses, on the same operands, in the same order: +// - score of (cell, head): each lane l's partial k8[0] * q[8l] + ... + k8[7] * q[8l + 7] with k8[e] = (float) code * sc, +// the 32 partials summed in warp_sum's pairs (reduce12's tree), times `scale`; +// - chunk softmax: m = warp_max over fmaxf(s[lane], s[lane + 32]); e = __expf(s - m) (0 for a masked or absent cell); +// l = warp_sum(e[lane] + e[lane + 32]); +// - chunk value: acc[h] = fmaf(e[c][h], v, acc[h]) over the chunk's cells in ascending order, masked cells skipped, +// v = (float) code * sc; +// - merge (attn_merge_kernel): M = fmaxf over the chunks' m; for each chunk in order with m != -FLT_MAX: +// w = __expf(m - M), L = fmaf(l, w, L), acc = fmaf(acc_c, w, acc); out = L > 0 ? acc / L : 0. +// qsa_pattn_parity compares the outputs with qsa_decode_attn_batch's byte for byte on synthetic selections. +// Only the default variant of the contributor's PR (#3943) is kept: ps_score_x_kernel + ps_value_d4_kernel. +#include "strata/kernels/qsa_pattn.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/core/geometry.hpp" + +#include + +#include +#include +#include +#include + +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +#define STRATA_PATTN_BUILT 1 // the CUDA build with STRATA_EXPERIMENTAL_SM60 only (not HIP, not Metal) +#include +#else +#define STRATA_PATTN_BUILT 0 +#endif + +namespace strata::kernels { + +// STRATA_PATTN_SM60=1 turns it on (a tester switch, read once). In a build without the sm_6x kernels it says so and stays off. +int pattn_mode() { + static const int m = [] { + const char* v = std::getenv("STRATA_PATTN_SM60"); + const int x = v != nullptr && *v != '\0' ? std::atoi(v) : 0; + if (x == 0) return 0; +#if STRATA_PATTN_BUILT + std::fprintf(stderr, "strata pattn: STRATA_PATTN_SM60=%d: the prompt path's QSA attention on the sm_6x score / " + "value kernels (bit for bit qsa_decode_attn_batch; int8 K/V)\n", x); + return 1; +#else + std::fprintf(stderr, "strata pattn: STRATA_PATTN_SM60 is set, but this build has no sm_6x kernels " + "(CUDA with STRATA_EXPERIMENTAL_SM60 only); the usual attention runs\n"); + return 0; +#endif + }(); + return m; +} + +#if STRATA_PATTN_BUILT +namespace { + +constexpr int HD = 256; +constexpr int G = 12; +static_assert(HD == strata::core::kCompiledGeometry.head_dim && + G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, + "qsa_pattn is compiled for core/geometry.hpp"); +constexpr int CHUNK = 64; +constexpr int THREADS = 256; +constexpr int WARPS = THREADS / 32; +constexpr int NSC = HD / KV_Q8_GROUP; // scales per row (4) + +__device__ __forceinline__ float warp_sum_x(float v) { + v += __shfl_xor_sync(0xffffffffu, v, 16); v += __shfl_xor_sync(0xffffffffu, v, 8); + v += __shfl_xor_sync(0xffffffffu, v, 4); v += __shfl_xor_sync(0xffffffffu, v, 2); + v += __shfl_xor_sync(0xffffffffu, v, 1); + return v; +} +__device__ __forceinline__ float warp_max_x(float v) { + v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 16)); v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 8)); + v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 4)); v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 2)); + v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, 1)); + return v; +} + +// pool row of cell `c0 + t` of query selection `ids` (attn_chunk_kernel_pre75's srow), -1 masked / absent +__device__ __forceinline__ long long cell_row(const QsaAttnPools& p, const int32_t* __restrict__ ids, int c0, int t, + int n_here, int n_kv_heads, int kvh, int page_size) { + long long r = -1; + if (t < n_here) { + const int cell = __ldg(ids + c0 + t); + const long long page = (long long) __ldg(p.page_table + cell / page_size); + if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + return r; +} + +// the chunk's K codes (16-byte loads) and scales (as float) into shared memory; masked / absent cells read row 0 +__device__ __forceinline__ void stage_rows(const int8_t* __restrict__ codes, const uint16_t* __restrict__ scales, + const long long* srow, int n_here, int t, int8_t (*sk)[HD], + float (*sks)[NSC]) { + uint4 kv[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = t + THREADS * j, c = idx >> 4, part = idx & 15; + const long long row = srow[c]; + const long long rr = (c < n_here && row >= 0) ? row : 0; + kv[j] = __ldg(reinterpret_cast(codes + rr * HD) + part); + } + float sc; + { + const int c = t >> 2, g = t & 3; + const long long row = srow[c]; + const long long rr = (c < n_here && row >= 0) ? row : 0; + sc = __half2float(__ushort_as_half(__ldg(scales + rr * NSC + g))); + } +#pragma unroll + for (int j = 0; j < 4; ++j) reinterpret_cast(&sk[0][0])[t + THREADS * j] = kv[j]; + sks[t >> 2][t & 3] = sc; +} + +constexpr int PS_BLK = G * CHUNK + 2 * CHUNK + 2 * G; // floats per (query, KV head, chunk): e, rows (int64), m, l +constexpr int NCM = 33; // chunks the value kernel keeps (cap <= 2112) + +// --------------------------------------------------------------------------------------------------------------------- +// ps_score_x_kernel: the score phase two cells at a time with a select-free reduce-scatter. reduce12's selects exist +// because the two lanes of an exchange send different slots; here every lane keeps the same slots and sends the same +// slots, and the lane-dependent part is moved into which query head each register slot holds (q is loaded once, so the +// permutation costs nothing per cell) and which of the two cells is "first": +// slot i (0..11) of lane L holds head P_L(i) = 6 ((i / 6) ^ b3) + ((i % 6 + 3 b2) % 6) (b_k: bit k of L) +// first = cell B if b4 else cell A, second = the other one; part1[i] / part2[i] = lane partials of (first / second, +// head P_L(i)) - the same expression as attn_chunk_kernel_pre75. +// level 16: r[i] = part1[i] + shfl(part2[i], 16) (partner: b4 flipped, so its second is my first, same P) +// level 8 : r6[i] = r[i] + shfl(r[i + 6], 8) (P_{L^8}(i) = P_L(i + 6)) +// level 4 : r3[i] = r6[i] + shfl(r6[i + 3], 4) (P_{L^4}(i) = P_L(i + 3), i < 3) +// level 2 / 1: reduce24's (heads 6 b3 + 3 b2 + {0, 1, 2}; o0 head +2 b1, o1 head +1 where b1 = 0) +// At every level the value at lane L is its partial at L plus its partial at L ^ o, the same operands warp_sum adds, +// so every score is reduce12's bit for bit. A pair with an absent / masked cell runs the same code on row 0's staged +// codes and that cell's outputs are not stored (it gets -FLT_MAX). 25 shuffles, 25 adds and 4 selects per pair +// instead of 2 x (15 + 15 + ~30). +__device__ __forceinline__ int px_head(int i, int lane) { + const int b3 = (lane >> 3) & 1, b2 = (lane >> 2) & 1; + return 6 * ((i / 6) ^ b3) + ((i % 6 + 3 * b2) % 6); +} +__device__ __forceinline__ void load_q_perm(const float* __restrict__ qh, int lane, float4 (&qa)[G], float4 (&qb)[G]) { +#pragma unroll + for (int i = 0; i < G; ++i) { + const float4* p4 = reinterpret_cast(qh + (size_t) px_head(i, lane) * HD + lane * 8); + qa[i] = __ldg(p4); + qb[i] = __ldg(p4 + 1); + } +} +__device__ __forceinline__ void dequant8(const int8_t* krow, float sc, int lane, float (&k8)[8]) { + const uint2 raw = *reinterpret_cast(krow + lane * 8); + const int8_t* cb = reinterpret_cast(&raw); +#pragma unroll + for (int e = 0; e < 8; ++e) k8[e] = (float) cb[e] * sc; +} +__device__ __forceinline__ float dot8(const float (&k8)[8], const float4& qa, const float4& qb) { + return k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + + k8[7] * qb.w; +} +template +__device__ __forceinline__ void score_chunk_x(const float4 (&qa)[G], const float4 (&qb)[G], const int8_t (*sk)[HD], + const float (*sks)[NSC], const long long* srow, float (*sp)[CHUNK], + int n_here, float scale, int warp, int lane) { + const bool h16 = (lane & 16) != 0, h2 = (lane & 2) != 0, even = (lane & 1) == 0; + const int hb = 6 * ((lane >> 3) & 1) + 3 * ((lane >> 2) & 1); + const int h0 = hb + (h2 ? 2 : 0), h1 = hb + 1; +#pragma unroll UNR + for (int i = 0; i < CHUNK / WARPS; i += 2) { + const int ca = warp + WARPS * i, cb = warp + WARPS * (i + 1); + const bool va = ca < n_here && srow[ca] >= 0, vb = cb < n_here && srow[cb] >= 0; + if (!va && !vb) { + if (lane < G) { sp[lane][ca] = -FLT_MAX; sp[lane][cb] = -FLT_MAX; } + continue; + } + const int c1 = h16 ? cb : ca, c2 = h16 ? ca : cb; // first / second (the staged rows of absent cells are row 0's) + float r[G]; + { + float k8[8]; + dequant8(sk[c2], sks[c2][lane >> 3], lane, k8); + float p2[G]; +#pragma unroll + for (int s = 0; s < G; ++s) p2[s] = dot8(k8, qa[s], qb[s]); + dequant8(sk[c1], sks[c1][lane >> 3], lane, k8); +#pragma unroll + for (int s = 0; s < G; ++s) r[s] = dot8(k8, qa[s], qb[s]) + __shfl_xor_sync(0xffffffffu, p2[s], 16); + } + float r6[6]; +#pragma unroll + for (int s = 0; s < 6; ++s) r6[s] = r[s] + __shfl_xor_sync(0xffffffffu, r[s + 6], 8); + float r3[3]; +#pragma unroll + for (int s = 0; s < 3; ++s) r3[s] = r6[s] + __shfl_xor_sync(0xffffffffu, r6[s + 3], 4); + const float x0 = (h2 ? r3[2] : r3[0]) + __shfl_xor_sync(0xffffffffu, h2 ? r3[0] : r3[2], 2); + const float x1 = r3[1] + __shfl_xor_sync(0xffffffffu, r3[1], 2); + const float o0 = x0 + __shfl_xor_sync(0xffffffffu, x0, 1); + const float o1 = x1 + __shfl_xor_sync(0xffffffffu, x1, 1); + const bool vmine = h16 ? vb : va; + if (even && vmine) { + sp[h0][c1] = o0 * scale; + if (!h2) sp[h1][c1] = o1 * scale; + } + if (lane < G) { + if (!va) sp[lane][ca] = -FLT_MAX; + if (!vb) sp[lane][cb] = -FLT_MAX; + } + } +} + +// ps_score_kernel with score_chunk_x (q loaded in the permuted slot order) +template +__global__ void __launch_bounds__(THREADS, 2) ps_score_x_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, float* __restrict__ blocks, + int n_chunks, int cap) { + q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; + ids += (size_t) blockIdx.z * (size_t) cap; + step += (size_t) blockIdx.z * kStepCount; + const int chunk = blockIdx.x, kvh = blockIdx.y; + float* const blk = blocks + (((size_t) blockIdx.z * n_kv_heads + kvh) * n_chunks + chunk) * PS_BLK; + __shared__ __align__(16) int8_t sk[CHUNK][HD]; + __shared__ __align__(16) float sks[CHUNK][NSC]; + __shared__ float sp[G][CHUNK]; + __shared__ long long srow[CHUNK]; + const int n_ids = __ldg(step + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int c0 = chunk * CHUNK; + const int n_here = min(CHUNK, n_ids - c0); + if (n_here <= 0) { + if (t < G) { blk[G * CHUNK + 2 * CHUNK + t] = -FLT_MAX; blk[G * CHUNK + 2 * CHUNK + G + t] = 0.0f; } + return; + } + if (t < CHUNK) { + const long long r = cell_row(p, ids, c0, t, n_here, n_kv_heads, kvh, page_size); + srow[t] = r; + reinterpret_cast(blk + G * CHUNK)[t] = r; + } + float4 qa[G], qb[G]; + load_q_perm(q + (size_t) (kvh * G) * HD, lane, qa, qb); + __syncthreads(); + stage_rows(p.k_q, p.k_scale, srow, n_here, t, sk, sks); + __syncthreads(); + score_chunk_x(qa, qb, sk, sks, srow, sp, n_here, scale, warp, lane); + __syncthreads(); + for (int h = warp; h < G; h += WARPS) { + const float a = sp[h][lane], b = sp[h][lane + 32]; + const float m = warp_max_x(fmaxf(a, b)); + const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f; + const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f; + blk[h * CHUNK + lane] = ea; + blk[h * CHUNK + lane + 32] = eb; + const float l = warp_sum_x(ea + eb); + if (lane == 0) { blk[G * CHUNK + 2 * CHUNK + h] = m; blk[G * CHUNK + 2 * CHUNK + G + h] = l; } + } +} + +// ps_value_d4_kernel: the value kernel with four dims a thread (64 threads, one CTA per (KV head, query)): a cell's four +// codes are one 32-bit load (a warp reads 128 contiguous bytes), its 12 weights three broadcast float4 reads for 48 +// fmaf. V loads run four cells ahead. Per (dim, head) the fold and the merge are ps_value_kernel's. +__global__ void __launch_bounds__(64) ps_value_d4_kernel(QsaAttnPools p, const int32_t* __restrict__ steps, + const float* __restrict__ blocks, int n_kv_heads, int n_chunks, + float* __restrict__ attn) { + constexpr int NT = 64; + const int kvh = blockIdx.x, z = blockIdx.y; + const int t = threadIdx.x; + const float* const blk0 = blocks + ((size_t) z * n_kv_heads + kvh) * n_chunks * PS_BLK; + __shared__ float sm_m[NCM][G], sm_w[NCM][G], sm_l[NCM][G]; + __shared__ float sL[G]; + __shared__ __align__(16) float spt[CHUNK][G]; + __shared__ long long srow[CHUNK]; + __shared__ int s_masked; + const int width = __ldg(steps + (size_t) z * kStepCount + kStepWidth); + const int n_act = width > 0 ? min(n_chunks, (width - 1) / CHUNK + 1) : 0; + for (int i = t; i < n_act * G; i += NT) { + const int c = i / G, h = i % G; + sm_m[c][h] = __ldg(blk0 + (size_t) c * PS_BLK + G * CHUNK + 2 * CHUNK + h); + sm_l[c][h] = __ldg(blk0 + (size_t) c * PS_BLK + G * CHUNK + 2 * CHUNK + G + h); + } + __syncthreads(); + if (t < G) { + float M = -FLT_MAX; + for (int c = 0; c < n_act; ++c) M = fmaxf(M, sm_m[c][t]); + float L = 0.0f; + for (int c = 0; c < n_act; ++c) { + const float m = sm_m[c][t]; + const float w = __expf(m - M); + sm_w[c][t] = w; + const float L_next = fmaf(sm_l[c][t], w, L); + L = (m == -FLT_MAX) ? L : L_next; + } + sL[t] = L; + } + const int d0 = 4 * t, g = d0 / KV_Q8_GROUP; + float acc[4][G]; +#pragma unroll + for (int h = 0; h < G; ++h) +#pragma unroll + for (int d = 0; d < 4; ++d) acc[d][h] = 0.0f; + for (int c = 0; c < n_act; ++c) { + const float* blk = blk0 + (size_t) c * PS_BLK; + const int n_here = min(CHUNK, width - c * CHUNK); + __syncthreads(); + if (t == 0) s_masked = 0; + __syncthreads(); + { + const long long r = __ldg(reinterpret_cast(blk + G * CHUNK) + t); + srow[t] = r; + if (t < n_here && r < 0) s_masked = 1; + } +#pragma unroll + for (int j = 0; j < G * CHUNK / NT; ++j) { + const int idx = t + NT * j, h = idx / CHUNK, cell = idx % CHUNK; + spt[cell][h] = __ldg(blk + idx); + } + __syncthreads(); + float a[4][G]; +#pragma unroll + for (int h = 0; h < G; ++h) +#pragma unroll + for (int d = 0; d < 4; ++d) a[d][h] = 0.0f; + const auto fold4 = [&](int cl, uint32_t codes, float sc) { + const float v0 = (float) (int8_t) (codes & 0xFF) * sc, v1 = (float) (int8_t) ((codes >> 8) & 0xFF) * sc; + const float v2 = (float) (int8_t) ((codes >> 16) & 0xFF) * sc, v3 = (float) (int8_t) (codes >> 24) * sc; + const float4* w4 = reinterpret_cast(spt[cl]); + const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2]; + const float ww[G] = {w0.x, w0.y, w0.z, w0.w, w1.x, w1.y, w1.z, w1.w, w2.x, w2.y, w2.z, w2.w}; +#pragma unroll + for (int h = 0; h < G; ++h) { + a[0][h] = fmaf(ww[h], v0, a[0][h]); + a[1][h] = fmaf(ww[h], v1, a[1][h]); + a[2][h] = fmaf(ww[h], v2, a[2][h]); + a[3][h] = fmaf(ww[h], v3, a[3][h]); + } + }; + const auto vld = [&](int cl, uint32_t& codes, float& sc) { + const long long r = srow[cl]; + const long long rr = r >= 0 ? r : 0; + codes = __ldg(reinterpret_cast(p.v_q + rr * HD + d0)); + sc = __half2float(__ushort_as_half(__ldg(p.v_scale + rr * NSC + g))); + }; + if (!s_masked) { + int cl = 0; + for (; cl + 4 <= n_here; cl += 4) { + uint32_t k0, k1, k2, k3; + float s0, s1, s2, s3; + vld(cl, k0, s0); vld(cl + 1, k1, s1); vld(cl + 2, k2, s2); vld(cl + 3, k3, s3); + fold4(cl, k0, s0); + fold4(cl + 1, k1, s1); + fold4(cl + 2, k2, s2); + fold4(cl + 3, k3, s3); + } + for (; cl < n_here; ++cl) { + uint32_t k0; + float s0; + vld(cl, k0, s0); + fold4(cl, k0, s0); + } + } else { + for (int cl = 0; cl < n_here; ++cl) { + if (srow[cl] < 0) continue; + uint32_t k0; + float s0; + vld(cl, k0, s0); + fold4(cl, k0, s0); + } + } +#pragma unroll + for (int h = 0; h < G; ++h) { + const bool live = !(sm_m[c][h] == -FLT_MAX); + const float w = sm_w[c][h]; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const float acc_next = fmaf(a[d][h], w, acc[d][h]); + acc[d][h] = live ? acc_next : acc[d][h]; + } + } + } + __syncthreads(); + float* out = attn + ((size_t) z * n_kv_heads + kvh) * G * HD; +#pragma unroll + for (int h = 0; h < G; ++h) { + const float L = sL[h]; + *reinterpret_cast(out + (size_t) h * HD + d0) = + make_float4(L > 0.0f ? acc[0][h] / L : 0.0f, L > 0.0f ? acc[1][h] / L : 0.0f, + L > 0.0f ? acc[2][h] / L : 0.0f, L > 0.0f ? acc[3][h] / L : 0.0f); + } +} + +bool sm6x_device() { + static int cc[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cc[dev] == 0) { + int major = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) { + cudaGetLastError(); + return false; + } + cc[dev] = major; + } + return cc[dev] == 6; +} + +} // namespace + +bool qsa_pattn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, + void* stream) { + return sm6x_device() && qsa_pattn_batch_any_arch(q, pools, ids, steps, cap, s, scratch, scratch_floats, attn, n_q, stream); +} + +bool qsa_pattn_batch_any_arch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, + int64_t n_q, void* stream) { + if (n_q <= 0) return true; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || + !pools.page_table || pools.k_q == nullptr || pools.v_q == nullptr || pools.k_q4 != nullptr || + pools.v_q4 != nullptr || !pools.k_scale || !pools.v_scale) + return false; + const cudaStream_t st = (cudaStream_t) stream; + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const float scale = 1.0f / sqrtf((float) HD); + if (n_chunks > NCM) return false; // a longer selection keeps the usual path + // the scratch holds the blocks of one batch of queries (probabilities, rows, m and l of every chunk), evenly split + const uint64_t per_q = (uint64_t) s.n_head_kv * (uint64_t) n_chunks * PS_BLK; + const int64_t max_batch = (int64_t) (scratch_floats / per_q); + if (max_batch < 1) return false; + const int64_t n_batches = (n_q + max_batch - 1) / max_batch; + const int64_t batch = (n_q + n_batches - 1) / n_batches; + for (int64_t t0 = 0; t0 < n_q; t0 += batch) { + const int64_t nb = n_q - t0 < batch ? n_q - t0 : batch; + const dim3 g1((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) nb); + const dim3 g2((unsigned) s.n_head_kv, (unsigned) nb); + const float* qb = q + (size_t) t0 * s.n_head * HD; + const int32_t* ib = ids + (size_t) t0 * cap; + const int32_t* sb = steps + (size_t) t0 * kStepCount; + ps_score_x_kernel<1><<>>(qb, pools, ib, sb, (int) s.n_head_kv, (int) s.page_size, scale, + scratch, n_chunks, (int) cap); + ps_value_d4_kernel<<>>(pools, sb, scratch, (int) s.n_head_kv, n_chunks, + attn + (size_t) t0 * s.n_head * HD); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + // a launch that did not start: say so once, and let the caller run the usual attention over the whole chunk + static bool warned = false; + if (!warned) { + warned = true; + std::fprintf(stderr, "strata pattn: launch failed (%s); the usual attention runs instead\n", cudaGetErrorString(e)); + } + return false; + } + return true; +} + +#else // not the experimental sm_60 CUDA build +bool qsa_pattn_batch(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, + float*, uint64_t, float*, int64_t, void*) { return false; } +bool qsa_pattn_batch_any_arch(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, + float*, uint64_t, float*, int64_t, void*) { return false; } +#endif + +} // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index e956dc8b..283aba9e 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -1553,6 +1553,385 @@ bool scores_early_exit() { static const bool on = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }(); return on; } + +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// STRATA_SELECT_LONG (verify.cpp): the long-context decode select, qsa_block_scores_long / qsa_block_topk_long. +// ---- decode block scores bit for bit block_scores_multi_kernel's, without its shuffles (STRATA_SCORES_DX, default on +// 6.x, under STRATA_SELECT_LONG). The multi kernel gives a block to a warp and pays 5 shuffles per head per (block, query) for 4 products per +// lane: on GP100 a decode window's call costs ~88 us more per query at 300K cells. Here lane i of warp h builds, for +// block i of a 32-block tile and indexer head h, the same 32-leaf tree as block_scores_multi_kernel's xor butterfly (lanes visited in +// 5-bit-reversed order, depth-first: the xor butterfly's association) for every query of the call at once, the key +// staged once per tile in shared memory and read by all of the queries; the relu sum over the heads then runs in the +// warp kernel's order (0 + r0 + r1 + r2 + r3) from shared memory. Blocks < n_bid; the tail block n_bid is +// block_scores_tail_kernel's (the multi kernel's arithmetic for it). A fixed grid strides over the tiles below the +// call's largest n_bid (capturable). +__device__ __forceinline__ int dx_lane(int j) { return (int) (__brev((unsigned) j) >> 27); } // 5-bit reversal +constexpr int DX_NB = 32; // blocks per tile: one per lane +constexpr int DX_T = 32 * IDX_HEADS; // warp h: indexer head h +constexpr int DX_KS = IDX_DIM + 4; // a key row in shared memory (a quarter warp's 16-byte reads: 32 banks) + +template +__global__ void __launch_bounds__(DX_T) block_scores_dx_kernel(const float* __restrict__ pooled, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int64_t max_blocks, + float* __restrict__ out) { + extern __shared__ __align__(16) float dx_smem[]; + float* Ks = dx_smem; // [DX_NB][DX_KS] + float* Qs = Ks + DX_NB * DX_KS; // [NQ][IDX_HEADS][IDX_DIM] + float* Ds = Qs + NQ * IDX_HEADS * IDX_DIM; // [NQ][IDX_HEADS][DX_NB]: each head's sum, for the relu pass + __shared__ int64_t s_nbid[NQ]; + const int t = threadIdx.x, lane = t & 31, h = t >> 5; + if (t < NQ) s_nbid[t] = steps[t * kStepCount + kStepNBid]; + __syncthreads(); + int64_t top = 0; +#pragma unroll + for (int q = 0; q < NQ; ++q) top = s_nbid[q] > top ? s_nbid[q] : top; + if (top > max_blocks) top = max_blocks; + if ((int64_t) blockIdx.x * DX_NB >= top) return; // CTA-uniform + for (int i = t; i < NQ * IDX_HEADS * IDX_DIM / 4; i += DX_T) + reinterpret_cast(Qs)[i] = reinterpret_cast(q_idx)[i]; + const float* krow = Ks + lane * DX_KS; + // the next tile's keys in registers while this one is scored (coalesced: thread t row (t + 128 i) / 32, float4 t % 32) + constexpr int PF = DX_NB * (IDX_DIM / 4) / DX_T; + float4 pre[PF]; + const int64_t stride = (int64_t) gridDim.x * DX_NB; + auto fetch = [&](int64_t tb) { +#pragma unroll + for (int i = 0; i < PF; ++i) { + const int idx = t + i * DX_T, row = idx / (IDX_DIM / 4), c4 = idx % (IDX_DIM / 4); + pre[i] = tb + row < top ? __ldg(reinterpret_cast(pooled + (tb + row) * IDX_DIM) + c4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + }; + fetch((int64_t) blockIdx.x * DX_NB); + for (int64_t b0 = (int64_t) blockIdx.x * DX_NB; b0 < top; b0 += stride) { +#pragma unroll + for (int i = 0; i < PF; ++i) { + const int idx = t + i * DX_T, row = idx / (IDX_DIM / 4), c4 = idx % (IDX_DIM / 4); + *reinterpret_cast(Ks + row * DX_KS + c4 * 4) = pre[i]; + } + __syncthreads(); + if (b0 + stride < top) fetch(b0 + stride); + float half0[NQ], half1[NQ]; +#pragma unroll 1 + for (int c = 0; c < 4; ++c) { + float l0[NQ], l1[NQ], l2[NQ]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int L = dx_lane(8 * c + jj); + const float4 k4 = *reinterpret_cast(krow + L * 4); +#pragma unroll + for (int q = 0; q < NQ; ++q) { + const float4 q4 = *reinterpret_cast(Qs + (q * IDX_HEADS + h) * IDX_DIM + L * 4); + const float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; + // the depth-first tree over the slice's 8 leaves (pairs, quads, the octet), then the octets + if (jj == 0 || jj == 2 || jj == 4 || jj == 6) l0[q] = d; + else if (jj == 1 || jj == 5) l1[q] = l0[q] + d; + else if (jj == 3) l2[q] = l1[q] + (l0[q] + d); + else { + const float oct = l2[q] + (l1[q] + (l0[q] + d)); + if (c == 0) half0[q] = oct; + else if (c == 1) half0[q] = half0[q] + oct; + else if (c == 2) half1[q] = oct; + else half1[q] = half1[q] + oct; + } + } + } + } +#pragma unroll + for (int q = 0; q < NQ; ++q) Ds[(q * IDX_HEADS + h) * DX_NB + lane] = half0[q] + half1[q]; + __syncthreads(); // also: every warp is done reading Ks before the next tile + for (int q = h; q < NQ; q += IDX_HEADS) { + const int64_t b = b0 + lane; + if (b >= s_nbid[q]) continue; + float score = 0.0f; +#pragma unroll + for (int hh = 0; hh < IDX_HEADS; ++hh) { + const float d = Ds[(q * IDX_HEADS + hh) * DX_NB + lane]; + score += d > 0.0f ? d : 0.0f; + } + out[q * max_blocks + b] = score; + } + } +} + +// ---- the decode top-k over several CTAs per query without clusters (any CUDA card; on sm_6x by default under +// STRATA_SELECT_LONG). A decode +// window's 1-5 queries otherwise run one 1,024-thread CTA each (block_topk_wide_kernel past ~135K cells) on one SM +// apiece: on GP100 0.39 ms per call at 300K cells and 1.15 ms at 1M, x12 QSA layers per window. Here each query gets +// n CTAs (a grid of n x nq), CTA r taking blocks [r * per, (r + 1) * per), and the four radix passes, the count and the +// emit are six kernels in a row on the caller's stream - capturable, no co-residency or spin waits: the kernel boundary +// is the barrier. Exchange goes through the caller's scratch (qsa_topk_multi_scratch_ints): pass 0's histograms one +// row per CTA (plain stores), passes 1-3 summed with atomics into rows the pass-0 kernel zeroes, (prefix, above) after +// each digit, and each warp's cells above / at the threshold. Nothing is carried from one call to the next. +// Warp w of a CTA takes the rows [w * rpw, (w + 1) * rpw) of 32 consecutive blocks (lane l block l of a row: coalesced), +// MT_U rows' loads in flight at a time; the loops stay rolled (GP100's instruction cache: a fully unrolled 33-row body +// doubled every kernel's time). +// +// IDENTICAL IDS, as block_topk_cluster_kernel's: thr (the width-th largest key, cells counted with their weights) and +// `above` are pure functions of the integer histograms whatever order they are summed in, and the digit rule is +// block_topk_kernel's (the largest digit d >= 1 whose cells at or above it reach `need`, else 0), here as a 256-thread +// scan. The emit writes every cell of a block above thr and the first eq_budget = width - above cells at thr, ascending +// (block_topk_wide_kernel's row emit, offset by the cells of the warps and CTAs before). +constexpr int MT_T = 256; // threads per CTA +constexpr int MT_W = MT_T / 32; // warps per CTA +constexpr int MT_U = 4; // rows of loads in flight per warp +constexpr int MT_NMAX = 32; // CTAs per query, at most +constexpr int MT_MAXQ = 16; // more queries per call fill the GPU with one CTA each already +// scratch per query (int32): pass 0's rows [MT_NMAX][256], passes 1-3 [3][256], state [5][2], counts [MT_NMAX][MT_W][2] +constexpr int MT_ACC = MT_NMAX * 256, MT_STATE = MT_ACC + 3 * 256, MT_CNT = MT_STATE + 16; +constexpr int MT_Q_INTS = MT_CNT + 2 * MT_NMAX * MT_W + 64; +static_assert(MT_NMAX * MT_W <= MT_T, "the emit sums the earlier CTAs' warp counts one per thread"); + +struct MtQuery { + int64_t n_kv, n_bid, width, lo, hi, row0; // row0: the first block of this warp's first row + int rpw, wtail; + bool all; // n_kv <= width: every cell, nothing to select +}; + +__device__ __forceinline__ MtQuery mt_query(const int32_t* __restrict__ steps) { + const int32_t* st = steps + (int64_t) blockIdx.y * kStepCount; + MtQuery m; + m.n_kv = st[kStepNKv]; + m.n_bid = st[kStepNBid]; + m.width = st[kStepWidth]; + m.all = m.n_kv <= m.width; + // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0) + m.wtail = (int) (m.n_kv - m.n_bid * R); + const int64_t nbe = m.n_bid + (m.wtail > 0 ? 1 : 0); + const int64_t per = (nbe + gridDim.x - 1) / gridDim.x; + m.lo = (int64_t) blockIdx.x * per < nbe ? (int64_t) blockIdx.x * per : nbe; + m.hi = m.lo + per < nbe ? m.lo + per : nbe; + m.rpw = (int) (((m.hi - m.lo + 31) / 32 + MT_W - 1) / MT_W); + m.row0 = m.lo + (int64_t) (threadIdx.x >> 5) * m.rpw * 32; + return m; +} + +// rows j0 .. j0 + MT_U - 1 of this warp: key[u] for block row0 + 32 (j0 + u) + lane (0 past hi or the warp's rows) +__device__ __forceinline__ void mt_load(const MtQuery& m, const float* __restrict__ sc, int j0, uint32_t (&key)[MT_U]) { + const int lane = threadIdx.x & 31; +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + key[u] = (j0 + u < m.rpw && b < m.hi) ? order_key(__ldg(sc + b)) : 0u; + } +} + +// inclusive scan of one value per thread over the MT_T threads +template __device__ __forceinline__ V mt_incl_scan(V v, V* s_w) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + V x = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const V y = __shfl_up_sync(0xffffffffu, x, o); + if (lane >= o) x += y; + } + if (lane == 31) s_w[warp] = x; + __syncthreads(); + V off = 0; + for (int w = 0; w < warp; ++w) off += s_w[w]; + __syncthreads(); + return x + off; +} + +// The digit at `shift` from the 256 counts (thread t holds digit 255 - t's): block_topk_kernel's rule. +__device__ __forceinline__ void mt_choose(int v, int64_t width, int shift, uint32_t& prefix, int& above, int* s_w, + int* s_ex, int* s_i) { + const int t = threadIdx.x; + if (t == 0) *s_i = 255; // no digit >= 1 reaches it: 0, all of 1..255 above + const int incl = mt_incl_scan(v, s_w); + s_ex[t] = incl - v; + const int64_t need = width - above; + if (t < 255 && incl >= need && incl - v < need) *s_i = t; // the one t where the running count crosses `need` + __syncthreads(); + const int i = *s_i; + prefix |= (uint32_t) (255 - i) << shift; + above += s_ex[i]; + __syncthreads(); +} + +// pass PASS's histogram of the CTA's keys under the prefix so far (PASS >= 1 first takes digit PASS - 1) +template +__global__ void __launch_bounds__(MT_T) block_topk_multi_hist_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, + int64_t max_blocks, int32_t* __restrict__ scratch) { + __shared__ int h[MT_W][256]; + __shared__ int s_w[MT_W], s_ex[256], s_i; + const MtQuery m = mt_query(steps); + if (m.all) return; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float* sc = scores + (int64_t) blockIdx.y * max_blocks; + uint32_t key[MT_U]; + mt_load(m, sc, 0, key); // in flight while the digit is taken + for (int i = t; i < MT_W * 256; i += MT_T) (&h[0][0])[i] = 0; + int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS; + uint32_t prefix = 0; + int above = 0; + if (PASS == 0) { + if (blockIdx.x == 0) // passes 1-3 sum into these: zero them for this call + for (int i = t; i < 3 * 256; i += MT_T) qs[MT_ACC + i] = 0; + } else { + int v = 0; + if (PASS == 1) { // pass 0: one row per CTA +#pragma unroll 8 + for (unsigned r = 0; r < gridDim.x; ++r) v += qs[r * 256 + 255 - t]; + } else { + prefix = (uint32_t) qs[MT_STATE + 2 * (PASS - 1)]; + above = qs[MT_STATE + 2 * (PASS - 1) + 1]; + v = qs[MT_ACC + (PASS - 2) * 256 + 255 - t]; + } + mt_choose(v, m.width, 32 - 8 * PASS, prefix, above, s_w, s_ex, &s_i); + if (blockIdx.x == 0 && t == 0) { + qs[MT_STATE + 2 * PASS] = (int) prefix; + qs[MT_STATE + 2 * PASS + 1] = above; + } + } + __syncthreads(); + const int shift = 24 - 8 * PASS; + const uint32_t hmask = PASS == 0 ? 0u : (0xffffffffu << (shift + 8)); +#pragma unroll 1 + for (int j0 = 0; j0 < m.rpw; j0 += MT_U) { // uniform over the warp: the ballots see all its lanes + if (j0 > 0) mt_load(m, sc, j0, key); +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + if (j0 + u >= m.rpw) break; + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + const int bin = (b < m.hi && (key[u] & hmask) == prefix) ? (int) ((key[u] >> shift) & 255) : -1; + // the scores share their top bits: the lanes on the first lane's bin in one atomic (no __match_any_sync on 6.x) + const unsigned pend = __ballot_sync(0xffffffffu, bin >= 0); + if (pend) { + const int leader = __ffs(pend) - 1; + const int lb = __shfl_sync(0xffffffffu, bin, leader); + const unsigned same = __ballot_sync(0xffffffffu, bin == lb); + if (lane == leader) atomicAdd(&h[warp][lb], __popc(same) * R); + else if (bin >= 0 && bin != lb) atomicAdd(&h[warp][bin], R); + } + if (bin >= 0 && b == m.n_bid) atomicAdd(&h[warp][bin], m.wtail - R); + } + } + __syncthreads(); + int sum = 0; +#pragma unroll + for (int w = 0; w < MT_W; ++w) sum += h[w][t]; + if (PASS == 0) qs[blockIdx.x * 256 + t] = sum; + else if (sum != 0) atomicAdd(&qs[MT_ACC + (PASS - 1) * 256 + t], sum); +} + +// digit 3 (the threshold), then each warp's cells above it and at it +__global__ void __launch_bounds__(MT_T) block_topk_multi_count_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, + int64_t max_blocks, int32_t* __restrict__ scratch) { + __shared__ int s_w[MT_W], s_ex[256], s_i; + const MtQuery m = mt_query(steps); + if (m.all) return; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float* sc = scores + (int64_t) blockIdx.y * max_blocks; + uint32_t key[MT_U]; + mt_load(m, sc, 0, key); + int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS; + uint32_t prefix = (uint32_t) qs[MT_STATE + 6]; + int above = qs[MT_STATE + 7]; + mt_choose(qs[MT_ACC + 2 * 256 + 255 - t], m.width, 0, prefix, above, s_w, s_ex, &s_i); + if (blockIdx.x == 0 && t == 0) { + qs[MT_STATE + 8] = (int) prefix; + qs[MT_STATE + 9] = above; + } + const uint32_t thr = prefix; + int gt = 0, eq = 0; +#pragma unroll 1 + for (int j0 = 0; j0 < m.rpw; j0 += MT_U) { + if (j0 > 0) mt_load(m, sc, j0, key); +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + if (j0 + u >= m.rpw || b >= m.hi) continue; + const int w = b == m.n_bid ? m.wtail : R; + if (key[u] > thr) gt += w; + else if (key[u] == thr) eq += w; + } + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + gt += __shfl_xor_sync(0xffffffffu, gt, o); + eq += __shfl_xor_sync(0xffffffffu, eq, o); + } + if (lane == 0) { + qs[MT_CNT + 2 * (blockIdx.x * MT_W + warp)] = gt; + qs[MT_CNT + 2 * (blockIdx.x * MT_W + warp) + 1] = eq; + } +} + +// the cells, ascending: a warp's first cell goes after the cells the CTAs and warps before it selected +__global__ void __launch_bounds__(MT_T) block_topk_multi_emit_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, + int64_t max_blocks, int64_t cap, + int32_t* __restrict__ ids, + const int32_t* __restrict__ scratch) { + __shared__ unsigned long long s_w[MT_W]; + const MtQuery m = mt_query(steps); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + int32_t* out = ids + (int64_t) blockIdx.y * cap; + if (m.all) { // the identity, split over the CTAs + for (int64_t j = (int64_t) blockIdx.x * MT_T + t; j < m.n_kv; j += (int64_t) gridDim.x * MT_T) out[j] = (int32_t) j; + return; + } + const float* sc = scores + (int64_t) blockIdx.y * max_blocks; + uint32_t key[MT_U]; + mt_load(m, sc, 0, key); + const int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS; + const uint32_t thr = (uint32_t) qs[MT_STATE + 8]; + const int eq_budget = (int) (m.width - qs[MT_STATE + 9]); // cells at thr that fit, lowest index first + // the cells of the warps before this one: the earlier CTAs' (one warp count per thread), then this CTA's + unsigned long long c = 0; + if (t < (int) blockIdx.x * MT_W) + c = (unsigned long long) (unsigned) qs[MT_CNT + 2 * t] | ((unsigned long long) (unsigned) qs[MT_CNT + 2 * t + 1] << 32); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) c += __shfl_xor_sync(0xffffffffu, c, o); + if (lane == 0) s_w[warp] = c; + __syncthreads(); + unsigned long long before = 0; + for (int w = 0; w < MT_W; ++w) before += s_w[w]; + for (int w = 0; w < warp; ++w) { + const int i = (int) blockIdx.x * MT_W + w; + before += (unsigned long long) (unsigned) qs[MT_CNT + 2 * i] | + ((unsigned long long) (unsigned) qs[MT_CNT + 2 * i + 1] << 32); + } + const int gt_before = (int) (before & 0xffffffffu), eq_before = (int) (before >> 32); + int run_sel = gt_before + (eq_before < eq_budget ? eq_before : eq_budget), run_eq = eq_before; +#pragma unroll 1 + for (int j0 = 0; j0 < m.rpw; j0 += MT_U) { + if (j0 > 0) mt_load(m, sc, j0, key); +#pragma unroll + for (int u = 0; u < MT_U; ++u) { + if (j0 + u >= m.rpw) break; + const int64_t b = m.row0 + 32 * (j0 + u) + lane; + const int w = b < m.hi ? (b == m.n_bid ? m.wtail : R) : 0; + const uint32_t k = key[u]; + const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0; + if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue; // a row without a selected block + int pe = my_eq; // tied cells up to and with this lane +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, pe, o); + if (lane >= o) pe += y; + } + const int left = eq_budget - (run_eq + pe - my_eq); + const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left); + const int my_sel = my_gt + take; + int ps = my_sel; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, ps, o); + if (lane >= o) ps += y; + } + int32_t* dst = out + run_sel + ps - my_sel; + for (int cc = 0; cc < my_sel; ++cc) dst[cc] = (int32_t) (b * R + cc); + run_eq += __shfl_sync(0xffffffffu, pe, 31); + run_sel += __shfl_sync(0xffffffffu, ps, 31); + } + } +} +#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60 } // namespace bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead, const float* q_idx, @@ -2584,4 +2963,153 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64 if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); } } +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// STRATA_SCORES_DX: 0 off, 1 on for any CUDA card; unset: on for compute capability 6.x (block_scores_dx_kernel). +// `sms`: the device's multiprocessors (the grid: as many CTAs as fit on each). +static bool scores_dx_device(int& sms) { + static const int env = [] { + const char* v = std::getenv("STRATA_SCORES_DX"); + return v == nullptr || *v == '\0' ? -1 : std::atoi(v); + }(); + if (env == 0) return false; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return false; } + static thread_local int cached_device = -1, cached_sms = 0; + static thread_local bool pascal = false; + if (dev != cached_device) { + int major = 0; + pascal = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + strata::cc_major_of(major) == 6; + if (cudaDeviceGetAttribute(&cached_sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) cached_sms = 0; + cudaGetLastError(); + cached_device = dev; + } + sms = cached_sms; + return sms > 0 && (env > 0 || pascal); +} + +template +static void scores_dx_launch(const float* pooled, const float* q_idx, const int32_t* steps, int64_t max_blocks, + float* scores, int sms, cudaStream_t st) { + const size_t smem = (size_t) (DX_NB * DX_KS + NQ * IDX_HEADS * IDX_DIM + NQ * IDX_HEADS * DX_NB) * sizeof(float); + static thread_local int per_sm[64][9] = {}; // CTAs per multiprocessor, by device and NQ + int dev = 0; + cudaGetDevice(&dev); + int& occ = per_sm[dev & 63][NQ]; + if (occ == 0 && (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, block_scores_dx_kernel, DX_T, smem) != + cudaSuccess || occ < 1)) { + cudaGetLastError(); + occ = 2; + } + const int64_t tiles = (max_blocks + DX_NB - 1) / DX_NB, want = (int64_t) occ * sms; + const unsigned grid = (unsigned) (want < tiles ? want : tiles); + block_scores_dx_kernel<<>>(pooled, q_idx, steps, max_blocks, scores); +} + +static bool qsa_block_scores_dx(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, + int64_t nq, int64_t max_blocks, float* scores, void* stream) { + int sms = 0; + if (nq < 1 || nq > MQ || !scores_dx_device(sms)) return false; + const cudaStream_t st = (cudaStream_t) stream; + switch (nq) { + case 1: scores_dx_launch<1>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 2: scores_dx_launch<2>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 3: scores_dx_launch<3>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 4: scores_dx_launch<4>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 5: scores_dx_launch<5>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 6: scores_dx_launch<6>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + case 7: scores_dx_launch<7>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + default: scores_dx_launch<8>(pooled, q_idx, steps, max_blocks, scores, sms, st); break; + } + block_scores_tail_kernel<<<(unsigned) nq, 32, 0, st>>>(dead, q_idx, steps, max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (dx): %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} +#endif + +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// STRATA_TOPK_MULTI: 0 off, 1 on for any CUDA card and capacity; unset: on for compute capability 6.x past the register +// kernel's reach (GP100: 0.39 -> 0.04 ms per call at 300K cells; see block_topk_multi_hist_kernel) +static int topk_multi_mode() { + static const int env = [] { + const char* v = std::getenv("STRATA_TOPK_MULTI"); + return v == nullptr || *v == '\0' ? -1 : std::atoi(v); + }(); + if (env >= 0) return env != 0 ? 1 : 0; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return 0; } + static thread_local int cached_device = -1; + static thread_local int mode = 0; + if (dev != cached_device) { + int major = 0; + mode = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + strata::cc_major_of(major) == 6 ? 2 : 0; + cudaGetLastError(); + cached_device = dev; + } + return mode; +} + +static bool qsa_block_topk_multi(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + int32_t* ids, void* stream, int32_t* scratch) { + // CTAs per query from the capacity (the grid is fixed in a captured graph; each CTA's share follows n_bid): one per + // 2,048 blocks, at most MT_NMAX. STRATA_TOPK_MULTI_N: a fixed count (tests) + static const int n_env = [] { const char* v = std::getenv("STRATA_TOPK_MULTI_N"); return v ? std::atoi(v) : 0; }(); + int64_t n = n_env > 0 ? n_env : (max_blocks + 2047) / 2048; + n = n < 1 ? 1 : n > MT_NMAX ? MT_NMAX : n; + const dim3 grid((unsigned) n, (unsigned) nq); + const cudaStream_t st = (cudaStream_t) stream; + block_topk_multi_hist_kernel<0><<>>(scores, steps, max_blocks, scratch); + block_topk_multi_hist_kernel<1><<>>(scores, steps, max_blocks, scratch); + block_topk_multi_hist_kernel<2><<>>(scores, steps, max_blocks, scratch); + block_topk_multi_hist_kernel<3><<>>(scores, steps, max_blocks, scratch); + block_topk_multi_count_kernel<<>>(scores, steps, max_blocks, scratch); + block_topk_multi_emit_kernel<<>>(scores, steps, max_blocks, cap, ids, scratch); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk multi: %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} +#endif + +// ---- STRATA_SELECT_LONG (verify.cpp, opt-in): the decode select past ~64K cells. Outside the SM60 build (and on HIP) +// these are the plain calls; the scratch is never asked for. +int64_t qsa_topk_multi_scratch_ints(int64_t nq) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + return (nq < MT_MAXQ ? nq : MT_MAXQ) * (int64_t) MT_Q_INTS; +#else + (void) nq; + return 0; +#endif +} + +void qsa_block_topk_long(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks, int32_t* multi_scratch) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + // several CTAs per query through the caller's scratch (decode calls: no active count, a few queries) + static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr; + if (nq > 0 && multi_scratch != nullptr && !old && active_blocks <= 0 && nq <= MT_MAXQ && s.idx_block == R && + cap >= qsa_selection_width(kTopkMaxCells, s)) { + const int mode = topk_multi_mode(); + if ((mode == 1 || (mode == 2 && max_blocks > (int64_t) TK_T * TK_PER)) && + qsa_block_topk_multi(scores, steps, nq, max_blocks, cap, ids, stream, multi_scratch)) + return; + } +#else + (void) multi_scratch; +#endif + qsa_block_topk(scores, steps, nq, max_blocks, cap, s, ids, stream, active_blocks); +} + +void qsa_block_scores_long(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + if (nq > 0 && s.idx_dim == IDX_DIM && s.idx_n_head == IDX_HEADS && s.idx_block == R && scores_multi_on() && + nq <= MQ && active_blocks <= 0 && + qsa_block_scores_dx(pooled, dead, q_idx, steps, nq, max_blocks, scores, stream)) + return; +#endif + qsa_block_scores(pooled, dead, q_idx, steps, nq, max_blocks, s, scores, stream, active_blocks); +} + } // namespace strata::kernels diff --git a/src/kernels/iq_nibble_parity.cpp b/src/kernels/iq_nibble_parity.cpp new file mode 100644 index 00000000..40196bdd --- /dev/null +++ b/src/kernels/iq_nibble_parity.cpp @@ -0,0 +1,954 @@ +// src/kernels/iq_nibble_parity.cpp - STRATA_EXPERT_NIBBLE (strata/core/expert_nibble.hpp): the 4-bit gate/up expert +// slots against the production kernels and the GGUF blobs, bit for bit. +// +// build/iq_nibble_parity --header the host half of expert_nibble.hpp (no GPU) +// build/iq_nibble_parity [ ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512] +// [--plans 8] [--synthetic 64] [--no-ggml] [--negative] +// build/iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml] no model, no shard +// +// Each model (any shard of it; its other shards are opened beside it) gives `--layers-per-fmt` layers of each +// converted format (IQ2_S, IQ3_XXS, IQ3_S; or `--layers`), `--ne` experts each, read from the GGUF tensors into the +// blob the pack holds (gate rows, up rows, down rows). Per layer: +// (1) nibble::transcode, 64 blobs a batch as the startup fill runs it: 0 items that do not round-trip; +// (2) every gate/up byte of a slot is written (8 slots transcoded again into another pre-fill byte); +// (3) nibble::hash_slots against nibble::hash_host on every slot read back (and a flipped byte must change it); +// (4) the host codec on every item: decode_item then encode_item gives the code back; +// (5) ggml's reference dequantizer (to_float) on every GGUF row against the weight the 4-bit slot gives through +// dequantize_row_iq2_s / _iq3_xxs / _iq3_s's own expression (code, scale byte, fp16 d): every weight, bit for bit; +// (6) nibble::check_gguf (the start-up check: the GGUF blocks rebuilt from every slot against the blob): 0 words +// differ; nibble::gather_gguf (the prompt path's MMQ gather) in groups of 16 and of 1..15 from a later first +// position: the rebuilt [gate | up] and the down rows byte for byte the blob's, the MMQ tail after the group zero; +// (7) native_expert_grouped on the converted slots (native_expert_layout_nib) against the same call on the GGUF +// blobs (native_expert_layout): hq and out byte for byte for every entry, and gate / up where the reference +// layout writes them - in the card's default layout (a GP100: mode 8, whose gate/up kernel writes hq) and in the +// CUDA layout (native_expert_set_mode(0)), each with native_grouped_set_v1 off and on (h too, in mode 0 + v1); +// top-10 routing T = 1..6 at 0% and 50% sharing (`--plans` each), one group of T entries (G = 1) per T, plans of +// groups with 0..11 entries (more than one GRP_NC pass, empty groups); grid_groups 0 (cap) and 4 (the PCIe +// call's stride); the default kernel per format and each skeleton forced (S, P); q8_1 activations random, all +// +127, all -127 and alternating +-127 (the sum of x at its extremes, +-4064). +// `--synthetic N`: per format, N experts whose gate/up blocks are random bytes (every grid index, sign byte and scale +// nibble the format has; the coverage is counted and must be complete) and whose fp16 d cycle through +-the smallest +// subnormal, +-65504, +-1, the smallest normal and two ordinary values; checks (1)-(7) on them. +// `--synthetic-only`: the synthetic experts alone, for every gate/up format x both down types (IQ4_NL, Q2_0), the down rows +// random bytes with ordinary fp16 scales: checks (1)-(7) with no model file (a GP100 is still needed). +// `--negative`: the control - one code byte per slot changed after the transcode; (6) and (7) must then report differences. +// Exit 0 when every check is equal; 1 otherwise; 2 on a usage or setup error. A build without STRATA_EXPERT_NIBBLE_BUILT +// (the CUDA build with STRATA_EXPERIMENTAL_SM60) has no 4-bit kernels: --header only. +#include "strata/artifact/gguf_reader.hpp" +#include "strata/core/expert_nibble.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/iq_kernels.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace nib = strata::core::nibble; +namespace K = strata::kernels; +namespace cpu = strata::kernels::cpu; + +int fails = 0; +void expect(bool ok, const char* what) { + if (!ok) { + std::printf("FAIL %s\n", what); + ++fails; + } +} + +// Every value the format holds at every one of an item's 32 positions (the other positions cycle through the set), +// encoded, decoded and compared; and one value outside the set must be refused. +void round_trip(int fmt, const std::vector& set, int8_t outside) { + int8_t g[32], back[32]; + uint32_t q[4]; + for (size_t shift = 0; shift < set.size(); ++shift) { + for (int i = 0; i < 32; ++i) g[i] = set[(shift + (size_t) i) % set.size()]; + const bool ok = nib::encode_item(fmt, g, q); + nib::decode_item(fmt, q, back); + expect(ok && std::memcmp(g, back, 32) == 0, (std::string(nib::fmt_name(fmt)) + " round trip").c_str()); + } + for (int i = 0; i < 32; ++i) g[i] = set[0]; + g[17] = outside; + expect(!nib::encode_item(fmt, g, q), (std::string(nib::fmt_name(fmt)) + " refuses a value outside the set").c_str()); +} + +int header_check() { + expect(nib::kGuBytes == 1766400 && nib::kScOff == 1638400 && nib::kDOff == 1740800, "layout sizes"); + expect(nib::code_off(nib::kNFf, 0) == nib::kUpCodesOff, "up rows' codes"); + expect(nib::slot_bytes_for(921600) % nib::kSlotAlign == 0, "slot alignment"); + round_trip(nib::kIQ2_S, { 8, 25, 43, -8, -25, -43 }, 9); + round_trip(nib::kIQ3_XXS, { 4, 12, 20, 28, 36, 44, 52, 62, -4, -12, -20, -28, -36, -44, -52, -62 }, 5); + std::vector s3; + for (int v = -15; v <= 15; v += 2) s3.push_back((int8_t) v); + round_trip(nib::kIQ3_S, s3, 2); + // IQ2_S's nibble is the decode kernel's PRMT selector into {8,25,43,0} {-8,-25,-43,0} + { + int8_t g[32] = {}, back[32]; + uint32_t q[4]; + for (int i = 0; i < 32; ++i) g[i] = (int8_t) (i % 2 ? -25 : 43); + nib::encode_item(nib::kIQ2_S, g, q); + expect((q[0] & 0xFu) == 2u && (q[0] >> 4 & 0xFu) == 5u, "IQ2_S selector nibbles"); + nib::decode_item(nib::kIQ2_S, q, back); + expect(std::memcmp(g, back, 32) == 0, "IQ2_S selector decode"); + } + expect(nib::gu_skeleton(nib::kIQ2_S) == nib::kSkelP && nib::gu_skeleton(nib::kIQ3_XXS) == nib::kSkelS && + nib::gu_skeleton(nib::kIQ3_S) == nib::kSkelS, + "kernel table"); + { + const uint8_t b[6] = { 1, 2, 3, 4, 5, 6 }; + const uint64_t h = nib::hash_host(b, 6); + const uint64_t want = (uint64_t) (0x04030201u ^ 0u) * nib::kHashMul + (uint64_t) (0x00000605u ^ 1u) * nib::kHashMul; + expect(h == want, "hash_host"); + } + std::printf("%s (%d failures)\n", fails == 0 ? "header OK" : "header FAILED", fails); + return fails == 0 ? 0 : 1; +} + +// ------------------------------------------------------------------------------------------------ the GPU parity + +#define CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); \ + std::exit(2); \ + } \ + } while (0) + +struct Q81 { // block_q8_1: fp16 d, fp16 s (= d * sum), 32 int8 + uint16_t d, s; + int8_t qs[32]; +}; +static_assert(sizeof(Q81) == 36, "block_q8_1"); + +constexpr int64_t kEmbd = nib::kNEmbd, kFf = nib::kNFf; +constexpr int kTok = 12; // activation rows: T <= 6 for routing plans, 12 for the 0..11-entry plans + +// One layer: `ne` GGUF blobs (gate rows | up rows | down rows, as the pack and the host arena hold them) on the host +// and the device, and their converted slots. +struct Layer { + std::string tag; + int layer = -1; + cpu::NativeFmt f; + nib::LayerVram V; + K::NativeExpertLayout Lr, Ln; + int ne = 0; + std::vector host; // ne x f.bytes + uint8_t* raw = nullptr; // device copy of `host` + uint8_t* slots = nullptr; // ne x V.slot_bytes (the last one only `hashed` long: nothing past it is readable) +}; + +bool layer_fmt(const strata::GgufModel& m, int l, int& gt, int& dt) { + const auto* g = m.find("blk." + std::to_string(l) + ".ffn_gate_exps.weight"); + const auto* d = m.find("blk." + std::to_string(l) + ".ffn_down_exps.weight"); + if (g == nullptr || d == nullptr) return false; + gt = (int) g->type; + dt = (int) d->type; + return true; +} + +// The blobs of experts [0, ne) of layer l. +bool read_layer(const strata::GgufModel& m, int l, int ne, Layer& Y) { + const char* roles[3] = { "gate", "up", "down" }; + const strata::TensorInfo* t[3] = {}; + size_t sh[3] = {}; + for (int r = 0; r < 3; ++r) t[r] = m.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &sh[r]); + if (!t[0] || !t[1] || !t[2]) return false; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, kEmbd, kFf, Y.f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); + return false; + } + const size_t gu_role = Y.f.up_off, dn_role = Y.f.bytes - Y.f.down_off; + Y.layer = l; + Y.ne = ne; + Y.host.resize((size_t) ne * Y.f.bytes); + const uint8_t* G = m.shard(sh[0]).tensor_data(*t[0]); + const uint8_t* U = m.shard(sh[1]).tensor_data(*t[1]); + const uint8_t* D = m.shard(sh[2]).tensor_data(*t[2]); + for (int e = 0; e < ne; ++e) { + uint8_t* b = Y.host.data() + (size_t) e * Y.f.bytes; + std::memcpy(b, G + (size_t) e * gu_role, gu_role); + std::memcpy(b + Y.f.up_off, U + (size_t) e * gu_role, gu_role); + std::memcpy(b + Y.f.down_off, D + (size_t) e * dn_role, dn_role); + } + return true; +} + +// check (6): nibble::check_gguf over every slot (the start-up check), and nibble::gather_gguf (the prompt path's gather) +// in groups of 16 and from later first positions, against the blobs byte for byte (and the MMQ tail zeroed). +// `expect_diff`: the negative control (only the report says so: the counts must then be > 0). +long long gguf_parity(const Layer& Y, const unsigned long long* dp, bool expect_diff) { + long long bad_total = 0; + const int ne = Y.ne; + unsigned long long* dbad = nullptr; + CK(cudaMalloc(&dbad, 8)); + CK(cudaMemset(dbad, 0, 8)); + for (int e0 = 0; e0 < ne; e0 += 64) { + const int rc = nib::check_gguf(Y.V, Y.raw + (size_t) e0 * Y.V.raw_bytes, std::min(64, ne - e0), dp + e0, dbad, nullptr); + if (rc != 0) { + std::printf("check_gguf: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + } + CK(cudaDeviceSynchronize()); + unsigned long long cbad = 0; + CK(cudaMemcpy(&cbad, dbad, 8, cudaMemcpyDeviceToHost)); + CK(cudaFree(dbad)); + // the gathers: MMQ's group buffers (16 experts of [gate | up] and of down, each followed by the 4096-byte tail) + const uint64_t gub = (uint64_t) nib::kRows * Y.f.gu_row, db = Y.V.down_bytes, zero = 4096; + uint8_t *ggu = nullptr, *gd = nullptr; + CK(cudaMalloc(&ggu, 16 * gub + zero)); + CK(cudaMalloc(&gd, 16 * db + zero)); + std::vector hgu(16 * gub + zero), hd(16 * db + zero); + std::vector hp(ne); + CK(cudaMemcpy(hp.data(), dp, (size_t) ne * 8, cudaMemcpyDeviceToHost)); + long long gbad = 0, groups = 0; + for (int e0 = 0; e0 < ne; e0 += 16) { + const int first = (e0 / 16) % 4 == 3 ? 1 + (e0 / 64) % 15 : 0; // every 4th group from a later position + const int n = std::min(16, ne - e0); + if (first >= n) continue; + const uint8_t* sl[16] = {}; + for (int q = first; q < n; ++q) sl[q] = (const uint8_t*) (uintptr_t) hp[(size_t) (e0 + q)]; + CK(cudaMemset(ggu, 0xA5, 16 * gub + zero)); + CK(cudaMemset(gd, 0xA5, 16 * db + zero)); + const int rc = nib::gather_gguf(Y.V, sl, first, n, ggu, gub, gd, db, zero, nullptr); + if (rc != 0) { + std::printf("gather_gguf: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + CK(cudaDeviceSynchronize()); + CK(cudaMemcpy(hgu.data(), ggu, hgu.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(hd.data(), gd, hd.size(), cudaMemcpyDeviceToHost)); + for (int q = first; q < n; ++q) { + const uint8_t* raw = Y.host.data() + (size_t) (e0 + q) * Y.f.bytes; + gbad += std::memcmp(hgu.data() + (size_t) q * gub, raw, gub) != 0; + gbad += std::memcmp(hd.data() + (size_t) q * db, raw + Y.f.down_off, db) != 0; + } + for (uint64_t i = 0; i < zero; ++i) gbad += hgu[(size_t) n * gub + i] != 0 || hd[(size_t) n * db + i] != 0 ? 1 : 0; + ++groups; + } + CK(cudaFree(ggu)); + CK(cudaFree(gd)); + std::printf(" check_gguf: %llu words differ; gather_gguf (%lld groups, the tail zeroed): %lld matrices or tail bytes differ%s\n", + cbad, groups, gbad, expect_diff ? " (NEGATIVE CONTROL: both must be > 0)" : ""); + bad_total += (long long) cbad + gbad; // the negative control fails the run, as (7) does: it must + return bad_total; +} + +// Plans the layer, uploads the blobs, transcodes them into slots (checks 1-6). +long long convert(Layer& Y, bool ggml_check) { + long long bad_total = 0; + nib::Config c; + c.on = true; + Y.V = nib::plan_layer(Y.layer, Y.f, c); + Y.Lr = K::native_expert_layout(Y.f.gu_type, Y.f.d_type, kEmbd, kFf); + Y.Ln = K::native_expert_layout_nib(Y.f.gu_type, Y.f.d_type, kEmbd, kFf); + if (!Y.V.on || Y.V.slot_bytes != Y.Ln.bytes || Y.V.down_off != Y.Ln.down_off || Y.Lr.bytes != Y.f.bytes) { + std::printf("layer %d: plan_layer / native_expert_layout_nib disagree (on %d, slot %llu vs %zu)\n", Y.layer, + (int) Y.V.on, (unsigned long long) Y.V.slot_bytes, Y.Ln.bytes); + return 1; + } + const int ne = Y.ne; + const size_t slots_bytes = (size_t) (ne - 1) * Y.V.slot_bytes + Y.V.hashed; + CK(cudaMalloc(&Y.raw, Y.host.size())); + CK(cudaMemcpy(Y.raw, Y.host.data(), Y.host.size(), cudaMemcpyHostToDevice)); + CK(cudaMalloc(&Y.slots, slots_bytes)); + CK(cudaMemset(Y.slots, 0xA5, slots_bytes)); + std::vector hp(ne); + for (int e = 0; e < ne; ++e) hp[e] = (unsigned long long) (Y.slots + (size_t) e * Y.V.slot_bytes); + unsigned long long *dp = nullptr, *dbad = nullptr, *dhash = nullptr; + CK(cudaMalloc(&dp, (size_t) ne * 8)); + CK(cudaMalloc(&dbad, 8)); + CK(cudaMalloc(&dhash, (size_t) ne * 8)); + CK(cudaMemcpy(dp, hp.data(), (size_t) ne * 8, cudaMemcpyHostToDevice)); + CK(cudaMemset(dbad, 0, 8)); + // (1) the startup fill's batches: 64 blobs at a time, then the down rows behind the codes + for (int e0 = 0; e0 < ne; e0 += 64) { + const int n = std::min(64, ne - e0); + const int rc = nib::transcode(Y.V, Y.raw + (size_t) e0 * Y.V.raw_bytes, n, dp + e0, dbad, nullptr); + if (rc != 0) { + std::printf("transcode: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + } + for (int e = 0; e < ne; ++e) + CK(cudaMemcpyAsync(Y.slots + (size_t) e * Y.V.slot_bytes + nib::kDownOff, + Y.raw + (size_t) e * Y.V.raw_bytes + Y.V.raw_down_off, Y.V.down_bytes, cudaMemcpyDeviceToDevice)); + CK(cudaDeviceSynchronize()); + unsigned long long bad = 0; + CK(cudaMemcpy(&bad, dbad, 8, cudaMemcpyDeviceToHost)); + std::printf("%s layer %2d %-7s / down %-6s: %d experts, blob %zu B, slot %llu B (x%.3f); transcode: %llu of %lld items do not round-trip\n", + Y.tag.c_str(), Y.layer, nib::fmt_name(Y.f.gu_type), ggml_type_name((ggml_type) Y.f.d_type), ne, Y.f.bytes, + (unsigned long long) Y.V.slot_bytes, (double) Y.V.slot_bytes / (double) Y.f.bytes, bad, + (long long) ne * nib::kRows * nib::kItems); + bad_total += (long long) bad; + bad_total += gguf_parity(Y, dp, false); + // (2) every gate/up byte written: the first 8 blobs again into slots pre-filled with 0x5A + { + const int n8 = std::min(8, ne); + uint8_t* alt = nullptr; + unsigned long long* ap = nullptr; + CK(cudaMalloc(&alt, (size_t) n8 * Y.V.slot_bytes)); + CK(cudaMemset(alt, 0x5A, (size_t) n8 * Y.V.slot_bytes)); + std::vector ah(n8); + for (int e = 0; e < n8; ++e) ah[e] = (unsigned long long) (alt + (size_t) e * Y.V.slot_bytes); + CK(cudaMalloc(&ap, (size_t) n8 * 8)); + CK(cudaMemcpy(ap, ah.data(), (size_t) n8 * 8, cudaMemcpyHostToDevice)); + CK(cudaMemset(dbad, 0, 8)); + if (nib::transcode(Y.V, Y.raw, n8, ap, dbad, nullptr) != 0) std::exit(2); + CK(cudaDeviceSynchronize()); + std::vector a(nib::kGuBytes), b(nib::kGuBytes); + long long wbad = 0; + for (int e = 0; e < n8; ++e) { + CK(cudaMemcpy(a.data(), Y.slots + (size_t) e * Y.V.slot_bytes, nib::kGuBytes, cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(b.data(), alt + (size_t) e * Y.V.slot_bytes, nib::kGuBytes, cudaMemcpyDeviceToHost)); + wbad += std::memcmp(a.data(), b.data(), nib::kGuBytes) != 0; + } + std::printf(" every gate/up byte written (0xA5 vs 0x5A pre-fill, %d slots): %lld differ\n", n8, wbad); + bad_total += wbad; + CK(cudaFree(alt)); + CK(cudaFree(ap)); + } + // (3) the device hash of every slot against the host reference over the slot read back + const int rc = nib::hash_slots(Y.V, dp, ne, dhash, nullptr); + if (rc != 0) { + std::printf("hash_slots: %s\n", cudaGetErrorString((cudaError_t) rc)); + std::exit(2); + } + std::vector hh(ne); + CK(cudaMemcpy(hh.data(), dhash, (size_t) ne * 8, cudaMemcpyDeviceToHost)); + std::vector sl(slots_bytes); + CK(cudaMemcpy(sl.data(), Y.slots, slots_bytes, cudaMemcpyDeviceToHost)); + std::atomic hbad{ 0 }, cbad{ 0 }, dnbad{ 0 }, gbad{ 0 }; + std::atomic grows{ 0 }; + std::string first_ggml; + std::atomic first_set{ 0 }; + const ggml_type_traits* tr = ggml_get_type_traits((ggml_type) Y.f.gu_type); + const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + std::vector th; + for (unsigned ti = 0; ti < nth; ++ti) + th.emplace_back([&, ti]() { + std::vector ref((size_t) kEmbd), got((size_t) kEmbd); + for (int e = (int) ti; e < ne; e += (int) nth) { + const uint8_t* s = sl.data() + (size_t) e * Y.V.slot_bytes; + const uint8_t* raw = Y.host.data() + (size_t) e * Y.f.bytes; + hbad += nib::hash_host(s, Y.V.hashed) != hh[e]; + if (e == 0) { // the hash sees every byte: one flipped must change it + std::vector t2(s, s + Y.V.hashed); + t2[Y.V.hashed - 1] ^= 1; + hbad += nib::hash_host(t2.data(), Y.V.hashed) == hh[e]; + } + dnbad += std::memcmp(s + nib::kDownOff, raw + Y.V.raw_down_off, Y.V.down_bytes) != 0; + for (int64_t r = 0; r < nib::kRows; ++r) { + // (4) the host codec + for (int64_t k = 0; k < nib::kItems; ++k) { + uint32_t q[4], q2[4]; + int8_t g[32]; + std::memcpy(q, s + nib::code_off(r, k), 16); + nib::decode_item(Y.f.gu_type, q, g); + const bool ok = nib::encode_item(Y.f.gu_type, g, q2); + cbad += !ok || std::memcmp(q, q2, 16) != 0; + } + if (!ggml_check) continue; + // (5) ggml's dequantizer of the GGUF row against the slot's weights through its expression + const uint8_t* row = raw + (r < kFf ? (size_t) r * Y.f.gu_row : Y.f.up_off + (size_t) (r - kFf) * Y.f.gu_row); + tr->to_float(row, ref.data(), kEmbd); + for (int64_t k = 0; k < nib::kItems; ++k) { + uint32_t q[4]; + std::memcpy(q, s + nib::code_off(r, k), 16); + int8_t gv[32]; + nib::decode_item(Y.f.gu_type, q, gv); + const int sc = s[nib::scale_off(r, k)]; + ggml_fp16_t dh; + std::memcpy(&dh, s + nib::d_off(r, k / 8), sizeof dh); + const float d = ggml_fp16_to_fp32(dh); + for (int j = 0; j < 32; ++j) { + const float db = Y.f.gu_type == nib::kIQ2_S ? d * (0.5f + ((j < 16 ? sc : sc >> 4) & 0xf)) * 0.25f + : Y.f.gu_type == nib::kIQ3_XXS ? d * (0.5f + sc) * 0.5f + : d * sc; + const int a = gv[j] < 0 ? -(int) gv[j] : (int) gv[j]; + float v = db * a; + if (gv[j] < 0) v = -v; + got[(size_t) (k * 32 + j)] = v; + } + } + ++grows; + if (std::memcmp(ref.data(), got.data(), ref.size() * sizeof(float)) != 0) { + ++gbad; + if (first_set.exchange(1) == 0) { + size_t cc = 0; + while (cc < ref.size() && std::memcmp(&ref[cc], &got[cc], 4) == 0) ++cc; + char buf[200]; + std::snprintf(buf, sizeof buf, "expert %d row %lld column %zu: slot %.9g, GGUF %.9g", e, + (long long) r, cc, (double) got[cc], (double) ref[cc]); + first_ggml = buf; + } + } + } + } + }); + for (auto& t : th) t.join(); + std::printf(" hash_slots vs hash_host: %lld of %d slots differ (+1 flipped-byte check); down rows: %lld of %d slots differ;" + " host codec: %lld of %lld items differ\n", + hbad.load(), ne, dnbad.load(), ne, cbad.load(), (long long) ne * nib::kRows * nib::kItems); + if (ggml_check) + std::printf(" ggml to_float of the GGUF rows vs the slot's weights: %lld of %lld rows differ%s%s\n", gbad.load(), + grows.load(), first_ggml.empty() ? "" : "; first: ", first_ggml.c_str()); + bad_total += hbad + dnbad + cbad + gbad; + CK(cudaFree(dp)); + CK(cudaFree(dbad)); + CK(cudaFree(dhash)); + return bad_total; +} + +// ---- plans: synthetic top-10 routing and resident_plan_kernel's grouping (groups by first appearance) +struct Plan { + int ng = 0, ne = 0, ntok = 0, maxn = 0; + std::vector gid, start, tok, dst; +}; + +void make_routing(std::mt19937& rng, int NE, int T, int share_pct, std::vector& ids) { + ids.clear(); + std::vector prev, cur; + for (int t = 0; t < T; ++t) { + cur.clear(); + const bool sh = t > 0 && share_pct > 0; + if (sh) { + std::vector p = prev; + std::shuffle(p.begin(), p.end(), rng); + cur.assign(p.begin(), p.begin() + 10 * share_pct / 100); + } + while ((int) cur.size() < 10) { + const int e = (int) (rng() % (unsigned) NE); + if (std::find(cur.begin(), cur.end(), e) != cur.end()) continue; + if (sh && std::find(prev.begin(), prev.end(), e) != prev.end()) continue; + cur.push_back(e); + } + std::shuffle(cur.begin(), cur.end(), rng); + ids.insert(ids.end(), cur.begin(), cur.end()); + prev = cur; + } +} + +Plan build_plan(const std::vector& ids) { + const int n = (int) ids.size(); + Plan p; + std::vector first(n), cnt, grp_of(n, -1); + for (int j = 0; j < n; ++j) { + int f = j; + for (int i = 0; i < j; ++i) + if (ids[i] == ids[j]) { f = i; break; } + first[j] = f; + } + for (int j = 0; j < n; ++j) + if (first[j] == j) { + grp_of[j] = p.ng++; + p.gid.push_back(ids[j]); + cnt.push_back(0); + } + for (int j = 0; j < n; ++j) cnt[grp_of[first[j]]]++; + p.start.assign(p.ng + 1, 0); + int acc = 0; + for (int g = 0; g < p.ng; ++g) { + p.start[g] = acc; + acc += cnt[g]; + p.maxn = std::max(p.maxn, cnt[g]); + } + p.start[p.ng] = acc; + p.tok.assign(n, 0); + p.dst.assign(n, 0); + std::vector fill(p.ng, 0); + for (int j = 0; j < n; ++j) { + const int g = grp_of[first[j]]; + const int at = p.start[g] + fill[g]++; + p.tok[at] = j / 10; + p.dst[at] = j; + } + p.ne = n; + p.ntok = n / 10; + return p; +} + +// one group of T entries (G = 1): an expert every token of the window routes to +Plan single_group(std::mt19937& rng, int NE, int T) { + Plan p; + p.ntok = T; + p.ng = 1; + p.gid.push_back((int) (rng() % (unsigned) NE)); + p.start = { 0, T }; + for (int t = 0; t < T; ++t) { + p.tok.push_back(t); + p.dst.push_back(T - 1 - t); + } + p.ne = T; + p.maxn = T; + return p; +} + +// groups of 0..11 entries (more than one GRP_NC pass, empty groups), 12 tokens, distinct tokens within a group, +// destination rows in any order +Plan synthetic_plan(std::mt19937& rng, int NE) { + Plan p; + p.ntok = kTok; + std::vector ids(NE); + for (int i = 0; i < NE; ++i) ids[i] = i; + std::shuffle(ids.begin(), ids.end(), rng); + const int sizes[] = { 3, 0, 11, 1, 5, 8, 0, 2, 4, 9, 6, 7, 10, 1 }; + int acc = 0; + for (int g = 0; g < (int) (sizeof sizes / sizeof sizes[0]); ++g) { + p.gid.push_back(ids[(size_t) g % ids.size()]); + p.start.push_back(acc); + std::vector toks(kTok); + for (int i = 0; i < kTok; ++i) toks[i] = i; + std::shuffle(toks.begin(), toks.end(), rng); + std::sort(toks.begin(), toks.begin() + sizes[g]); + for (int i = 0; i < sizes[g]; ++i) { + p.tok.push_back(toks[i]); + p.dst.push_back(acc + i); + } + acc += sizes[g]; + p.maxn = std::max(p.maxn, sizes[g]); + } + p.start.push_back(acc); + p.ng = (int) p.gid.size(); + p.ne = acc; + std::vector perm(acc); + for (int i = 0; i < acc; ++i) perm[i] = i; + std::shuffle(perm.begin(), perm.end(), rng); + for (int i = 0; i < acc; ++i) p.dst[i] = perm[i]; + return p; +} + +std::vector make_x(std::mt19937& rng) { + std::vector x((size_t) kTok * (kEmbd / 32)); + for (size_t i = 0; i < x.size(); ++i) { + Q81& b = x[i]; + const int tok = (int) (i / (kEmbd / 32)); + const float d = 0.002f + 0.03f * (float) (rng() % 1000) / 1000.0f; + int sum = 0; + for (int j = 0; j < 32; ++j) { + int q = (int) (rng() % 255) - 127; + if (tok == 1) q = 127; // the sum of x at its extremes (+-4064) + if (tok == 2) q = -127; + if (tok == 3 && (i % (kEmbd / 32)) < 8) q = (j & 1) ? 127 : -127; + b.qs[j] = (int8_t) q; + sum += q; + } + b.d = ggml_fp32_to_fp16(d); + b.s = ggml_fp32_to_fp16(d * (float) sum); + } + return x; +} + +struct Dev { + unsigned long long* ptr = nullptr; + int32_t *start = nullptr, *ng = nullptr, *tok = nullptr, *dst = nullptr; +}; +Dev upload(const Plan& p, const Layer& Y, bool conv) { + Dev d; + std::vector hp(std::max(1, p.ng)); + for (int g = 0; g < p.ng; ++g) + hp[g] = conv ? (unsigned long long) (Y.slots + (size_t) p.gid[g] * Y.V.slot_bytes) + : (unsigned long long) (Y.raw + (size_t) p.gid[g] * Y.f.bytes); + CK(cudaMalloc(&d.ptr, (size_t) std::max(1, p.ng) * 8)); + CK(cudaMalloc(&d.start, (size_t) (p.ng + 1) * 4)); + CK(cudaMalloc(&d.ng, 4)); + CK(cudaMalloc(&d.tok, (size_t) std::max(1, p.ne) * 4)); + CK(cudaMalloc(&d.dst, (size_t) std::max(1, p.ne) * 4)); + CK(cudaMemcpy(d.ptr, hp.data(), hp.size() * 8, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d.start, p.start.data(), (size_t) (p.ng + 1) * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d.ng, &p.ng, 4, cudaMemcpyHostToDevice)); + if (p.ne) { + CK(cudaMemcpy(d.tok, p.tok.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d.dst, p.dst.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + } + return d; +} +void release(Dev& d) { + CK(cudaFree(d.ptr)); + CK(cudaFree(d.start)); + CK(cudaFree(d.ng)); + CK(cudaFree(d.tok)); + CK(cudaFree(d.dst)); +} + +struct Outs { + std::vector gate, up, h, hq, out; +}; +// one native_expert_grouped call; scratch and out pre-filled with `fill` so an unwritten value shows +Outs run(const Layer& Y, const Plan& p, bool conv, const void* dx, void* scr, float* dout, int64_t gy, int mode, + uint8_t fill) { + // the window's capacity, as verify sizes it: T x 10 groups and entries (the blocks past the plan's groups idle) + const int64_t cap_e = std::max((int64_t) p.ntok * 10, std::max(p.ne, p.ng)), cap_g = cap_e; + Dev d = upload(p, Y, conv); + CK(cudaMemset(scr, fill, K::native_expert_scratch_bytes(cap_e, kFf))); + CK(cudaMemset(dout, fill, (size_t) cap_e * kEmbd * 4)); + K::native_expert_set_mode(mode, 0); + K::native_expert_grouped(conv ? Y.Ln : Y.Lr, d.ptr, d.start, d.ng, d.dst, d.tok, cap_g, cap_e, dx, scr, dout, nullptr, gy); + K::native_expert_set_mode(-1, 0); + CK(cudaGetLastError()); + CK(cudaDeviceSynchronize()); + const size_t f = (size_t) cap_e * kFf * 4, fa = (f + 255) & ~(size_t) 255; + Outs o; + o.gate.resize((size_t) p.ne * kFf * 4); + o.up.resize(o.gate.size()); + o.h.resize(o.gate.size()); + o.hq.resize((size_t) p.ne * (kFf / 32) * 36); + o.out.resize((size_t) p.ne * kEmbd * 4); + const uint8_t* s = (const uint8_t*) scr; + if (p.ne) { + CK(cudaMemcpy(o.gate.data(), s, o.gate.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(o.up.data(), s + fa, o.up.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(o.h.data(), s + 2 * fa, o.h.size(), cudaMemcpyDeviceToHost)); + CK(cudaMemcpy(o.hq.data(), s + 3 * fa, o.hq.size(), cudaMemcpyDeviceToHost)); + std::vector all((size_t) cap_e * kEmbd * 4); + CK(cudaMemcpy(all.data(), dout, all.size(), cudaMemcpyDeviceToHost)); + for (int e = 0; e < p.ne; ++e) + std::memcpy(o.out.data() + (size_t) e * kEmbd * 4, all.data() + (size_t) p.dst[e] * kEmbd * 4, kEmbd * 4); + } + release(d); + return o; +} + +long long diff_rows(const std::vector& a, const std::vector& b, size_t row) { + long long n = 0; + for (size_t i = 0; i + row <= a.size(); i += row) n += std::memcmp(a.data() + i, b.data() + i, row) != 0; + return n; +} + +// check (7): every plan, both grid strides, every kernel choice, both layouts, v1 off / on, against the GGUF blobs +// through the production kernels +long long grouped_parity(const Layer& Y, std::mt19937& rng, int plans, const void* dx, void* scr, float* dout) { + struct Case { + Plan p; + int T; + }; + std::vector cases; + for (int T = 1; T <= 6; ++T) { + for (int share : { 0, 50 }) + for (int i = 0; i < plans; ++i) { + std::vector ids; + make_routing(rng, Y.ne, T, share, ids); + cases.push_back({ build_plan(ids), T }); + } + cases.push_back({ single_group(rng, Y.ne, T), T }); + } + for (int i = 0; i < 4; ++i) cases.push_back({ synthetic_plan(rng, Y.ne), kTok }); + int hist[13] = {}; + for (const Case& cs : cases) + for (int g = 0; g < cs.p.ng; ++g) hist[std::min(12, cs.p.start[g + 1] - cs.p.start[g])]++; + struct Var { + int v, mode; + bool v1; + const char* name; + }; + // mode -1: the card's default layout (a GP100: mode 8 - its reference gate/up kernel writes hq, not gate / up); + // mode 0: the CUDA layout + const Var vars[] = { { -1, -1, false, "default, card" }, { 0, -1, false, "S, card" }, { 1, -1, false, "P, card" }, + { -1, -1, true, "default, card, V1" }, { -1, 0, false, "default, mode 0" }, + { 0, 0, false, "S, mode 0" }, { 1, 0, false, "P, mode 0" }, { -1, 0, true, "default, mode 0, V1" }, + // STRATA_NIB_GU_PROTO (nib_gu_proto.cuh): the staged-once kernel, id 31 + { 31, -1, false, "gu-proto 31, card" }, { 31, 0, false, "gu-proto 31, mode 0" }, + { 31, 0, true, "gu-proto 31, mode 0, V1" } }; + constexpr int NV = (int) (sizeof vars / sizeof vars[0]); + long long rows[NV] = {}, bad[NV][5] = {}, total = 0; + for (const Case& cs : cases) + for (int64_t gy : { (int64_t) 0, (int64_t) 4 }) { + Outs ref[2][2]; // [mode 0][v1] + bool have[2][2] = {}; + for (int vi = 0; vi < NV; ++vi) { + const int m0 = vars[vi].mode == 0 ? 1 : 0, r1 = vars[vi].v1 ? 1 : 0; + K::native_grouped_set_v1(vars[vi].v1); + if (!have[m0][r1]) { + K::native_expert_nib_set_variant(-1); + ref[m0][r1] = run(Y, cs.p, false, dx, scr, dout, gy, vars[vi].mode, 0xFF); + have[m0][r1] = true; + } + K::native_expert_nib_set_variant(vars[vi].v); + const Outs o = run(Y, cs.p, true, dx, scr, dout, gy, vars[vi].mode, 0x00); + rows[vi] += cs.p.ne; + // gate / up: written by both arms in the CUDA layout, and by every arm of a striding call (gy 4: mode 0) + const bool gu = vars[vi].mode == 0 || gy == 4; + if (gu) { + bad[vi][0] += diff_rows(ref[m0][r1].gate, o.gate, kFf * 4); + bad[vi][1] += diff_rows(ref[m0][r1].up, o.up, kFf * 4); + } + if (vars[vi].v1 && gu) bad[vi][2] += diff_rows(ref[m0][r1].h, o.h, kFf * 4); + bad[vi][3] += diff_rows(ref[m0][r1].hq, o.hq, (kFf / 32) * 36); + bad[vi][4] += diff_rows(ref[m0][r1].out, o.out, kEmbd * 4); + } + } + K::native_expert_nib_set_variant(-1); + K::native_grouped_set_v1(false); + std::printf(" plans: %zu (T 1..6 x sharing 0/50%% x %d, G=1 per T, 4 of 0..11 entries); groups by entries:", cases.size(), + plans); + for (int n = 0; n <= 12; ++n) std::printf(" %d:%d", n, hist[n]); + std::printf("\n"); + for (int vi = 0; vi < NV; ++vi) { + const long long b = bad[vi][0] + bad[vi][1] + bad[vi][2] + bad[vi][3] + bad[vi][4]; + std::printf(" native_expert_grouped %-20s: %6lld entries x 2 strides, rows differing: gate %lld, up %lld, h %s, hq %lld, out %lld\n", + vars[vi].name, rows[vi], bad[vi][0], bad[vi][1], + vars[vi].v1 ? std::to_string(bad[vi][2]).c_str() : "-", bad[vi][3], bad[vi][4]); + total += b; + } + return total; +} + +// --synthetic: random gate/up blocks, d cycling through the fp16 extremes; the coverage of each field is counted +long long synthesize(Layer& Y, std::mt19937& rng) { + static const uint16_t kD[] = { 0x0001, 0x8001, 0x7BFF, 0xFBFF, 0x3C00, 0xBC00, 0x0400, 0x1A00, 0x2400 }; + const int gt = Y.f.gu_type; + const size_t bb = gt == nib::kIQ2_S ? 82 : gt == nib::kIQ3_XXS ? 98 : 110; // block_iq2_s / iq3_xxs / iq3_s + const size_t nblk = (size_t) nib::kRows * nib::kSuper; + std::set grid, sign, scale, dset; + for (int e = 0; e < Y.ne; ++e) { + uint8_t* b = Y.host.data() + (size_t) e * Y.f.bytes; + for (size_t i = 0; i < 2 * Y.f.up_off; ++i) b[i] = (uint8_t) rng(); + for (size_t k = 0; k < nblk; ++k) { + uint8_t* blk = b + k * bb; + const uint16_t d = kD[((size_t) e * nblk + k) % (sizeof kD / sizeof kD[0])]; + std::memcpy(blk, &d, 2); + dset.insert(d); + const uint8_t* qs = blk + 2; + for (int ib = 0; ib < 8; ++ib) { + if (gt == nib::kIQ2_S) { + const uint8_t* qh = blk + 66; + const uint8_t* sc = blk + 74; + for (int l = 0; l < 4; ++l) { + grid.insert(qs[4 * ib + l] | ((qh[ib] << (8 - 2 * l)) & 0x300)); + sign.insert(qs[32 + 4 * ib + l]); + } + scale.insert(sc[ib] & 15); + scale.insert(sc[ib] >> 4); + } else if (gt == nib::kIQ3_XXS) { + uint32_t aux; + std::memcpy(&aux, blk + 66 + 4 * ib, 4); + for (int l = 0; l < 8; ++l) grid.insert(qs[8 * ib + l]); + for (int l = 0; l < 4; ++l) sign.insert((int) ((aux >> (7 * l)) & 127)); + scale.insert((int) (aux >> 28)); + } else { + const uint8_t qh = blk[66 + ib]; + const uint8_t* sg = blk + 74; + const uint8_t* sc = blk + 106; + for (int l = 0; l < 4; ++l) { + grid.insert(qs[8 * ib + 2 * l] | ((qh << (8 - 2 * l)) & 256)); + grid.insert(qs[8 * ib + 2 * l + 1] | ((qh << (7 - 2 * l)) & 256)); + sign.insert(sg[4 * ib + l]); + } + scale.insert((sc[ib / 2] >> (4 * (ib & 1))) & 15); + } + } + } + } + const size_t want_grid = gt == nib::kIQ2_S ? 1024 : gt == nib::kIQ3_XXS ? 256 : 512; + const size_t want_sign = gt == nib::kIQ3_XXS ? 128 : 256; + const bool ok = grid.size() == want_grid && sign.size() == want_sign && scale.size() == 16 && + dset.size() == sizeof kD / sizeof kD[0]; + std::printf("synthetic %-7s: %d experts, coverage: grid indices %zu/%zu, sign %s %zu/%zu, scale nibbles %zu/16, d values %zu/%zu" + " (+-min subnormal, +-65504, +-1, min normal, 2 ordinary) %s\n", + nib::fmt_name(gt), Y.ne, grid.size(), want_grid, gt == nib::kIQ3_XXS ? "indices" : "bytes", sign.size(), + want_sign, scale.size(), dset.size(), sizeof kD / sizeof kD[0], ok ? "complete" : "INCOMPLETE"); + return ok ? 0 : 1; +} + +std::vector split_ints(const std::string& s) { + std::vector v; + size_t p = 0; + while (p < s.size()) { + v.push_back(std::atoi(s.c_str() + p)); + p = s.find(',', p); + if (p == std::string::npos) break; + ++p; + } + return v; +} + +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + if (argc == 2 && std::strcmp(argv[1], "--header") == 0) return header_check(); + std::vector shards; + int per_fmt = 2, NE = 512, plans = 8, syn = 64; + bool ggml_check = true, negative = false, syn_only = false; + std::vector only; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s needs a value\n", a.c_str()); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--layers-per-fmt") per_fmt = std::atoi(next()); + else if (a == "--layers") only = split_ints(next()); + else if (a == "--ne") NE = std::atoi(next()); + else if (a == "--plans") plans = std::atoi(next()); + else if (a == "--synthetic") syn = std::atoi(next()); + else if (a == "--no-ggml") ggml_check = false; + else if (a == "--negative") negative = true; + else if (a == "--synthetic-only") syn_only = true; + else if (a.size() > 5 && a.substr(a.size() - 5) == ".gguf") shards.push_back(a); + else { + std::fprintf(stderr, + "usage: iq_nibble_parity --header\n" + " iq_nibble_parity [ ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512]\n" + " [--plans 8] [--synthetic 64] [--no-ggml] [--negative]\n" + " iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml]\n"); + return 2; + } + } + if ((shards.empty() && !syn_only) || NE < 16 || NE > 512) { + std::fprintf(stderr, "iq_nibble_parity: give at least one model shard (.gguf); --ne 16..512\n"); + return 2; + } + CK(cudaSetDevice(0)); + cudaDeviceProp prop{}; + CK(cudaGetDeviceProperties(&prop, 0)); + char bus[64] = {}; + CK(cudaDeviceGetPCIBusId(bus, sizeof bus, 0)); + std::printf("device 0: %s, bus %s, cc %d.%d, %d SMs\n", prop.name, bus, prop.major, prop.minor, prop.multiProcessorCount); + if (prop.major != 6 || prop.minor != 0) { + std::fprintf(stderr, "iq_nibble_parity: the 4-bit kernels are the sm_60 build's; this GPU is cc %d.%d (skipped)\n", + prop.major, prop.minor); + return 77; + } + if (!STRATA_EXPERT_NIBBLE_BUILT || nib::prepare(nullptr) != 0) { + std::fprintf(stderr, "iq_nibble_parity: no 4-bit kernels in this build, or the GGUF codebooks are not unique\n"); + return 2; + } + std::mt19937 rng(20261019); + void* scr = nullptr; + float* dout = nullptr; + void* dx = nullptr; + const int64_t capmax = (int64_t) kTok * 10; + CK(cudaMalloc(&scr, K::native_expert_scratch_bytes(capmax, kFf))); + CK(cudaMalloc((void**) &dout, (size_t) capmax * kEmbd * 4)); + const std::vector hx = make_x(rng); + CK(cudaMalloc(&dx, hx.size() * sizeof(Q81))); + CK(cudaMemcpy(dx, hx.data(), hx.size() * sizeof(Q81), cudaMemcpyHostToDevice)); + + if (syn_only) { // no model: every gate/up format with each down type, random experts + long long total_s = 0; + int done = 0; + for (const int gt : {nib::kIQ2_S, nib::kIQ3_XXS, nib::kIQ3_S}) + for (const int dt : {20, 42}) { // the packs' down types: IQ4_NL, Q2_0 + Layer S; + std::string err; + if (!cpu::native_fmt(gt, dt, kEmbd, kFf, S.f, err)) { + std::printf("%s / down type %d: %s\n", nib::fmt_name(gt), dt, err.c_str()); + ++total_s; + continue; + } + S.tag = "syn"; + S.layer = 0; + S.ne = std::max(16, std::min(syn, NE)); + S.host.resize((size_t) S.ne * S.f.bytes); + for (auto& b : S.host) b = (uint8_t) rng(); + // block_iq4_nl and block_q2_0 are 18 bytes, the fp16 scale first: an ordinary scale in every block of the down rows + for (int e = 0; e < S.ne; ++e) + for (size_t o = S.f.down_off; o + 18 <= S.f.bytes; o += 18) { + const uint16_t sc = (uint16_t) ((9u << 10) | (rng() & 0x3FFu)); + std::memcpy(S.host.data() + (size_t) e * S.f.bytes + o, &sc, 2); + } + long long sb = synthesize(S, rng); + sb += convert(S, ggml_check); + sb += grouped_parity(S, rng, plans, dx, scr, dout); + total_s += sb; + ++done; + CK(cudaFree(S.raw)); + CK(cudaFree(S.slots)); + } + std::printf("\n%s: %d synthetic format pairs, %lld differences\n", total_s == 0 && done == 6 ? "PASS" : "FAIL", done, total_s); + return total_s == 0 && done == 6 ? 0 : 1; + } + long long total = 0; + int layers_done = 0; + std::vector syn_done; + for (size_t si = 0; si < shards.size(); ++si) { + std::unique_ptr model; + try { + model = std::make_unique(strata::GgufModel::open(shards[si])); + } catch (const std::exception& ex) { + std::fprintf(stderr, "iq_nibble_parity: %s\n", ex.what()); + return 2; + } + const std::string tag(1, (char) ('A' + si)); + std::printf("\n#### model %s: %s (%zu shards)\n", tag.c_str(), shards[si].c_str(), model->size()); + std::vector pick; + int count[64] = {}; + for (int l = 0; l < 256; ++l) { + int gt = -1, dt = -1; + if (!layer_fmt(*model, l, gt, dt)) break; + if (!nib::fmt_built(gt)) continue; + const bool want = only.empty() ? count[gt]++ < per_fmt : std::find(only.begin(), only.end(), l) != only.end(); + if (want) pick.push_back(l); + } + for (int l : pick) { + Layer Y; + Y.tag = tag; + if (!read_layer(*model, l, NE, Y)) { + std::printf("layer %d: cannot read its experts\n", l); + ++total; + continue; + } + long long b = convert(Y, ggml_check); + if (negative) { // the control: one code byte changed per slot (item 3 of row 5), which (6) must see + for (int e = 0; e < Y.ne; ++e) { + uint8_t* at = Y.slots + (size_t) e * Y.V.slot_bytes + nib::code_off(5, 3); + uint8_t v = 0; + CK(cudaMemcpy(&v, at, 1, cudaMemcpyDeviceToHost)); + v ^= 0x11; + CK(cudaMemcpy(at, &v, 1, cudaMemcpyHostToDevice)); + } + std::printf(" NEGATIVE CONTROL: one code byte changed per slot - the rows below must differ\n"); + std::vector hp(Y.ne); + for (int e = 0; e < Y.ne; ++e) hp[e] = (unsigned long long) (Y.slots + (size_t) e * Y.V.slot_bytes); + unsigned long long* dp = nullptr; + CK(cudaMalloc(&dp, (size_t) Y.ne * 8)); + CK(cudaMemcpy(dp, hp.data(), (size_t) Y.ne * 8, cudaMemcpyHostToDevice)); + b += gguf_parity(Y, dp, true); + CK(cudaFree(dp)); + } + b += grouped_parity(Y, rng, plans, dx, scr, dout); + total += b; + ++layers_done; + // the synthetic experts of this format, once: this layer's blobs with random gate/up blocks + if (syn > 0 && std::find(syn_done.begin(), syn_done.end(), Y.f.gu_type) == syn_done.end() && !negative) { + syn_done.push_back(Y.f.gu_type); + Layer S; + S.tag = "syn"; + S.layer = Y.layer; + S.f = Y.f; + S.ne = std::min(syn, Y.ne); + S.host.assign(Y.host.begin(), Y.host.begin() + (ptrdiff_t) ((size_t) S.ne * Y.f.bytes)); + long long sb = synthesize(S, rng); + sb += convert(S, ggml_check); + sb += grouped_parity(S, rng, std::max(1, plans / 2), dx, scr, dout); + total += sb; + CK(cudaFree(S.raw)); + CK(cudaFree(S.slots)); + } + CK(cudaFree(Y.raw)); + CK(cudaFree(Y.slots)); + } + } + std::printf("\n%s: %d layers (+ %zu synthetic formats), %lld differences\n", total == 0 ? "PASS" : "FAIL", layers_done, + syn_done.size(), total); + return total == 0 ? 0 : 1; +} diff --git a/src/kernels/mmvq_il_parity.cpp b/src/kernels/mmvq_il_parity.cpp index 9e78015a..9e9cd165 100644 --- a/src/kernels/mmvq_il_parity.cpp +++ b/src/kernels/mmvq_il_parity.cpp @@ -260,21 +260,38 @@ void emit_table() { } // the per-architecture lookup, no GPU needed for its answers +// The two Ada runs sm_89's table was merged from (mmvq_il_parity --bench --emit-table, issue 3453): by type IQ4_XS, Q4_K, +// Q5_K, Q6_K, Q3_K, then 2/3/4 columns, then the five n_out classes. +const int kAda4070[5][3][5] = { + {{0, 0, 0, 1, 0}, {1, 1, 1, 1, 1}, {2, 2, 1, 1, 1}}, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}}, + {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {1, 2, 1, 2, 2}}, {{0, 0, 0, 0, 0}, {0, 0, 1, 2, 2}, {0, 1, 4, 1, 1}}, + {{1, 1, 1, 2, 1}, {1, 1, 1, 1, 1}, {2, 1, 1, 1, 1}}}; +const int kAda4080[5][3][5] = { + {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}}, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}, + {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}, {0, 0, 1, 1, 1}}, {{0, 0, 0, 1, 0}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}, + {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}}; int check_tables() { int bad = 0; + const char* e89 = std::getenv("STRATA_MMVQ_IL_89"); + const bool opt89 = e89 != nullptr && e89[0] == '1'; // sm_89's own tables are opt-in (#3453) for (int type : {23, 12, 13, 14, 11}) for (int nc = 2; nc <= 4; ++nc) for (int n_out : {512, 2560, 6144, 10240, 12288, 248320}) { const int a = native_mmvq_il_rows_for(86, type, nc, n_out); - // sm_89 has no table of its own: it answers the shared table (what sm_86 answered before its own - // 143-dense table, which differs only in Q3_K, a type the shared table does not use); sm_120 has its own - // since 147-verify - const int b = native_mmvq_il_rows_for(89, type, nc, n_out); - if ((type != 11 && b != a) || (type == 11 && b != 0)) { - ++bad; - std::printf("FAIL table: sm_89 differs from sm_86 at type %d ncols %d n_out %d\n", type, nc, n_out); - } if (a != 0 && a != 1 && a != 2 && a != 4) { ++bad; std::printf("FAIL table: rows %d\n", a); } + // sm_89 (#3453): the cells where an RTX 4070 and an RTX 4080 gave the same rows count, else 0 + const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4; + const int ti = type == 23 ? 0 : type == 12 ? 1 : type == 13 ? 2 : type == 14 ? 3 : 4; + const int b = native_mmvq_il_rows_for(89, type, nc, n_out); + // STRATA_MMVQ_IL_89=1: the agreement; unset: what sm_89 answered before #3453 (the shared table, which is + // sm_86's except Q3_K, a type the shared table has no row for) + const int want = opt89 ? (kAda4070[ti][nc - 2][cls] == kAda4080[ti][nc - 2][cls] ? kAda4070[ti][nc - 2][cls] : 0) + : (type == 11 ? 0 : a); + if (b != want) { + ++bad; + std::printf("FAIL table: sm_89 is %d, %s says %d at type %d ncols %d n_out %d\n", b, + opt89 ? "the 4070/4080 agreement" : "the shared table", want, type, nc, n_out); + } } // Volta has its own table (PR 1401): Q6_K at 2 columns, 2560 rows -> 1 row a warp; the Ampere table says 0 there if (native_mmvq_il_rows_for(70, 14, 2, 2560) != 1 || native_mmvq_il_rows_for(86, 14, 2, 2560) != 0) { @@ -286,6 +303,12 @@ int check_tables() { ++bad; std::printf("FAIL table: the sm_60 table is not the P100's\n"); } + // sm_89 one column: only Q3_K with STRATA_MMVQ_IL_89=1 (the 4070 and the 4080 agree), else none; wider than 4: the plain kernels + if (native_mmvq_il_rows_for(89, 11, 1, 2560) != 0 || native_mmvq_il_rows_for(89, 11, 1, 6144) != (opt89 ? 1 : 0) || + native_mmvq_il_rows_for(89, 12, 1, 6144) != 0) { + ++bad; + std::printf("FAIL table: the sm_89 one-column row is not Q3_K only\n"); + } if (native_mmvq_il_rows_for(89, 99, 2, 2560) != 0 || native_mmvq_il_rows_for(89, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(86, 12, 5, 2560) != 0 || native_mmvq_il_rows_for(120, 12, 9, 2560) != 0) { ++bad; diff --git a/src/kernels/native_expert_bench.cpp b/src/kernels/native_expert_bench.cpp index 3263ee7a..e51bf774 100644 --- a/src/kernels/native_expert_bench.cpp +++ b/src/kernels/native_expert_bench.cpp @@ -2,11 +2,21 @@ // another, bit for bit, and each one's time. // // build/native_expert_bench [iters] +// build/native_expert_bench --nibble [--t 1,2,3,4,5,6] [--share 0,50] [--plans 200] +// [--trials 7] [--mode -1|0] [--variant -1|0|1] // // Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit // in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the // reference mode's: the verify window's text depends on it. +// +// --nibble (STRATA_EXPERT_NIBBLE, strata/core/expert_nibble.hpp): the layer's 512 experts as GGUF blobs (P, the +// production kernels) and as 4-bit slots made by the engine's transcoder (N: native_expert_layout_nib); the verify +// window's whole expert step (gate/up + SwiGLU/q8_1 + down) and its gate/up phase alone, per (T, sharing) over +// `--plans` top-10 routings (0% or 50% of a token's experts shared with the previous token's), every plan's out rows +// compared byte for byte first; interleaved trials, medians. `--mode`: both arms' layout (-1 the card's default, a +// GP100's mode 8; 0 the CUDA layout); `--variant`: the 4-bit gate/up kernel (-1 per format, 0 S, 1 P). #include "strata/artifact/gguf_reader.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/kernels/cpu/native_expert.hpp" #include "strata/kernels/iq_kernels.hpp" @@ -20,6 +30,8 @@ #include #include #include +#include +#include #include #include #include @@ -28,8 +40,11 @@ namespace cpu = strata::kernels::cpu; namespace K = strata::kernels; +int nibble_main(int argc, char** argv); + int main(int argc, char** argv) { setvbuf(stdout, nullptr, _IONBF, 0); + if (argc >= 2 && std::strcmp(argv[1], "--nibble") == 0) return nibble_main(argc, argv); if (argc < 7) { std::fprintf(stderr, "usage: native_expert_bench [iters]\n"); return 2; @@ -175,3 +190,407 @@ int main(int argc, char** argv) { std::printf("native_expert_bench: %d differing\n", failures); return failures ? 1 : 0; } + +// ------------------------------------------------------------------------------------------------ --nibble +#if STRATA_EXPERT_NIBBLE_BUILT +namespace { + +namespace nib = strata::core::nibble; + +#define NB_CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); \ + std::exit(2); \ + } \ + } while (0) + +struct NbPlan { + int ng = 0, ne = 0, t = 0; + std::vector gid, start, tok, dst; +}; + +// synthetic routing: t tokens of top-10, `share` % of each token's experts the previous token's; groups by first +// appearance (resident_plan_kernel's order), entries in token order +NbPlan nb_route(std::mt19937& rng, int t, int share) { + std::vector ids, prev, cur; + for (int k = 0; k < t; ++k) { + cur.clear(); + const bool sh = k > 0 && share > 0; + if (sh) { + std::vector p = prev; + std::shuffle(p.begin(), p.end(), rng); + cur.assign(p.begin(), p.begin() + 10 * share / 100); + } + while ((int) cur.size() < 10) { + const int e = (int) (rng() % 512u); + if (std::find(cur.begin(), cur.end(), e) != cur.end()) continue; + if (sh && std::find(prev.begin(), prev.end(), e) != prev.end()) continue; + cur.push_back(e); + } + std::shuffle(cur.begin(), cur.end(), rng); + ids.insert(ids.end(), cur.begin(), cur.end()); + prev = cur; + } + NbPlan p; + p.t = t; + std::map> by; // expert -> its entries (j = token * 10 + k) + std::vector first; + for (int j = 0; j < (int) ids.size(); ++j) { + if (by.find(ids[j]) == by.end()) first.push_back(ids[j]); + by[ids[j]].push_back(j); + } + for (int e : first) { + p.gid.push_back(e); + p.start.push_back(p.ne); + for (int j : by[e]) { + p.tok.push_back(j / 10); + p.dst.push_back(j); + ++p.ne; + } + } + p.start.push_back(p.ne); + p.ng = (int) p.gid.size(); + return p; +} + +struct NbDev { + unsigned long long* ptr = nullptr; + int32_t *start = nullptr, *ng = nullptr, *tok = nullptr, *dst = nullptr; +}; +NbDev nb_upload(const NbPlan& p, const uint8_t* base, size_t stride) { + NbDev d; + std::vector hp(std::max(1, p.ng)); + for (int g = 0; g < p.ng; ++g) hp[g] = (unsigned long long) (base + (size_t) p.gid[g] * stride); + NB_CK(cudaMalloc((void**) &d.ptr, hp.size() * 8)); + NB_CK(cudaMalloc((void**) &d.start, (size_t) (p.ng + 1) * 4)); + NB_CK(cudaMalloc((void**) &d.ng, 4)); + NB_CK(cudaMalloc((void**) &d.tok, (size_t) std::max(1, p.ne) * 4)); + NB_CK(cudaMalloc((void**) &d.dst, (size_t) std::max(1, p.ne) * 4)); + NB_CK(cudaMemcpy(d.ptr, hp.data(), hp.size() * 8, cudaMemcpyHostToDevice)); + NB_CK(cudaMemcpy(d.start, p.start.data(), (size_t) (p.ng + 1) * 4, cudaMemcpyHostToDevice)); + NB_CK(cudaMemcpy(d.ng, &p.ng, 4, cudaMemcpyHostToDevice)); + if (p.ne) { + NB_CK(cudaMemcpy(d.tok, p.tok.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + NB_CK(cudaMemcpy(d.dst, p.dst.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice)); + } + return d; +} +void nb_free(NbDev& d) { + cudaFree(d.ptr); + cudaFree(d.start); + cudaFree(d.ng); + cudaFree(d.tok); + cudaFree(d.dst); +} + +std::vector nb_ints(const std::string& s) { + std::vector v; + std::stringstream ss(s); + std::string t; + while (std::getline(ss, t, ',')) v.push_back(std::atoi(t.c_str())); + return v; +} + +} // namespace + +int nibble_main(int argc, char** argv) { + if (argc < 4) { + std::fprintf(stderr, "usage: native_expert_bench --nibble [--t 1,2,3,4,5,6] [--share 0,50] " + "[--plans 200] [--trials 7] [--mode -1|0] [--variant -1|0|1]\n"); + return 2; + } + const std::string shard = argv[2]; + const std::vector layers = nb_ints(argv[3]); + std::vector Ts = { 1, 2, 3, 4, 5, 6 }, shares = { 0, 50 }; + int plans = 200, trials = 7, mode = -1, variant = -1; + std::vector vs; // gu-proto: the nibble gate/up kernels compared with the production one (-1), gate/up only + for (int i = 4; i + 1 < argc; i += 2) { + const std::string a = argv[i]; + if (a == "--t") Ts = nb_ints(argv[i + 1]); + else if (a == "--share") shares = nb_ints(argv[i + 1]); + else if (a == "--plans") plans = std::atoi(argv[i + 1]); + else if (a == "--trials") trials = std::atoi(argv[i + 1]); + else if (a == "--mode") mode = std::atoi(argv[i + 1]); + else if (a == "--variant") variant = std::atoi(argv[i + 1]); + else if (a == "--vs") vs = nb_ints(argv[i + 1]); + else { + std::fprintf(stderr, "unknown option %s\n", a.c_str()); + return 2; + } + } + std::unique_ptr model; + try { + model = std::make_unique(strata::GgufModel::open(shard)); + } catch (const std::exception& ex) { + std::fprintf(stderr, "native_expert_bench: %s\n", ex.what()); + return 2; + } + cudaDeviceProp prop{}; + NB_CK(cudaGetDeviceProperties(&prop, 0)); + char bus[64] = {}; + NB_CK(cudaDeviceGetPCIBusId(bus, sizeof bus, 0)); + std::printf("device 0: %s, bus %s, cc %d.%d; layout %s, 4-bit kernel %s\n", prop.name, bus, prop.major, prop.minor, + mode < 0 ? "the card's default" : ("mode " + std::to_string(mode)).c_str(), + variant < 0 ? "per format" : variant == 1 ? "P" : "S"); + K::native_expert_nib_set_variant(variant); + const int64_t H = nib::kNEmbd, FF = nib::kNFf; + constexpr int kTokMax = 8; + int failures = 0; + cudaStream_t s; + NB_CK(cudaStreamCreate(&s)); + cudaEvent_t e0, e1; + NB_CK(cudaEventCreate(&e0)); + NB_CK(cudaEventCreate(&e1)); + // the activations: kTokMax tokens of normal floats, quantized as the verify window quantizes them + std::mt19937 rng(20261019); + std::normal_distribution nd(0.f, 1.f); + std::vector x((size_t) kTokMax * H); + for (auto& v : x) v = nd(rng); + void *dx = nullptr, *dxq = nullptr, *dscr = nullptr; + float* dout = nullptr; + const int64_t cap = (int64_t) kTokMax * 10; + NB_CK(cudaMalloc(&dx, x.size() * 4)); + NB_CK(cudaMalloc(&dxq, (size_t) kTokMax * H / 32 * 36)); + NB_CK(cudaMalloc(&dscr, K::native_expert_scratch_bytes(cap, FF))); + NB_CK(cudaMalloc((void**) &dout, (size_t) cap * H * 4)); + NB_CK(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice)); + K::quantize_q8_1_rows((const float*) dx, kTokMax, H, dxq, s); + for (int l : layers) { + const char* roles[3] = { "gate", "up", "down" }; + const strata::TensorInfo* t[3] = {}; + size_t sh[3] = {}; + for (int r = 0; r < 3; ++r) t[r] = model->find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &sh[r]); + if (!t[0] || !t[1] || !t[2]) { + std::printf("layer %d: no expert tensors\n", l); + ++failures; + continue; + } + cpu::NativeFmt f; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); + ++failures; + continue; + } + nib::Config c; + c.on = true; + const nib::LayerVram V = nib::plan_layer(l, f, c); + if (!V.on) { + std::printf("layer %d: %s is not converted\n", l, ggml_type_name((ggml_type) f.gu_type)); + continue; + } + // the 512 blobs (P) and their 4-bit slots (N, the engine's transcoder) + std::vector host((size_t) 512 * f.bytes); + const size_t dn_role = f.bytes - f.down_off; + for (int e = 0; e < 512; ++e) { + uint8_t* b = host.data() + (size_t) e * f.bytes; + std::memcpy(b, model->shard(sh[0]).tensor_data(*t[0]) + (size_t) e * f.up_off, f.up_off); + std::memcpy(b + f.up_off, model->shard(sh[1]).tensor_data(*t[1]) + (size_t) e * f.up_off, f.up_off); + std::memcpy(b + f.down_off, model->shard(sh[2]).tensor_data(*t[2]) + (size_t) e * dn_role, dn_role); + } + uint8_t *raw = nullptr, *slots = nullptr; + unsigned long long *dp = nullptr, *dbad = nullptr; + NB_CK(cudaMalloc((void**) &raw, host.size())); + NB_CK(cudaMalloc((void**) &slots, (size_t) 512 * V.slot_bytes)); + NB_CK(cudaMalloc((void**) &dp, 512 * 8)); + NB_CK(cudaMalloc((void**) &dbad, 8)); + NB_CK(cudaMemcpy(raw, host.data(), host.size(), cudaMemcpyHostToDevice)); + std::vector hp(512); + for (int e = 0; e < 512; ++e) hp[e] = (unsigned long long) (slots + (size_t) e * V.slot_bytes); + NB_CK(cudaMemcpy(dp, hp.data(), 512 * 8, cudaMemcpyHostToDevice)); + NB_CK(cudaMemset(dbad, 0, 8)); + for (int b0 = 0; b0 < 512; b0 += 64) + if (nib::transcode(V, raw + (size_t) b0 * V.raw_bytes, 64, dp + b0, dbad, s) != 0) return 2; + for (int e = 0; e < 512; ++e) + NB_CK(cudaMemcpyAsync(slots + (size_t) e * V.slot_bytes + nib::kDownOff, raw + (size_t) e * V.raw_bytes + V.raw_down_off, + V.down_bytes, cudaMemcpyDeviceToDevice, s)); + unsigned long long bad = 0; + NB_CK(cudaMemcpyAsync(&bad, dbad, 8, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaStreamSynchronize(s)); + if (bad) { + std::printf("layer %d: %llu items do not round-trip\n", l, bad); + ++failures; + continue; + } + const auto Lr = K::native_expert_layout(f.gu_type, f.d_type, H, FF); + const auto Ln = K::native_expert_layout_nib(f.gu_type, f.d_type, H, FF); + std::printf("layer %2d %-7s/%-6s: 512 experts, blob %zu B, 4-bit slot %llu B\n", l, nib::fmt_name(f.gu_type), + ggml_type_name((ggml_type) f.d_type), f.bytes, (unsigned long long) V.slot_bytes); + // one set of plans: every plan's out rows compared first, then P and N timed interleaved, phase 0 (the whole + // step) and 1 (gate/up + SwiGLU/q8_1), us per launch (median of the trials) + auto bench = [&](const std::vector& ps, int tt, double us[2][2]) -> long long { + std::vector dr(ps.size()), dn(ps.size()); + for (size_t i = 0; i < ps.size(); ++i) { + dr[i] = nb_upload(ps[i], raw, f.bytes); + dn[i] = nb_upload(ps[i], slots, V.slot_bytes); + } + const int64_t cp = std::max((int64_t) tt * 10, 1); + auto launch = [&](int arm, size_t i) { + const NbDev& d = arm ? dn[i] : dr[i]; + K::native_expert_grouped(arm ? Ln : Lr, d.ptr, d.start, d.ng, d.dst, d.tok, std::max(cp, ps[i].ng), + std::max(cp, ps[i].ne), dxq, dscr, dout, s, 0); + }; + long long diff = 0; + std::vector a((size_t) cap * H * 4), b(a.size()); + K::native_expert_set_mode(mode, 0); + for (size_t i = 0; i < ps.size(); ++i) { + const size_t n = (size_t) ps[i].ne * H * 4; + NB_CK(cudaMemsetAsync(dout, 0xFF, a.size(), s)); + launch(0, i); + NB_CK(cudaMemcpyAsync(a.data(), dout, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaMemsetAsync(dout, 0x00, a.size(), s)); + launch(1, i); + NB_CK(cudaMemcpyAsync(b.data(), dout, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaStreamSynchronize(s)); + diff += std::memcmp(a.data(), b.data(), n) != 0; + } + for (int ph = 0; ph < 2; ++ph) { + K::native_expert_set_mode(mode, ph); + std::vector tm[2]; + for (int arm = 0; arm < 2; ++arm) + for (size_t i = 0; i < std::min(ps.size(), 20); ++i) launch(arm, i); + for (int tr = 0; tr < trials; ++tr) + for (int arm = 0; arm < 2; ++arm) { + NB_CK(cudaEventRecord(e0, s)); + for (size_t i = 0; i < ps.size(); ++i) launch(arm, i); + NB_CK(cudaEventRecord(e1, s)); + NB_CK(cudaEventSynchronize(e1)); + float ms = 0; + NB_CK(cudaEventElapsedTime(&ms, e0, e1)); + tm[arm].push_back(1e3f * ms / (float) ps.size()); + } + for (int arm = 0; arm < 2; ++arm) { + std::sort(tm[arm].begin(), tm[arm].end()); + us[ph][arm] = tm[arm][tm[arm].size() / 2]; + } + } + K::native_expert_set_mode(mode, 0); + for (size_t i = 0; i < ps.size(); ++i) { + nb_free(dr[i]); + nb_free(dn[i]); + } + return diff; + }; + if (!vs.empty()) { // gu-proto: nibble production (-1) against each id in --vs, gate/up only (phase 3) + std::vector arms = { -1 }; + arms.insert(arms.end(), vs.begin(), vs.end()); + for (int v : vs) { + int regs = 0, loc = 0, occ = 0; + if (K::native_expert_nib_variant_attr(v, f.gu_type, ®s, &loc, &occ)) + std::printf(" variant %d: %d registers, %d B local, %d blocks/SM\n", v, regs, loc, occ); + } + const size_t fsz = (size_t) cap * FF * 4, fa = (fsz + 255) & ~(size_t) 255; + for (int tt : Ts) { + if (tt < 1 || tt > kTokMax) continue; + for (int share : shares) { + std::vector ps; + double G = 0; + for (int i = 0; i < plans; ++i) { + ps.push_back(nb_route(rng, tt, share)); + G += ps.back().ng; + } + std::vector dn(ps.size()); + for (size_t i = 0; i < ps.size(); ++i) dn[i] = nb_upload(ps[i], slots, V.slot_bytes); + const int64_t cp = std::max((int64_t) tt * 10, 1); + auto launch = [&](int v, size_t i) { + K::native_expert_nib_set_variant(v); + K::native_expert_grouped(Ln, dn[i].ptr, dn[i].start, dn[i].ng, dn[i].dst, dn[i].tok, + std::max(cp, ps[i].ng), std::max(cp, ps[i].ne), dxq, dscr, + dout, s, 0); + }; + K::native_expert_set_mode(mode, 3); + // every plan: each arm's gate and up rows (the plan's entries) byte for byte the production arm's + std::vector drows(arms.size(), 0); + std::vector ref(2 * fsz), got(2 * fsz); + for (size_t i = 0; i < ps.size(); ++i) { + const size_t n = (size_t) ps[i].ne * FF * 4; + // native_expert_grouped's up rows start after cap_entries gate rows (256-aligned) + const size_t fi = (size_t) std::max(cp, ps[i].ne) * FF * 4, fai = (fi + 255) & ~(size_t) 255; + for (size_t a = 0; a < arms.size(); ++a) { + NB_CK(cudaMemsetAsync(dscr, a == 0 ? 0xFF : 0x00, 2 * fa, s)); + launch(arms[a], i); + std::vector& o = a == 0 ? ref : got; + NB_CK(cudaMemcpyAsync(o.data(), dscr, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaMemcpyAsync(o.data() + fsz, (const uint8_t*) dscr + fai, n, cudaMemcpyDeviceToHost, s)); + NB_CK(cudaStreamSynchronize(s)); + if (a == 0) continue; + for (size_t r = 0; r < (size_t) ps[i].ne; ++r) { + drows[a] += std::memcmp(ref.data() + r * FF * 4, got.data() + r * FF * 4, FF * 4) != 0; + drows[a] += std::memcmp(ref.data() + fsz + r * FF * 4, got.data() + fsz + r * FF * 4, FF * 4) != 0; + } + } + } + long long rows = 0; + for (const NbPlan& p : ps) rows += 2LL * p.ne; + std::vector> tm(arms.size()); + for (size_t a = 0; a < arms.size(); ++a) + for (size_t i = 0; i < std::min(ps.size(), 20); ++i) launch(arms[a], i); + for (int tr = 0; tr < trials; ++tr) + for (size_t a = 0; a < arms.size(); ++a) { + NB_CK(cudaEventRecord(e0, s)); + for (size_t i = 0; i < ps.size(); ++i) launch(arms[a], i); + NB_CK(cudaEventRecord(e1, s)); + NB_CK(cudaEventSynchronize(e1)); + float ms = 0; + NB_CK(cudaEventElapsedTime(&ms, e0, e1)); + tm[a].push_back(1e3f * ms / (float) ps.size()); + } + K::native_expert_set_mode(mode, 0); + K::native_expert_nib_set_variant(variant); + std::printf(" T=%d share %2d%% (G %.2f, %lld gate/up rows a plan set), gate/up us per launch (median, min..max of %d):\n", + tt, share, G / plans, rows, trials); + double base = 0; + for (size_t a = 0; a < arms.size(); ++a) { + std::sort(tm[a].begin(), tm[a].end()); + const double med = tm[a][tm[a].size() / 2]; + if (a == 0) base = med; + std::printf(" %4d: %8.2f (%7.2f..%7.2f) x%.3f %s\n", arms[a], med, tm[a].front(), tm[a].back(), + base / med, a == 0 ? "reference" : drows[a] ? ("rows differ: " + std::to_string(drows[a])).c_str() : "bitwise equal"); + } + for (size_t i = 0; i < ps.size(); ++i) nb_free(dn[i]); + } + } + cudaFree(raw); + cudaFree(slots); + cudaFree(dp); + cudaFree(dbad); + continue; + } + for (int tt : Ts) { + if (tt < 1 || tt > kTokMax) continue; + for (int share : shares) { + std::vector ps; + double G = 0; + for (int i = 0; i < plans; ++i) { + ps.push_back(nb_route(rng, tt, share)); + G += ps.back().ng; + } + double us[2][2]; + const long long diff = bench(ps, tt, us); + std::printf(" T=%d share %2d%% (G %.2f): step P %7.2f N %7.2f us x%.3f | gate/up+swiglu P %7.2f N %7.2f us x%.3f | %s\n", + tt, share, G / plans, us[0][0], us[0][1], us[0][0] / us[0][1], us[1][0], us[1][1], + us[1][0] / us[1][1], diff ? "DIFFERS" : "bitwise equal"); + if (diff) { + std::printf(" %lld of %d plans differ\n", diff, plans); + ++failures; + } + } + } + cudaFree(raw); + cudaFree(slots); + cudaFree(dp); + cudaFree(dbad); + } + K::native_expert_set_mode(-1, 0); + K::native_expert_nib_set_variant(-1); + std::printf("native_expert_bench --nibble: %d failing\n", failures); + return failures ? 1 : 0; +} +#else +int nibble_main(int, char**) { + std::fprintf(stderr, "native_expert_bench --nibble: no 4-bit kernels in this build (STRATA_EXPERIMENTAL_SM60, CUDA)\n"); + return 2; +} +#endif diff --git a/src/kernels/qsa_pattn_parity.cpp b/src/kernels/qsa_pattn_parity.cpp new file mode 100644 index 00000000..ab67038d --- /dev/null +++ b/src/kernels/qsa_pattn_parity.cpp @@ -0,0 +1,260 @@ +// src/kernels/qsa_pattn_parity.cpp - STRATA_PATTN_SM60's score and value kernels (qsa_pattn.cu, PR #3943) against the +// decode kernels' output, bitwise (GPU, synthetic data, no model). +// +// The reference is what the prompt path reads on sm_6x today: the chunk pass of attn_chunk_kernel_pre75 (the Daily's +// chunk kernel, qsa_decode_attn_chunks_only with daily_chunk 1, which runs on any card) and attn_merge_kernel +// (qsa_decode_attn_merge_only, v2 0). The candidate is qsa_pattn_batch_any_arch (no compute-capability test), so the +// same bytes can be checked on an Ampere card too: the two paths do the same operations in the same order, and a +// pass there shows the indexing, masking and merge are right. The last word is a run on a Pascal card (P100): there +// the checked entry qsa_pattn_batch must take the shapes and the production qsa_decode_attn_batch must give the same +// bytes as the reference. +// +// Data: random int8 K/V codes, fp16 scales in a safe range, normal queries, a shuffled page table with ~3% unresident +// (-1) pages and one run of 64 unresident pages (so whole chunks are masked and some queries read nothing), selections +// shaped like the drafter's window, the indexer's (ascending with gaps) and unordered with repeats, caps 64 / 130 / +// 2051 / 2112 (1, 3 and 33 chunks), widths 0 .. cap, n_q up to 40 with a scratch that holds only 2 queries of the +// decode layout (so qsa_pattn_batch runs several batches). The pattn scratch and the output are filled with +// junk before each call, so a read of a block that was not written shows up as a difference. +// +// qsa_pattn_parity [--device N] exit 0: every case is bit-identical; 77: no GPU or a build without the kernels +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_pattn.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_pattn_parity: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(2); + } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc((void**) &p, n * sizeof(T) + 256), "cudaMalloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 256), "cudaMemset"); + return p; +} +template T* upload(const std::vector& h) { + T* d = dalloc(h.size()); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +// positive fp16 scale in [1/64, 1/32): codes up to 127 give |x| < 4 +uint16_t f16_scale_q8(uint32_t r) { return (uint16_t) ((9u << 10) | (r & 0x3FFu)); } + +constexpr int64_t kCells = 40960; // the cells this harness can address +constexpr int64_t kHole = 8192; // 64 unresident pages in a row: cells [kHole, kHole + 256) + +void selection(int32_t* ids, int64_t cap, int width, int shape, std::mt19937& rng) { + const int64_t w = std::max(0, std::min(width, cap)); + if (shape == 0) { // the drafter's window: consecutive cells, often across the unresident run + int64_t start; + if (rng() % 2 == 0) start = std::max(0, kHole - 64 * (int64_t) (rng() % 8)); + else start = (int64_t) (rng() % (uint32_t) (kCells - std::max(w, 1))); + if (start + w > kCells) start = kCells - w; + for (int64_t j = 0; j < cap; ++j) ids[j] = (int32_t) ((start + j) % kCells); + } else if (shape == 1) { // the indexer's: ascending with gaps + std::vector v((size_t) cap); + for (auto& x : v) x = (int32_t) (rng() % (uint32_t) kCells); + std::sort(v.begin(), v.begin() + w); + std::copy(v.begin(), v.end(), ids); + } else { // unordered, with repeats + for (int64_t j = 0; j < cap; ++j) ids[j] = (int32_t) (rng() % (uint32_t) kCells); + } +} + +struct Harness { + k::QsaShapes s = k::qsa_real_shapes(); + k::QsaAttnPools pools; + int32_t* table = nullptr; + float *q = nullptr, *scratch_ref = nullptr, *scratch_new = nullptr, *attn_ref = nullptr, *attn_new = nullptr; + int32_t *ids = nullptr, *steps = nullptr; + int64_t max_q = 0, max_cap = 0; + std::vector to_free; + + template T* keep(T* p) { to_free.push_back(p); return p; } + + void init(std::mt19937& rng, int64_t max_q_, int64_t max_cap_) { + max_q = max_q_; + max_cap = max_cap_; + const int64_t PS = s.page_size, pages = kCells / PS, H = s.n_head_kv, D = s.head_dim; + std::vector tab((size_t) pages); // logical page -> physical page: a permutation, with holes + for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i; + std::shuffle(tab.begin(), tab.end(), rng); + for (int64_t i = 0; i < pages; ++i) + if (rng() % 32u == 0) tab[(size_t) i] = -1; + for (int64_t i = kHole / PS; i < (kHole + 256) / PS; ++i) tab[(size_t) i] = -1; + table = keep(upload(tab)); + const int64_t rows = pages * H * PS; + pools.page_table = table; + std::vector c((size_t) (rows * D)); + for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127); + pools.k_q = keep(upload(c)); + for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127); + pools.v_q = keep(upload(c)); + std::vector sc((size_t) (rows * (D / 64))); + for (auto& x : sc) x = f16_scale_q8(rng()); + pools.k_scale = keep(upload(sc)); + for (auto& x : sc) x = f16_scale_q8(rng()); + pools.v_scale = keep(upload(sc)); + q = keep(dalloc((size_t) (max_q * s.n_head * D))); + ids = keep(dalloc((size_t) (max_q * max_cap))); + steps = keep(dalloc((size_t) (max_q * k::kStepCount))); + const size_t sf = (size_t) (k::qsa_decode_attn_scratch_floats(max_cap, s) * (uint64_t) max_q); + scratch_ref = keep(dalloc(sf)); + scratch_new = keep(dalloc(sf)); + attn_ref = keep(dalloc((size_t) (max_q * s.n_head * D))); + attn_new = keep(dalloc((size_t) (max_q * s.n_head * D))); + } + ~Harness() { + for (void* p : to_free) cudaFree(p); + } + + // returns 0 identical, 1 differs, -1 the candidate declined (build without the kernels) + int run(int64_t cap, int n_q, int scr_q, const std::vector& widths, std::mt19937& rng, bool on_pascal, + long long& nonzero) { + const int64_t D = s.head_dim, NH = s.n_head; + std::normal_distribution nd(0.0f, 1.0f); + std::vector hq((size_t) (n_q * NH * D)); + for (auto& x : hq) x = nd(rng); + ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q"); + std::vector hid((size_t) (n_q * cap)); + std::vector hst((size_t) (n_q * k::kStepCount), 0); + for (int i = 0; i < n_q; ++i) { + selection(hid.data() + (size_t) i * cap, cap, widths[(size_t) i], (int) (rng() % 3u), rng); + hst[(size_t) i * k::kStepCount + k::kStepWidth] = widths[(size_t) i]; + } + ck(cudaMemcpy(ids, hid.data(), hid.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps"); + const size_t n = (size_t) (n_q * NH * D); + const size_t sbytes = (size_t) k::qsa_decode_attn_scratch_floats(cap, s) * (size_t) n_q * 4; + + // the reference: the pre-sm_75 chunk kernel and attn_merge_kernel + ck(cudaMemset(scratch_ref, 0xFF, sbytes), "scratch_ref fill"); + ck(cudaMemset(attn_ref, 0xFF, n * 4), "attn_ref fill"); + k::qsa_decode_attn_chunks_only(q, pools, ids, steps, cap, s, scratch_ref, n_q, 1, nullptr); + k::qsa_decode_attn_merge_only(steps, cap, s, scratch_ref, attn_ref, n_q, 0, nullptr); + ck(cudaDeviceSynchronize(), "reference"); + std::vector a(n), b(n); + ck(cudaMemcpy(a.data(), attn_ref, n * 4, cudaMemcpyDeviceToHost), "read reference"); + nonzero = 0; + for (size_t i = 0; i < n; ++i) { + if (!std::isfinite(a[i])) { std::printf("FAIL: the reference has a non-finite value\n"); return 1; } + if (a[i] != 0.0f) ++nonzero; + } + + // the candidate: the scratch holds scr_q queries of the decode layout (the caller's attn_batch), junk in it + ck(cudaMemset(scratch_new, 0xFF, sbytes), "scratch_new fill"); + ck(cudaMemset(attn_new, 0x7F, n * 4), "attn_new fill"); + const uint64_t scratch_floats = (uint64_t) scr_q * k::qsa_decode_attn_scratch_floats(cap, s); + const bool took = k::qsa_pattn_batch_any_arch(q, pools, ids, steps, cap, s, scratch_new, scratch_floats, attn_new, + n_q, nullptr); + if (!took) return -1; + ck(cudaDeviceSynchronize(), "candidate"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read candidate"); + bool same = std::memcmp(a.data(), b.data(), n * 4) == 0; + if (!same) { + size_t first = 0; + while (first < n && std::memcmp(&a[first], &b[first], 4) == 0) ++first; + std::printf("FAIL cap %lld n_q %d scratch %d queries, widths", (long long) cap, n_q, scr_q); + for (int32_t w : widths) std::printf(" %d", w); + std::printf(": first difference at query %lld head %lld dim %lld: %.9g vs %.9g\n", + (long long) (first / (NH * D)), (long long) (first / D % NH), (long long) (first % D), a[first], + b[first]); + } + if (on_pascal) { // the checked entry takes the shapes, and the production path is the reference + ck(cudaMemset(scratch_new, 0xFF, sbytes), "scratch_new refill"); + ck(cudaMemset(attn_new, 0x7F, n * 4), "attn_new refill"); + if (!k::qsa_pattn_batch(q, pools, ids, steps, cap, s, scratch_new, scratch_floats, attn_new, n_q, nullptr)) { + std::printf("FAIL: qsa_pattn_batch declined on a compute capability 6 card (cap %lld n_q %d)\n", + (long long) cap, n_q); + same = false; + } else { + ck(cudaDeviceSynchronize(), "checked entry"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read checked entry"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::printf("FAIL: qsa_pattn_batch differs from the reference (cap %lld n_q %d)\n", (long long) cap, n_q); + same = false; + } + } + ck(cudaMemset(scratch_new, 0xFF, sbytes), "scratch_new refill"); + k::qsa_decode_attn_batch(q, pools, ids, steps, cap, s, scratch_new, attn_new, n_q, nullptr); + ck(cudaDeviceSynchronize(), "production"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read production"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::printf("FAIL: qsa_decode_attn_batch differs from the reference (cap %lld n_q %d)\n", (long long) cap, + n_q); + same = false; + } + } + return same ? 0 : 1; + } +}; +} // namespace + +int main(int argc, char** argv) { + int device = 0; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else { + std::fprintf(stderr, "usage: qsa_pattn_parity [--device N]\n"); + return 2; + } + } + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::puts("SKIP: no GPU"); + return 77; + } + ck(cudaSetDevice(device), "cudaSetDevice"); + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + const bool on_pascal = prop.major == 6; + std::printf("qsa_pattn_parity on device %d (%s, %d.%d)%s\n", device, prop.name, prop.major, prop.minor, + on_pascal ? ": the checked entry and the production path are compared too" : ""); + + std::mt19937 rng(20261026u); + Harness hx; + hx.init(rng, 40, 2112); + + const int32_t base_widths[] = {0, 1, 63, 64, 65, 1023, 1024, 1025, 2051, 2112}; + const int n_base = (int) (sizeof(base_widths) / sizeof(base_widths[0])); + long long cases = 0, failed = 0, nonzero_total = 0; + for (int64_t cap : {(int64_t) 64, (int64_t) 130, (int64_t) 2051, (int64_t) 2112}) { + for (int n_q : {1, 2, 3, 7, 40}) { + for (int scr_q : {n_q, 2}) { + if (scr_q > n_q) continue; + for (int wc = 0; wc < n_base + 3; ++wc) { + std::vector widths; + for (int i = 0; i < n_q; ++i) + widths.push_back(std::min((int32_t) cap, wc < n_base ? base_widths[wc] : base_widths[rng() % (uint32_t) n_base])); + long long nz = 0; + const int r = hx.run(cap, n_q, scr_q, widths, rng, on_pascal, nz); + if (r < 0) { + std::puts("SKIP: this build has no sm_6x kernels (CUDA with STRATA_EXPERIMENTAL_SM60)"); + return 77; + } + nonzero_total += nz; + ++cases; + if (r != 0) ++failed; + } + } + } + } + std::printf("qsa_pattn_parity: %lld cases, %lld differ, %lld nonzero output values in all -> %s\n", cases, failed, + nonzero_total, failed == 0 && nonzero_total > 0 ? "PASS" : "FAIL"); + return failed == 0 && nonzero_total > 0 ? 0 : 1; +} diff --git a/src/kernels/qsa_select_long_parity.cpp b/src/kernels/qsa_select_long_parity.cpp new file mode 100644 index 00000000..affb41ac --- /dev/null +++ b/src/kernels/qsa_select_long_parity.cpp @@ -0,0 +1,214 @@ +// src/kernels/qsa_select_long_parity.cpp - STRATA_SELECT_LONG's decode select (PR #3820): qsa_block_scores_long +// (block_scores_dx_kernel) and qsa_block_topk_long (the multi-CTA top-k) against qsa_block_scores and qsa_block_topk, +// bit for bit (GPU, synthetic data, no model). +// +// Needs the CUDA build with STRATA_EXPERIMENTAL_SM60 (elsewhere the _long calls forward to the plain ones and there is +// nothing to compare; the test skips with 77) and STRATA_SCORES_DX=1 STRATA_TOPK_MULTI=1 in the environment, which make +// the new kernels run on any card (on compute capability 6.x they are the default). STRATA_TOPK_MULTI_N= fixes the +// CTAs per query (the ctest "n3" case), otherwise one per 2,048 blocks of capacity. +// +// scores: random pooled keys, queries and a dead key; nq 1..8 queries with their own n_bid (a decode window's +// consecutive positions, so tail blocks of 0..3 cells), n_bid 0 / 1 / 31 / 32 / 33 / 1000 / 70001 ...; the +// scores of every block 0..n_bid of every query are compared by memcmp (the tail block n_bid included). +// top-k: scores that are random, all equal, 7 distinct values (many ties across CTAs, so the "first eq_budget cells +// at the threshold" rule is exercised) and random with a boosted tail block; contexts 1,000 (width equals +// n_kv: the identity) up to 524,288 cells; nq 1, 2, 5, 8, 16; capacity max_blocks = the largest context / 4 + 2. +// The selected ids of every query are compared on the first `width` entries. The multi-CTA scratch is filled +// with junk before every call (the contract says no initial value) and must have been written (the new +// kernels ran; a forwarded call would leave it untouched). +// +// qsa_select_long_parity [--device N] exit 0: all cases identical; 77: no GPU or a build without the kernels +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_select.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_select_long_parity: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(2); + } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc((void**) &p, n * sizeof(T) + 64), "cudaMalloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 64), "cudaMemset"); + return p; +} +template T* upload(const std::vector& h) { + T* d = dalloc(h.size()); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} + +// steps of a decode window: query i at position pos0 + i +std::vector make_steps(int nq, int64_t pos0, const k::QsaShapes& s) { + std::vector st((size_t) nq * k::kStepCount, 0); + for (int i = 0; i < nq; ++i) { + int32_t* p = st.data() + (size_t) i * k::kStepCount; + const int64_t pos = pos0 + i; + p[k::kStepPos] = (int32_t) pos; + p[k::kStepNKv] = (int32_t) (pos + 1); + p[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); + p[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); + } + return st; +} + +long long g_cases = 0, g_failed = 0; + +void check_scores(const k::QsaShapes& s, int nq, int64_t n_bid0, std::mt19937& rng) { + const int64_t D = s.idx_dim, H = s.idx_n_head; + const int64_t max_blocks = n_bid0 + nq + 8; + std::normal_distribution nd(0.0f, 1.0f); + std::vector pooled((size_t) (max_blocks * D)), dead((size_t) D), q((size_t) (nq * H * D)); + for (auto& x : pooled) x = nd(rng); + for (auto& x : dead) x = nd(rng); + for (auto& x : q) x = nd(rng); + // the window's last query has n_bid0 blocks; the others one position earlier each (their tails differ) + const std::vector steps = make_steps(nq, n_bid0 * s.idx_block - 1 + (int64_t) (rng() % 4u) - (nq - 1), s); + float *dp = upload(pooled), *dd = upload(dead), *dq = upload(q); + int32_t* dst = upload(steps); + float* a = dalloc((size_t) (nq * max_blocks)); + float* b = dalloc((size_t) (nq * max_blocks)); + ck(cudaMemset(a, 0xFF, (size_t) (nq * max_blocks) * 4), "fill a"); + ck(cudaMemset(b, 0xFF, (size_t) (nq * max_blocks) * 4), "fill b"); + k::qsa_block_scores(dp, dd, dq, dst, nq, max_blocks, s, a, nullptr); + k::qsa_block_scores_long(dp, dd, dq, dst, nq, max_blocks, s, b, nullptr, -1); + ck(cudaDeviceSynchronize(), "scores"); + std::vector ha((size_t) (nq * max_blocks)), hb(ha.size()); + ck(cudaMemcpy(ha.data(), a, ha.size() * 4, cudaMemcpyDeviceToHost), "read a"); + ck(cudaMemcpy(hb.data(), b, hb.size() * 4, cudaMemcpyDeviceToHost), "read b"); + bool ok = true; + for (int i = 0; i < nq && ok; ++i) { + const int64_t nb = steps[(size_t) i * k::kStepCount + k::kStepNBid]; + for (int64_t j = 0; j <= nb; ++j) { // block n_bid is the tail + if (std::memcmp(&ha[(size_t) (i * max_blocks + j)], &hb[(size_t) (i * max_blocks + j)], 4) != 0) { + std::printf("FAIL scores nq %d n_bid0 %lld: query %d block %lld: %.9g vs %.9g\n", nq, (long long) n_bid0, i, + (long long) j, ha[(size_t) (i * max_blocks + j)], hb[(size_t) (i * max_blocks + j)]); + ok = false; + break; + } + } + } + ++g_cases; + if (!ok) ++g_failed; + for (void* p : {(void*) dp, (void*) dd, (void*) dq, (void*) dst, (void*) a, (void*) b}) cudaFree(p); +} + +void check_topk(const k::QsaShapes& s, int nq, int64_t ctx, int mode, int64_t max_blocks, std::mt19937& rng, bool& multi_ran) { + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); + const std::vector steps = make_steps(nq, ctx - nq, s); + std::vector sc((size_t) (nq * max_blocks), -999.0f); + std::uniform_real_distribution ur(0.0f, 200.0f); + for (int i = 0; i < nq; ++i) { + const int32_t nb = steps[(size_t) i * k::kStepCount + k::kStepNBid]; + const bool tail = steps[(size_t) i * k::kStepCount + k::kStepNKv] % s.idx_block != 0; + for (int64_t j = 0; j <= nb; ++j) { + float v = mode == 1 ? 3.0f : mode == 2 ? (float) (rng() % 7u) : ur(rng); + sc[(size_t) (i * max_blocks + j)] = v; + } + if (tail && mode != 1) sc[(size_t) (i * max_blocks + nb)] += 1e9f; + } + float* ds = upload(sc); + int32_t* dst = upload(steps); + int32_t* ia = dalloc((size_t) (nq * cap)); + int32_t* ib = dalloc((size_t) (nq * cap)); + const int64_t scratch_ints = k::qsa_topk_multi_scratch_ints(nq); + int32_t* scratch = dalloc((size_t) scratch_ints); + ck(cudaMemset(scratch, 0xFF, (size_t) scratch_ints * 4), "scratch junk"); + ck(cudaMemset(ia, 0xFF, (size_t) (nq * cap) * 4), "fill ia"); + ck(cudaMemset(ib, 0xFF, (size_t) (nq * cap) * 4), "fill ib"); + k::qsa_block_topk(ds, dst, nq, max_blocks, cap, s, ia, nullptr); + k::qsa_block_topk_long(ds, dst, nq, max_blocks, cap, s, ib, nullptr, -1, scratch); + ck(cudaDeviceSynchronize(), "topk"); + std::vector ha((size_t) (nq * cap)), hb(ha.size()), hs((size_t) scratch_ints); + ck(cudaMemcpy(ha.data(), ia, ha.size() * 4, cudaMemcpyDeviceToHost), "read ia"); + ck(cudaMemcpy(hb.data(), ib, hb.size() * 4, cudaMemcpyDeviceToHost), "read ib"); + ck(cudaMemcpy(hs.data(), scratch, hs.size() * 4, cudaMemcpyDeviceToHost), "read scratch"); + // the multi kernels write the scratch (pass 0's histogram rows) when the contexts are above the identity width + const bool touched = std::any_of(hs.begin(), hs.end(), [](int32_t v) { return v != -1; }); + if (touched) multi_ran = true; + bool ok = true; + for (int i = 0; i < nq && ok; ++i) { + const int64_t w = steps[(size_t) i * k::kStepCount + k::kStepWidth]; + if (!std::equal(ha.begin() + i * cap, ha.begin() + i * cap + w, hb.begin() + i * cap)) { + size_t first = 0; + while (ha[(size_t) (i * cap) + first] == hb[(size_t) (i * cap) + first]) ++first; + std::printf("FAIL topk nq %d ctx %lld mode %d max_blocks %lld: query %d entry %zu: %d vs %d\n", nq, + (long long) ctx, mode, (long long) max_blocks, i, first, ha[(size_t) (i * cap) + first], + hb[(size_t) (i * cap) + first]); + ok = false; + } + } + ++g_cases; + if (!ok) ++g_failed; + for (void* p : {(void*) ds, (void*) dst, (void*) ia, (void*) ib, (void*) scratch}) cudaFree(p); +} +} // namespace + +int main(int argc, char** argv) { + int device = 0; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else { + std::fprintf(stderr, "usage: qsa_select_long_parity [--device N]\n"); + return 2; + } + } + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::puts("SKIP: no GPU"); + return 77; + } + ck(cudaSetDevice(device), "cudaSetDevice"); + if (k::qsa_topk_multi_scratch_ints(1) <= 0) { + std::puts("SKIP: this build has no multi-CTA select (CUDA with STRATA_EXPERIMENTAL_SM60)"); + return 77; + } + const char* dx = std::getenv("STRATA_SCORES_DX"); + const char* mt = std::getenv("STRATA_TOPK_MULTI"); + if (dx == nullptr || dx[0] != '1' || mt == nullptr || mt[0] != '1') { + std::fprintf(stderr, "qsa_select_long_parity: set STRATA_SCORES_DX=1 and STRATA_TOPK_MULTI=1 (the kernels are " + "otherwise default only on compute capability 6.x)\n"); + return 2; + } + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + std::printf("qsa_select_long_parity on device %d (%s, %d.%d), STRATA_TOPK_MULTI_N=%s\n", device, prop.name, prop.major, + prop.minor, std::getenv("STRATA_TOPK_MULTI_N") ? std::getenv("STRATA_TOPK_MULTI_N") : "(per capacity)"); + + const k::QsaShapes s = k::qsa_real_shapes(); + std::mt19937 rng(20261026u); + for (int nq : {1, 2, 3, 5, 8}) + for (int64_t nb : {(int64_t) 8, (int64_t) 31, (int64_t) 32, (int64_t) 33, (int64_t) 1000, (int64_t) 70001, (int64_t) 131072}) + check_scores(s, nq, nb, rng); + + bool multi_ran = false; + const int64_t max_ctx = 524288, max_blocks = max_ctx / s.idx_block + 2; + for (int nq : {1, 2, 5, 8, 16}) + for (int64_t ctx : {(int64_t) 1000, (int64_t) 2051, (int64_t) 2055, (int64_t) 8192, (int64_t) 70000, (int64_t) 135164, + (int64_t) 135168, (int64_t) 300003, max_ctx}) + for (int mode = 0; mode < 3; ++mode) + check_topk(s, nq, ctx, mode, max_blocks, rng, multi_ran); + // a smaller capacity than the context asks for (max_blocks only bounds the row stride) + for (int nq : {1, 4}) check_topk(s, nq, 40000, 0, 40000 / s.idx_block + 2, rng, multi_ran); + if (!multi_ran) { + std::printf("FAIL: the multi-CTA top-k never wrote its scratch: the new kernels did not run\n"); + ++g_failed; + } + std::printf("qsa_select_long_parity: %lld cases, %lld differ -> %s\n", g_cases, g_failed, g_failed == 0 ? "PASS" : "FAIL"); + return g_failed == 0 ? 0 : 1; +} diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index e7ff5d45..e832cffe 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -144,6 +144,54 @@ __global__ void swiglu_kernel(const float* __restrict__ gu, float* __restrict__ h[i] = g / (1.0f + __expf(-g)) * u; } +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +// swiglu_kernel (n_ff 640), then quantize_mmq_q8_1's rows of its output, in one pass: a block per row (128 +// threads, 4 values each, blockIdx.y the row's 512-value half), H never stored. Each value is swiglu_kernel's +// expression and each 32-value block quantize_mmq_q8_1's (the same unit and flags: the same bits). +template +__global__ void __launch_bounds__(128) swiglu_quant_kernel(const float* __restrict__ gu, block_q8_1_mmq* __restrict__ y, + int64_t rows) { + constexpr int64_t n_ff = 640, ne0 = 1024; // the padded row: pad512(640) + const int64_t i0 = ((int64_t) blockDim.x * blockIdx.y + threadIdx.x) * 4; + if (i0 >= ne0) return; + const int64_t r = blockIdx.x; + float4 xi = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + if (i0 < n_ff) { + const float* row = gu + r * 2 * n_ff; + float4 g4, u4; + if constexpr (IL) { // gate 2k, up 2k + 1 + const float4 a = *reinterpret_cast(row + 2 * i0), b = *reinterpret_cast(row + 2 * i0 + 4); + g4 = make_float4(a.x, a.z, b.x, b.z); + u4 = make_float4(a.y, a.w, b.y, b.w); + } else { + g4 = *reinterpret_cast(row + i0); + u4 = *reinterpret_cast(row + n_ff + i0); + } + xi.x = g4.x / (1.0f + __expf(-g4.x)) * u4.x; + xi.y = g4.y / (1.0f + __expf(-g4.y)) * u4.y; + xi.z = g4.z / (1.0f + __expf(-g4.z)) * u4.z; + xi.w = g4.w / (1.0f + __expf(-g4.w)) * u4.w; + } + float amax = fabsf(xi.x); + amax = fmaxf(amax, fabsf(xi.y)); + amax = fmaxf(amax, fabsf(xi.z)); + amax = fmaxf(amax, fabsf(xi.w)); +#pragma unroll + for (int offset = 32 / 8; offset > 0; offset >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE)); + const float d_inv = 127.0f / amax; + char4 c; + c.x = roundf(xi.x * d_inv); + c.y = roundf(xi.y * d_inv); + c.z = roundf(xi.z * d_inv); + c.w = roundf(xi.w * d_inv); + const float d = 1.0f / d_inv; + const int64_t k_block = i0 / QK8_1_MMQ, iqs = i0 % QK8_1_MMQ; + block_q8_1_mmq* yb = y + k_block * rows + r; + reinterpret_cast(yb->qs)[iqs / 4] = c; + if (iqs % 32 == 0) yb->d4[iqs / 32] = d; +} +#endif + // swiglu_kernel on the MMQ gate/up output with each expert's gate and up scales applied as it is read: the products // scale_gu_rows stored, without the pass that stored them __global__ void swiglu_scaled_kernel(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff, @@ -665,6 +713,28 @@ void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interlea ck(cudaGetLastError(), "swiglu"); } +bool swiglu_quant_ok(int t) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + // the q8_1 D4 rows quantize() writes for a down product's H (K 640) + return supported(t) && !fp4_activations(t) && mmq_get_q8_1_ds_layout((ggml_type) t) == MMQ_Q8_1_DS_LAYOUT_D4; +#else + (void) t; + return false; // HIP: not checked against the HIP build's quantizer; outside the SM60 build: not built +#endif +} + +void swiglu_quant(const float* gu, void* hq, int64_t rows, bool interleaved, void* stream) { +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) + if (rows <= 0) return; + const dim3 grid((unsigned) rows, 2); + if (interleaved) swiglu_quant_kernel<<>>(gu, (block_q8_1_mmq*) hq, rows); + else swiglu_quant_kernel<<>>(gu, (block_q8_1_mmq*) hq, rows); + ck(cudaGetLastError(), "swiglu_quant"); +#else + (void) gu; (void) hq; (void) rows; (void) interleaved; (void) stream; +#endif +} + void iota(int32_t* dst, int64_t n, void* stream) { if (n <= 0) return; iota_kernel<<>>(dst, n); diff --git a/src/prefill/moe_ws.cu b/src/prefill/moe_ws.cu new file mode 100644 index 00000000..4a50719c --- /dev/null +++ b/src/prefill/moe_ws.cu @@ -0,0 +1,165 @@ +// src/prefill/moe_ws.cu - see include/strata/prefill/moe_ws.hpp: which layers and products take the weight-stationary +// kernels (moe_ws_gu_iq2.cu, moe_ws_gu_iq3.cu, moe_ws_down.cu), their work tables and launches. +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include +#include +#include +#include +#include +#include + +namespace strata::prefill::ws { +namespace { + +// ws / per-group MMQ (one 512-expert top-10 layer, lognormal counts sigma 0.5 and 1.0, the worse of the two; isolated +// sustained medians measured on a GP100 die, the variant moe_ws_*.cu picks) at 2.5, 10, 35 and 160 rows per routed +// expert +struct Measured { int type; float r[4]; }; +constexpr double kU[4] = {2.5, 10.0, 35.0, 160.0}; +constexpr Measured kMeasured[] = { + {GGML_TYPE_IQ2_XXS, {0.276f, 0.494f, 0.728f, 0.754f}}, + {GGML_TYPE_IQ2_XS, {0.299f, 0.513f, 0.750f, 0.824f}}, + {GGML_TYPE_IQ2_S, {0.317f, 0.520f, 0.754f, 0.816f}}, + {GGML_TYPE_IQ3_XXS, {0.329f, 0.514f, 0.755f, 0.786f}}, + {GGML_TYPE_IQ3_S, {0.347f, 0.521f, 0.715f, 0.793f}}, + {GGML_TYPE_Q2_0, {0.246f, 0.389f, 0.555f, 0.614f}}, + {GGML_TYPE_IQ4_NL, {0.292f, 0.492f, 0.682f, 0.742f}}, +}; + +const Measured* measured(int t) { + for (const Measured& m : kMeasured) + if (m.type == t) return &m; + return nullptr; +} +bool gu_type(int t) { + return t == GGML_TYPE_IQ2_XXS || t == GGML_TYPE_IQ2_XS || t == GGML_TYPE_IQ2_S || t == GGML_TYPE_IQ3_XXS || + t == GGML_TYPE_IQ3_S; +} + +} // namespace + +namespace { +std::atomic g_mode_override{-1}; // set_mode (tests); -1: the environment +} // namespace + +void set_mode(int v) { g_mode_override.store(v < 0 ? -1 : (v != 0 ? 1 : 0), std::memory_order_relaxed); } + +int mode() { +#if defined(__HIPCC__) + return 0; +#else + const int o = g_mode_override.load(std::memory_order_relaxed); + if (o >= 0) return o; + static const int m = [] { + const char* e = std::getenv("STRATA_MMQ_WS"); // opt-in + if (e == nullptr || std::atoi(e) != 1) return 0; + // GP100 (cc 6.0) only: tuned and checked there (any visible GPU that is not: off for all) + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n <= 0) { cudaGetLastError(); return 0; } + for (int d = 0; d < n; ++d) { + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, d) != cudaSuccess || p.major != 6 || p.minor != 0) { cudaGetLastError(); return 0; } + } + return 1; + }(); + return m; +#endif +} + +bool supported(int gt, int dt) { return mode() != 0 && gu_type(gt) && (dt == GGML_TYPE_Q2_0 || dt == GGML_TYPE_IQ4_NL); } + +namespace { +std::atomic g_fast_override{-1}; // set_fast (benches, tests); -1: the environment +} // namespace + +int fast() { + const int o = g_fast_override.load(std::memory_order_relaxed); + if (o >= 0) return o; + static const int f = [] { + const char* e = std::getenv("STRATA_WS_FAST"); // opt-in + return e != nullptr && std::atoi(e) == 1 ? 1 : 0; + }(); + return f; +} + +void set_fast(int v) { g_fast_override.store(v < 0 ? -1 : (v != 0 ? 1 : 0), std::memory_order_relaxed); } + +bool faster(int t, double u) { + const Measured* m = measured(t); + if (m == nullptr) return false; + // linear in log u between the measured points, the ends held + if (u <= kU[0]) return m->r[0] < 1.0f; + for (int i = 1; i < 4; ++i) + if (u <= kU[i]) { + const double f = std::log(u / kU[i - 1]) / std::log(kU[i] / kU[i - 1]); + return m->r[i - 1] + f * (m->r[i] - m->r[i - 1]) < 1.0; + } + return m->r[3] < 1.0f; +} + +size_t chunks(const int32_t* order, size_t n, const int32_t* cnt, const int32_t* bounds, Chunk* out) { + // largest expert first: MMQ's order is ascending by count where the resident sort ran (walked backwards), else + // by id (sorted here) + bool asc = true; + for (size_t j = 1; j < n && asc; ++j) asc = cnt[order[j - 1]] <= cnt[order[j]]; + static thread_local std::vector by; + by.resize(n); + for (size_t j = 0; j < n; ++j) by[j] = (int32_t) (n - 1 - j); + if (!asc) + std::stable_sort(by.begin(), by.end(), [&](int32_t a, int32_t b) { return cnt[order[a]] > cnt[order[b]]; }); + size_t k = 0; + for (const int32_t j : by) { + const int32_t c = cnt[order[j]], b = bounds[j]; + for (int32_t tk = 0; tk < c; tk += kChunkRows) out[k++] = Chunk{j, b + tk, std::min(kChunkRows, c - tk), 0}; + } + return k; +} + +bool gate_up(const Layer& L, void* stream) { + if (L.n <= 0 || L.nchunks <= 0) return true; + const double u = (double) L.rows / L.n; + if (mode() != 1 || !faster(L.gu_type, u)) return false; + const cudaStream_t s = (cudaStream_t) stream; + switch (L.gu_type) { + case GGML_TYPE_IQ2_XXS: detail::gu_iq2_xxs(L, u, s); break; + case GGML_TYPE_IQ2_XS: detail::gu_iq2_xs(L, u, s); break; + case GGML_TYPE_IQ2_S: detail::gu_iq2_s(L, u, s); break; + case GGML_TYPE_IQ3_XXS: detail::gu_iq3_xxs(L, u, s); break; + case GGML_TYPE_IQ3_S: detail::gu_iq3_s(L, u, s); break; + default: + std::fprintf(stderr, "prefill ws: gate/up type %d has no kernel\n", L.gu_type); + std::exit(1); + } + return true; +} + +void down(const Layer& L, void* stream) { + if (L.n <= 0 || L.nchunks <= 0) return; + const double u = (double) L.rows / L.n; + const cudaStream_t s = (cudaStream_t) stream; + switch (L.d_type) { + case GGML_TYPE_Q2_0: detail::dn_q2_0(L, u, s); break; + case GGML_TYPE_IQ4_NL: { + const bool f = fast() == 1; + if (f) { // once per process: the switch is on and the WS path runs + static const bool said = [] { + std::fprintf(stderr, "strata prefill: STRATA_WS_FAST=1: the weight-stationary IQ4_NL down's 32-token " + "tier with switched token pairs and transposed dy (the same Dm bits)\n"); + return true; + }(); + (void) said; + } + detail::dn_iq4_nl(L, u, s, f); + break; + } + default: + std::fprintf(stderr, "prefill ws: down type %d has no kernel\n", L.d_type); + std::exit(1); + } +} + +} // namespace strata::prefill::ws diff --git a/src/prefill/moe_ws.cuh b/src/prefill/moe_ws.cuh new file mode 100644 index 00000000..ef37d434 --- /dev/null +++ b/src/prefill/moe_ws.cuh @@ -0,0 +1,49 @@ +// src/prefill/moe_ws.cuh - the weight-stationary expert kernels' shared pieces (see moe_ws.hpp): included after +// ggml-cuda's common.cuh and mmq.cuh by moe_ws.cu and the moe_ws_*.cu that hold the kernels (a few formats per file, +// so the instances compile in parallel). +#pragma once + +#include "strata/prefill/moe_ws.hpp" + +#include + +namespace strata::prefill::ws::detail { + +// The two ways every kernel multiplies: int8 values sign-extended to int16 pairs (one PRMT per pair: bytes 0,2 and 1,3) +// and a pair of products added to a 32-bit sum by two XMAD (mad.wide.s16) - MMQ's dp4a on sm_60, one product at a time. +// A 32-value block's integer sum is exact (|sum| < 2^22 for every format here), so the order of its MACs is free. +__device__ __forceinline__ void split2(const int v, int& lo02, int& hi13) { + asm("prmt.b32 %0, %1, 0, 0xA280;" : "=r"(lo02) : "r"(v)); + asm("prmt.b32 %0, %1, 0, 0xB391;" : "=r"(hi13) : "r"(v)); +} +__device__ __forceinline__ int mad2(const int w, const int a, int c) { + asm("{\n\t.reg .s16 al, ah, bl, bh;\n\t" + "mov.b32 {al, ah}, %1;\n\tmov.b32 {bl, bh}, %2;\n\t" + "mad.wide.s16 %0, al, bl, %0;\n\tmad.wide.s16 %0, ah, bh, %0;\n\t}" + : "+r"(c) : "r"(w), "r"(a)); + return c; +} +// float(sum) for |sum| < 2^22 without the quarter-rate I2F: a chain seeded with 1.5 * 2^23 holds the float's bits +constexpr int kMagicI = 0x4B400000; +constexpr float kMagicF = 12582912.0f; + +// CTA b's chunk and first weight row: chunk b / pieces, piece b % pieces (`pieces` = weight rows / rows per CTA) - the +// chunks' order, each chunk's pieces next to each other +template +__device__ __forceinline__ Chunk cta_work(const Chunk* __restrict__ chunks, int& r0) { + r0 = (int) (blockIdx.x % PIECES) * ROWS; + const int4 c = __ldg((const int4*) chunks + blockIdx.x / PIECES); + return Chunk{c.x, c.y, c.z, c.w}; +} + +// one launch of a layer's product, the variant picked by u (rows per routed expert); grid = nchunks x pieces +void gu_iq2_xxs(const Layer& L, double u, cudaStream_t s); +void gu_iq2_xs(const Layer& L, double u, cudaStream_t s); +void gu_iq2_s(const Layer& L, double u, cudaStream_t s); +void gu_iq3_xxs(const Layer& L, double u, cudaStream_t s); +void gu_iq3_s(const Layer& L, double u, cudaStream_t s); +void dn_q2_0(const Layer& L, double u, cudaStream_t s); +// `fast`: ws::fast() (STRATA_WS_FAST=1) - the 32-token tier's fast kernel, the same Dm rows +void dn_iq4_nl(const Layer& L, double u, cudaStream_t s, bool fast); + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/moe_ws_down.cu b/src/prefill/moe_ws_down.cu new file mode 100644 index 00000000..346f3a82 --- /dev/null +++ b/src/prefill/moe_ws_down.cu @@ -0,0 +1,645 @@ +// src/prefill/moe_ws_down.cu - weight-stationary down products (see moe_ws.hpp): Q2_0 and IQ4_NL, [2560 x 640] read in +// place at the blob's down offset, K stopping at 640 (nothing past a matrix is read). A CTA = 128 or 256 threads = +// as many weight rows of one expert (a row per thread, all of the chunk's H rows TPP at a time, the sums in registers); +// per K step the next step's weight bytes and q8_1 words are loaded into registers before this step's compute and +// stored to shared memory after it (one barrier pair per step). The H rows are ONE mmq::swiglu_quant over all of the +// layer's rows: [k/128][rows] block_q8_1_mmq, of which blocks 0-4 are read. (Measured on a GP100 die: ws / per-group +// MMQ 0.24-0.29 at 2.5 rows per expert, 0.38-0.49 at 10, 0.52-0.68 at 35, 0.61-0.74 at 160; bit-identical, +// compute-sanitizer clean with exact-size matrices.) +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include +#include +#include + +namespace strata::prefill::ws::detail { +namespace { + +constexpr int DN_ROWS = 2560, DN_K = 640; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// ---- Q2_0: 18-B blocks {f16 d; 16 B of 2-bit codes}, 180-B rows; a step is 128 values = 2 blocks = 36 B of a row. +// MMQ's values {-1, 0, 1, 2}[code] (ggml_cuda_mmq_load_tiles_q2_0's PRMT, the selector masked to 3 bits) and the +// activations' int8 are both made exact fp16 pairs; a 32-value block is 16 HFMA2 into 2 half2 sums, each fp16 lane +// summing 8 products of magnitude <= 256 - integers <= 2048, exact - added in fp32: the float MMQ's I2F(sumi) gives. +// Epilogue as MMQ's sm_60 SASS: per 32-value block FMUL.FTZ (dx * dy), FFMA.FTZ (prod, sum, acc), blocks in K order. +namespace q20 { +constexpr int NT = 128, ROWB = 180, NSTEP = DN_K / 128, QB = 144, PIECES = DN_ROWS / NT; + +__device__ __forceinline__ uint32_t prmt(const uint32_t a, const uint32_t b, const uint32_t s) { + uint32_t d; + asm("prmt.b32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(s)); + return d; +} +__device__ __forceinline__ uint32_t hfma2(const uint32_t a, const uint32_t b, const uint32_t c) { + uint32_t d; + asm("fma.rn.f16x2 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); + return d; +} +__device__ __forceinline__ uint32_t hadd2(const uint32_t a, const uint32_t b) { + uint32_t d; + asm("add.rn.f16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); + return d; +} +// the two fp16 lanes of h converted exactly to f32 and added +__device__ __forceinline__ float h2sum(const uint32_t h) { + float f; + asm("{\n\t.reg .f16 lo, hi;\n\t.reg .f32 a, b;\n\tmov.b32 {lo, hi}, %1;\n\t" + "cvt.f32.f16 a, lo;\n\tcvt.f32.f16 b, hi;\n\tadd.f32 %0, a, b;\n\t}" + : "=f"(f) : "r"(h)); + return f; +} +__device__ __forceinline__ float f16_to_f32(const uint32_t bits16) { + float f; + asm("{\n\t.reg .b16 h;\n\tcvt.u16.u32 h, %1;\n\tcvt.f32.f16 %0, h;\n\t}" : "=f"(f) : "r"(bits16)); + return f; +} + +// the 16 values of the int16 qa = x2 & 0xFFFF, qb = x2 >> 16 of a block's codes (value i at bits 2i) as fp16 pairs +// (v0,v4) (v1,v5) (v2,v6) (v3,v7), qa's to wa and qb's to wb: prmt(H, 0, sel) with nibbles 1 / 3 of sel the code with +// its low bit flipped and nibbles 0 / 2 zero (byte 0 of H, the zero high byte) +__device__ __forceinline__ void dec2_h16(const uint32_t x2, uint32_t (&wa)[4], uint32_t (&wb)[4]) { + constexpr uint32_t H = 0x3C40BC00u; // bytes 00 BC 40 3C = fp16 high bytes of {0, -1, +2, +1}[c ^ 1] = {-1,0,1,2}[c] + const uint32_t x = x2 ^ 0x55555555u; + const uint32_t m0 = (x << 4) & 0x30303030u, m1 = (x << 2) & 0x30303030u, m2 = x & 0x30303030u, m3 = (x >> 2) & 0x30303030u; + wa[0] = prmt(H, 0u, m0); + wa[1] = prmt(H, 0u, m1); + wa[2] = prmt(H, 0u, m2); + wa[3] = prmt(H, 0u, m3); + wb[0] = prmt(H, 0u, m0 >> 16); + wb[1] = prmt(H, 0u, m1 >> 16); + wb[2] = prmt(H, 0u, m2 >> 16); + wb[3] = prmt(H, 0u, m3 >> 16); +} + +// the 8 int8 of activation words A (values 0-3) and B (4-7) as fp16 pairs (a0,a4) (a1,a5) (a2,a6) (a3,a7): +// u = a + 128; fp16 bits 0x64uu = 1024 + u exactly; minus 1152 = a exactly +__device__ __forceinline__ void act_h16(const uint32_t A, const uint32_t B, uint32_t (&a)[4]) { + const uint32_t P1 = prmt(A, B, 0x5140u) ^ 0x80808080u; // u0 u4 u1 u5 + const uint32_t P2 = prmt(A, B, 0x7362u) ^ 0x80808080u; // u2 u6 u3 u7 + constexpr uint32_t M = 0x64646464u, NEG1152 = 0xE480E480u; + a[0] = hadd2(prmt(P1, M, 0x4140u), NEG1152); + a[1] = hadd2(prmt(P1, M, 0x4342u), NEG1152); + a[2] = hadd2(prmt(P2, M, 0x4140u), NEG1152); + a[3] = hadd2(prmt(P2, M, 0x4342u), NEG1152); +} + +// the exact integer dot of one 32-value block (weights w[16], activations a0..a3 = 16 fp16 pairs) as a float +__device__ __forceinline__ float block_sum(const uint32_t (&w)[16], const uint4 a0, const uint4 a1, const uint4 a2, + const uint4 a3) { + uint32_t p = hfma2(w[0], a0.x, 0u), q = hfma2(w[1], a0.y, 0u); + p = hfma2(w[2], a0.z, p); q = hfma2(w[3], a0.w, q); + p = hfma2(w[4], a1.x, p); q = hfma2(w[5], a1.y, q); + p = hfma2(w[6], a1.z, p); q = hfma2(w[7], a1.w, q); + p = hfma2(w[8], a2.x, p); q = hfma2(w[9], a2.y, q); + p = hfma2(w[10], a2.z, p); q = hfma2(w[11], a2.w, q); + p = hfma2(w[12], a3.x, p); q = hfma2(w[13], a3.y, q); + p = hfma2(w[14], a3.z, p); q = hfma2(w[15], a3.w, q); + return h2sum(p) + h2sum(q); +} + +// TPP tokens per pass; tokens guarded in pairs (a pair's token past the count runs on a clamped row, not written). +// Per step every thread stages exactly 9 words of the CTA's 128 x 36 B (row stride 9 words: conflict-free decode reads) +// and threads < 8 TPP one 16-value q8_1 piece each. +template +__global__ void __launch_bounds__(NT, 4) dn_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const int64_t xadd, + const char* __restrict__ xq, const int total_rows, + float* __restrict__ dst) { + constexpr int G = 2, WPR = 9, AQ = TPP * 8, AI = (AQ + NT - 1) / NT; + static_assert(TPP % G == 0, ""); + __shared__ int wsm[NT * WPR]; + __shared__ __align__(16) uint32_t act_s[TPP][4][16]; + __shared__ __align__(8) float dy_s[4][TPP]; + int r0; + const Chunk c = cta_work(chunks, r0); + const char* __restrict__ W = w + xoff[c.j] + xadd + (size_t) r0 * ROWB; + const int tid = threadIdx.x; + int woff[WPR]; // word tid + NT i of the step's NT x 9 words: row (tid + NT i) / 9, word (tid + NT i) % 9 +#pragma unroll + for (int i = 0; i < WPR; ++i) { + const int idx = tid + i * NT, r = idx / WPR; + woff[i] = r * ROWB + 4 * (idx - r * WPR); + } + int wpre[WPR]; + uint4 apre[AI]; + float dpre[AI]; + auto load_w = [&](const int st) { + const char* __restrict__ Ws = W + st * 36; +#pragma unroll + for (int i = 0; i < WPR; ++i) wpre[i] = __ldg((const int*) (Ws + woff[i])); + }; + auto store_w = [&]() { +#pragma unroll + for (int i = 0; i < WPR; ++i) wsm[tid + i * NT] = wpre[i]; + }; + auto load_a = [&](const int st, const int trow0, const int nt) { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = tid + i * NT; + if (AQ % NT == 0 || idx < AQ) { + const int t = idx >> 3, m = idx & 7; + const char* blk = xq + ((size_t) st * total_rows + trow0 + min(t, nt - 1)) * QB; + apre[i] = __ldg((const uint4*) (blk + 16) + m); // values 16m .. 16m + 15 of the 128 + dpre[i] = __ldg((const float*) blk + (m >> 1)); // d of their 32-value block + } + } + }; + auto store_a = [&]() { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = tid + i * NT; + if (AQ % NT == 0 || idx < AQ) { + const int t = idx >> 3, m = idx & 7, b = m >> 1, hf = m & 1; + uint32_t p0[4], p1[4]; + act_h16(apre[i].x, apre[i].y, p0); + act_h16(apre[i].z, apre[i].w, p1); + uint4* d = (uint4*) &act_s[t][b][8 * hf]; + d[0] = make_uint4(p0[0], p0[1], p0[2], p0[3]); + d[1] = make_uint4(p1[0], p1[1], p1[2], p1[3]); + dy_s[b][t] = dpre[i]; // both pieces of a block write the same value + } + } + }; + + load_w(0); + load_a(0, c.row0, min(TPP, c.rows)); + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int st = 0; st < NSTEP; ++st) { + __syncthreads(); + store_w(); + store_a(); + __syncthreads(); + if (st + 1 < NSTEP) { + load_w(st + 1); + load_a(st + 1, trow0, nt); + } else if (p0 + TPP < c.rows) { + load_w(0); + load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP)); + } + // the row's 9 step words: block 0 = d0 | qs0 at bytes 0..17 (the codes 2 bytes into a word: funnel shift), + // block 1 = d1 in the top half of word 4, qs1 = words 5..8 + const uint32_t* cw = (const uint32_t*) (wsm + tid * WPR); +#pragma unroll 1 + for (int b = 0; b < 4; ++b) { // 32-value block: Q2_0 block b / 2, half b % 2 (int16 4h .. 4h + 3), K order + const int pq = b >> 1, h = b & 1; + const int base = pq ? 5 + 2 * h : 2 * h, sh = pq ? 0 : 16; + const uint32_t c0 = cw[base], c1 = cw[base + 1], c2 = cw[min(base + 2, WPR - 1)]; + const float dx = f16_to_f32(pq ? cw[4] >> 16 : cw[0] & 0xFFFFu); + uint32_t wv[16], wa[4], wb[4]; + dec2_h16(__funnelshift_r(c0, c1, sh), wa, wb); // int16 0 and 1 of the half +#pragma unroll + for (int k = 0; k < 4; ++k) { wv[k] = wa[k]; wv[4 + k] = wb[k]; } + dec2_h16(__funnelshift_r(c1, c2, sh), wa, wb); // int16 2 and 3 +#pragma unroll + for (int k = 0; k < 4; ++k) { wv[8 + k] = wa[k]; wv[12 + k] = wb[k]; } +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += G) { + if (t0 < nt) { + const float2 d2 = *(const float2*) &dy_s[b][t0]; +#pragma unroll + for (int t = t0; t < t0 + G; ++t) { + const uint4* a4 = (const uint4*) act_s[t][b]; + const float s = block_sum(wv, a4[0], a4[1], a4[2], a4[3]); + acc[t] = __fmaf_rn(__fmul_rn(dx, t == t0 ? d2.x : d2.y), s, acc[t]); + } + } + } + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + tid] = acc[t]; + } +} +} // namespace q20 + +// ---- IQ4_NL: 18-B blocks {f16 d; 16 B of 4-bit indices into kvalues_iq4nl}, 360-B rows; a step is SB blocks (SB 4: +// 72 B of a row, 8-byte aligned; SB 2: 36 B). The int8 values are get_int_from_table_16's table lookups (the 16-byte +// table in registers) without its final byte reorder - the same values paired (v4k, v4k+1), (v4k+16, v4k+17), ... and +// the activations paired the same way (PRMT 0x9180 / 0xB3A2); one XMAD chain per (row, token, block), then MMQ's sm_60 +// FMUL.FTZ (dx * dy), I2F (sumi), FFMA.FTZ, blocks in K order. Staging: 3 rows per warp and k (lanes 0-26, a row's 9 +// 4- or 8-byte pieces), the last k guarded so no row past the CTA's is read. +namespace nl4 { +constexpr int NB = DN_K / QK4_NL, BB = (int) sizeof(block_iq4_nl), ROWB = NB * BB; // 20, 18, 360 +static_assert(NB == 20 && BB == 18 && ROWB == 360, ""); + +// bytes (0,1) and (2,3) of v, each sign-extended to 16 bits +__device__ __forceinline__ void split01(const int v, int& p01, int& p23) { + asm("prmt.b32 %0, %1, 0, 0x9180;" : "=r"(p01) : "r"(v)); + asm("prmt.b32 %0, %1, 0, 0xB3A2;" : "=r"(p23) : "r"(v)); +} +// the 16-byte kvalues_iq4nl table as 4 words, read byte by byte +__device__ __forceinline__ void load_tab(uint32_t (&tab)[4]) { +#pragma unroll + for (int i = 0; i < 4; ++i) { + uint32_t v = 0; +#pragma unroll + for (int b = 0; b < 4; ++b) v |= (uint32_t) (uint8_t) kvalues_iq4nl[4 * i + b] << (8 * b); + tab[i] = v; + } +} +// a 32-value block from its 4 qs words (q[k]: values 4k..4k+3 in the low nibbles, 16+4k.. in the high ones): 16 int16 +// pair words against the activation pairs split01 makes of activation words m = 0..7 (at act[2m], act[2m + 1]). +// get_int_from_table_16's body (CUDA branch) up to its two lookup words tmp[0] = (v4k, v4k+16, v4k+1, v4k+17), +// tmp[1] = (v4k+2, v4k+18, v4k+3, v4k+19) +__device__ __forceinline__ void dec(const int (&q)[4], const uint32_t (&tab)[4], int (&wv)[16]) { +#pragma unroll + for (int k = 0; k < 4; ++k) { + const uint32_t q4 = (uint32_t) q[k]; + uint32_t tmp[2]; + const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1)); +#pragma unroll + for (uint32_t i = 0; i < 2; ++i) { + const uint32_t shift = 16 * i; + const uint32_t low = __byte_perm(tab[0], tab[1], q4 >> shift); + const uint32_t high = __byte_perm(tab[2], tab[3], q4 >> shift); + tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); + } + split2((int) tmp[0], wv[2 * k], wv[2 * (k + 4)]); // (v4k, v4k+1) | (v16+4k, v17+4k) + split2((int) tmp[1], wv[2 * k + 1], wv[2 * (k + 4) + 1]); // (v4k+2, v4k+3) | (v18+4k, v19+4k) + } +} +// block PAR of block pair p of the staged step (9 words per pair: even block d = lo16(w0), qs = bytes 2..17 by funnel +// shifts; odd block d = hi16(w4), qs = w5..w8) +template +__device__ __forceinline__ float load_blk(const int* __restrict__ cw, const int p, int (&q)[4]) { + const int* c = cw + 9 * p; + if constexpr (PAR == 0) { +#pragma unroll + for (int k = 0; k < 4; ++k) q[k] = (int) __funnelshift_r((uint32_t) c[k], (uint32_t) c[k + 1], 16); + return __half2float(__ushort_as_half((unsigned short) ((uint32_t) c[0] & 0xFFFFu))); + } else { +#pragma unroll + for (int k = 0; k < 4; ++k) q[k] = c[5 + k]; + return __half2float(__ushort_as_half((unsigned short) ((uint32_t) c[4] >> 16))); + } +} + +template +__device__ __forceinline__ void blk_compute(const int* __restrict__ cw, const int p, const uint32_t (&tab)[4], + const int (*act_s)[SB][16], const float (*dy_s)[SB], const int nt, + float (&acc)[TPP]) { + const int b = 2 * p + PAR; // block within the step + int wv[16]; + float dx; + { + int q[4]; + dx = load_blk(cw, p, q); + dec(q, tab, wv); + } + // tokens in groups of G behind one guard (a group's tokens past nt run on stale shared memory, not written) +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += G) { + if (t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + G; ++t) { + const int4* a4 = (const int4*) act_s[t][b]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const float dy = dy_s[t][b]; + int s0 = 0; + s0 = mad2(wv[0], a0.x, s0); s0 = mad2(wv[1], a0.y, s0); s0 = mad2(wv[2], a0.z, s0); s0 = mad2(wv[3], a0.w, s0); + s0 = mad2(wv[4], a1.x, s0); s0 = mad2(wv[5], a1.y, s0); s0 = mad2(wv[6], a1.z, s0); s0 = mad2(wv[7], a1.w, s0); + s0 = mad2(wv[8], a2.x, s0); s0 = mad2(wv[9], a2.y, s0); s0 = mad2(wv[10], a2.z, s0); s0 = mad2(wv[11], a2.w, s0); + s0 = mad2(wv[12], a3.x, s0); s0 = mad2(wv[13], a3.y, s0); s0 = mad2(wv[14], a3.z, s0); s0 = mad2(wv[15], a3.w, s0); + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __int2float_rn(s0), acc[t]); + } + } + } +} + +template +__global__ void __launch_bounds__(NT, 1) dn_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const int64_t xadd, + const block_q8_1_mmq* __restrict__ xq, const int total_rows, + float* __restrict__ dst) { + static_assert((SB == 2 || SB == 4) && NT % 32 == 0 && TPP % G == 0, ""); + constexpr int NW = NT / 32, WPS = 9 * SB / 2, S = WPS | 1, NSTEP = NB / SB, PIECES = DN_ROWS / NT; + constexpr int KI = (NT + 3 * NW - 1) / (3 * NW); + constexpr int AW = 9 * SB; // activation words per token and step (SB d + 8 SB qs words) + constexpr int AI = (TPP * AW + NT - 1) / NT; + using PT = typename std::conditional::type; + __shared__ int wsm[NT * S]; + __shared__ __align__(16) int act_s[TPP][SB][16]; + __shared__ float dy_s[TPP][SB]; + uint32_t tab[4]; + load_tab(tab); + int r0; + const Chunk c = cta_work(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int sub = lane / 9, pc = lane - 9 * sub; // sub 3: lanes 27-31, idle + const int srow0 = 3 * warp + sub; + const bool sact = sub < 3; + const char* __restrict__ Wg = w + xoff[c.j] + xadd + (size_t) (r0 + srow0) * ROWB + pc * (int) sizeof(PT); + int* __restrict__ ws_st = wsm + srow0 * S + pc * (int) (sizeof(PT) / 4); + PT pre[KI]; + int apre[AI]; + auto load_w = [&](const int st) { + if (sact) { + const char* g = Wg + st * (SB * BB); +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) pre[k] = __ldg((const PT*) (g + (size_t) k * 3 * NW * ROWB)); + } + }; + auto store_w = [&]() { + if (sact) { +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) { + if constexpr (SB == 4) { + ws_st[k * 3 * NW * S] = pre[k].x; + ws_st[k * 3 * NW * S + 1] = pre[k].y; + } else { + ws_st[k * 3 * NW * S] = pre[k]; + } + } + } + }; + // word wd of token t's step: d4[b0 + wd] for wd < SB, else qs word 8 b0 + (wd - SB) + auto load_a = [&](const int st, const int trow0, const int nt) { + const int kb = (st * SB) >> 2, b0 = (st * SB) & 3; // the 128-value q8_1 block and the first 32-block in it +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + const int* blk = (const int*) (xq + (size_t) kb * total_rows + trow0 + t); + apre[i] = __ldg(blk + (wd < SB ? b0 + wd : 4 + 8 * b0 + (wd - SB))); + } + } + }; + auto store_a = [&](const int nt) { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + if (wd < SB) { + dy_s[t][wd] = __int_as_float(apre[i]); + } else { + const int m = wd - SB, bb = m >> 3, mm = m & 7; + int lo, hi; + split01(apre[i], lo, hi); + *(int2*) &act_s[t][bb][2 * mm] = make_int2(lo, hi); + } + } + } + }; + load_w(0); + load_a(0, c.row0, min(TPP, c.rows)); + const int* cw = wsm + threadIdx.x * S; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int st = 0; st < NSTEP; ++st) { + __syncthreads(); + store_w(); + store_a(nt); + __syncthreads(); + if (st + 1 < NSTEP) { + load_w(st + 1); + load_a(st + 1, trow0, nt); + } else if (p0 + TPP < c.rows) { + load_w(0); + load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP)); + } +#pragma unroll 1 + for (int p = 0; p < SB / 2; ++p) { + blk_compute(cw, p, tab, act_s, dy_s, nt, acc); + blk_compute(cw, p, tab, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + threadIdx.x] = acc[t]; + } +} + +// ---- STRATA_WS_FAST=1 (ws::fast(), moe_ws.hpp): the 256 x 32 tier (2-block steps, pairs of tokens) with fewer +// instructions per pass, the same Dm rows bit for bit: every token's operations and their order are dn_kernel's. +// (Prototyped as a bench variant on one GP100 die: memcmp-equal to dn_kernel on real IQ4_NL layers at T 1024 and +// 1536, lognormal sigma 0.5 / 1.0 and a flat-32 control; 4.7-9.2% faster, 122 -> 102 registers, still two CTAs per +// SM. moe_ws_down_bench checks and times it against dn_kernel.) +// DUFF a switch on the number of token pairs falls through the 16 unrolled pairs (a jump table) instead of a guard +// per pair and block +// DYT dy as [block][token]: a pair's two dy in one LDS.64 +template +__device__ __forceinline__ void blk_compute_fast(const int* __restrict__ cw, const int p, const uint32_t (&tab)[4], + const int (*act_s)[SB][16], const float* __restrict__ dyb, const int nt, + float (&acc)[TPP]) { + static_assert(TPP / G == 16 && G == 2, "the switch below: 16 token pairs"); + const int b = 2 * p + PAR; // block within the step + int wv[16]; + float dx; + { + int q[4]; + dx = load_blk(cw, p, q); + dec(q, tab, wv); + } + // pairs past nt's run on stale shared memory and are not written, as dn_kernel's + auto grp = [&](auto K) { + constexpr int t0 = decltype(K)::value * G; + const float2 d2 = *(const float2*) &dyb[b * TPP + t0]; +#pragma unroll + for (int t = t0; t < t0 + G; ++t) { + const int4* a4 = (const int4*) act_s[t][b]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + int s0 = 0; + s0 = mad2(wv[0], a0.x, s0); s0 = mad2(wv[1], a0.y, s0); s0 = mad2(wv[2], a0.z, s0); s0 = mad2(wv[3], a0.w, s0); + s0 = mad2(wv[4], a1.x, s0); s0 = mad2(wv[5], a1.y, s0); s0 = mad2(wv[6], a1.z, s0); s0 = mad2(wv[7], a1.w, s0); + s0 = mad2(wv[8], a2.x, s0); s0 = mad2(wv[9], a2.y, s0); s0 = mad2(wv[10], a2.z, s0); s0 = mad2(wv[11], a2.w, s0); + s0 = mad2(wv[12], a3.x, s0); s0 = mad2(wv[13], a3.y, s0); s0 = mad2(wv[14], a3.z, s0); s0 = mad2(wv[15], a3.w, s0); + acc[t] = __fmaf_rn(__fmul_rn(dx, t == t0 ? d2.x : d2.y), __int2float_rn(s0), acc[t]); + } + }; + using std::integral_constant; + switch ((nt + G - 1) / G) { + case 16: grp(integral_constant{}); [[fallthrough]]; + case 15: grp(integral_constant{}); [[fallthrough]]; + case 14: grp(integral_constant{}); [[fallthrough]]; + case 13: grp(integral_constant{}); [[fallthrough]]; + case 12: grp(integral_constant{}); [[fallthrough]]; + case 11: grp(integral_constant{}); [[fallthrough]]; + case 10: grp(integral_constant{}); [[fallthrough]]; + case 9: grp(integral_constant{}); [[fallthrough]]; + case 8: grp(integral_constant{}); [[fallthrough]]; + case 7: grp(integral_constant{}); [[fallthrough]]; + case 6: grp(integral_constant{}); [[fallthrough]]; + case 5: grp(integral_constant{}); [[fallthrough]]; + case 4: grp(integral_constant{}); [[fallthrough]]; + case 3: grp(integral_constant{}); [[fallthrough]]; + case 2: grp(integral_constant{}); [[fallthrough]]; + case 1: grp(integral_constant{}); [[fallthrough]]; + default: break; + } +} + +// dn_kernel with blk_compute_fast and dy_s as [SB][TPP]; everything else is dn_kernel's +template +__global__ void __launch_bounds__(NT, 1) dn_kernel_fast(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const int64_t xadd, + const block_q8_1_mmq* __restrict__ xq, const int total_rows, + float* __restrict__ dst) { + static_assert((SB == 2 || SB == 4) && NT % 32 == 0 && TPP % G == 0, ""); + constexpr int NW = NT / 32, WPS = 9 * SB / 2, S = WPS | 1, NSTEP = NB / SB, PIECES = DN_ROWS / NT; + constexpr int KI = (NT + 3 * NW - 1) / (3 * NW); + constexpr int AW = 9 * SB; // activation words per token and step (SB d + 8 SB qs words) + constexpr int AI = (TPP * AW + NT - 1) / NT; + using PT = typename std::conditional::type; + __shared__ int wsm[NT * S]; + __shared__ __align__(16) int act_s[TPP][SB][16]; + __shared__ __align__(8) float dy_s[SB * TPP]; // [SB][TPP]: dy of token t, block b at b * TPP + t + uint32_t tab[4]; + load_tab(tab); + int r0; + const Chunk c = cta_work(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int sub = lane / 9, pc = lane - 9 * sub; // sub 3: lanes 27-31, idle + const int srow0 = 3 * warp + sub; + const bool sact = sub < 3; + const char* __restrict__ Wg = w + xoff[c.j] + xadd + (size_t) (r0 + srow0) * ROWB + pc * (int) sizeof(PT); + int* __restrict__ ws_st = wsm + srow0 * S + pc * (int) (sizeof(PT) / 4); + PT pre[KI]; + int apre[AI]; + auto load_w = [&](const int st) { + if (sact) { + const char* g = Wg + st * (SB * BB); +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) pre[k] = __ldg((const PT*) (g + (size_t) k * 3 * NW * ROWB)); + } + }; + auto store_w = [&]() { + if (sact) { +#pragma unroll + for (int k = 0; k < KI; ++k) + if (k < KI - 1 || srow0 + 3 * NW * k < NT) { + if constexpr (SB == 4) { + ws_st[k * 3 * NW * S] = pre[k].x; + ws_st[k * 3 * NW * S + 1] = pre[k].y; + } else { + ws_st[k * 3 * NW * S] = pre[k]; + } + } + } + }; + auto load_a = [&](const int st, const int trow0, const int nt) { + const int kb = (st * SB) >> 2, b0 = (st * SB) & 3; +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + const int* blk = (const int*) (xq + (size_t) kb * total_rows + trow0 + t); + apre[i] = __ldg(blk + (wd < SB ? b0 + wd : 4 + 8 * b0 + (wd - SB))); + } + } + }; + auto store_a = [&](const int nt) { +#pragma unroll + for (int i = 0; i < AI; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * AW) { + const int t = idx / AW, wd = idx - t * AW; + if (wd < SB) { + dy_s[wd * TPP + t] = __int_as_float(apre[i]); + } else { + const int m = wd - SB, bb = m >> 3, mm = m & 7; + int lo, hi; + split01(apre[i], lo, hi); + *(int2*) &act_s[t][bb][2 * mm] = make_int2(lo, hi); + } + } + } + }; + load_w(0); + load_a(0, c.row0, min(TPP, c.rows)); + const int* cw = wsm + threadIdx.x * S; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int st = 0; st < NSTEP; ++st) { + __syncthreads(); + store_w(); + store_a(nt); + __syncthreads(); + if (st + 1 < NSTEP) { + load_w(st + 1); + load_a(st + 1, trow0, nt); + } else if (p0 + TPP < c.rows) { + load_w(0); + load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP)); + } +#pragma unroll 1 + for (int p = 0; p < SB / 2; ++p) { + blk_compute_fast(cw, p, tab, act_s, dy_s, nt, acc); + blk_compute_fast(cw, p, tab, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace nl4 + +} // namespace + +// Q2_0: 8 tokens per pass below 5 rows per expert, then 16 (equal at 5) +void dn_q2_0(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + const unsigned grid = (unsigned) (L.nchunks * q20::PIECES); + if (u < 5.0) q20::dn_kernel<8><<>>(L.chunks, (const char*) L.w, L.xoff, L.down_off, (const char*) L.hq, + (int) L.rows, L.dm); + else q20::dn_kernel<16><<>>(L.chunks, (const char*) L.w, L.xoff, L.down_off, (const char*) L.hq, + (int) L.rows, L.dm); + ck(cudaGetLastError(), "down Q2_0"); +} + +// IQ4_NL: 128 rows x 8 tokens (4-block steps) below 5 rows per expert, 256 x 16 below 20, then 256 x 32 (2-block steps); +// `fast` (STRATA_WS_FAST=1): the 256 x 32 tier runs dn_kernel_fast instead - the same Dm rows +void dn_iq4_nl(const Layer& L, double u, cudaStream_t s, bool fast) { + if (L.nchunks <= 0) return; + const char* w = (const char*) L.w; + const block_q8_1_mmq* x = (const block_q8_1_mmq*) L.hq; + if (u < 5.0) + nl4::dn_kernel<128, 8, 4, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 128)), 128, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x, + (int) L.rows, L.dm); + else if (u < 20.0) + nl4::dn_kernel<256, 16, 4, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x, + (int) L.rows, L.dm); + else if (fast) + nl4::dn_kernel_fast<256, 32, 2, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, + L.down_off, x, + (int) L.rows, L.dm); + else + nl4::dn_kernel<256, 32, 2, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x, + (int) L.rows, L.dm); + ck(cudaGetLastError(), "down IQ4_NL"); +} + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/moe_ws_gu_iq2.cu b/src/prefill/moe_ws_gu_iq2.cu new file mode 100644 index 00000000..4df68b6d --- /dev/null +++ b/src/prefill/moe_ws_gu_iq2.cu @@ -0,0 +1,736 @@ +// src/prefill/moe_ws_gu_iq2.cu - weight-stationary gate/up products (see moe_ws.hpp): IQ2_XXS, IQ2_XS and IQ2_S, +// [1280 x 2560] read in place. A CTA = 128 threads = 128 weight rows of one expert (a row per thread, all of the +// chunk's activation rows TPP at a time, the sums in registers); K advances 128 values a step (half a 256-value block +// = 4 sub-blocks): the step's bytes of the 128 rows and the step's q8_1 block of each token go to shared memory (the +// activations split to int16 pairs once), then each thread decodes its row's 4 sub-blocks once per pass and runs them +// against the tokens. Bits: per 32-value sub-block MMQ's int8 values (ggml_cuda_mmq_load_tiles_iq2_*) and scale +// expressions, then MMQ's epilogue (IQ2_XXS: acc = fma(dx * dy, float(sum), acc); IQ2_XS / IQ2_S, a scale per 16 +// values: t = fma(float(sum 0-15), d0, 0), t = fma(float(sum 16-31), d1, t), acc = fma(t, dy, acc)), sub-blocks in K +// order. (Measured on a GP100 die: ws / per-group MMQ 0.26-0.33 at 2.5 +// rows per expert, 0.46-0.52 at 10, 0.67-0.76 at 35, 0.75-0.82 at 160; bit-identical, compute-sanitizer clean with +// exact-size matrices.) +// +// Decode: every iq2xxs / iq2xs / iq2s_grid byte is 0x08, 0x19 or 0x2B, so a grid entry is 8 nibble codes (0, 1, 2) +// and a value's sign adds 4 to its nibble: __byte_perm(0x002B1908, 0x00D5E7F8, codes | signs) is MMQ's +// __vsub4(g ^ s, s) word, one PRMT per 4 values (checked against MMQ's expressions for every entry and sign byte). +// Staging without per-lane branches: rows are 660 / 740 / 820 B, so block kc starts 2 * (kc & 1) bytes into a 4-byte +// word for the whole CTA - an even block's words are two aligned loads and a funnel shift (the second load ends at most +// 2 bytes into block kc + 1 of the same row), an odd block's are aligned; d sits the other way round (an odd block's d +// is the high half of the word 2 bytes before it, inside block kc - 1). Every load of a lane is issued before its +// stores, and nothing outside a row is read (the last row's last block is odd). Token groups of TG: one `t < nt` +// branch per group, so the XMAD chains of the group's tokens interleave (a group's tokens past the count are not +// written). +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include +#include + +namespace strata::prefill::ws::detail { +namespace { + +constexpr int GU_ROWS = 1280, GU_K = 2560, NB = GU_K / QK_K, NSTEP = 2 * NB, NT = 128, NW = NT / 32, PIECES = GU_ROWS / NT; +constexpr uint32_t PX = 0x002B1908u, PY = 0x00D5E7F8u; // codes 0-2: +8 +25 +43 | codes 4-6: -8 -25 -43 + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// the step's activations of IQ2_XS / IQ2_S: nt consecutive 144-B block_q8_1_mmq, d4 -> dy_s, int8 -> int16 pairs +template +__device__ __forceinline__ void stage_act(const block_q8_1_mmq* __restrict__ xq, const int hc, const int total_rows, + const int trow0, const int nt, int (*act_s)[4][16], float (*dy_s)[4]) { + constexpr int NA = (TPP * 36 + NT - 1) / NT; + int av[NA]; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) av[i] = __ldg(xr + idx); + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) { + const int t = idx / 36, wd = idx - t * 36; + if (wd < 4) { + dy_s[t][wd] = __int_as_float(av[i]); + } else { + const int m = wd - 4; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][m / 8][2 * (m % 8)] = make_int2(lo, hi); + } + } + } +} + +// IQ2_XS / IQ2_S: sub-block s's 16 int16-pair words wv and scales d0 / d1 against the tokens (vec_dot_q8_0_16_q8_1's +// epilogue). CVT 0: four XMAD chains and I2F; 1: two chains seeded with kMagicI (exact for the 16-value sums, +// |sum| <= 16 * 43 * 127 < 2^22) +template +__device__ __forceinline__ void mac16(const int (&wv)[16], const float dx0, const float dx1, const int s, + const int (*act_s)[4][16], const float (*dy_s)[4], const int nt, float (&acc)[TPP]) { +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const float dy = dy_s[t][s]; + float fa, fb; // float(sum of values 0-15), float(sum of values 16-31): exact + if constexpr (CVT == 0) { + int s0 = 0, s1 = 0, s2 = 0, s3 = 0; + s0 = mad2(wv[0], a0.x, s0); s1 = mad2(wv[1], a0.y, s1); s0 = mad2(wv[2], a0.z, s0); s1 = mad2(wv[3], a0.w, s1); + s0 = mad2(wv[4], a1.x, s0); s1 = mad2(wv[5], a1.y, s1); s0 = mad2(wv[6], a1.z, s0); s1 = mad2(wv[7], a1.w, s1); + s2 = mad2(wv[8], a2.x, s2); s3 = mad2(wv[9], a2.y, s3); s2 = mad2(wv[10], a2.z, s2); s3 = mad2(wv[11], a2.w, s3); + s2 = mad2(wv[12], a3.x, s2); s3 = mad2(wv[13], a3.y, s3); s2 = mad2(wv[14], a3.z, s2); s3 = mad2(wv[15], a3.w, s3); + fa = __int2float_rn(s0 + s1); + fb = __int2float_rn(s2 + s3); + } else { + int sa = kMagicI, sb = kMagicI; + sa = mad2(wv[0], a0.x, sa); sb = mad2(wv[8], a2.x, sb); + sa = mad2(wv[1], a0.y, sa); sb = mad2(wv[9], a2.y, sb); + sa = mad2(wv[2], a0.z, sa); sb = mad2(wv[10], a2.z, sb); + sa = mad2(wv[3], a0.w, sa); sb = mad2(wv[11], a2.w, sb); + sa = mad2(wv[4], a1.x, sa); sb = mad2(wv[12], a3.x, sb); + sa = mad2(wv[5], a1.y, sa); sb = mad2(wv[13], a3.y, sb); + sa = mad2(wv[6], a1.z, sa); sb = mad2(wv[14], a3.z, sb); + sa = mad2(wv[7], a1.w, sa); sb = mad2(wv[15], a3.w, sb); + fa = __fsub_rn(__int_as_float(sa), kMagicF); + fb = __fsub_rn(__int_as_float(sb), kMagicF); + } + float tf = __fmaf_rn(fa, dx0, 0.0f); + tf = __fmaf_rn(fb, dx1, tf); + acc[t] = __fmaf_rn(tf, dy, acc[t]); + } + } + } +} + +// d0 / d1 = ((ls & 15 | ls >> 4) * d + d / 2) / 4 as MMQ's sm_60 SASS computes them +__device__ __forceinline__ void scales16(const int ls, const int dbits, float& d0, float& d1) { + const float d = __half2float(__ushort_as_half((unsigned short) (dbits & 0xFFFF))); + const float dh = __fmul_rn(d, 0.5f); + d0 = __fmul_rn(__fmaf_rn(d, __int2float_rn(ls & 0x0F), dh), 0.25f); + d1 = __fmul_rn(__fmaf_rn(d, __int2float_rn(ls >> 4), dh), 0.25f); +} + +// ---- IQ2_XXS: 66-B blocks; per row and step 8 qs words (4 grid bytes, then aux32: 4 x 7 sign bits + the scale) and +// d (stride 9). Every lane slot is one word type: qs words rows tid/8 + 16 i (word tid%8), d the thread's own row. +// A partial pass's token groups run past the count on copies of row nt - 1 (not written); a full pass has no branch. +namespace xxs2 { +constexpr int BB = (int) sizeof(block_iq2_xxs), ROWB = NB * BB, CWS = 9; +static_assert(BB == 66 && ROWB % 4 == 0, "block_iq2_xxs"); + +// nibble b = the code of byte b of iq2xxs_grid[i] +__device__ __forceinline__ uint32_t grid_codes(const int i) { + const uint2 g = ((const uint2*) iq2xxs_grid)[i]; + uint32_t w = 0; +#pragma unroll + for (int b = 0; b < 8; ++b) { + const uint32_t v = ((b < 4 ? g.x : g.y) >> (8 * (b & 3))) & 0xFF; + w |= ((uint32_t) (v > 0x08u) + (uint32_t) (v > 0x19u)) << (4 * b); + } + return w; +} +// a 7-bit sign field: MMQ's unpack_ksigns byte (bit 7 = parity) spread to bit 2 of nibble b +__device__ __forceinline__ uint32_t sign_spread(const int v) { + const uint32_t s = (uint32_t) v ^ ((uint32_t) (__popc(v) & 1) << 7); + uint32_t w = 0; +#pragma unroll + for (int b = 0; b < 8; ++b) w |= ((s >> b) & 1u) << (4 * b + 2); + return w; +} + +template +__device__ __forceinline__ void sb_compute(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ tabA, + const uint32_t* __restrict__ tabB, const int (*act_s)[4][16], + const float (*dy_s)[4], const int nt, float (&acc)[TPP]) { + int wv[16]; + float dx; + { + const uint32_t q2 = (uint32_t) cw[2 * s + 0]; + const uint32_t aux32 = (uint32_t) cw[2 * s + 1]; +#pragma unroll + for (int l = 0; l < QR2_XXS; ++l) { + const uint32_t sel = tabA[(q2 >> (8 * l)) & 0xFF] | tabB[(aux32 >> (7 * l)) & 0x7F]; + split2((int) __byte_perm(PX, PY, sel), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) __byte_perm(PX, PY, sel >> 16), wv[4 * l + 2], wv[4 * l + 3]); + } + const int ls = aux32 >> 27 | 1; + const float d = __ushort_as_half((unsigned short) (cw[8] & 0xFFFF)); + dx = d * ls / 8; // MMQ: (d * scale + d / 2) / 4 + } +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (FULL || t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const int a[16] = {a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w, a2.x, a2.y, a2.z, a2.w, a3.x, a3.y, a3.z, a3.w}; + const float dy = dy_s[t][s]; + int sc[CH]; + sc[0] = kMagicI; +#pragma unroll + for (int c = 1; c < CH; ++c) sc[c] = 0; +#pragma unroll + for (int m = 0; m < 16; ++m) sc[m % CH] = mad2(wv[m], a[m], sc[m % CH]); + int sum = sc[0]; +#pragma unroll + for (int c = 1; c < CH; ++c) sum += sc[c]; + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __fsub_rn(__int_as_float(sum), kMagicF), acc[t]); + } + } + } +} + +template +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0 && (TPP * 32) % NT == 0 && TPP * 4 <= NT, ""); + constexpr int NDS = 8; // qs-word slots per lane: rows tid/8 + i*NT/8, word tid%8 + constexpr int RS = NT / 8; // rows per slot + constexpr int NA = TPP * 32 / NT; // activation qs-word slots per lane + __shared__ __align__(16) uint32_t tabA[256]; + __shared__ __align__(16) uint32_t tabB[128]; + __shared__ __align__(16) int act_s[TPP][4][16]; // [token][32-block of the step][8 words split to 16] + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + const int tid = threadIdx.x; + for (int i = tid; i < 256; i += NT) tabA[i] = grid_codes(i); + for (int i = tid; i < 128; i += NT) tabB[i] = sign_spread(i); + int r0; + const Chunk c = cta_work(chunks, r0); + const char* __restrict__ W = w + xoff[c.j] + (size_t) r0 * ROWB; + const char* __restrict__ Wq = W + (size_t) (tid >> 3) * ROWB + 4 * (tid & 7); // + i*RS*ROWB + kc*BB + 32h + const char* __restrict__ Wd = W + (size_t) tid * ROWB; // + kc*BB + int* __restrict__ sq = wsm + (tid >> 3) * CWS + (tid & 7); // + i*RS*CWS + int* __restrict__ sd = wsm + tid * CWS + 8; + const int* cw = wsm + tid * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); // nt consecutive 36-word blocks + __syncthreads(); + int av[NA], dv = 0; +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5; + av[i] = __ldg(xr + min(t, nt - 1) * 36 + 4 + (idx & 31)); // clamped: no branch, never past row nt-1 + } + if (TPP * 4 == NT || tid < TPP * 4) dv = __ldg(xr + min(tid >> 2, nt - 1) * 36 + (tid & 3)); + const char* bq = Wq + kc * BB + 32 * h; + if (kc & 1) { // odd block: qs words aligned; d = high half of the word 2 bytes before the block + int v[NDS]; +#pragma unroll + for (int i = 0; i < NDS; ++i) v[i] = __ldg((const int*) (bq + 2 + (size_t) i * RS * ROWB)); + const int vd = __ldg((const int*) (Wd + kc * BB - 2)); +#pragma unroll + for (int i = 0; i < NDS; ++i) sq[i * RS * CWS] = v[i]; + *sd = (int) ((uint32_t) vd >> 16); + } else { // even block: qs words 2 bytes into a word: two aligned words + funnel shift; d = low half + int lo[NDS], hi[NDS]; +#pragma unroll + for (int i = 0; i < NDS; ++i) { + lo[i] = __ldg((const int*) (bq + (size_t) i * RS * ROWB)); + hi[i] = __ldg((const int*) (bq + 4 + (size_t) i * RS * ROWB)); + } + const int vd = __ldg((const int*) (Wd + kc * BB)); +#pragma unroll + for (int i = 0; i < NDS; ++i) sq[i * RS * CWS] = (int) __funnelshift_r((uint32_t) lo[i], (uint32_t) hi[i], 16); + *sd = vd; + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5, wd = idx & 31; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][wd >> 3][2 * (wd & 7)] = make_int2(lo, hi); + } + if (TPP * 4 == NT || tid < TPP * 4) dy_s[tid >> 2][tid & 3] = __int_as_float(dv); + __syncthreads(); + if (nt == TPP) { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute(cw, s, tabA, tabB, act_s, dy_s, nt, acc); + } else { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute(cw, s, tabA, tabB, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + tid] = acc[t]; + } +} +} // namespace xxs2 + +// ---- IQ2_XS: 74-B blocks; per row and step the qs u16 [16h, 16h + 16) (8 words), the scales [4h, 4h + 4) and d: +// 10 words, row stride 11, staged by lanes 0-9 / 16-25 of each warp (two rows per warp and k). The grid codes and +// ksigns' spread signs (q2 & 0x1FF, q2 >> 9) are tables generated from ggml's iq2xs_grid. +namespace xs2 { +constexpr int BB = 74, ROWB = NB * BB, CW = 10, CWS = 11, KR = NT / (2 * NW); + +__device__ const uint32_t kIq2xsCode[512] = { + 0x00000000u, 0x00000002u, 0x00000011u, 0x00000020u, 0x00000022u, 0x00000101u, 0x00000110u, 0x00000112u, + 0x00000121u, 0x00000200u, 0x00000202u, 0x00000211u, 0x00000220u, 0x00001001u, 0x00001010u, 0x00001012u, + 0x00001021u, 0x00001100u, 0x00001102u, 0x00001111u, 0x00001120u, 0x00001201u, 0x00001210u, 0x00002000u, + 0x00002002u, 0x00002011u, 0x00002020u, 0x00002101u, 0x00002110u, 0x00002121u, 0x00002200u, 0x00010001u, + 0x00010010u, 0x00010012u, 0x00010021u, 0x00010100u, 0x00010102u, 0x00010111u, 0x00010120u, 0x00010122u, + 0x00010201u, 0x00010210u, 0x00011000u, 0x00011002u, 0x00011011u, 0x00011020u, 0x00011101u, 0x00011110u, + 0x00011200u, 0x00011220u, 0x00012001u, 0x00012010u, 0x00012100u, 0x00020000u, 0x00020002u, 0x00020011u, + 0x00020020u, 0x00020101u, 0x00020110u, 0x00020200u, 0x00021001u, 0x00021010u, 0x00021100u, 0x00021111u, + 0x00022000u, 0x00022022u, 0x00100001u, 0x00100010u, 0x00100012u, 0x00100021u, 0x00100100u, 0x00100102u, + 0x00100111u, 0x00100120u, 0x00100201u, 0x00100210u, 0x00101000u, 0x00101002u, 0x00101011u, 0x00101020u, + 0x00101101u, 0x00101110u, 0x00101112u, 0x00101200u, 0x00102001u, 0x00102010u, 0x00102100u, 0x00110000u, + 0x00110002u, 0x00110011u, 0x00110020u, 0x00110101u, 0x00110110u, 0x00110200u, 0x00111001u, 0x00111010u, + 0x00111100u, 0x00111201u, 0x00112000u, 0x00120001u, 0x00120010u, 0x00120100u, 0x00120212u, 0x00121000u, + 0x00121002u, 0x00122010u, 0x00200000u, 0x00200002u, 0x00200011u, 0x00200020u, 0x00200022u, 0x00200101u, + 0x00200110u, 0x00200200u, 0x00200211u, 0x00201001u, 0x00201010u, 0x00201100u, 0x00201120u, 0x00202000u, + 0x00202200u, 0x00202222u, 0x00210001u, 0x00210010u, 0x00210100u, 0x00211000u, 0x00212001u, 0x00212021u, + 0x00220000u, 0x00220200u, 0x00220220u, 0x00222112u, 0x00222200u, 0x01000001u, 0x01000010u, 0x01000012u, + 0x01000021u, 0x01000100u, 0x01000102u, 0x01000111u, 0x01000120u, 0x01000201u, 0x01000210u, 0x01001000u, + 0x01001002u, 0x01001011u, 0x01001020u, 0x01001101u, 0x01001110u, 0x01001200u, 0x01001222u, 0x01002001u, + 0x01002010u, 0x01002100u, 0x01010000u, 0x01010002u, 0x01010011u, 0x01010020u, 0x01010101u, 0x01010110u, + 0x01010200u, 0x01011001u, 0x01011010u, 0x01011100u, 0x01012000u, 0x01012110u, 0x01012112u, 0x01020001u, + 0x01020010u, 0x01020012u, 0x01020100u, 0x01021000u, 0x01021200u, 0x01100000u, 0x01100002u, 0x01100011u, + 0x01100020u, 0x01100101u, 0x01100110u, 0x01100200u, 0x01101001u, 0x01101010u, 0x01101021u, 0x01101100u, + 0x01101210u, 0x01102000u, 0x01110001u, 0x01110010u, 0x01110100u, 0x01111000u, 0x01120000u, 0x01120110u, + 0x01121021u, 0x01200001u, 0x01200010u, 0x01200100u, 0x01200102u, 0x01201000u, 0x01201110u, 0x01202012u, + 0x01210000u, 0x01210011u, 0x01211212u, 0x01221101u, 0x01222221u, 0x02000000u, 0x02000002u, 0x02000011u, + 0x02000020u, 0x02000022u, 0x02000101u, 0x02000110u, 0x02000200u, 0x02001001u, 0x02001010u, 0x02001100u, + 0x02002000u, 0x02002200u, 0x02010001u, 0x02010010u, 0x02010100u, 0x02011000u, 0x02011020u, 0x02011211u, + 0x02020000u, 0x02020202u, 0x02022000u, 0x02022220u, 0x02100001u, 0x02100010u, 0x02100100u, 0x02100221u, + 0x02101000u, 0x02110000u, 0x02111001u, 0x02111102u, 0x02112121u, 0x02120001u, 0x02120122u, 0x02122212u, + 0x02200000u, 0x02200020u, 0x02200022u, 0x02200200u, 0x02201111u, 0x02202020u, 0x02202202u, 0x02211220u, + 0x02212100u, 0x02220020u, 0x02220200u, 0x02222002u, 0x02222020u, 0x02222022u, 0x10000001u, 0x10000010u, + 0x10000012u, 0x10000021u, 0x10000100u, 0x10000102u, 0x10000111u, 0x10000120u, 0x10000201u, 0x10000210u, + 0x10001000u, 0x10001002u, 0x10001011u, 0x10001020u, 0x10001022u, 0x10001101u, 0x10001110u, 0x10001200u, + 0x10001211u, 0x10002001u, 0x10002010u, 0x10002100u, 0x10010000u, 0x10010002u, 0x10010011u, 0x10010020u, + 0x10010101u, 0x10010110u, 0x10010200u, 0x10011001u, 0x10011010u, 0x10011100u, 0x10012000u, 0x10012011u, + 0x10012202u, 0x10020001u, 0x10020010u, 0x10020100u, 0x10020102u, 0x10020221u, 0x10021000u, 0x10100000u, + 0x10100002u, 0x10100011u, 0x10100020u, 0x10100101u, 0x10100110u, 0x10100121u, 0x10100200u, 0x10101001u, + 0x10101010u, 0x10101100u, 0x10102000u, 0x10102110u, 0x10110001u, 0x10110010u, 0x10110100u, 0x10110210u, + 0x10111000u, 0x10112122u, 0x10120000u, 0x10120022u, 0x10121010u, 0x10121100u, 0x10200001u, 0x10200010u, + 0x10200100u, 0x10201000u, 0x10201011u, 0x10201110u, 0x10201202u, 0x10210000u, 0x10210101u, 0x10211010u, + 0x10211100u, 0x10211221u, 0x10220010u, 0x11000000u, 0x11000002u, 0x11000011u, 0x11000020u, 0x11000101u, + 0x11000110u, 0x11000200u, 0x11000220u, 0x11001001u, 0x11001010u, 0x11001100u, 0x11002000u, 0x11010001u, + 0x11010010u, 0x11010100u, 0x11010111u, 0x11011000u, 0x11011002u, 0x11020000u, 0x11021010u, 0x11022222u, + 0x11100001u, 0x11100010u, 0x11100100u, 0x11100201u, 0x11101000u, 0x11101200u, 0x11102001u, 0x11102201u, + 0x11110000u, 0x11110020u, 0x11112000u, 0x11112020u, 0x11120201u, 0x11121220u, 0x11122201u, 0x11200000u, + 0x11200110u, 0x11201001u, 0x11201100u, 0x11202121u, 0x11210122u, 0x11211000u, 0x11211002u, 0x11222011u, + 0x12000001u, 0x12000010u, 0x12000100u, 0x12001000u, 0x12001110u, 0x12001202u, 0x12002012u, 0x12002221u, + 0x12010000u, 0x12020210u, 0x12021022u, 0x12022102u, 0x12100000u, 0x12100112u, 0x12110100u, 0x12111000u, + 0x12111011u, 0x12112210u, 0x12200001u, 0x12201222u, 0x12210211u, 0x12220012u, 0x12221110u, 0x12221202u, + 0x20000000u, 0x20000002u, 0x20000011u, 0x20000020u, 0x20000101u, 0x20000110u, 0x20000200u, 0x20000222u, + 0x20001001u, 0x20001010u, 0x20001100u, 0x20002000u, 0x20002002u, 0x20002220u, 0x20002222u, 0x20010001u, + 0x20010010u, 0x20010012u, 0x20010100u, 0x20011000u, 0x20011101u, 0x20011121u, 0x20020000u, 0x20020200u, + 0x20022000u, 0x20022002u, 0x20022200u, 0x20022220u, 0x20100001u, 0x20100010u, 0x20100100u, 0x20100102u, + 0x20100111u, 0x20101000u, 0x20101200u, 0x20102021u, 0x20110000u, 0x20111010u, 0x20112211u, 0x20120120u, + 0x20121222u, 0x20200000u, 0x20200020u, 0x20200211u, 0x20201122u, 0x20202000u, 0x20202002u, 0x20202220u, + 0x20210012u, 0x20220202u, 0x20222000u, 0x20222020u, 0x20222112u, 0x20222220u, 0x21000001u, 0x21000010u, + 0x21000100u, 0x21001000u, 0x21001112u, 0x21002010u, 0x21010000u, 0x21010202u, 0x21011210u, 0x21021112u, + 0x21022021u, 0x21100000u, 0x21100011u, 0x21101010u, 0x21101100u, 0x21101120u, 0x21110221u, 0x21112100u, + 0x21112102u, 0x21121001u, 0x21201101u, 0x21202212u, 0x21211021u, 0x21220111u, 0x21221200u, 0x22000000u, + 0x22000002u, 0x22000020u, 0x22000022u, 0x22000200u, 0x22000222u, 0x22002200u, 0x22011101u, 0x22011121u, + 0x22012212u, 0x22020000u, 0x22020002u, 0x22020020u, 0x22020222u, 0x22022000u, 0x22022200u, 0x22101000u, + 0x22102111u, 0x22121211u, 0x22122120u, 0x22200022u, 0x22200200u, 0x22200202u, 0x22200220u, 0x22202200u, + 0x22202220u, 0x22210010u, 0x22212010u, 0x22212012u, 0x22220220u, 0x22220222u, 0x22222101u, 0x22222222u, +}; +__device__ const uint32_t kIq2xsSign[128] = { + 0x00000000u, 0x40000004u, 0x40000040u, 0x00000044u, 0x40000400u, 0x00000404u, 0x00000440u, 0x40000444u, + 0x40004000u, 0x00004004u, 0x00004040u, 0x40004044u, 0x00004400u, 0x40004404u, 0x40004440u, 0x00004444u, + 0x40040000u, 0x00040004u, 0x00040040u, 0x40040044u, 0x00040400u, 0x40040404u, 0x40040440u, 0x00040444u, + 0x00044000u, 0x40044004u, 0x40044040u, 0x00044044u, 0x40044400u, 0x00044404u, 0x00044440u, 0x40044444u, + 0x40400000u, 0x00400004u, 0x00400040u, 0x40400044u, 0x00400400u, 0x40400404u, 0x40400440u, 0x00400444u, + 0x00404000u, 0x40404004u, 0x40404040u, 0x00404044u, 0x40404400u, 0x00404404u, 0x00404440u, 0x40404444u, + 0x00440000u, 0x40440004u, 0x40440040u, 0x00440044u, 0x40440400u, 0x00440404u, 0x00440440u, 0x40440444u, + 0x40444000u, 0x00444004u, 0x00444040u, 0x40444044u, 0x00444400u, 0x40444404u, 0x40444440u, 0x00444444u, + 0x44000000u, 0x04000004u, 0x04000040u, 0x44000044u, 0x04000400u, 0x44000404u, 0x44000440u, 0x04000444u, + 0x04004000u, 0x44004004u, 0x44004040u, 0x04004044u, 0x44004400u, 0x04004404u, 0x04004440u, 0x44004444u, + 0x04040000u, 0x44040004u, 0x44040040u, 0x04040044u, 0x44040400u, 0x04040404u, 0x04040440u, 0x44040444u, + 0x44044000u, 0x04044004u, 0x04044040u, 0x44044044u, 0x04044400u, 0x44044404u, 0x44044440u, 0x04044444u, + 0x04400000u, 0x44400004u, 0x44400040u, 0x04400044u, 0x44400400u, 0x04400404u, 0x04400440u, 0x44400444u, + 0x44404000u, 0x04404004u, 0x04404040u, 0x44404044u, 0x04404400u, 0x44404404u, 0x44404440u, 0x04404444u, + 0x44440000u, 0x04440004u, 0x04440040u, 0x44440044u, 0x04440400u, 0x44440404u, 0x44440440u, 0x04440444u, + 0x04444000u, 0x44444004u, 0x44444040u, 0x04444044u, 0x44444400u, 0x04444404u, 0x04444440u, 0x44444444u, +}; + +template +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0, ""); + __shared__ uint32_t tabA_s[512]; + __shared__ uint32_t tabB_s[128]; + __shared__ __align__(16) int act_s[TPP][4][16]; // [token][sub-block][8 int8x4 words split to 16 int16 pairs] + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + for (int i = threadIdx.x; i < 512; i += NT) tabA_s[i] = kIq2xsCode[i]; + for (int i = threadIdx.x; i < 128; i += NT) tabB_s[i] = kIq2xsSign[i]; + int r0; + const Chunk c = cta_work(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int ci = lane & 15, rsub = lane >> 4; // lanes 0-9 stage one row, 16-25 the next; ci = the compact word + const bool cact = ci < CW; + const char* __restrict__ Wr = w + xoff[c.j] + (size_t) (r0 + 2 * warp + rsub) * ROWB; // + k * 2 NW rows + int* __restrict__ wsl = wsm + (2 * warp + rsub) * CWS + ci; // + k * 2 NW * CWS + const int* cw = wsm + threadIdx.x * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + // compact word ci's byte offset inside the block: qs words (ci 0-7), scales (ci 8); d (ci 9) apart + const int boff = ci < 8 ? 2 + 32 * h + 4 * ci : 66 + 4 * h; + __syncthreads(); + if (cact) { + const char* blk0 = Wr + kc * BB; + if (kc & 1) { // odd block: words aligned, one load each; d = high half of the word at blk - 2 + const int o = ci < 9 ? boff : -2, sh = ci < 9 ? 0 : 16; + int v[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) v[k] = __ldg((const int*) (blk0 + (size_t) k * 2 * NW * ROWB + o)); +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v[k], v[k], sh); + } else { // even block: words 2 bytes into a word, two loads + funnel shift; d = low half at blk + const int o0 = ci < 9 ? boff - 2 : 0, o1 = ci < 9 ? boff + 2 : 0, sh = ci < 9 ? 16 : 0; + int v0[KR], v1[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) { + const char* b = blk0 + (size_t) k * 2 * NW * ROWB; + v0[k] = __ldg((const int*) (b + o0)); + v1[k] = __ldg((const int*) (b + o1)); + } +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v0[k], v1[k], sh); + } + } + stage_act(xq, hc, total_rows, trow0, nt, act_s, dy_s); + __syncthreads(); +#pragma unroll 1 + for (int s = 0; s < 4; ++s) { // cw: [0..7] qs u16 pairs (sub-block s = words 2s, 2s+1), [8] scales, [9] d + int wv[16]; + float dx0, dx1; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint32_t q2 = ((uint32_t) cw[2 * s + (l >> 1)] >> (16 * (l & 1))) & 0xFFFFu; + const uint32_t sel = tabA_s[q2 & 0x1FFu] | tabB_s[q2 >> 9]; + split2((int) __byte_perm(PX, PY, sel), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) __byte_perm(PX, PY, sel >> 16), wv[4 * l + 2], wv[4 * l + 3]); + } + scales16((cw[8] >> (8 * s)) & 0xFF, cw[9], dx0, dx1); + mac16(wv, dx0, dx1, s, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace xs2 + +// ---- IQ2_S: 82-B blocks; per row and step the grid bytes qs[16h..] (4 words), the sign bytes qs[32 + 16h..] (4), +// qh[4h..4h + 3], scales[4h..4h + 3] and d: 11 words, row stride 11, staged by lanes 0-10 / 16-26 of each warp. The grid +// index is 10 bits (qs | qh bits), the sign byte is explicit: tables generated from ggml's iq2s_grid. +namespace s2 { +constexpr int BB = (int) sizeof(block_iq2_s), ROWB = NB * BB, CW = 11, CWS = 11, KR = NT / (2 * NW); +static_assert(BB == 82, "block_iq2_s"); + +__device__ const uint32_t kIq2sCode[1024] = { + 0x00000000u, 0x00000002u, 0x00000011u, 0x00000020u, 0x00000022u, 0x00000101u, 0x00000110u, 0x00000112u, + 0x00000121u, 0x00000200u, 0x00000202u, 0x00000211u, 0x00000220u, 0x00001001u, 0x00001010u, 0x00001012u, + 0x00001021u, 0x00001100u, 0x00001102u, 0x00001111u, 0x00001120u, 0x00001201u, 0x00001210u, 0x00001212u, + 0x00001221u, 0x00002000u, 0x00002002u, 0x00002011u, 0x00002020u, 0x00002101u, 0x00002110u, 0x00002200u, + 0x00002211u, 0x00002222u, 0x00010001u, 0x00010010u, 0x00010012u, 0x00010021u, 0x00010100u, 0x00010102u, + 0x00010111u, 0x00010120u, 0x00010201u, 0x00010210u, 0x00011000u, 0x00011002u, 0x00011011u, 0x00011020u, + 0x00011101u, 0x00011110u, 0x00011112u, 0x00011121u, 0x00011200u, 0x00011211u, 0x00011220u, 0x00012001u, + 0x00012010u, 0x00012100u, 0x00012102u, 0x00012111u, 0x00012201u, 0x00012210u, 0x00020000u, 0x00020002u, + 0x00020011u, 0x00020020u, 0x00020101u, 0x00020110u, 0x00020200u, 0x00020222u, 0x00021001u, 0x00021010u, + 0x00021012u, 0x00021021u, 0x00021100u, 0x00021111u, 0x00022000u, 0x00022011u, 0x00022022u, 0x00022110u, + 0x00022202u, 0x00100001u, 0x00100010u, 0x00100012u, 0x00100021u, 0x00100100u, 0x00100102u, 0x00100111u, + 0x00100120u, 0x00100201u, 0x00100210u, 0x00100212u, 0x00100221u, 0x00101000u, 0x00101002u, 0x00101011u, + 0x00101020u, 0x00101022u, 0x00101101u, 0x00101110u, 0x00101112u, 0x00101121u, 0x00101200u, 0x00101202u, + 0x00101211u, 0x00102001u, 0x00102010u, 0x00102012u, 0x00102021u, 0x00102100u, 0x00102111u, 0x00102120u, + 0x00102201u, 0x00102210u, 0x00110000u, 0x00110002u, 0x00110011u, 0x00110020u, 0x00110022u, 0x00110101u, + 0x00110110u, 0x00110112u, 0x00110121u, 0x00110200u, 0x00110211u, 0x00110220u, 0x00111001u, 0x00111010u, + 0x00111012u, 0x00111021u, 0x00111100u, 0x00111102u, 0x00111111u, 0x00111120u, 0x00111201u, 0x00111210u, + 0x00112000u, 0x00112002u, 0x00112011u, 0x00112020u, 0x00112101u, 0x00112110u, 0x00112200u, 0x00120001u, + 0x00120010u, 0x00120012u, 0x00120021u, 0x00120100u, 0x00120111u, 0x00121000u, 0x00121011u, 0x00121020u, + 0x00121101u, 0x00121110u, 0x00121200u, 0x00122001u, 0x00122010u, 0x00122100u, 0x00200000u, 0x00200002u, + 0x00200011u, 0x00200020u, 0x00200101u, 0x00200110u, 0x00200112u, 0x00200121u, 0x00200200u, 0x00200211u, + 0x00200222u, 0x00201001u, 0x00201010u, 0x00201012u, 0x00201021u, 0x00201100u, 0x00201102u, 0x00201111u, + 0x00201120u, 0x00201201u, 0x00201210u, 0x00202000u, 0x00202011u, 0x00202110u, 0x00202222u, 0x00210001u, + 0x00210010u, 0x00210100u, 0x00210102u, 0x00210111u, 0x00210120u, 0x00210201u, 0x00211000u, 0x00211011u, + 0x00211020u, 0x00211101u, 0x00211110u, 0x00211200u, 0x00212001u, 0x00212100u, 0x00220000u, 0x00220101u, + 0x00220110u, 0x00220202u, 0x00220220u, 0x00220222u, 0x00221100u, 0x00222121u, 0x01000001u, 0x01000010u, + 0x01000012u, 0x01000021u, 0x01000100u, 0x01000102u, 0x01000111u, 0x01000120u, 0x01000201u, 0x01000210u, + 0x01000212u, 0x01001000u, 0x01001002u, 0x01001011u, 0x01001020u, 0x01001101u, 0x01001110u, 0x01001112u, + 0x01001121u, 0x01001200u, 0x01001202u, 0x01001211u, 0x01001220u, 0x01002001u, 0x01002010u, 0x01002012u, + 0x01002100u, 0x01002111u, 0x01002120u, 0x01002201u, 0x01002210u, 0x01010000u, 0x01010002u, 0x01010011u, + 0x01010020u, 0x01010022u, 0x01010101u, 0x01010110u, 0x01010112u, 0x01010121u, 0x01010200u, 0x01010202u, + 0x01010211u, 0x01010220u, 0x01011001u, 0x01011010u, 0x01011012u, 0x01011021u, 0x01011100u, 0x01011102u, + 0x01011111u, 0x01011120u, 0x01011201u, 0x01011210u, 0x01012000u, 0x01012002u, 0x01012011u, 0x01012020u, + 0x01012101u, 0x01012110u, 0x01020001u, 0x01020010u, 0x01020021u, 0x01020100u, 0x01020111u, 0x01020201u, + 0x01020210u, 0x01021000u, 0x01021011u, 0x01021101u, 0x01021110u, 0x01022001u, 0x01022010u, 0x01022100u, + 0x01100000u, 0x01100002u, 0x01100011u, 0x01100020u, 0x01100101u, 0x01100110u, 0x01100112u, 0x01100121u, + 0x01100200u, 0x01100211u, 0x01100220u, 0x01101001u, 0x01101010u, 0x01101012u, 0x01101021u, 0x01101100u, + 0x01101102u, 0x01101111u, 0x01101120u, 0x01101201u, 0x01101210u, 0x01102000u, 0x01102002u, 0x01102011u, + 0x01102020u, 0x01102101u, 0x01102110u, 0x01102200u, 0x01110001u, 0x01110010u, 0x01110012u, 0x01110021u, + 0x01110100u, 0x01110102u, 0x01110111u, 0x01110120u, 0x01110201u, 0x01110210u, 0x01111000u, 0x01111002u, + 0x01111011u, 0x01111020u, 0x01111101u, 0x01111110u, 0x01111200u, 0x01112001u, 0x01112010u, 0x01112100u, + 0x01120000u, 0x01120011u, 0x01120020u, 0x01120101u, 0x01120110u, 0x01120200u, 0x01121001u, 0x01121010u, + 0x01121100u, 0x01122000u, 0x01122222u, 0x01200001u, 0x01200010u, 0x01200012u, 0x01200021u, 0x01200100u, + 0x01200111u, 0x01200120u, 0x01200201u, 0x01201000u, 0x01201002u, 0x01201011u, 0x01201020u, 0x01201101u, + 0x01201110u, 0x01201200u, 0x01202001u, 0x01202010u, 0x01210000u, 0x01210002u, 0x01210011u, 0x01210020u, + 0x01210101u, 0x01210110u, 0x01210200u, 0x01211001u, 0x01211010u, 0x01211100u, 0x01211221u, 0x01212202u, + 0x01220010u, 0x01220100u, 0x01221000u, 0x01221112u, 0x02000000u, 0x02000002u, 0x02000011u, 0x02000020u, + 0x02000101u, 0x02000110u, 0x02000112u, 0x02000121u, 0x02000200u, 0x02000211u, 0x02000222u, 0x02001001u, + 0x02001010u, 0x02001100u, 0x02001102u, 0x02001111u, 0x02001210u, 0x02002000u, 0x02002022u, 0x02002110u, + 0x02002222u, 0x02010001u, 0x02010010u, 0x02010100u, 0x02010102u, 0x02010111u, 0x02010201u, 0x02011000u, + 0x02011002u, 0x02011011u, 0x02011101u, 0x02011110u, 0x02011200u, 0x02012001u, 0x02012010u, 0x02012100u, + 0x02020000u, 0x02020022u, 0x02020202u, 0x02020220u, 0x02020222u, 0x02021010u, 0x02021100u, 0x02022020u, + 0x02022022u, 0x02022220u, 0x02100001u, 0x02100010u, 0x02100012u, 0x02100021u, 0x02100100u, 0x02100111u, + 0x02100120u, 0x02100201u, 0x02100210u, 0x02101000u, 0x02101002u, 0x02101011u, 0x02101020u, 0x02101101u, + 0x02101110u, 0x02101200u, 0x02102001u, 0x02102010u, 0x02102100u, 0x02110000u, 0x02110011u, 0x02110020u, + 0x02110101u, 0x02110110u, 0x02110200u, 0x02111001u, 0x02111010u, 0x02111100u, 0x02111212u, 0x02112000u, + 0x02120001u, 0x02120010u, 0x02120100u, 0x02121000u, 0x02121121u, 0x02200000u, 0x02200011u, 0x02200101u, + 0x02200110u, 0x02201001u, 0x02201010u, 0x02201100u, 0x02202022u, 0x02202222u, 0x02210001u, 0x02210010u, + 0x02210100u, 0x02212111u, 0x02220022u, 0x02220202u, 0x02221210u, 0x02222020u, 0x02222022u, 0x10000001u, + 0x10000010u, 0x10000012u, 0x10000021u, 0x10000100u, 0x10000102u, 0x10000111u, 0x10000120u, 0x10000122u, + 0x10000201u, 0x10000210u, 0x10000212u, 0x10001000u, 0x10001002u, 0x10001011u, 0x10001020u, 0x10001022u, + 0x10001101u, 0x10001110u, 0x10001112u, 0x10001121u, 0x10001200u, 0x10001202u, 0x10001211u, 0x10002001u, + 0x10002010u, 0x10002100u, 0x10002111u, 0x10002120u, 0x10002201u, 0x10002210u, 0x10010000u, 0x10010002u, + 0x10010011u, 0x10010020u, 0x10010101u, 0x10010110u, 0x10010112u, 0x10010121u, 0x10010200u, 0x10010202u, + 0x10010211u, 0x10011001u, 0x10011010u, 0x10011012u, 0x10011021u, 0x10011100u, 0x10011102u, 0x10011111u, + 0x10011120u, 0x10011201u, 0x10011210u, 0x10012000u, 0x10012002u, 0x10012011u, 0x10012020u, 0x10012101u, + 0x10012110u, 0x10012200u, 0x10020001u, 0x10020010u, 0x10020100u, 0x10020102u, 0x10020111u, 0x10020120u, + 0x10020210u, 0x10021000u, 0x10021011u, 0x10021020u, 0x10021101u, 0x10021110u, 0x10021200u, 0x10022001u, + 0x10022010u, 0x10100000u, 0x10100002u, 0x10100011u, 0x10100020u, 0x10100022u, 0x10100101u, 0x10100110u, + 0x10100112u, 0x10100121u, 0x10100200u, 0x10100202u, 0x10100211u, 0x10100220u, 0x10101001u, 0x10101010u, + 0x10101012u, 0x10101021u, 0x10101100u, 0x10101102u, 0x10101111u, 0x10101120u, 0x10101201u, 0x10101210u, + 0x10102000u, 0x10102002u, 0x10102011u, 0x10102020u, 0x10102101u, 0x10102110u, 0x10102200u, 0x10110001u, + 0x10110010u, 0x10110012u, 0x10110021u, 0x10110100u, 0x10110102u, 0x10110111u, 0x10110120u, 0x10110201u, + 0x10110210u, 0x10111000u, 0x10111002u, 0x10111011u, 0x10111020u, 0x10111101u, 0x10111110u, 0x10111200u, + 0x10111222u, 0x10112001u, 0x10112010u, 0x10112100u, 0x10120000u, 0x10120002u, 0x10120011u, 0x10120020u, + 0x10120101u, 0x10120110u, 0x10120200u, 0x10121001u, 0x10121010u, 0x10121100u, 0x10122000u, 0x10122211u, + 0x10200001u, 0x10200010u, 0x10200021u, 0x10200100u, 0x10200102u, 0x10200111u, 0x10200120u, 0x10200201u, + 0x10200210u, 0x10201000u, 0x10201002u, 0x10201011u, 0x10201020u, 0x10201101u, 0x10201110u, 0x10201200u, + 0x10202010u, 0x10202100u, 0x10210000u, 0x10210002u, 0x10210011u, 0x10210020u, 0x10210101u, 0x10210110u, + 0x10210200u, 0x10211001u, 0x10211010u, 0x10211100u, 0x10212000u, 0x10212112u, 0x10220001u, 0x10220010u, + 0x10220100u, 0x10221000u, 0x11000000u, 0x11000002u, 0x11000011u, 0x11000020u, 0x11000101u, 0x11000110u, + 0x11000112u, 0x11000121u, 0x11000200u, 0x11000202u, 0x11000211u, 0x11000220u, 0x11001001u, 0x11001010u, + 0x11001012u, 0x11001021u, 0x11001100u, 0x11001102u, 0x11001111u, 0x11001120u, 0x11001201u, 0x11001210u, + 0x11002000u, 0x11002002u, 0x11002011u, 0x11002020u, 0x11002101u, 0x11002110u, 0x11010001u, 0x11010010u, + 0x11010012u, 0x11010021u, 0x11010100u, 0x11010102u, 0x11010111u, 0x11010120u, 0x11010201u, 0x11010210u, + 0x11011000u, 0x11011002u, 0x11011011u, 0x11011020u, 0x11011101u, 0x11011110u, 0x11011200u, 0x11012001u, + 0x11012010u, 0x11012100u, 0x11020000u, 0x11020011u, 0x11020020u, 0x11020101u, 0x11020110u, 0x11020200u, + 0x11021001u, 0x11021010u, 0x11021100u, 0x11021221u, 0x11022000u, 0x11100001u, 0x11100010u, 0x11100012u, + 0x11100021u, 0x11100100u, 0x11100102u, 0x11100111u, 0x11100120u, 0x11100201u, 0x11100210u, 0x11101000u, + 0x11101002u, 0x11101011u, 0x11101020u, 0x11101101u, 0x11101110u, 0x11101200u, 0x11102001u, 0x11102010u, + 0x11102100u, 0x11110000u, 0x11110002u, 0x11110011u, 0x11110020u, 0x11110101u, 0x11110110u, 0x11110200u, + 0x11111001u, 0x11111010u, 0x11111100u, 0x11112000u, 0x11120001u, 0x11120010u, 0x11120100u, 0x11120212u, + 0x11121000u, 0x11200000u, 0x11200002u, 0x11200011u, 0x11200020u, 0x11200101u, 0x11200110u, 0x11200200u, + 0x11201001u, 0x11201010u, 0x11201100u, 0x11201122u, 0x11202000u, 0x11210001u, 0x11210010u, 0x11210100u, + 0x11211000u, 0x11220000u, 0x11220121u, 0x11222011u, 0x11222220u, 0x12000001u, 0x12000010u, 0x12000012u, + 0x12000100u, 0x12000102u, 0x12000111u, 0x12000120u, 0x12000201u, 0x12000210u, 0x12001000u, 0x12001011u, + 0x12001020u, 0x12001101u, 0x12001110u, 0x12001200u, 0x12002010u, 0x12002100u, 0x12010000u, 0x12010002u, + 0x12010011u, 0x12010020u, 0x12010101u, 0x12010110u, 0x12010200u, 0x12011001u, 0x12011010u, 0x12011100u, + 0x12012000u, 0x12012121u, 0x12020010u, 0x12020100u, 0x12021000u, 0x12021112u, 0x12022201u, 0x12100000u, + 0x12100011u, 0x12100020u, 0x12100101u, 0x12100110u, 0x12100200u, 0x12101001u, 0x12101010u, 0x12101100u, + 0x12102000u, 0x12110001u, 0x12110010u, 0x12110100u, 0x12111000u, 0x12111022u, 0x12111220u, 0x12112102u, + 0x12120000u, 0x12122110u, 0x12200001u, 0x12200010u, 0x12200100u, 0x12201211u, 0x12202120u, 0x12210000u, + 0x12210222u, 0x12221002u, 0x12222201u, 0x20000000u, 0x20000002u, 0x20000011u, 0x20000020u, 0x20000101u, + 0x20000110u, 0x20000121u, 0x20000200u, 0x20000211u, 0x20001001u, 0x20001010u, 0x20001100u, 0x20001102u, + 0x20001111u, 0x20001120u, 0x20001201u, 0x20002000u, 0x20002011u, 0x20002101u, 0x20002110u, 0x20010001u, + 0x20010010u, 0x20010021u, 0x20010100u, 0x20010102u, 0x20010111u, 0x20010120u, 0x20010201u, 0x20010210u, + 0x20011000u, 0x20011002u, 0x20011011u, 0x20011020u, 0x20011101u, 0x20011110u, 0x20012001u, 0x20012010u, + 0x20012100u, 0x20012221u, 0x20020000u, 0x20020011u, 0x20020022u, 0x20020101u, 0x20020110u, 0x20021001u, + 0x20021010u, 0x20021100u, 0x20100001u, 0x20100010u, 0x20100012u, 0x20100021u, 0x20100100u, 0x20100102u, + 0x20100111u, 0x20100120u, 0x20100201u, 0x20101000u, 0x20101002u, 0x20101011u, 0x20101020u, 0x20101101u, + 0x20101110u, 0x20101200u, 0x20102001u, 0x20102010u, 0x20102100u, 0x20110000u, 0x20110002u, 0x20110011u, + 0x20110020u, 0x20110101u, 0x20110110u, 0x20110200u, 0x20111001u, 0x20111010u, 0x20111100u, 0x20112000u, + 0x20112022u, 0x20120001u, 0x20120010u, 0x20120100u, 0x20120221u, 0x20121000u, 0x20200000u, 0x20200011u, + 0x20200101u, 0x20200110u, 0x20201001u, 0x20201010u, 0x20201100u, 0x20202202u, 0x20210001u, 0x20210010u, + 0x20211000u, 0x20211211u, 0x20220202u, 0x20221120u, 0x20221122u, 0x20222002u, 0x20222202u, 0x21000001u, + 0x21000010u, 0x21000021u, 0x21000100u, 0x21000102u, 0x21000111u, 0x21000120u, 0x21000210u, 0x21001000u, + 0x21001002u, 0x21001011u, 0x21001020u, 0x21001101u, 0x21001110u, 0x21001200u, 0x21002001u, 0x21002010u, + 0x21002100u, 0x21010000u, 0x21010011u, 0x21010101u, 0x21010110u, 0x21011001u, 0x21011010u, 0x21011100u, + 0x21011122u, 0x21020001u, 0x21020010u, 0x21020100u, 0x21021000u, 0x21022212u, 0x21100000u, 0x21100002u, + 0x21100011u, 0x21100020u, 0x21100101u, 0x21100110u, 0x21100200u, 0x21101001u, 0x21101010u, 0x21101100u, + 0x21102000u, 0x21102112u, 0x21110001u, 0x21110010u, 0x21110100u, 0x21111000u, 0x21112120u, 0x21112201u, + 0x21120000u, 0x21121012u, 0x21121210u, 0x21200001u, 0x21200010u, 0x21200100u, 0x21200212u, 0x21201000u, + 0x21202221u, 0x21210000u, 0x21211021u, 0x21211102u, 0x21222100u, 0x22000000u, 0x22000011u, 0x22000022u, + 0x22000110u, 0x22000202u, 0x22000222u, 0x22001001u, 0x22001010u, 0x22001100u, 0x22002202u, 0x22002222u, + 0x22011000u, 0x22011211u, 0x22020002u, 0x22020022u, 0x22020202u, 0x22020220u, 0x22020222u, 0x22022002u, + 0x22022020u, 0x22022022u, 0x22022220u, 0x22100001u, 0x22100010u, 0x22100100u, 0x22101000u, 0x22102021u, + 0x22102210u, 0x22110000u, 0x22110121u, 0x22121101u, 0x22200022u, 0x22200220u, 0x22202202u, 0x22211110u, + 0x22212012u, 0x22220020u, 0x22220022u, 0x22220200u, 0x22220202u, 0x22220220u, 0x22222020u, 0x22222222u, +}; +__device__ const uint32_t kIq2sSign[256] = { + 0x00000000u, 0x00000004u, 0x00000040u, 0x00000044u, 0x00000400u, 0x00000404u, 0x00000440u, 0x00000444u, + 0x00004000u, 0x00004004u, 0x00004040u, 0x00004044u, 0x00004400u, 0x00004404u, 0x00004440u, 0x00004444u, + 0x00040000u, 0x00040004u, 0x00040040u, 0x00040044u, 0x00040400u, 0x00040404u, 0x00040440u, 0x00040444u, + 0x00044000u, 0x00044004u, 0x00044040u, 0x00044044u, 0x00044400u, 0x00044404u, 0x00044440u, 0x00044444u, + 0x00400000u, 0x00400004u, 0x00400040u, 0x00400044u, 0x00400400u, 0x00400404u, 0x00400440u, 0x00400444u, + 0x00404000u, 0x00404004u, 0x00404040u, 0x00404044u, 0x00404400u, 0x00404404u, 0x00404440u, 0x00404444u, + 0x00440000u, 0x00440004u, 0x00440040u, 0x00440044u, 0x00440400u, 0x00440404u, 0x00440440u, 0x00440444u, + 0x00444000u, 0x00444004u, 0x00444040u, 0x00444044u, 0x00444400u, 0x00444404u, 0x00444440u, 0x00444444u, + 0x04000000u, 0x04000004u, 0x04000040u, 0x04000044u, 0x04000400u, 0x04000404u, 0x04000440u, 0x04000444u, + 0x04004000u, 0x04004004u, 0x04004040u, 0x04004044u, 0x04004400u, 0x04004404u, 0x04004440u, 0x04004444u, + 0x04040000u, 0x04040004u, 0x04040040u, 0x04040044u, 0x04040400u, 0x04040404u, 0x04040440u, 0x04040444u, + 0x04044000u, 0x04044004u, 0x04044040u, 0x04044044u, 0x04044400u, 0x04044404u, 0x04044440u, 0x04044444u, + 0x04400000u, 0x04400004u, 0x04400040u, 0x04400044u, 0x04400400u, 0x04400404u, 0x04400440u, 0x04400444u, + 0x04404000u, 0x04404004u, 0x04404040u, 0x04404044u, 0x04404400u, 0x04404404u, 0x04404440u, 0x04404444u, + 0x04440000u, 0x04440004u, 0x04440040u, 0x04440044u, 0x04440400u, 0x04440404u, 0x04440440u, 0x04440444u, + 0x04444000u, 0x04444004u, 0x04444040u, 0x04444044u, 0x04444400u, 0x04444404u, 0x04444440u, 0x04444444u, + 0x40000000u, 0x40000004u, 0x40000040u, 0x40000044u, 0x40000400u, 0x40000404u, 0x40000440u, 0x40000444u, + 0x40004000u, 0x40004004u, 0x40004040u, 0x40004044u, 0x40004400u, 0x40004404u, 0x40004440u, 0x40004444u, + 0x40040000u, 0x40040004u, 0x40040040u, 0x40040044u, 0x40040400u, 0x40040404u, 0x40040440u, 0x40040444u, + 0x40044000u, 0x40044004u, 0x40044040u, 0x40044044u, 0x40044400u, 0x40044404u, 0x40044440u, 0x40044444u, + 0x40400000u, 0x40400004u, 0x40400040u, 0x40400044u, 0x40400400u, 0x40400404u, 0x40400440u, 0x40400444u, + 0x40404000u, 0x40404004u, 0x40404040u, 0x40404044u, 0x40404400u, 0x40404404u, 0x40404440u, 0x40404444u, + 0x40440000u, 0x40440004u, 0x40440040u, 0x40440044u, 0x40440400u, 0x40440404u, 0x40440440u, 0x40440444u, + 0x40444000u, 0x40444004u, 0x40444040u, 0x40444044u, 0x40444400u, 0x40444404u, 0x40444440u, 0x40444444u, + 0x44000000u, 0x44000004u, 0x44000040u, 0x44000044u, 0x44000400u, 0x44000404u, 0x44000440u, 0x44000444u, + 0x44004000u, 0x44004004u, 0x44004040u, 0x44004044u, 0x44004400u, 0x44004404u, 0x44004440u, 0x44004444u, + 0x44040000u, 0x44040004u, 0x44040040u, 0x44040044u, 0x44040400u, 0x44040404u, 0x44040440u, 0x44040444u, + 0x44044000u, 0x44044004u, 0x44044040u, 0x44044044u, 0x44044400u, 0x44044404u, 0x44044440u, 0x44044444u, + 0x44400000u, 0x44400004u, 0x44400040u, 0x44400044u, 0x44400400u, 0x44400404u, 0x44400440u, 0x44400444u, + 0x44404000u, 0x44404004u, 0x44404040u, 0x44404044u, 0x44404400u, 0x44404404u, 0x44404440u, 0x44404444u, + 0x44440000u, 0x44440004u, 0x44440040u, 0x44440044u, 0x44440400u, 0x44440404u, 0x44440440u, 0x44440444u, + 0x44444000u, 0x44444004u, 0x44444040u, 0x44444044u, 0x44444400u, 0x44444404u, 0x44444440u, 0x44444444u, +}; + +template +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0, ""); + __shared__ __align__(16) uint32_t tabA_s[1024]; + __shared__ __align__(16) uint32_t tabB_s[256]; + __shared__ __align__(16) int act_s[TPP][4][16]; + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + for (int i = threadIdx.x; i < 1024; i += NT) tabA_s[i] = kIq2sCode[i]; + for (int i = threadIdx.x; i < 256; i += NT) tabB_s[i] = kIq2sSign[i]; + int r0; + const Chunk c = cta_work(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int ci = lane & 15, rsub = lane >> 4; // lanes 0-10 stage one row, 16-26 the next; ci = the compact word + const bool cact = ci < CW; + const char* __restrict__ Wr = w + xoff[c.j] + (size_t) (r0 + 2 * warp + rsub) * ROWB; // + k * 2 NW rows + int* __restrict__ wsl = wsm + (2 * warp + rsub) * CWS + ci; // + k * 2 NW * CWS + const int* cw = wsm + threadIdx.x * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + // compact word ci's byte offset inside the block (ci 0-9); d (ci 10) sits at +0 + const int boff = ci < 4 ? 2 + 16 * h + 4 * ci : ci < 8 ? 18 + 16 * h + 4 * ci : ci == 8 ? 66 + 4 * h : 74 + 4 * h; + __syncthreads(); + if (cact) { + const char* blk0 = Wr + kc * BB; + if (kc & 1) { // odd block: words aligned, one load each; d = high half of the word at blk - 2 + const int o = ci < 10 ? boff : -2, sh = ci < 10 ? 0 : 16; + int v[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) v[k] = __ldg((const int*) (blk0 + (size_t) k * 2 * NW * ROWB + o)); +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v[k], v[k], sh); + } else { // even block: words 2 bytes into a word, two loads + funnel shift; d = low half at blk + const int o0 = ci < 10 ? boff - 2 : 0, o1 = ci < 10 ? boff + 2 : 0, sh = ci < 10 ? 16 : 0; + int v0[KR], v1[KR]; +#pragma unroll + for (int k = 0; k < KR; ++k) { + const char* b = blk0 + (size_t) k * 2 * NW * ROWB; + v0[k] = __ldg((const int*) (b + o0)); + v1[k] = __ldg((const int*) (b + o1)); + } +#pragma unroll + for (int k = 0; k < KR; ++k) wsl[k * 2 * NW * CWS] = __funnelshift_r(v0[k], v1[k], sh); + } + } + stage_act(xq, hc, total_rows, trow0, nt, act_s, dy_s); + __syncthreads(); +#pragma unroll 1 + for (int s = 0; s < 4; ++s) { // cw: [0..3] grid bytes, [4..7] sign bytes, [8] qh, [9] scales, [10] d + int wv[16]; + float dx0, dx1; + const int qs_packed = cw[s], signs_packed_32 = cw[4 + s], qh = (cw[8] >> (8 * s)) & 0xFF; +#pragma unroll + for (int l = 0; l < QR2_S; ++l) { + const int idx = ((qs_packed >> (8 * l)) & 0xFF) | ((qh << (8 - 2 * l)) & 0x300); + const uint32_t sel = tabA_s[idx] | tabB_s[(signs_packed_32 >> (8 * l)) & 0xFF]; + split2((int) __byte_perm(PX, PY, sel), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) __byte_perm(PX, PY, sel >> 16), wv[4 * l + 2], wv[4 * l + 3]); + } + scales16((cw[9] >> (8 * s)) & 0xFF, cw[10], dx0, dx1); + mac16(wv, dx0, dx1, s, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace s2 + +template +void go(F kernel, const Layer& L, cudaStream_t s) { + kernel<<<(unsigned) (L.nchunks * PIECES), NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, (const block_q8_1_mmq*) L.xq, + (int) L.rows, L.gu); +} + +} // namespace + +// tokens per pass by u (the measured crossovers): IQ2_XXS 8 below 5 rows per expert, 16 below 25, then 32 (4-token +// groups); IQ2_XS 8 below 6, 16 below 20, then 16 in 4-token groups; IQ2_S 8 below 5, 16 below 25, then 32 +void gu_iq2_xxs(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 5.0) go(xxs2::gu_kernel<8, 3, 2>, L, s); + else if (u < 25.0) go(xxs2::gu_kernel<16, 3, 2>, L, s); + else go(xxs2::gu_kernel<32, 2, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ2_XXS"); +} + +void gu_iq2_xs(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 6.0) go(xs2::gu_kernel<8, 1, 2>, L, s); + else if (u < 20.0) go(xs2::gu_kernel<16, 0, 2>, L, s); + else go(xs2::gu_kernel<16, 1, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ2_XS"); +} + +void gu_iq2_s(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 5.0) go(s2::gu_kernel<8, 0, 2>, L, s); + else if (u < 25.0) go(s2::gu_kernel<16, 1, 2>, L, s); + else go(s2::gu_kernel<32, 1, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ2_S"); +} + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/moe_ws_gu_iq3.cu b/src/prefill/moe_ws_gu_iq3.cu new file mode 100644 index 00000000..efd551dc --- /dev/null +++ b/src/prefill/moe_ws_gu_iq3.cu @@ -0,0 +1,370 @@ +// src/prefill/moe_ws_gu_iq3.cu - weight-stationary gate/up products (see moe_ws.hpp): IQ3_XXS and IQ3_S, [1280 x 2560] +// read in place. A CTA = 128 threads = 128 weight rows of one expert (a row per thread, all of the chunk's activation +// rows TPP at a time, the sums in registers); K advances 128 values a step (half a 256-value block = 4 sub-blocks): +// the step's bytes of the 128 rows and the step's q8_1 block of each token go to shared memory (the activations split +// to int16 pairs once), then each thread decodes its row's 4 sub-blocks once per pass and runs them against the tokens. +// Bits: per 32-value sub-block MMQ's int8 values (ggml_cuda_mmq_load_tiles_iq3_*: grid entries, its __vcmpne4 sign +// masks applied as (g ^ s) + (s & 0x01010101) == __vsub4(g ^ s, s), every grid byte >= 1) and scale expression, then +// MMQ's epilogue acc = fma(dx * dy, float(sum), acc), sub-blocks in K order. (Measured on a GP100 die: +// ws / per-group MMQ 0.31-0.35 at 2.5 rows per expert, 0.49-0.52 at 10, 0.67-0.76 at 35, +// 0.78-0.79 at 160; bit-identical, compute-sanitizer clean with exact-size matrices.) +// +// Staging without per-lane branches: rows are 980 / 1100 B, so block kc starts 2 * (kc & 1) bytes into a 4-byte word +// for the whole CTA - an even block's words are two aligned loads and a funnel shift (the second load ends at most 2 +// bytes into block kc + 1 of the same row), an odd block's are aligned; d sits the other way round (an odd block's d is +// the high half of the word 2 bytes before it, inside block kc - 1). Every load of a lane is issued before its stores, +// and nothing outside a row is read (the last row's last block is odd). +#include "common.cuh" +#include "mmq.cuh" + +#include "moe_ws.cuh" + +#include +#include + +namespace strata::prefill::ws::detail { +namespace { + +constexpr int GU_ROWS = 1280, GU_K = 2560, NB = GU_K / QK_K, NSTEP = 2 * NB, NT = 128, PIECES = GU_ROWS / NT; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// ---- IQ3_XXS: 98-B blocks; per row and step 8 grid-index words, 4 aux words (signs + scale) and d (stride 13). +// Every lane slot is one word type: grid words rows tid/8 + 16 i (word tid%8), aux words rows tid/4 + 32 i (word +// tid%4), d the thread's own row. Token groups of TG: one branch per group on a partial pass (a group's tokens past +// the count run on copies of row nt - 1 and are not written), none on a full pass. +namespace xxs3 { +constexpr int BB = (int) sizeof(block_iq3_xxs), ROWB = NB * BB, CWS = 13; +static_assert(BB == 98 && ROWB % 4 == 0, "block_iq3_xxs"); + +template +__device__ __forceinline__ void sb_compute(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ grid, + const int2* __restrict__ lut, const int (*act_s)[4][16], + const float (*dy_s)[4], const int nt, float (&acc)[TPP]) { + int wv[16]; + float dx; + { + const uint32_t qa = (uint32_t) cw[2 * s + 0], qb = (uint32_t) cw[2 * s + 1]; // 8 grid indices + const uint32_t aux32 = (uint32_t) cw[8 + s]; +#pragma unroll + for (int l = 0; l < QR3_XXS; ++l) { + const uint32_t qw = l < 2 ? qa : qb; + const uint32_t g0 = grid[(qw >> (16 * (l & 1))) & 0xFF], g1 = grid[(qw >> (16 * (l & 1) + 8)) & 0xFF]; + const int2 sg = lut[(aux32 >> (7 * l)) & 0x7F]; + split2((int) ((g0 ^ (uint32_t) sg.x) + ((uint32_t) sg.x & 0x01010101u)), wv[4 * l + 0], wv[4 * l + 1]); + split2((int) ((g1 ^ (uint32_t) sg.y) + ((uint32_t) sg.y & 0x01010101u)), wv[4 * l + 2], wv[4 * l + 3]); + } + const int ls = aux32 >> 28; + const float d = __ushort_as_half((unsigned short) (cw[12] & 0xFFFF)); + dx = (ls*d + d/2)/2; // MMQ's expression, verbatim + } +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (FULL || t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const int a[16] = {a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w, a2.x, a2.y, a2.z, a2.w, a3.x, a3.y, a3.z, a3.w}; + const float dy = dy_s[t][s]; + int sc[CH]; + sc[0] = kMagicI; +#pragma unroll + for (int c = 1; c < CH; ++c) sc[c] = 0; +#pragma unroll + for (int m = 0; m < 16; ++m) sc[m % CH] = mad2(wv[m], a[m], sc[m % CH]); + int sum = sc[0]; +#pragma unroll + for (int c = 1; c < CH; ++c) sum += sc[c]; + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __fsub_rn(__int_as_float(sum), kMagicF), acc[t]); + } + } + } +} + +template +__global__ void __launch_bounds__(NT, 1) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0 && (TPP * 32) % NT == 0 && TPP * 4 <= NT, ""); + constexpr int NG = 8, RG = NT / 8; // grid-index-word slots: rows tid/8 + i*RG, word tid%8 + constexpr int NX = 4, RX = NT / 4; // aux-word slots: rows tid/4 + i*RX, word tid%4 + constexpr int NA = TPP * 32 / NT; + __shared__ uint32_t grid_s[256]; + __shared__ int2 lut_s[128]; + __shared__ __align__(16) int act_s[TPP][4][16]; + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + const int tid = threadIdx.x; + for (int i = tid; i < 256; i += NT) grid_s[i] = iq3xxs_grid[i]; + for (int i = tid; i < 128; i += NT) { + const uint32_t signs = unpack_ksigns((uint8_t) i); + lut_s[i] = make_int2(__vcmpne4(signs & 0x08040201, 0), __vcmpne4(signs & 0x80402010, 0)); + } + int r0; + const Chunk c = cta_work(chunks, r0); + const char* __restrict__ W = w + xoff[c.j] + (size_t) r0 * ROWB; + const char* __restrict__ Wg = W + (size_t) (tid >> 3) * ROWB + 4 * (tid & 7); // + i*RG*ROWB + kc*BB + 32h + const char* __restrict__ Wx = W + (size_t) (tid >> 2) * ROWB + 64 + 4 * (tid & 3); // + i*RX*ROWB + kc*BB + 16h + const char* __restrict__ Wd = W + (size_t) tid * ROWB; + int* __restrict__ sg_ = wsm + (tid >> 3) * CWS + (tid & 7); + int* __restrict__ sx_ = wsm + (tid >> 2) * CWS + 8 + (tid & 3); + int* __restrict__ sd_ = wsm + tid * CWS + 12; + const int* cw = wsm + tid * CWS; + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + const int kc = hc >> 1, h = hc & 1; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); + __syncthreads(); + int av[NA], dv = 0; +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5; + av[i] = __ldg(xr + min(t, nt - 1) * 36 + 4 + (idx & 31)); // clamped: no branch, never past row nt-1 + } + if (TPP * 4 == NT || tid < TPP * 4) dv = __ldg(xr + min(tid >> 2, nt - 1) * 36 + (tid & 3)); + const char* bg = Wg + kc * BB + 32 * h; // even kc: the aligned word 2 bytes before the data word + const char* bx = Wx + kc * BB + 16 * h; + if (kc & 1) { // odd block: data words aligned (at +2); d = high half of the word 2 bytes before the block + int vg[NG], vx[NX]; +#pragma unroll + for (int i = 0; i < NG; ++i) vg[i] = __ldg((const int*) (bg + 2 + (size_t) i * RG * ROWB)); +#pragma unroll + for (int i = 0; i < NX; ++i) vx[i] = __ldg((const int*) (bx + 2 + (size_t) i * RX * ROWB)); + const int vd = __ldg((const int*) (Wd + kc * BB - 2)); +#pragma unroll + for (int i = 0; i < NG; ++i) sg_[i * RG * CWS] = vg[i]; +#pragma unroll + for (int i = 0; i < NX; ++i) sx_[i * RX * CWS] = vx[i]; + *sd_ = (int) ((uint32_t) vd >> 16); + } else { // even block: data words 2 bytes into a word: two aligned words + funnel shift; d = low half + int lg[NG], hg[NG], lx[NX], hx[NX]; +#pragma unroll + for (int i = 0; i < NG; ++i) { + lg[i] = __ldg((const int*) (bg + (size_t) i * RG * ROWB)); + hg[i] = __ldg((const int*) (bg + 4 + (size_t) i * RG * ROWB)); + } +#pragma unroll + for (int i = 0; i < NX; ++i) { + lx[i] = __ldg((const int*) (bx + (size_t) i * RX * ROWB)); + hx[i] = __ldg((const int*) (bx + 4 + (size_t) i * RX * ROWB)); + } + const int vd = __ldg((const int*) (Wd + kc * BB)); +#pragma unroll + for (int i = 0; i < NG; ++i) sg_[i * RG * CWS] = (int) __funnelshift_r((uint32_t) lg[i], (uint32_t) hg[i], 16); +#pragma unroll + for (int i = 0; i < NX; ++i) sx_[i * RX * CWS] = (int) __funnelshift_r((uint32_t) lx[i], (uint32_t) hx[i], 16); + *sd_ = vd; + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = tid + i * NT, t = idx >> 5, wd = idx & 31; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][wd >> 3][2 * (wd & 7)] = make_int2(lo, hi); + } + if (TPP * 4 == NT || tid < TPP * 4) dy_s[tid >> 2][tid & 3] = __int_as_float(dv); + __syncthreads(); + if (nt == TPP) { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute(cw, s, grid_s, lut_s, act_s, dy_s, nt, acc); + } else { +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute(cw, s, grid_s, lut_s, act_s, dy_s, nt, acc); + } + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + tid] = acc[t]; + } +} +} // namespace xxs3 + +// ---- IQ3_S: 110-B blocks; per row and step a compact copy of the bytes the 4 sub-blocks read - qs 32 B, signs 16 B, +// qh 4 B, d and the 2 scale bytes: 14 words, row stride 15 - staged by lanes 0-13 / 16-29 of each warp (two rows per +// warp and k), each word built from two aligned loads by one PRMT. The sign masks come from a 256-entry table of MMQ's +// own __vcmpne4 expressions. Token groups of TG behind one `t < nt` branch. +namespace s3 { +constexpr int BB = 110, ROWB = NB * BB, CW = 14, CWS = 15, NW = NT / 32, KN = NT / (2 * NW); + +__device__ __forceinline__ int2 mmq_signs(const int sb) { // ggml_cuda_mmq_load_tiles_iq3_s's, verbatim + const int s0 = __vcmpne4(((sb & 0x03) << 7) | ((sb & 0x0C) << 21), 0x00000000); + const int s1 = __vcmpne4(((sb & 0x30) << 3) | ((sb & 0xC0) << 17), 0x00000000); + return make_int2(s0, s1); +} + +// sub-block s of the staged half: kqsx = 4 h + s's 8 int8x4 words and scale. cw: [0..7] qs, [8..11] sign bytes, +// [12] qh, [13] d | the half's 2 scale bytes << 16 +__device__ __forceinline__ float dec(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ grid, + const int2* __restrict__ lut, int (&q)[8]) { + const int2 qs_packed = make_int2(cw[2 * s + 0], cw[2 * s + 1]); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = (cw[12] >> (8 * s)) & 0xFF; + const int signs_packed_32 = cw[8 + s]; + const int w13 = cw[13]; +#pragma unroll + for (int l = 0; l < QR3_S; ++l) { + const int2 grid_pos = make_int2(grid[qs[2 * l + 0] | ((qh << (8 - 2 * l)) & 0x100)], + grid[qs[2 * l + 1] | ((qh << (7 - 2 * l)) & 0x100)]); + const int2 sg = lut[(signs_packed_32 >> (8 * l)) & 0xFF]; + q[2 * l + 0] = (grid_pos.x ^ sg.x) + (sg.x & 0x01010101); + q[2 * l + 1] = (grid_pos.y ^ sg.y) + (sg.y & 0x01010101); + } + const int ls = 1 + 2 * (((w13 >> (16 + 8 * (s >> 1))) >> (4 * (s & 1))) & 0x0F); + const float d = __ushort_as_half((unsigned short) (w13 & 0xFFFF)); + return ls * d; +} + +// compact word ci of step half h in a block of parity odd: its two aligned words (offsets from the block) and selector +__device__ __forceinline__ void stage_map(const int ci, const int h, const int odd, int& o0, int& o1, int& sel) { + const int off = ci < 8 ? 2 + 32 * h + 4 * ci : ci < 12 ? 74 + 16 * h + 4 * (ci - 8) : 66 + 4 * h; + const bool dw = ci == 13; + o0 = dw ? (odd ? -2 : 0) : (odd ? off : off - 2); + o1 = dw ? (odd ? 106 : 104 + 4 * h) : (odd ? off : off + 2); + sel = dw ? (odd ? (h ? 0x7632 : 0x5432) : (h ? 0x5410 : 0x7610)) : (odd ? 0x3210 : 0x5432); +} + +template +__device__ __forceinline__ void sb_compute(const int* __restrict__ cw, const int s, const uint32_t* __restrict__ grid, + const int2* __restrict__ lut, const int (*act_s)[4][16], const float (*dy_s)[4], + const int nt, float (&acc)[TPP]) { + int q[8]; + const float dx = dec(cw, s, grid, lut, q); + int wv[16]; +#pragma unroll + for (int m = 0; m < 8; ++m) split2(q[m], wv[2 * m], wv[2 * m + 1]); +#pragma unroll + for (int t0 = 0; t0 < TPP; t0 += TG) { + if (t0 < nt) { +#pragma unroll + for (int t = t0; t < t0 + TG; ++t) { + const int4* a4 = (const int4*) act_s[t][s]; + const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3]; + const float dy = dy_s[t][s]; + int s0 = 0, s1 = 0, s2 = 0, s3 = 0; + s0 = mad2(wv[0], a0.x, s0); s1 = mad2(wv[1], a0.y, s1); s2 = mad2(wv[2], a0.z, s2); s3 = mad2(wv[3], a0.w, s3); + s0 = mad2(wv[4], a1.x, s0); s1 = mad2(wv[5], a1.y, s1); s2 = mad2(wv[6], a1.z, s2); s3 = mad2(wv[7], a1.w, s3); + s0 = mad2(wv[8], a2.x, s0); s1 = mad2(wv[9], a2.y, s1); s2 = mad2(wv[10], a2.z, s2); s3 = mad2(wv[11], a2.w, s3); + s0 = mad2(wv[12], a3.x, s0); s1 = mad2(wv[13], a3.y, s1); s2 = mad2(wv[14], a3.z, s2); s3 = mad2(wv[15], a3.w, s3); + acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __int2float_rn((s0 + s1) + (s2 + s3)), acc[t]); + } + } + } +} + +template +__global__ void __launch_bounds__(NT) gu_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w, + const int64_t* __restrict__ xoff, const block_q8_1_mmq* __restrict__ xq, + const int total_rows, float* __restrict__ dst) { + static_assert(TPP % TG == 0, ""); + constexpr size_t KSTR = (size_t) 2 * NW * ROWB; // a staging lane's rows are 2 * NW apart + __shared__ uint32_t grid_s[512]; + __shared__ int2 lut_s[256]; + __shared__ __align__(16) int act_s[TPP][4][16]; + __shared__ float dy_s[TPP][4]; + __shared__ int wsm[NT * CWS]; + for (int i = threadIdx.x; i < 512; i += NT) grid_s[i] = iq3s_grid[i]; + for (int i = threadIdx.x; i < 256; i += NT) lut_s[i] = mmq_signs(i); + int r0; + const Chunk c = cta_work(chunks, r0); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int ci = lane & 15, rsub = lane >> 4; // lanes 0-13 stage one row, 16-29 the next; ci = the compact word + const bool cact = ci < CW; + const char* __restrict__ Wr = w + xoff[c.j] + (size_t) (r0 + 2 * warp + rsub) * ROWB; // + k * KSTR + int* __restrict__ wsl = wsm + (2 * warp + rsub) * CWS + ci; // + k * 2 NW * CWS + for (int p0 = 0; p0 < c.rows; p0 += TPP) { + const int nt = min(TPP, c.rows - p0); + const int trow0 = c.row0 + p0; + float acc[TPP]; +#pragma unroll + for (int t = 0; t < TPP; ++t) acc[t] = 0.0f; +#pragma unroll 1 + for (int hc = 0; hc < NSTEP; ++hc) { + __syncthreads(); + if (cact) { // branch-free inside: every lane issues its 2 * KN loads, then its KN stores + int o0, o1, sel; + stage_map(ci, hc & 1, (hc >> 1) & 1, o0, o1, sel); + const char* b = Wr + (hc >> 1) * BB; + int v0[KN], v1[KN]; +#pragma unroll + for (int k = 0; k < KN; ++k) v0[k] = __ldg((const int*) (b + k * KSTR + o0)); +#pragma unroll + for (int k = 0; k < KN; ++k) v1[k] = __ldg((const int*) (b + k * KSTR + o1)); +#pragma unroll + for (int k = 0; k < KN; ++k) wsl[k * 2 * NW * CWS] = (int) __byte_perm(v0[k], v1[k], sel); + } + { // the step's activations: nt consecutive 144-B blocks, loads first, then split + store + constexpr int NA = (TPP * 36 + NT - 1) / NT; + int av[NA]; + const int* xr = (const int*) (xq + (size_t) hc * total_rows + trow0); +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) av[i] = __ldg(xr + idx); + } +#pragma unroll + for (int i = 0; i < NA; ++i) { + const int idx = threadIdx.x + i * NT; + if (idx < nt * 36) { + const int t = idx / 36, wd = idx - t * 36; + if (wd < 4) { + dy_s[t][wd] = __int_as_float(av[i]); + } else { + const int m = wd - 4; + int lo, hi; + split2(av[i], lo, hi); + *(int2*) &act_s[t][m / 8][2 * (m % 8)] = make_int2(lo, hi); + } + } + } + } + __syncthreads(); + const int* cw = wsm + threadIdx.x * CWS; +#pragma unroll 1 + for (int s = 0; s < 4; ++s) sb_compute(cw, s, grid_s, lut_s, act_s, dy_s, nt, acc); + } +#pragma unroll + for (int t = 0; t < TPP; ++t) + if (t < nt) dst[(size_t) (trow0 + t) * GU_ROWS + r0 + threadIdx.x] = acc[t]; + } +} +} // namespace s3 + +template +void go(F kernel, const Layer& L, cudaStream_t s) { + kernel<<<(unsigned) (L.nchunks * PIECES), NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, (const block_q8_1_mmq*) L.xq, + (int) L.rows, L.gu); +} + +} // namespace + +// tokens per pass by u (the measured crossovers): IQ3_XXS 8 below 5 rows per expert, 16 below 25, then 32 (4-token +// groups); IQ3_S 8 below 4, 16 below 15, then 32 +void gu_iq3_xxs(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 5.0) go(xxs3::gu_kernel<8, 4, 2>, L, s); + else if (u < 25.0) go(xxs3::gu_kernel<16, 4, 2>, L, s); + else go(xxs3::gu_kernel<32, 2, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ3_XXS"); +} + +void gu_iq3_s(const Layer& L, double u, cudaStream_t s) { + if (L.nchunks <= 0) return; + if (u < 4.0) go(s3::gu_kernel<8, 2>, L, s); + else if (u < 15.0) go(s3::gu_kernel<16, 2>, L, s); + else go(s3::gu_kernel<32, 4>, L, s); + ck(cudaGetLastError(), "gate/up IQ3_S"); +} + +} // namespace strata::prefill::ws::detail diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 8b08b511..68b55646 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -39,13 +39,16 @@ #include "strata/core/native_head.hpp" #include "strata/kernels/verify_kernels.hpp" #include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_pattn.hpp" #include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/kernels/qsa_select.hpp" #include "strata/prefill/gemm.hpp" #include "strata/prefill/moe_fused.hpp" +#include "strata/prefill/moe_ws.hpp" #include "strata/prefill/moe_fused_iq.hpp" #include "strata/prefill/moe_mmq.hpp" #include "strata/core/peer_experts.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/prefill/kernels.hpp" #include "strata/prefill/kva.hpp" // STRATA_KVA: the optional approximate-prefill plan (research, off by default) @@ -87,6 +90,8 @@ bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, voi void*, size_t) { return false; } void gather_strata_q2(const uint8_t*, void*, void*, void*) {} void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} +bool swiglu_quant_ok(int) { return false; } +void swiglu_quant(const float*, void*, int64_t, bool, void*) {} void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {} void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {} void iota(int32_t*, int64_t, void*) {} @@ -117,6 +122,17 @@ void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, float*, void*) {} } // namespace strata::prefill::fused #endif +#ifndef STRATA_PREFILL_WS +// the weight-stationary experts (moe_ws.hpp) are in the CUDA STRATA_EXPERIMENTAL_SM60 build only +namespace strata::prefill::ws { +int mode() { return 0; } +bool supported(int, int) { return false; } +bool faster(int, double) { return false; } +size_t chunks(const int32_t*, size_t, const int32_t*, const int32_t*, Chunk*) { return 0; } +bool gate_up(const Layer&, void*) { return false; } +void down(const Layer&, void*) {} +} // namespace strata::prefill::ws +#endif #if defined(STRATA_GPU_METAL) // The Metal backend reads a prompt through its decode window (metal/src/engine/window.cpp): init keeps the chunk, run @@ -923,6 +939,13 @@ struct Prefill::Impl { float *Xscale = nullptr, *Hscale = nullptr, *grp_tail = nullptr; // NVFP4: activation scales, expert tails float* row_sd = nullptr; // NVFP4 in MMQ: each Dm row's s_down, applied by the combine as it reads the row std::vector bounds_host; + // STRATA_MMQ_WS=1 (moe_ws.hpp): a layer whose experts are all resident - their byte offsets from the expert cache's + // base in MMQ order and the CTAs' chunks, built on the host per layer and uploaded with the bounds (the device + // buffers exist only where ws::mode() != 0; the host copies are the unmapped path's) + int64_t* xoff_dev = nullptr; + std::vector xoff_host; + ws::Chunk* ws_chunks = nullptr; + std::vector ws_chunks_host; std::unique_ptr mmq_ctx; std::vector ids_host, slot_host, src_host, cnt, off; // set_cpu_pool: a small chunk's CPU experts. The layer's MoE input (T x N, from `mixed`), the rows the pool writes @@ -1491,7 +1514,10 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.steps_up.init(T * strata::kernels::kStepCount); m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1); { - const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)); + // the routing tables, the MMQ group bounds; STRATA_MMQ_WS: the in-place offsets (n_expert int64) and the + // weight-stationary layers' chunks (4 int32 each, 16-byte aligned) + const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)) + + (ws::mode() != 0 ? 2 * (size_t) m.g->n_expert + 4 * ws::max_chunks((int64_t) T * K, m.g->n_expert) + 3 : 0); const char* gc = std::getenv("STRATA_GROUP_COPY"); if (m.grp_n < need && !(gc && gc[0] == '1')) { if (m.grp_host) cudaFreeHost(m.grp_host); @@ -1646,6 +1672,10 @@ bool Prefill::carve(size_t T, void* alloc) { m.bounds_dev = o.take((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok); m.grp_gu = o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); m.grp_d = o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); + if (ws::mode() != 0) { // STRATA_MMQ_WS: the offsets and chunks (bytes_needed_impl takes the same) + m.xoff_dev = o.take((size_t) m.g->n_expert, ok); + m.ws_chunks = (ws::Chunk*) o.take(4 * ws::max_chunks((int64_t) T * K, m.g->n_expert), ok); + } // (written at every run's start, not here: when serving, these are live expert-cache slots until a request // lends them - a write now would corrupt a resident expert) if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); @@ -2379,6 +2409,10 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se o.take((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok); o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); + if (ws::mode() != 0) { // carve's STRATA_MMQ_WS offsets and chunks + o.take((size_t) g.n_expert, ok); + o.take(4 * ws::max_chunks((int64_t) T * K, g.n_expert), ok); + } } if (owned_pages) { if (stage_slots(T) > 0) o.take((size_t) stage_slots(T) * (size_t) MAXBLOB(), ok); // one allocation @@ -2435,6 +2469,31 @@ void Prefill::arm_cpu_share(bool applies, bool by_default) { bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); } size_t Prefill::slot_guard_bytes() { return mmq::direct_slot_guard(); } +bool Prefill::nibble_prompt_check(std::string& why) { + const auto& lay = strata::kernels::cpu::expert_layout(); + if (mmq::direct_mode() != 0) { + why = "STRATA_MMQ_DIRECT (the prompt MMQ would read the 4-bit slots in place)"; + return false; + } + for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) { + if (!core::nibble::layer(l).on) continue; + const auto& f = lay.fmt[(size_t) l]; + const char* w = !mmq_plan().any || (size_t) l >= mmq_plan().layer.size() || !mmq_plan().layer[(size_t) l] + ? "no prompt MMQ for it (the FP16 path dequantizes GGUF blocks)" + : mmq_plan().wmma_only[(size_t) l] ? "the WMMA tiles read GGUF blocks" + : fused::native_supported(f.gu_type, f.d_type) ? "the fused prompt kernels read GGUF blocks" + : mmq::matrix_bytes(f.gu_type, 1280, N) != (size_t) core::nibble::kRows * f.gu_row || + mmq::matrix_bytes(f.d_type, N, 640) != f.bytes - f.down_off + ? "MMQ's matrices are not the blob's [gate | up] and down" + : nullptr; + if (w != nullptr) { + why = "layer " + std::to_string(l) + ": " + w; + return false; + } + } + return true; +} + namespace { const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) { @@ -3799,8 +3858,18 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, // V dequantized from its q4_0 blocks to fp16 at gather) static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; + // STRATA_PATTN_SM60=1 (qsa_pattn.hpp, sm_6x, int8 K/V): the decode kernels' output bit for bit from a + // score kernel and a value kernel that merges as it folds (no partials, no merge kernel), ~100 + // queries a batch in the same scratch; any refusal or launch failure runs the loop below if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, m.attn, T, m.cs)) +#if !defined(STRATA_GPU_METAL) // qsa_pattn.cu is in the CUDA / HIP kernel library only + if (!(strata::kernels::pattn_mode() != 0 && + strata::kernels::qsa_pattn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, m.attn_scratch, + (uint64_t) m.attn_batch * + strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), + m.attn, T, m.cs))) +#endif for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { const int64_t nb = std::min(m.attn_batch, T - t0); strata::kernels::qsa_decode_attn_batch(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap, @@ -3914,6 +3983,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const bool had_gu = lay.native && lay.fmt[(size_t) l].had_gu; const bool had_d = lay.native && lay.fmt[(size_t) l].had_d; const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; + // STRATA_EXPERT_NIBBLE=1: a layer whose gate/up experts are 4-bit codes in their slots is gathered + // for MMQ as the GGUF blocks rebuilt from them (core::nibble::gather_gguf); every other expert path + // reads GGUF blocks in the slot, so it stops there instead (never a wrong answer) +#if STRATA_EXPERT_NIBBLE_BUILT // every guard of this switch is compiled out of the other builds + const core::nibble::LayerVram& nib_l = core::nibble::layer(l); +#endif const int had_block = lay.native ? lay.fmt[(size_t) l].had_block : 0; const float* had_sx = had_gu ? m.had_sx[(size_t) l] : nullptr; // resolved in init const float* had_sh = had_d ? m.had_sh[(size_t) l] : nullptr; @@ -3951,6 +4026,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri bool cpu_arm = true; // auto: this layer may share (false: the arm without) int cpu_set = -1; // auto: the wall events' set, -1 when not measured bool cpu_cold = false; // auto: one-time costs in the window (no reading) +#if STRATA_EXPERT_NIBBLE_BUILT + if (fused_l && nib_l.on) core::nibble::fatal(l, "the prompt path's fused experts", "they read GGUF blocks"); +#endif if (fused_l) { if (static bool said = false; !said) { said = true; @@ -4356,6 +4434,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; + bool ws_layer = false; // STRATA_MMQ_WS: this layer's products weight-stationary (below) + ws::Layer wl; pt.mark(kPfGather, cs); // the routed experts' input: `mixed`, or (APR) its rotated copy, which the peer / the layer // split's helper also take (one rotation for both cards; `mixed` itself feeds the shared expert) @@ -4398,6 +4478,67 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri return false; } } + // STRATA_MMQ_WS=1 (moe_ws.hpp, GP100): a layer whose routed experts are ALL resident, on this + // GPU alone (no peer, CPU or streamed share), runs gate/up and down as one weight-stationary + // launch each, with ONE swiglu_quant over all its rows in between, instead of a gate/up, + // swiglu and down MMQ launch per 16-expert group - the same GU, H and Dm bits. The experts + // are read where they lie in the expert cache (offsets from its base). Only where both + // products beat the per-group MMQ at this layer's rows per expert, H can be q8_1 in one pass + // (no Hadamard, NVFP4 or FP4 rows; not STRATA_DBG_NAN, which reads H in floats), and not the + // fused layout (its Hq holds stream_all_min() - 1 tokens' rows). + static const bool ws_dbg = std::getenv("STRATA_DBG_NAN") != nullptr; + const double ws_u = n > 0 ? (double) rows_local / (double) n : 0.0; + if (ws::mode() != 0 && m.xoff_dev != nullptr && m.ws_chunks != nullptr && n > 0 && !ws_dbg && + lay.native && m.cache != nullptr && m.host_res != nullptr && !wmma_l && + !mmq_plan().direct[(size_t) l] && lay.fmt[(size_t) l].up_off == mmq_gub / 2 && + order_peer.empty() && rows_cpu == 0 && rows_local == T * K && !m.fused_bufs && + (!stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]) && !had_gu && !had_d && + !lay.fmt[(size_t) l].tail_off && !mmq::fp4_activations(mmq_gt) && + !mmq::fp4_activations(mmq_dt) && mmq::swiglu_quant_ok(mmq_dt) && + ws::supported(mmq_gt, mmq_dt) && ws::faster(mmq_gt, ws_u) && ws::faster(mmq_dt, ws_u)) { + const uint8_t* ip_base = m.cache->device_slot(0); + m.xoff_host.assign(n, -1); + bool all = true; // every expert resident + uint64_t at = 0; // their offsets' low bits + for (size_t j = 0; j < n && all; ++j) { + const int32_t s = m.host_res[(size_t) l * m.g->n_expert + order[j]]; + if (s < 0) { all = false; break; } + m.xoff_host[j] = (int64_t) (m.cache->device_slot(s) - ip_base); + at |= (uint64_t) m.xoff_host[j]; + } + ws_layer = all && ((uint64_t) (uintptr_t) ip_base | at | lay.fmt[(size_t) l].down_off) % ws::kAlign == 0; + if (ws_layer) { + if (static bool said_ws = false; !said_ws) { + said_ws = true; + std::fprintf(stderr, "strata prefill: a resident layer's experts weight-stationary, one " + "launch per product (STRATA_MMQ_WS=1)\n"); + } + // the offsets after the bounds in the mapped table, the chunks after them (16-byte + // aligned); or the host copies through pinned slots + const size_t xo = 3 * m.grp_tk + 2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2); + ws::Chunk* ch = nullptr; + if (grp_mapped) { + int32_t* xh = m.grp_host + xo; + std::memcpy(xh, m.xoff_host.data(), n * sizeof(int64_t)); + copy_i32((int32_t*) m.xoff_dev, m.grp_dev + xo, (int64_t) (2 * n), m.cs); + ch = (ws::Chunk*) (m.grp_host + (xo + 2 * m.g->n_expert + 3) / 4 * 4); + } else { + m.ws_chunks_host.resize(ws::max_chunks(T * K, m.g->n_expert)); + ch = m.ws_chunks_host.data(); + } + wl.nchunks = (int64_t) ws::chunks(order.data(), n, m.cnt.data(), m.bounds_host.data(), ch); + if (grp_mapped) { + copy_i32((int32_t*) m.ws_chunks, m.grp_dev + ((int32_t*) ch - m.grp_host), 4 * wl.nchunks, m.cs); + } else if (m.up_ring.h2d(m.xoff_dev, m.xoff_host.data(), n * sizeof(int64_t), m.cs) != cudaSuccess || + m.up_ring.h2d(m.ws_chunks, ch, (size_t) wl.nchunks * sizeof(ws::Chunk), m.cs) != cudaSuccess) { + err = "prefill: the weight-stationary tables' upload failed"; + return false; + } + wl.gu_type = mmq_gt; wl.d_type = mmq_dt; wl.w = ip_base; wl.xoff = m.xoff_dev; + wl.down_off = (int64_t) lay.fmt[(size_t) l].down_off; wl.chunks = m.ws_chunks; + wl.rows = T * K; wl.n = (int) n; wl.xq = m.Xq; wl.gu = m.GU; wl.hq = m.Hq; wl.dm = m.Dm; + } + } } else { gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs); // APR: Hadamard-folded gate/up take H (s * x); Xs is this layer's private gathered copy @@ -4795,6 +4936,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri wait_copied(gg_ents[gg_nslots - 1], (size_t) gg_slots[gg_nslots - 1]); pt.mark(kPfDequant, cs); } +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_l.on) { // the GGUF blocks rebuilt from the 4-bit slots: the bytes the copy gives + if (const int rc = core::nibble::gather_gguf(nib_l, gg.blob, gg.first, gg.n, m.grp_gu, mmq_gub, + m.grp_d, mmq_db, zero, m.cs); rc != 0) + core::nibble::fatal(l, "the prompt path's group gather", cudaGetErrorString((cudaError_t) rc)); + } else +#endif // NVFP4: each expert's scales go next to its group slot in the same launch if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub, m.grp_d, mmq_db, m.cs, f.tail_off, @@ -4820,6 +4968,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // a ring slot or the peer's), which STRATA_MMQ_DIRECT reads in place auto compute = [&](size_t j, const uint8_t* blob_dev, int slot, int32_t cslot) -> bool { const int32_t e = order[j]; +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_l.on && (!use_mmq || direct || wmma_l || cslot < 0 || !lay.native || + mmq_gub != (size_t) core::nibble::kRows * nib_l.raw_gu_row || + mmq_db != nib_l.down_bytes)) + core::nibble::fatal(l, "the prompt path", + !use_mmq ? "no MMQ for the layer (the FP16 path dequantizes GGUF blocks)" + : direct ? "STRATA_MMQ_DIRECT reads the slots in place" + : wmma_l ? "the WMMA tiles read GGUF blocks" + : cslot < 0 ? "an expert not in this GPU's slots (streamed or the peer's)" + : "the MMQ group buffers are not the blob's [gate | up] and down"); +#endif pt.mark(kPfDequant, cs); if (use_mmq) { // gather the expert into its group slot (GGUF blocks, unchanged or converted) @@ -4866,6 +5025,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri gg = mmq::GatherGroup{}; } else if (lay.native) { const auto& f = lay.fmt[(size_t) l]; +#if STRATA_EXPERT_NIBBLE_BUILT + if (nib_l.on) { // as the group gather (flush), one expert at its group position q + const uint8_t* one[mmq::kGatherGroupMax] = {}; + one[q] = blob_dev; + if (const int rc = core::nibble::gather_gguf(nib_l, one, (int) q, (int) q + 1, m.grp_gu, + mmq_gub, m.grp_d, mmq_db, + last_of_group ? MMQ_TAIL : 0, m.cs); rc != 0) + core::nibble::fatal(l, "the prompt path's gather", cudaGetErrorString((cudaError_t) rc)); + } else +#endif // NVFP4: this expert's scales go next to its group slot in the same launch mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs, @@ -4974,7 +5143,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640); return true; }; - if (!stream_all) { + if (ws_layer) { + // STRATA_MMQ_WS: the layer's gate/up in one launch, H of all its rows in one pass, its down + // in one launch (no expert of the layer is staged or streamed: nothing to wait for or give + // back beyond what the walk would) + stats_.experts_resident += (int64_t) order.size(); + pt.mark(kPfGemmGU, cs); + if (!ws::gate_up(wl, m.cs)) { // the layer was taken because ws::faster said so + err = "prefill: the weight-stationary gate/up declined a layer it was picked for"; + return false; + } + mmq::swiglu_quant(m.GU, m.Hq, T * K, !lay.native, m.cs); + pt.mark(kPfGemmD, cs); + ws::down(wl, m.cs); + if (stream_all && group_gather) give_back(consumed); + } else if (!stream_all) { size_t staged = 0; size_t pending = 0; const bool stream_ahead = stream_ahead_enabled(); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 54d221cd..50692887 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -25,6 +25,7 @@ #include "strata/core/device.hpp" #include "strata/core/remote_expert_opt.hpp" #include "strata/core/expert_cache.hpp" +#include "strata/core/expert_nibble.hpp" #include "strata/core/conversation_snapshot.hpp" #include "strata/core/conversation_file.hpp" #include "strata/core/session_save_reclaim.hpp" @@ -201,6 +202,7 @@ static void emit_lp_line(const strata::core::Verifier& ver, int t, int32_t token } namespace { +namespace nib = strata::core::nibble; // Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, // pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); // a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). @@ -433,6 +435,7 @@ bool resident_stage_swaps(strata::core::FileExpertSource& src, const std::vector if (slot < 0) continue; const SwapHome home = locate(s.layer); const strata::core::OnDevice on(home.dev); + nib::guard_raw(s.layer, "the adaptive tier's copy back (resident_stage_swaps)"); if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q, s.layer), home.cache->device_slot(slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, home.stream); e != cudaSuccess) { @@ -2293,6 +2296,297 @@ struct PcieAuto { } }; +// ---- STRATA_EXPERT_NIBBLE=1 (strata/core/expert_nibble.hpp): the gate/up experts of IQ2_S / IQ3_XXS / IQ3_S layers as +// 4-bit codes in their VRAM slots. Everything below runs only with the switch on. + +/// The largest slot an expert cache can hold for this pack: the GGUF `max_blob`, or a converted layer's 4-bit slot when +/// that is larger (the sizings that count slots of the largest blob would otherwise come out short of a full cache and +/// leave converted experts out of VRAM, which the switch refuses). `max_blob` exactly with the switch off. +uint64_t nibble_max_slot_bytes() { + const auto& lay = strata::kernels::cpu::expert_layout(); + uint64_t m = lay.max_blob; + if (nib::any_on()) + for (int64_t l = 0; l < lay.n_layers; ++l) m = std::max(m, nib::slot_bytes(l)); + return m; +} + +#if STRATA_EXPERT_NIBBLE_BUILT +/// One expert cache's converted slots. The startup fill hands a converted layer's pairs to `add` instead of +/// `fill_slot_blocking`; per layer, `kBatch` GGUF blobs at a time go H2D into one staging buffer (the bytes +/// fill_slot_blocking would copy, from the source's `blob_stable`, which stays valid) and, per batch, the +/// transcoder writes the codes, scales and d into the slots and round-trips every item, the GGUF down rows are copied +/// behind them, the GGUF blocks are rebuilt from every slot and compared with the blob (both count against the layer +/// in `d_bad`), and each slot's hash is recorded for STRATA_EXPERT_NIBBLE_RECHECK. One stream, so the staging +/// buffer's reuse is ordered without events. The device arrays live as long as the process (RECHECK reads them); +/// `finish` frees the staging buffer. +struct NibbleCache { + static constexpr int64_t kBatch = 64; + struct Pending { int32_t expert, slot; const uint8_t* blob; }; + struct Batch { int32_t layer; int64_t at, n; }; + strata::core::ExpertCache* cache = nullptr; + int dev = 0; ///< the cache's device + std::vector> pending; ///< per layer: queued, at most kBatch + std::vector batches; ///< what was transcoded and hashed, in that order + std::vector> pairs; ///< (layer, expert) of each converted slot, in that order + std::vector slots; ///< and its slot + unsigned long long* h_ptrs = nullptr; ///< pinned: the slots' device addresses, in that order + unsigned long long* d_ptrs = nullptr; ///< the same on the device (the transcoder's and hash's input) + unsigned long long* d_ref = nullptr; ///< each slot's hash as loaded + unsigned long long* d_now = nullptr; ///< RECHECK's + unsigned long long* d_bad = nullptr; ///< per layer: items that did not round-trip, words that differ + uint8_t* staging = nullptr; + uint64_t raw_max = 0; + cudaStream_t stream = nullptr; + int64_t cap = 0, n = 0; + double seconds = 0; + + bool active() const { return cache != nullptr; } + + static std::string cuda_fail(const char* what, cudaError_t e) { return std::string(what) + ": " + cudaGetErrorString(e); } + + /// For `c` on the current device, `want` converted pairs at most. + bool begin(strata::core::ExpertCache& c, int64_t want, std::string& err) { + if (cudaGetDevice(&dev) != cudaSuccess) dev = 0; + cache = &c; + cap = want > 0 ? want : 1; + const auto& lay = strata::kernels::cpu::expert_layout(); + pending.assign((size_t) lay.n_layers, {}); + for (int64_t l = 0; l < lay.n_layers; ++l) + if (nib::layer(l).on) raw_max = std::max(raw_max, nib::layer(l).raw_bytes); + cudaError_t e = cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking); + if (e == cudaSuccess) e = cudaMallocHost((void**) &h_ptrs, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_ptrs, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_ref, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_now, (size_t) cap * 8); + if (e == cudaSuccess) e = cudaMalloc((void**) &d_bad, (size_t) lay.n_layers * 8); + if (e == cudaSuccess) e = cudaMemsetAsync(d_bad, 0, (size_t) lay.n_layers * 8, stream); + if (e == cudaSuccess) e = cudaMalloc((void**) &staging, (size_t) ((uint64_t) kBatch * raw_max)); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill's buffers", e); + return false; + } + if (const int rc = nib::prepare((void*) stream); rc != 0) { + err = std::string("the 4-bit fill's GGUF codebooks: ") + + (rc == (int) cudaErrorInvalidValue ? "a grid entry is not unique" : cudaGetErrorString((cudaError_t) rc)); + return false; + } + return true; + } + + bool add(int32_t layer, int32_t expert, int32_t slot, const uint8_t* blob, std::string& err) { + auto& q = pending[(size_t) layer]; + q.push_back({expert, slot, blob}); + return (int64_t) q.size() < kBatch || flush(layer, err); + } + + bool flush(int32_t layer, std::string& err) { + auto& q = pending[(size_t) layer]; + if (q.empty()) return true; + const auto t0 = std::chrono::steady_clock::now(); + const nib::LayerVram& L = nib::layer(layer); + const int64_t k = (int64_t) q.size(); + if (n + k > cap) { + err = "the 4-bit fill was given more converted pairs than it counted"; + return false; + } + cudaError_t e = cudaSuccess; + for (int64_t i = 0; i < k && e == cudaSuccess; ++i) { + uint8_t* dst = cache->device_slot(q[(size_t) i].slot); + if (dst == nullptr || cache->slot_room(q[(size_t) i].slot) < L.hashed) { // a slot sized for the GGUF blob + err = "the 4-bit fill: slot " + std::to_string(q[(size_t) i].slot) + + (dst == nullptr ? " is outside the cache" : " is smaller than a 4-bit slot"); + return false; + } + h_ptrs[n + i] = (unsigned long long) (uintptr_t) dst; + e = cudaMemcpyAsync(staging + (uint64_t) i * L.raw_bytes, q[(size_t) i].blob, (size_t) L.raw_bytes, + cudaMemcpyHostToDevice, stream); + } + if (e == cudaSuccess) e = cudaMemcpyAsync(d_ptrs + n, h_ptrs + n, (size_t) k * 8, cudaMemcpyHostToDevice, stream); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill's copies in", e); + return false; + } + auto m2 = [&](const char* what, int rc) -> bool { // iq_kernels.cu's: a CUDA error code + if (rc == 0) return true; + err = std::string("the 4-bit ") + what + ": " + cudaGetErrorString((cudaError_t) rc); + return false; + }; + if (!m2("transcoder", nib::transcode(L, staging, k, d_ptrs + n, d_bad + layer, (void*) stream))) return false; + for (int64_t i = 0; i < k && e == cudaSuccess; ++i) + e = cudaMemcpyAsync((uint8_t*) (uintptr_t) h_ptrs[n + i] + nib::kDownOff, + staging + (uint64_t) i * L.raw_bytes + L.raw_down_off, (size_t) L.down_bytes, + cudaMemcpyDeviceToDevice, stream); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill's down rows", e); + return false; + } + if (!m2("GGUF check", nib::check_gguf(L, staging, k, d_ptrs + n, d_bad + layer, (void*) stream))) return false; + if (!m2("slot hash", nib::hash_slots(L, d_ptrs + n, k, d_ref + n, (void*) stream))) return false; + // the next batch's copies in land in the same staging bytes: they wait for this batch's kernels (one stream) + for (const Pending& p : q) { + pairs.emplace_back(layer, p.expert); + slots.push_back(p.slot); + } + batches.push_back({layer, n, k}); + n += k; + q.clear(); + seconds += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + return true; + } + + /// The rest of the queue, then waits: false (with `err` naming every layer) when an item did not round-trip or a + /// rebuilt GGUF block differs from its blob. + bool finish(std::string& err) { + for (int32_t l = 0; l < (int32_t) pending.size(); ++l) + if (!flush(l, err)) return false; + const auto t0 = std::chrono::steady_clock::now(); + cudaError_t e = cudaStreamSynchronize(stream); + std::vector bad(pending.size(), 0); + if (e == cudaSuccess) e = cudaMemcpy(bad.data(), d_bad, bad.size() * 8, cudaMemcpyDeviceToHost); + if (staging != nullptr) (void) cudaFree(staging); + staging = nullptr; + seconds += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit fill", e); + return false; + } + for (size_t l = 0; l < bad.size(); ++l) + if (bad[l] != 0) { + char b[192]; + std::snprintf(b, sizeof b, "%slayer %zu (%s): %llu items or words do not round-trip", err.empty() ? "" : "; ", + l, nib::fmt_name(nib::layer((int64_t) l).gu_type), bad[l]); + err += b; + } + if (!err.empty()) { + err += " - the 4-bit code does not hold these weights (STRATA_EXPERT_NIBBLE_SKIP= keeps a layer's " + "GGUF blocks)"; + return false; + } + return true; + } + + /// The end-to-end check of the fill as it is wired, on converted pair (layer, expert) with `raw` its GGUF blob: the + /// slot read back, its hash against expert_nibble.hpp's host reference of what the device recorded, its down rows + /// against the blob's. (Every item and every GGUF block of every slot was checked on the device by `finish`.) + bool check(int32_t layer, int32_t expert, const uint8_t* raw, std::string& err) const { + int64_t at = -1; + for (size_t i = 0; i < pairs.size() && at < 0; ++i) + if (pairs[i].first == layer && pairs[i].second == expert) at = (int64_t) i; + if (at < 0 || raw == nullptr) { + err = "the 4-bit check: no converted slot or no GGUF blob for layer " + std::to_string(layer) + " expert " + + std::to_string(expert); + return false; + } + const nib::LayerVram& L = nib::layer(layer); + std::vector got((size_t) L.hashed); + unsigned long long h = 0; + cudaError_t e = cudaMemcpy(got.data(), cache->device_slot(slots[(size_t) at]), got.size(), cudaMemcpyDeviceToHost); + if (e == cudaSuccess) e = cudaMemcpy(&h, d_ref + at, 8, cudaMemcpyDeviceToHost); + if (e != cudaSuccess) { + err = cuda_fail("the 4-bit check's read back", e); + return false; + } + const char* why = nib::hash_host(got.data(), L.hashed) != h ? "the device slot hash differs from the host reference" + : std::memcmp(got.data() + nib::kDownOff, raw + L.raw_down_off, (size_t) L.down_bytes) != 0 + ? "the down rows differ from the GGUF blob's" + : nullptr; + if (why != nullptr) { + err = "layer " + std::to_string(layer) + " expert " + std::to_string(expert) + " (" + nib::fmt_name(L.gu_type) + + "): " + why; + return false; + } + return true; + } + + /// STRATA_EXPERT_NIBBLE_RECHECK: every converted slot's hash again, on the device, against the one recorded at load. + /// False with the first slot that differs (or a CUDA error) in `err`; `bad_layer` its layer (-1: an error). + bool recheck(std::string& err, int64_t& bad_layer) { + bad_layer = -1; + if (n == 0) return true; + const strata::core::OnDevice on(dev); + for (const Batch& b : batches) { + const int rc = nib::hash_slots(nib::layer(b.layer), d_ptrs + b.at, b.n, d_now + b.at, (void*) stream); + if (rc != 0) { + err = cuda_fail("the slot hash", (cudaError_t) rc); + return false; + } + } + std::vector ref((size_t) n), now((size_t) n); + cudaError_t e = cudaStreamSynchronize(stream); + if (e == cudaSuccess) e = cudaMemcpy(ref.data(), d_ref, (size_t) n * 8, cudaMemcpyDeviceToHost); + if (e == cudaSuccess) e = cudaMemcpy(now.data(), d_now, (size_t) n * 8, cudaMemcpyDeviceToHost); + if (e != cudaSuccess) { + err = cuda_fail("the slot hash read back", e); + return false; + } + for (int64_t i = 0; i < n; ++i) + if (ref[(size_t) i] != now[(size_t) i]) { + char b[224]; + std::snprintf(b, sizeof b, "CUDA%d: layer %d expert %d (slot %d) hashes %016llx, %016llx at load", dev, + (int) pairs[(size_t) i].first, (int) pairs[(size_t) i].second, (int) slots[(size_t) i], + now[(size_t) i], ref[(size_t) i]); + err = b; + bad_layer = pairs[(size_t) i].first; + return false; + } + return true; + } +}; +#else +// A build without the 4-bit kernels (STRATA_EXPERT_NIBBLE_BUILT 0: HIP, Metal, a CUDA build without +// STRATA_EXPERIMENTAL_SM60): nibble_refusal refuses the switch, so no cache is ever converted and none of this is entered. +struct NibbleCache { + int64_t n = 0; + double seconds = 0; + std::vector> pairs; + bool active() const { return false; } + bool begin(strata::core::ExpertCache&, int64_t, std::string& err) { err = "the 4-bit slots are not in this build"; return false; } + bool add(int32_t, int32_t, int32_t, const uint8_t*, std::string& err) { err = "the 4-bit slots are not in this build"; return false; } + bool finish(std::string&) { return true; } + bool check(int32_t, int32_t, const uint8_t*, std::string& err) const { err = "the 4-bit slots are not in this build"; return false; } + bool recheck(std::string&, int64_t& bad_layer) { bad_layer = -1; return true; } +}; +#endif + +/// With STRATA_EXPERT_NIBBLE=1, why this start cannot have 4-bit slots (empty: nothing here stops it): what the build, +/// the GPUs, the environment and the options decide, before anything is allocated. The full residency, the loans and +/// the prompt chunk are checked where they are known. +std::string nibble_refusal(const Options& o) { + const nib::Config& c = nib::config(); + if (!c.error.empty()) return c.error; +#if !STRATA_EXPERT_NIBBLE_BUILT || !defined(STRATA_NATIVE_EXPERTS) + (void) o; + return "the 4-bit slots and their kernels are in the CUDA build with STRATA_EXPERIMENTAL_SM60 and native experts only"; +#else + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess || count <= 0) { + (void) cudaGetLastError(); + return "no CUDA device"; + } + for (int d = 0; d < count; ++d) { + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, d) != cudaSuccess) { + (void) cudaGetLastError(); + return "cannot read CUDA" + std::to_string(d) + "'s properties"; + } + if (p.major != 6 || p.minor != 0) + return "CUDA" + std::to_string(d) + " (" + p.name + ") is compute capability " + std::to_string(p.major) + "." + + std::to_string(p.minor) + ": the 4-bit slots are for compute capability 6.0 (GP100) only"; + } + if (std::string e = nib::env_conflicts(); !e.empty()) return e; + if (o.peer_device >= 1) return "--peer-device (its cache holds GGUF blobs)"; + for (size_t r = 0; r < o.expert_cache_remote.size(); ++r) + if (o.expert_cache_remote[r] > 0 || o.expert_cache_remote_auto[r]) + return "remote expert caches (--expert-cache-device1..3 hold GGUF blobs)"; + if (o.kv_grow) return "--kv-grow (the elastic K/V moves slots at their GGUF size)"; + if (o.vram_elastic) return "--vram-elastic (it refills slots with GGUF blobs)"; + if (o.expert_profile.empty()) + return "no --expert-profile (every expert must be VRAM-resident from the profile fill)"; + if (o.expert_cache == 0) return "--expert-cache 0 (no VRAM slots to convert)"; + return {}; +#endif +} + } // namespace // #1425 #1549 #1629: --ple-io direct (the default) does unbuffered random reads of the n-gram table; on some drives @@ -3609,6 +3903,49 @@ int main(int argc, char** argv) { } std::fprintf(stderr, "strata generate: primary device from STRATA_PRIMARY_DEVICE: CUDA%d\n", primary_device); } + // ---- STRATA_EXPERT_NIBBLE=1 keeps the gate/up experts of IQ2_S / IQ3_XXS / IQ3_S layers as 4-bit codes in their VRAM + // slots (strata/core/expert_nibble.hpp). Unset or 0: nothing here runs, no table is set, and every slot size below is + // the GGUF blob's, as before. On: if anything would read a converted slot as GGUF blocks or write GGUF bytes into + // one, the switch is ignored for this start with a warning (before anything is allocated); else the per-layer table + // is set before the first slot estimate and the adaptive tier is off (it swaps GGUF blobs in and out of slots). + // The residency, the loans and the prompt chunk are checked where they are known (those refuse the start). + const bool nib_asked = nib::config().on || nib::config().error.rfind("STRATA_EXPERT_NIBBLE=", 0) == 0; + const int64_t nib_chunk_asked = o.prefill_chunk; // an explicit --prefill N must stay N (the chunking is in the bits) + if (nib_asked) { + std::string why = nibble_refusal(o); + if (why.empty()) { + nib::set_layers(nib::plan_layers(strata::kernels::cpu::expert_layout(), why)); + if (why.empty() && !nib::any_on()) + why = "no layer of this pack is IQ2_S / IQ3_XXS / IQ3_S at 2560 x 640 among STRATA_EXPERT_NIBBLE_FMTS " + "and outside STRATA_EXPERT_NIBBLE_SKIP"; + if (why.empty()) (void) strata::prefill::Prefill::nibble_prompt_check(why); + } + if (!why.empty()) { + // a warning, not a refusal: this start goes on as it would without the switch (the usual GGUF slots) + std::fprintf(stderr, "strata generate: WARNING: STRATA_EXPERT_NIBBLE is off for this start: %s; the expert slots " + "stay GGUF blocks\n", why.c_str()); + nib::set_layers({}); + } else { + o.adapt_swaps = 0; + o.peer_adapt_swaps = 0; + const auto& lay = strata::kernels::cpu::expert_layout(); + int64_t n_on = 0, by_fmt[3] = {0, 0, 0}; + uint64_t more = 0; + for (int64_t l = 0; l < lay.n_layers; ++l) { + const nib::LayerVram& v = nib::layer(l); + if (!v.on) continue; + ++n_on; + ++by_fmt[v.gu_type == nib::kIQ2_S ? 0 : v.gu_type == nib::kIQ3_XXS ? 1 : 2]; + more += (v.slot_bytes - (v.raw_bytes + 255) / 256 * 256) * (uint64_t) lay.n_expert; + } + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: %lld of %lld layers keep their gate/up experts as 4-bit " + "codes in VRAM (IQ2_S %lld, IQ3_XXS %lld, IQ3_S %lld), %.2f GiB more VRAM than their GGUF " + "blobs for all %lld experts of each; the adaptive tier is off (--adapt-swaps 0)%s\n", + (long long) n_on, (long long) lay.n_layers, (long long) by_fmt[0], (long long) by_fmt[1], + (long long) by_fmt[2], (double) more / 1073741824.0, (long long) lay.n_expert, + nib::config().recheck ? "; STRATA_EXPERT_NIBBLE_RECHECK: every slot's hash after each request" : ""); + } + } // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). @@ -4336,7 +4673,7 @@ int main(int argc, char** argv) { const auto& lay = strata::kernels::cpu::expert_layout(); int64_t pairs_bytes = 0; for (const auto& pr : prof) - pairs_bytes += native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard) + pairs_bytes += native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard) : (int64_t) lay.max_blob; size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); @@ -4799,7 +5136,7 @@ int main(int argc, char** argv) { total_mass += (mass[r] = hi - lo); } auto cost = [&](int64_t l) -> int64_t { - return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(l), slot_guard) + return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard) : (int64_t) lay.max_blob; }; // the predicted window time (ms) of a placement, and the routed mass its caches hold @@ -4915,7 +5252,7 @@ int main(int argc, char** argv) { }; struct PartStat { int64_t lb, le; int64_t used; int64_t cnt; int64_t cap; }; auto can_start = [&](const std::vector& parts) -> bool { - const int64_t kMaxBlob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + const int64_t kMaxBlob = (int64_t) nibble_max_slot_bytes(); // max_blob (or a larger 4-bit slot) auto slots_est_of = [&](int i, uint64_t cn) -> int64_t { if (parts[i].cnt <= 0) return -1; const uint64_t avg = (parts[i].used > 0) @@ -6011,7 +6348,7 @@ int main(int argc, char** argv) { // which only ever grants MORE slots) uint64_t cap_bytes; if (o.expert_cache > 0) { - cap_bytes = (uint64_t) o.expert_cache * pl.max_blob; + cap_bytes = (uint64_t) o.expert_cache * nibble_max_slot_bytes(); } else { const int64_t pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; int64_t mtp_b = (!o.mtp.empty() && native_head.loaded()) @@ -6031,7 +6368,7 @@ int main(int argc, char** argv) { uint64_t used = 0; skip = 0; for (const auto& pr : profile) { - const uint64_t b = pl.native ? (pl.blob_bytes(pr.first) + 255) / 256 * 256 : (uint64_t) pl.max_blob; + const uint64_t b = pl.native ? (nib::slot_bytes(pr.first) + 255) / 256 * 256 : (uint64_t) pl.max_blob; if (used + b > cap_bytes) break; used += b; ++skip; @@ -6267,7 +6604,7 @@ int main(int argc, char** argv) { if (use_df2 && native_head.loaded()) mtp_bind += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20); // DFlash2's own draft head and logits, bound after this #endif const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + const int64_t blob = (int64_t) nibble_max_slot_bytes(); // max_blob (STRATA_EXPERT_NIBBLE: or a larger 4-bit slot) int64_t slots = ((int64_t) free_b - reserve) / blob; if (!profile.empty()) slots = std::min(slots, (int64_t) profile.size()); #if defined(STRATA_GPU_METAL) @@ -6365,7 +6702,7 @@ int main(int argc, char** argv) { free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t prefill_mib = owned_prefill_mib(); const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first; - const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); + const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) nibble_max_slot_bytes(), 0); if (o.expert_cache > fit) { // a WARNING that names the knob: the user asked for this size, and gets fewer slots std::fprintf(stderr, "strata generate: WARNING: layer split: --expert-cache %d leaves no room for the " @@ -6387,19 +6724,19 @@ int main(int argc, char** argv) { const size_t free_b = strata::core::device_free_bytes(); // the same reading the shared-cache sizing uses const auto& lay = strata::kernels::cpu::expert_layout(); const int asked = o.expert_cache; - const uint64_t budget = (uint64_t) asked * lay.max_blob; + const uint64_t budget = (uint64_t) asked * nibble_max_slot_bytes(); size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0; const uint64_t cap = std::min(budget, (uint64_t) free_room); uint64_t sum = 0; for (int64_t l = 0; l < g.n_layers; ++l) - sum += (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(l), slot_guard); + sum += (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard); int64_t q = sum > 0 ? (int64_t) (cap / sum) : 0; if (q > g.n_expert) q = g.n_expert; if (q > 0) { per_layer_bytes = sum; sized_slots.reserve((size_t) q * (size_t) g.n_layers); for (int64_t l = 0; l < g.n_layers; ++l) { - const int64_t b = (int64_t) lay.blob_bytes(l); + const int64_t b = (int64_t) nib::slot_bytes(l); for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b); } o.expert_cache = (int) sized_slots.size(); @@ -6415,16 +6752,16 @@ int main(int argc, char** argv) { // what the uniform sizing granted, in the 256-byte slots the loop below counts: the blob formats of 1280 / 2560 // rows are whole multiples of 256 already; an NVFP4 blob's 16-byte scale tail is not, and the unrounded budget // held one slot fewer than asked (--expert-cache 1: none) - const uint64_t budget = (uint64_t) o.expert_cache * ((lay.max_blob + 255) / 256 * 256); + const uint64_t budget = (uint64_t) o.expert_cache * ((nibble_max_slot_bytes() + 255) / 256 * 256); uint64_t used = 0; const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first; size_t free_room = free_b > keep_free ? free_b - keep_free : 0; const uint64_t cap = std::min(budget, (uint64_t) free_room); for (const auto& pr : profile) { - const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard); + const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard); if (used + b > cap) break; used += b; - sized_slots.push_back((int64_t) lay.blob_bytes(pr.first)); + sized_slots.push_back((int64_t) nib::slot_bytes(pr.first)); } // #831: the sized-slots loop walks the profile's pairs, so the profile's length is the ceiling; an explicit // --expert-cache above it used to be cut with no word. A warning only (what is allocated does not change). @@ -6474,7 +6811,7 @@ int main(int argc, char** argv) { sized_slots.clear(); if (q <= 0) { o.expert_cache = 0; return false; } for (int64_t l = 0; l < g.n_layers; ++l) { - const int64_t b = (int64_t) lay.blob_bytes(l); + const int64_t b = (int64_t) nib::slot_bytes(l); for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b); } o.expert_cache = (int) sized_slots.size(); @@ -6599,6 +6936,10 @@ int main(int argc, char** argv) { // admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile // the policy rather than a hint. int64_t prefilled = 0; + // STRATA_EXPERT_NIBBLE: each cache's converted slots (RECHECK reads them per request) + NibbleCache nib_x; + std::vector nib_st; + nib_st.reserve(stages.size()); if (!profile.empty() && srcp != nullptr) { // #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until // its range is full (one full layer used to end the whole fill, leaving most layers empty) @@ -6619,6 +6960,14 @@ int main(int argc, char** argv) { } const auto fill_t0 = std::chrono::steady_clock::now(); uint64_t fill_bytes = 0; + if (nib::any_on()) { // STRATA_EXPERT_NIBBLE: the converted layers' pairs go through the 4-bit fill instead + int64_t conv = 0; + for (int64_t i = 0; i < want; ++i) conv += nib::layer(profile[(size_t) i].first).on ? 1 : 0; + if (conv > 0 && !nib_x.begin(xcache, conv, err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: %s\n", err.c_str()); + return 1; + } + } for (int64_t i = 0; i < want; ++i) { if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { if (ahead.valid()) ahead.get(); @@ -6632,8 +6981,10 @@ int main(int argc, char** argv) { break; } const uint8_t* b = srcp->blob_stable(profile[(size_t) i].first, profile[(size_t) i].second); - if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err, - (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first))) { + const bool nib_pair = nib_x.active() && nib::layer(profile[(size_t) i].first).on; // STRATA_EXPERT_NIBBLE + if (b == nullptr || !(nib_pair ? nib_x.add(profile[(size_t) i].first, profile[(size_t) i].second, slot, b, err) + : xcache.fill_slot_blocking(slot, b, err, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first)))) { std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n", (long long) i, err.c_str()); return 1; @@ -6641,16 +6992,39 @@ int main(int argc, char** argv) { fill_bytes += strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first); ++prefilled; } + if (nib_x.active() && !nib_x.finish(err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %s\n", err.c_str()); + return 1; + } const double fill_s = std::chrono::duration(std::chrono::steady_clock::now() - fill_t0).count(); // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong // about bytes produces a plausible token, which is this project's most expensive failure mode; the // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. - if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), + // (STRATA_EXPERT_NIBBLE: a converted slot holds 4-bit codes, not the blob's bytes - the 4-bit check below is its check) + if (prefilled > 0 && !nib::layer(profile[0].first).on && + !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), srcp->blob_stable(profile[0].first, profile[0].second), err, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (nib_x.active() && nib_x.n > 0) { + // STRATA_EXPERT_NIBBLE: the hottest converted pair read back (its hash, its down rows); every item and every + // rebuilt GGUF block of every converted slot was already checked on the device + size_t c = 0; + while (c < (size_t) want && !nib::layer(profile[c].first).on) ++c; + if (!nib_x.check(profile[c].first, profile[c].second, srcp->blob_stable(profile[c].first, profile[c].second), + err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %s\n", err.c_str()); + return 1; + } + std::set ls; + for (const auto& pr : nib_x.pairs) ls.insert(pr.first); + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %lld slots of %zu layers transcoded to 4-bit " + "codes (%.2f s; every item round-tripped, every slot's GGUF blocks rebuilt and compared, " + "slot hashes recorded); layer %d expert %d read back\n", (long long) nib_x.n, ls.size(), + nib_x.seconds, (int) profile[c].first, (int) profile[c].second); + } mem_mark("the profile fill"); std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile in %.1f s (%.0f MB/s); " "slot 0 verified\n", @@ -6707,11 +7081,11 @@ int main(int argc, char** argv) { std::vector sized; int64_t used = 0; for (const auto& pr : st.profile) { - const int64_t b = native_pack ? strata::core::ExpertCache::slot_stride((int64_t) lay.blob_bytes(pr.first), slot_guard) + const int64_t b = native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard) : (int64_t) lay.max_blob; if (used + b > room) break; used += b; - sized.push_back((int64_t) lay.blob_bytes(pr.first)); + sized.push_back((int64_t) nib::slot_bytes(pr.first)); } // #841: a stage's cache can fail to open with the VRAM free (the card's allocation is also charged to the // Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each @@ -6736,25 +7110,57 @@ int main(int argc, char** argv) { return 1; } int64_t filled = 0; + NibbleCache& nib_c = nib_st.emplace_back(); // STRATA_EXPERT_NIBBLE: this stage's converted slots + if (nib::any_on()) { + int64_t conv = 0; + for (const auto& pr : st.profile) conv += nib::layer(pr.first).on ? 1 : 0; + if (conv > 0 && !nib_c.begin(st.cache, conv, err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + } for (const auto& pr : st.profile) { if (filled >= st.cache.slots()) break; const int32_t slot = st.cache.admit(pr.first, pr.second); if (slot == strata::core::kNotResident) break; const uint8_t* b = srcp->blob_stable(pr.first, pr.second); - if (b == nullptr || !st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first))) { + const bool nib_pair = nib_c.active() && nib::layer(pr.first).on; // STRATA_EXPERT_NIBBLE + if (b == nullptr || !(nib_pair ? nib_c.add(pr.first, pr.second, slot, b, err) + : st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first)))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n", st.dev, (long long) filled, err.c_str()); return 1; } ++filled; } - if (filled == 0 || !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), - srcp->blob_stable(st.profile[0].first, st.profile[0].second), err, - (int64_t) lay.blob_bytes(st.profile[0].first))) { + if (nib_c.active() && !nib_c.finish(err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + // (STRATA_EXPERT_NIBBLE: a converted slot holds 4-bit codes, not the blob's bytes - the 4-bit check below is its check) + if (filled == 0 || (!nib::layer(st.profile[0].first).on && + !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), + srcp->blob_stable(st.profile[0].first, st.profile[0].second), err, + (int64_t) lay.blob_bytes(st.profile[0].first)))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, filled == 0 ? "nothing filled" : err.c_str()); return 1; } + if (nib_c.active() && nib_c.n > 0) { // STRATA_EXPERT_NIBBLE: as CUDA0's above + size_t c = 0; + while (c < st.profile.size() && !nib::layer(st.profile[c].first).on) ++c; + const auto& pc = st.profile[c]; + if (!nib_c.check(pc.first, pc.second, srcp->blob_stable(pc.first, pc.second), err)) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + std::set ls; + for (const auto& pr : nib_c.pairs) ls.insert(pr.first); + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %lld slots of %zu layers transcoded to 4-bit " + "codes (%.2f s; every item round-tripped, every slot's GGUF blocks rebuilt and compared, " + "slot hashes recorded); layer %d expert %d read back\n", st.dev, (long long) nib_c.n, + ls.size(), nib_c.seconds, (int) pc.first, (int) pc.second); + } std::fprintf(stderr, "strata generate: layer split: CUDA%d runs layers %lld-%lld, expert cache %lld slots " "(%.2f GiB), %lld of its %zu profiled pairs; slot 0 verified\n", st.dev, (long long) st.lb, (long long) (st.le - 1), (long long) st.cache.slots(), st.cache.gib(), @@ -6762,6 +7168,40 @@ int main(int argc, char** argv) { } if (multi_gpu) std::fprintf(stderr, "strata generate: layer split: CUDA0 runs layers 0-%lld\n", (long long) (split_at[0] - 1)); + if (nib::any_on()) { + // STRATA_EXPERT_NIBBLE: every expert of every layer must be in VRAM, in the cache of the card that runs the layer. + // A converted layer's miss would be computed from the GGUF blob by the CPU or over PCIe, and a non-converted + // layer's residency would differ from the switch-off run's (its smaller slots leave room for more), so the + // replies' bits would too. Then no slot is written again. + for (int64_t l = 0; l < g.n_layers; ++l) { + const strata::core::ExpertCache* owner = &xcache; + int owner_dev = 0; + if (multi_gpu && !split_at.empty() && l >= split_at[0]) { + owner = nullptr; + for (const auto& stp : stages) + if (l >= stp->lb && l < stp->le) { owner = &stp->cache; owner_dev = stp->dev; } + } + int64_t missing = 0, first = -1; + for (int64_t e = 0; e < g.n_expert; ++e) + if (owner == nullptr || owner->slot_of(l, e) == strata::core::kNotResident) { + if (first < 0) first = e; + ++missing; + } + if (missing > 0) { + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE refuses the start: layer %lld has %lld of its %lld " + "experts out of CUDA%d's VRAM (expert %lld the first) - every expert must be resident " + "(a profile that ranks every pair and room on the card; STRATA_EXPERT_NIBBLE_SKIP=" + " keeps some layers' smaller GGUF slots)\n", (long long) l, (long long) missing, + (long long) g.n_expert, owner_dev, (long long) first); + return 1; + } + } + xcache.seal(); + for (auto& stp : stages) stp->cache.seal(); + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: all %lld experts of all %lld layers are VRAM-resident; " + "the expert caches are sealed (nothing writes a slot from here on)\n", + (long long) g.n_expert, (long long) g.n_layers); + } // ---- LAYER 2: exact startability probe on the live free figures. Every session, cache and batch slot is // carved by now, so `cudaMemGetInfo` reads what serve's own_fits (5855-5869) will read. Run serve's own @@ -8088,6 +8528,7 @@ int main(int argc, char** argv) { if (!cold.empty() && cold.back().first < heat(oi)) { vi = cold.back().second; const int32_t vs = host_res[(size_t) vi]; + nib::guard_raw(layer, "the elastic K/V's slot move (kvg_ensure)"); if (xcache.slot_offset(vs + 1) - xcache.slot_offset(vs) < lay.blob_bytes(layer) || cudaMemcpy(xcache.device_slot(vs), xcache.device_slot((int32_t) kvg.lo), (size_t) lay.blob_bytes(layer), cudaMemcpyDeviceToDevice) != cudaSuccess) @@ -8190,6 +8631,7 @@ int main(int argc, char** argv) { if (host_res[i] >= 0 || lay.blob_bytes(l) > room) continue; const uint8_t* b = srcp->blob_stable(l, e); if (b == nullptr) continue; + nib::guard_raw(l, "the elastic K/V's refill (kvg_trim)"); cudaMemcpyAsync(xcache.device_slot((int32_t) s), b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, nullptr); filled.emplace_back(i, (int32_t) s); @@ -8926,6 +9368,37 @@ int main(int argc, char** argv) { #endif bool any_loan = borrow != nullptr; for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; + if (nib::any_on()) { + // STRATA_EXPERT_NIBBLE: the prompt path keeps its own buffers (a loan is refilled with GGUF blobs) and reads in + // the chunk it reads without the switch (the chunking is part of the replies' bits: auto's ceiling, or + // --prefill N, and no host-aware plan of smaller chunks). Otherwise refused, never a quietly different reply. + std::string why; + const int64_t expect = o.prefill_auto ? auto_ceiling : nib_chunk_asked; + if (any_loan) why = "the prompt path borrows expert-cache slots (a loan is refilled with GGUF blobs)"; + else if (o.prefill_chunk != expect) + why = "the prompt chunk is " + std::to_string(o.prefill_chunk) + " tokens, not the " + std::to_string(expect) + + " it is without the switch when nothing limits it (that would change the replies' bits; an explicit " + "--prefill N that fits keeps N)"; + else if (pf_plan_chunk > 0) + why = "the host-aware plan reads long prompts in chunks of " + std::to_string(pf_plan_chunk) + " tokens"; + std::string room; + for (size_t i = 0; why.empty() && i <= stages.size(); ++i) { + const int dev = i == 0 ? -1 : stages[i - 1]->dev; + const strata::core::OnDevice on(dev); + size_t fb = 0, tb = 0; + if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } + char b[64]; + std::snprintf(b, sizeof b, "CUDA%d %.2f GiB", dev < 0 ? 0 : dev, (double) fb / 1073741824.0); + room += (room.empty() ? "" : ", ") + std::string(b); + } + if (!why.empty()) { + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE refuses the start: %s (STRATA_EXPERT_NIBBLE_SKIP= " + "keeps some layers' GGUF blocks and their smaller slots)\n", why.c_str()); + return 1; + } + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE: prompt chunk %lld, no loan; free after the prompt " + "buffers: %s\n", (long long) o.prefill_chunk, room.c_str()); + } if (any_loan) { if (borrow != nullptr) std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", @@ -10624,6 +11097,7 @@ int main(int argc, char** argv) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si]; const uint8_t* b = srcp->blob_stable(s.layer, s.in); + nib::guard_raw(s.layer, "the adaptive tier's copy in"); const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; const strata::core::OnDevice on(gs ? gs->dev : -1); @@ -10858,6 +11332,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(h.dev); for (const ASwap& w : aswaps) { if (w.home != hi || !w.exchange) continue; + nib::guard_raw(w.layer, "the async adaptive tier's copy back (a_back)"); if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(w.j, w.layer), h.cache->device_slot(w.slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), cudaMemcpyDeviceToHost, h.stream); e != cudaSuccess) { @@ -10895,6 +11370,7 @@ int main(int argc, char** argv) { auto a_in_one = [&](const ASwap& w, const uint8_t* b) { // step 2: one copy in (H2D), on its home's stream AHome& h = ahomes[(size_t) w.home]; const strata::core::OnDevice on(h.dev); + nib::guard_raw(w.layer, "the async adaptive tier's copy in (a_in_one)"); if (const cudaError_t e = cudaMemcpyAsync(h.cache->device_slot(w.slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), cudaMemcpyHostToDevice, h.stream); e != cudaSuccess) { @@ -15724,6 +16200,27 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: cancelled request keeps its conversation: %lld tokens live\n", (long long) pp_reached); } + if (nib::config().recheck && nib::any_on() && !cancelled) { + // STRATA_EXPERT_NIBBLE_RECHECK=1 (debug): every converted slot's hash again on its own device, against the + // hash recorded at load - a path that wrote a slot after the seal is found here + std::string rerr; + int64_t bad_layer = -1; + const auto rt0 = Clock::now(); + bool ok = nib_x.recheck(rerr, bad_layer); + int64_t checked = nib_x.n; + for (size_t i = 0; ok && i < nib_st.size(); ++i) { + ok = nib_st[i].recheck(rerr, bad_layer); + checked += nib_st[i].n; + } + if (!ok) { + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE_RECHECK: %s\n", rerr.c_str()); + if (bad_layer >= 0) nib::fatal(bad_layer, "STRATA_EXPERT_NIBBLE_RECHECK", "a slot changed after the load"); + std::fflush(stderr); + std::abort(); + } + std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE_RECHECK: %lld 4-bit slots hash as at load (%.0f ms)\n", + (long long) checked, std::chrono::duration(Clock::now() - rt0).count()); + } static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates) // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and @@ -16234,6 +16731,11 @@ int main(int argc, char** argv) { } else if (chunk != o.prefill_chunk) { k = 0; // a fixed chunk that does not fit: its own buffers, as before } + if (k > 0 && nib::any_on()) { // STRATA_EXPERT_NIBBLE: the lent slots would be refilled with GGUF blobs + std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE refuses the start: the prompt path would borrow %lld " + "cache slots (--no-prefill-borrow keeps its own buffers)\n", (long long) k); + return 1; + } const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; #if defined(STRATA_GPU_METAL) k = 0; // Metal: no loan of expert-cache slots (the prompt buffers are the Metal window's own); the refill after it copied into given-back allocations @@ -16822,6 +17324,7 @@ int main(int argc, char** argv) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = host_res[out]; const uint8_t* b = srcp->blob_stable(s.layer, s.in); + nib::guard_raw(s.layer, "the adaptive refill's copy in"); const size_t blob_n = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer); // asynchronous: the copies run while the MTP drafts; the next window waits for them if (slot < 0 || b == nullptr) { diff --git a/tests/cuda/prefill_swiglu_quant_test.cpp b/tests/cuda/prefill_swiglu_quant_test.cpp new file mode 100644 index 00000000..0d7b9d68 --- /dev/null +++ b/tests/cuda/prefill_swiglu_quant_test.cpp @@ -0,0 +1,94 @@ +// prefill_swiglu_quant_test - the prompt path's fused MMQ expert step against the kernels it replaces, byte for byte: +// mmq::swiglu_quant against swiglu + quantize (the down product's q8_1 rows of H), for down types the packs have +// (Q2_0, IQ4_NL, Q8_0), with the gate/up rows split (GGUF) and interleaved (the Strata pack), a zero row and a row +// with one huge value. Exit 77 without a CUDA device. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template T* as() const { return (T*) p; } +}; + +int swiglu_quant_case(ggml_type t, int64_t rows, bool interleaved, uint32_t seed) { + constexpr int64_t NFF = 640; + std::mt19937 rng(seed); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution mag(0.05f, 40.f); + std::vector gu((size_t) rows * 2 * NFF); + for (int64_t r = 0; r < rows; ++r) { + const float m = mag(rng); + for (int64_t k = 0; k < 2 * NFF; ++k) gu[(size_t) (r * 2 * NFF + k)] = nd(rng) * m; + } + if (rows > 3) { // a zero row, a row with one huge value + std::memset(gu.data() + 2 * NFF, 0, 2 * NFF * sizeof(float)); + gu[(size_t) (3 * 2 * NFF + 5)] = 3e4f; + } + const size_t qb = mmq::q8_bytes(rows, NFF); + Dev dgu(gu.size() * 4), dh((size_t) rows * NFF * 4 + 16), dq0(qb), dq1(qb); + ck(cudaMemcpy(dgu.p, gu.data(), gu.size() * 4, cudaMemcpyHostToDevice), "upload"); + ck(cudaMemset(dq0.p, 0x5a, qb), "memset"); + ck(cudaMemset(dq1.p, 0x5a, qb), "memset"); + // the two kernels it replaces, as prefill.cpp launches them + mmq::swiglu(dgu.as(), dh.as(), rows, NFF, interleaved, nullptr); + mmq::quantize(dh.as(), nullptr, dq0.p, (int) t, NFF, NFF, rows, nullptr); + mmq::swiglu_quant(dgu.as(), dq1.p, rows, interleaved, nullptr); + ck(cudaDeviceSynchronize(), "run"); + const size_t used = (size_t) rows * (1024 / 128) * 144; // the rows' 8 blocks of 128 values (144 bytes each) + std::vector a(used), b(used); + ck(cudaMemcpy(a.data(), dq0.p, used, cudaMemcpyDeviceToHost), "download"); + ck(cudaMemcpy(b.data(), dq1.p, used, cudaMemcpyDeviceToHost), "download"); + size_t bad = 0; + for (size_t i = 0; i < used; ++i) bad += a[i] != b[i]; + std::printf(" swiglu_quant %-6s %5lld rows%s: %zu of %zu bytes differ\n", ggml_type_name(t), (long long) rows, + interleaved ? " interleaved" : "", bad, used); + return bad == 0 ? 0 : 1; +} + +} // namespace + +int main() { + int ndev = 0; + if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { + std::printf("prefill_swiglu_quant_test: no CUDA device (skipped)\n"); + return 77; + } + int fails = 0; + try { + for (ggml_type t : {GGML_TYPE_Q2_0, GGML_TYPE_IQ4_NL, GGML_TYPE_Q8_0}) { + if (!mmq::swiglu_quant_ok((int) t)) { std::printf(" %s: not on the fused path here\n", ggml_type_name(t)); continue; } + for (bool il : {false, true}) { + fails += swiglu_quant_case(t, 1, il, 1); + fails += swiglu_quant_case(t, 37, il, 2); + fails += swiglu_quant_case(t, 4113, il, 3); + } + } + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill_swiglu_quant_test: %s\n", e.what()); + return 1; + } + std::printf("prefill_swiglu_quant_test: %s\n", fails ? "FAILED" : "ok"); + return fails ? 1 : 0; +} diff --git a/tests/cuda/prefill_ws_parity_test.cpp b/tests/cuda/prefill_ws_parity_test.cpp new file mode 100644 index 00000000..e11a4b90 --- /dev/null +++ b/tests/cuda/prefill_ws_parity_test.cpp @@ -0,0 +1,279 @@ +// prefill_ws_parity_test - the weight-stationary expert products of PR #3752 (STRATA_MMQ_WS, GP100) against the per-group +// MMQ they replace, byte for byte, on random experts (GPU, synthetic data, no model). +// +// A layer of E resident experts (random gate/up [1280 x 2560] and down [2560 x 640] blocks with sane fp16 scales, laid out +// as the expert cache holds them: gate rows then up rows, the down matrix at down_off) gets random activations, quantized +// as the prompt path does (mmq::quantize), and a routing of random row counts per expert (1 .. 300 rows, so u spans the +// measured range, some experts with one row). The reference is mmq::Context::run per expert (gate/up, then +// swiglu + quantize, then down), i.e. what Prefill does per 16-expert group; the candidate is ws::gate_up, ONE +// mmq::swiglu_quant over all rows and ws::down. Compared: GU (floats), Hq (the q8_1 bytes) and Dm (floats) of every row. +// The down is also run alone on the reference Hq, so a difference points at the product. For the IQ4_NL down the run +// repeats with STRATA_WS_FAST on (ws::set_fast(1)); the same Dm is required. +// +// The kernels were written for GP100 (the integer sums are exact, the float epilogue follows MMQ's sm_60 SASS), so the +// verdict is only given on a compute capability 6.0 card; on another card the kernels are run too (ws::set_mode(1)) +// and the counts printed for information, with exit 77. Needs the CUDA build with STRATA_EXPERIMENTAL_SM60. +// +// prefill_ws_parity_test [--device N] [--any] exit 0: all identical (cc 6.0); 77: other card; 1: a difference +#include "strata/prefill/moe_mmq.hpp" +#include "strata/prefill/moe_ws.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; +namespace ws = strata::prefill::ws; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + size_t n = 0; + explicit Dev(size_t bytes) : n(bytes) { + ck(cudaMalloc(&p, bytes + 256), "cudaMalloc"); + ck(cudaMemset(p, 0, bytes + 256), "cudaMemset"); + } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template T* as() const { return (T*) p; } + template void up(const std::vector& h) { ck(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); } + template std::vector down(size_t count) const { + std::vector h(count); + ck(cudaMemcpy(h.data(), p, count * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return h; + } +}; + +constexpr int64_t kNEmbd = 2560, kNFF = 640, kGuRows = 1280; + +// random blocks of `type` for a [rows x cols] matrix; every block starts with its fp16 scale d: a finite value in +// [2^-6, 2^-5) (all the formats used here put d first) +std::vector random_matrix(ggml_type type, int64_t rows, int64_t cols, std::mt19937& rng) { + const size_t bytes = mmq::matrix_bytes((int) type, rows, cols); + const size_t bs = ggml_type_size(type); + std::vector w(bytes); + for (auto& b : w) b = (uint8_t) rng(); + for (size_t o = 0; o + bs <= bytes; o += bs) { + const uint16_t d = (uint16_t) ((9u << 10) | (rng() & 0x3FFu)); + std::memcpy(&w[o], &d, 2); + } + return w; +} + +size_t count_diff(const std::vector& a, const std::vector& b, size_t n) { + size_t d = 0; + for (size_t i = 0; i < n; ++i) d += a[i] != b[i]; + return d; +} + +// the largest |a - b| over the largest |a|, both float arrays in byte form (how far apart two results are in rounding terms) +double max_norm_err(const std::vector& a, const std::vector& b, size_t bytes) { + const float* x = (const float*) a.data(); + const float* y = (const float*) b.data(); + double mx = 0.0, err = 0.0; + for (size_t i = 0; i < bytes / 4; ++i) { + mx = std::max(mx, (double) std::fabs(x[i])); + err = std::max(err, (double) std::fabs(x[i] - y[i])); + } + return mx > 0.0 ? err / mx : err; +} + +struct Result { + size_t gu = 0, hq = 0, dm = 0, dm_ref_hq = 0, dm_fast = 0, fast_vs_default = 0; + double e_gu = 0, e_dm = 0, e_dm_rh = 0; // normalized max errors against the reference + bool ran = true; +}; + +Result run_case(ggml_type gt, ggml_type dt, const std::vector& cnt, uint32_t seed, bool test_fast) { + std::mt19937 rng(seed); + const int E = (int) cnt.size(); + std::vector bounds(E + 1, 0); + for (int j = 0; j < E; ++j) bounds[j + 1] = bounds[j] + cnt[j]; + const int64_t rows = bounds[E]; + const size_t gub = mmq::matrix_bytes((int) gt, kGuRows, kNEmbd), db = mmq::matrix_bytes((int) dt, kNEmbd, kNFF); + const size_t stride = (gub + db + 255) / 256 * 256; + // the layer's experts, "resident" in one buffer at 256-byte aligned offsets (the expert cache's slots) + std::vector blob((size_t) E * stride, 0); + std::vector xoff(E); + for (int j = 0; j < E; ++j) { + xoff[j] = (int64_t) j * (int64_t) stride; + const auto g = random_matrix(gt, kGuRows, kNEmbd, rng), d = random_matrix(dt, kNEmbd, kNFF, rng); + std::memcpy(&blob[(size_t) xoff[j]], g.data(), gub); + std::memcpy(&blob[(size_t) xoff[j] + gub], d.data(), db); + } + std::normal_distribution nd(0.0f, 1.0f); + std::vector x((size_t) (rows * kNEmbd)); + for (auto& v : x) v = nd(rng) * 0.7f; + + const size_t xqb = mmq::q8_bytes(rows, kNEmbd), hqb = mmq::q8_bytes(rows, kNFF); + Dev dblob(blob.size()), dx(x.size() * 4), dxq(xqb), dbnd((size_t) (E + 1) * 4), dxoff((size_t) E * 8); + Dev dident((size_t) rows * 4), dgu_ref((size_t) rows * kGuRows * 4), dgu((size_t) rows * kGuRows * 4); + Dev dh((size_t) rows * kNFF * 4), dhq_ref(hqb), dhq(hqb), ddm_ref((size_t) rows * kNEmbd * 4), ddm((size_t) rows * kNEmbd * 4), + ddm_rh((size_t) rows * kNEmbd * 4), ddm_fast((size_t) rows * kNEmbd * 4); + dblob.up(blob); dx.up(x); dbnd.up(bounds); dxoff.up(xoff); + std::vector ident((size_t) rows); + for (int64_t i = 0; i < rows; ++i) ident[(size_t) i] = (int32_t) i; + dident.up(ident); + mmq::quantize(dx.as(), nullptr, dxq.p, (int) gt, kNEmbd, kNEmbd, rows, nullptr); + + // the reference: per expert, as a one-expert group (absolute rows) + mmq::Context ctx; + for (int j = 0; j < E; ++j) { + mmq::Product gu; + gu.w = dblob.as() + xoff[j]; gu.type = (int) gt; gu.w_rows = kGuRows; gu.w_cols = kNEmbd; gu.expert_bytes = gub; + gu.n = 1; gu.xq = dxq.p; gu.bounds = dbnd.as() + j; gu.ids = dident.as(); + gu.total_rows = rows; gu.max_rows = cnt[j]; gu.dst = dgu_ref.as(); gu.ld_dst = kGuRows; + ctx.run(gu, nullptr); + } + mmq::swiglu(dgu_ref.as(), dh.as(), rows, kNFF, false, nullptr); + mmq::quantize(dh.as(), nullptr, dhq_ref.p, (int) dt, kNFF, kNFF, rows, nullptr); + for (int j = 0; j < E; ++j) { + mmq::Product dn; + dn.w = dblob.as() + xoff[j] + gub; dn.type = (int) dt; dn.w_rows = kNEmbd; dn.w_cols = kNFF; dn.expert_bytes = db; + dn.n = 1; dn.xq = dhq_ref.p; dn.bounds = dbnd.as() + j; dn.ids = dident.as(); + dn.total_rows = rows; dn.max_rows = cnt[j]; dn.dst = ddm_ref.as(); dn.ld_dst = kNEmbd; + ctx.run(dn, nullptr); + } + ck(cudaDeviceSynchronize(), "reference"); + + // the candidate + std::vector order(E); + for (int j = 0; j < E; ++j) order[j] = j; + std::vector chunks(ws::max_chunks(rows, E)); + const size_t nch = ws::chunks(order.data(), (size_t) E, cnt.data(), bounds.data(), chunks.data()); + chunks.resize(nch); + Dev dch(std::max(1, nch) * sizeof(ws::Chunk)); + dch.up(chunks); + ws::Layer L; + L.gu_type = (int) gt; L.d_type = (int) dt; L.w = dblob.p; L.xoff = dxoff.as(); L.down_off = (int64_t) gub; + L.chunks = dch.as(); L.nchunks = (int64_t) nch; L.rows = rows; L.n = E; L.xq = dxq.p; L.gu = dgu.as(); + L.hq = dhq.p; L.dm = ddm.as(); + Result r; + if (!ws::gate_up(L, nullptr)) { r.ran = false; return r; } + mmq::swiglu_quant(dgu.as(), dhq.p, rows, false, nullptr); + ws::down(L, nullptr); + ck(cudaDeviceSynchronize(), "candidate"); + // the down alone on the reference H (a difference above this one is the gate/up's) + ws::Layer L2 = L; + L2.hq = dhq_ref.p; L2.dm = ddm_rh.as(); + ws::down(L2, nullptr); + if (test_fast) { + ws::set_fast(1); + ws::Layer L3 = L; + L3.dm = ddm_fast.as(); + ws::down(L3, nullptr); + ws::set_fast(-1); + } + ck(cudaDeviceSynchronize(), "candidate (down alone, fast)"); + + const size_t gun = (size_t) rows * kGuRows * 4, dmn = (size_t) rows * kNEmbd * 4; + const auto gur = dgu_ref.down(gun), gun_c = dgu.down(gun); + r.gu = count_diff(gur, gun_c, gun); + r.e_gu = max_norm_err(gur, gun_c, gun); + r.hq = count_diff(dhq_ref.down(hqb), dhq.down(hqb), hqb); + const auto dmr = ddm_ref.down(dmn); + const auto dmc = ddm.down(dmn), dmh = ddm_rh.down(dmn); + r.dm = count_diff(dmr, dmc, dmn); + r.dm_ref_hq = count_diff(dmr, dmh, dmn); + r.e_dm = max_norm_err(dmr, dmc, dmn); + r.e_dm_rh = max_norm_err(dmr, dmh, dmn); + if (test_fast) { + const auto dmf = ddm_fast.down(dmn); + r.dm_fast = count_diff(dmr, dmf, dmn); + r.fast_vs_default = count_diff(dmc, dmf, dmn); // STRATA_WS_FAST: the same bits as the default kernel, on any card + } + return r; +} + +std::vector counts(int E, int lo, int hi, std::mt19937& rng) { + std::vector c(E); + for (auto& v : c) v = lo + (int32_t) (rng() % (uint32_t) (hi - lo + 1)); + return c; +} +} // namespace + +int main(int argc, char** argv) { + int device = 0; + bool any = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else if (std::strcmp(argv[i], "--any") == 0) any = true; + else { + std::fprintf(stderr, "usage: prefill_ws_parity_test [--device N] [--any]\n"); + return 2; + } + } + int ndev = 0; + if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { + std::puts("prefill_ws_parity_test: no CUDA device (skipped)"); + return 77; + } + try { + ck(cudaSetDevice(device), "cudaSetDevice"); + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + const bool gp100 = prop.major == 6 && prop.minor == 0; + std::printf("prefill_ws_parity_test on %s (%d.%d)%s\n", prop.name, prop.major, prop.minor, + gp100 ? "" : ": not a GP100, so the counts are for information only"); + if (!gp100 && !any) { + std::puts("prefill_ws_parity_test: not a compute capability 6.0 card (skipped; --any runs it for information)"); + return 77; + } + ws::set_mode(1); + std::mt19937 rng(20261026u); + const ggml_type gus[] = {GGML_TYPE_IQ2_XXS, GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S, GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S}; + const ggml_type dns[] = {GGML_TYPE_Q2_0, GGML_TYPE_IQ4_NL}; + size_t total_diff = 0, total_fast = 0; + double worst_err = 0.0; + int cases = 0, declined = 0; + for (ggml_type gt : gus) + for (ggml_type dt : dns) { + // a spread of rows per expert (u from ~2 to ~150), and a tiny layer with one-row experts + const std::vector> shapes = {counts(24, 1, 12, rng), counts(24, 5, 40, rng), + counts(20, 60, 300, rng), {1, 2, 65, 1, 64, 63}}; + for (const auto& cnt : shapes) { + const Result r = run_case(gt, dt, cnt, 1000u + (uint32_t) cases, dt == GGML_TYPE_IQ4_NL); + ++cases; + if (!r.ran) { ++declined; std::printf(" %-8s -> %-6s %zu experts: ws declined (not faster here)\n", ggml_type_name(gt), ggml_type_name(dt), cnt.size()); continue; } + const size_t bad = r.gu + r.hq + r.dm + r.dm_ref_hq + r.dm_fast; + total_diff += gp100 ? bad : 0; + total_fast += r.fast_vs_default; + worst_err = std::max(worst_err, std::max(r.e_gu, r.e_dm_rh)); // Dm after the full chain also carries int8 flips of H + std::printf(" %-8s -> %-6s %2zu experts %5d rows: bytes differ GU %zu Hq %zu Dm %zu Dm(down alone) %zu Dm(fast) %zu" + " fast vs default %zu | max error / max value: GU %.2e Dm %.2e Dm(down alone) %.2e%s\n", + ggml_type_name(gt), ggml_type_name(dt), cnt.size(), + (int) std::accumulate(cnt.begin(), cnt.end(), 0), r.gu, r.hq, r.dm, r.dm_ref_hq, r.dm_fast, + r.fast_vs_default, r.e_gu, r.e_dm, r.e_dm_rh, gp100 && bad ? " <-- FAIL" : ""); + } + } + if (!gp100) { // no verdict on this card: the float epilogue of its MMQ is not the one the kernels follow + std::printf("prefill_ws_parity_test (information, %s): %d cases (%d declined), STRATA_WS_FAST vs default: %zu differing bytes, " + "largest GU / down-alone error against this card's MMQ %.2e of the largest value -> %s\n", prop.name, cases, declined, + total_fast, worst_err, total_fast == 0 && worst_err < 1e-5 && declined < cases ? "consistent" : "INCONSISTENT"); + return total_fast == 0 && worst_err < 1e-5 && declined < cases ? 77 : 1; + } + std::printf("prefill_ws_parity_test: %d cases (%d declined), %zu differing bytes, STRATA_WS_FAST vs default %zu -> %s\n", cases, + declined, total_diff, total_fast, total_diff == 0 && total_fast == 0 && declined < cases ? "PASS" : "FAIL"); + return total_diff == 0 && total_fast == 0 && declined < cases ? 0 : 1; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill_ws_parity_test: %s\n", e.what()); + return 1; + } +}