diff --git a/CMakeLists.txt b/CMakeLists.txt index fc480ac1..012d46c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,6 +426,25 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME qsa_slots_parity_lanecell COMMAND qsa_slots_parity) set_tests_properties(qsa_slots_parity qsa_slots_parity_lanecell PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(qsa_slots_parity_lanecell PROPERTIES ENVIRONMENT "STRATA_ATTN_LANECELL=1") + # fork: the Daily's decode attention (STRATA_ATTN_DAILY=1: PR #540's chunk kernel on every card and the bounded + # merge) against upstream's kernels, bitwise; the production entries checked with the variable off and on + add_executable(qsa_merge_daily_parity src/kernels/qsa_merge_daily_parity.cpp) + target_include_directories(qsa_merge_daily_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_merge_daily_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_merge_daily_parity_default COMMAND qsa_merge_daily_parity) + add_test(NAME qsa_merge_daily_parity_daily COMMAND qsa_merge_daily_parity) + set_tests_properties(qsa_merge_daily_parity_default PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=0" + SKIP_RETURN_CODE 77) + set_tests_properties(qsa_merge_daily_parity_daily PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=1" + SKIP_RETURN_CODE 77) + endif() + # QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA layer's decode kernels at a long + # context (block scores, top-k, attention over each row's selection, indexer append), row by row; GPU, synthetic, no + # model. Not in the default build: `cmake --build --target qsa_rows_bench`. + if(STRATA_ENABLE_CUDA) + add_executable(qsa_rows_bench EXCLUDE_FROM_ALL src/kernels/qsa_rows_bench.cpp) + target_include_directories(qsa_rows_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_rows_bench PRIVATE strata_kernels CUDA::cudart) endif() # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a @@ -895,6 +914,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. add_executable(gemm_f32_parity src/prefill/gemm_f32_parity.cu) target_link_libraries(gemm_f32_parity PRIVATE strata_prefill ) + # the hyper-connection read's fused up projection + mix (gr_upmix, STRATA_HC_UPMIX) against cuBLAS + gr_mix_r, + # bitwise where cuBLAS sums K in the same order, else within FP32 rounding and as close to FP64 (GPU, synthetic, + # no model; --bench adds timings) + add_executable(gr_upmix_parity src/prefill/gr_upmix_parity.cu) + target_link_libraries(gr_upmix_parity PRIVATE strata_prefill ) + add_test(NAME gr_upmix_parity COMMAND gr_upmix_parity) + set_tests_properties(gr_upmix_parity PROPERTIES SKIP_RETURN_CODE 77) endif() # native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic, # no model; --bench adds v1/new timings of a window's 48 calls in a graph) @@ -920,6 +946,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(router_chain_bench src/kernels/router_chain_bench.cpp) target_include_directories(router_chain_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(router_chain_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + # B6: the dense projections' time per verify row at the model's shapes, default vs STRATA_B6_MMVQ_ROWS, bitwise + if(STRATA_ENABLE_CUDA) + add_executable(b6_mmvq_bench src/kernels/b6_mmvq_bench.cpp) + target_include_directories(b6_mmvq_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(b6_mmvq_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() add_executable(gr_parity src/kernels/gr_parity.cpp) target_include_directories(gr_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(gr_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -1046,6 +1078,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(qsa_topk_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(qsa_topk_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME qsa_topk_parity COMMAND qsa_topk_parity --selftest) + # the register kernel from the smallest prompt batch (the line gfx1151 moves to 4096 blocks): same ids at every case + add_test(NAME qsa_topk_parity_reg_always COMMAND qsa_topk_parity --selftest) + set_tests_properties(qsa_topk_parity_reg_always PROPERTIES ENVIRONMENT "STRATA_TOPK_REG_MIN_BLOCKS=0") # ---- P2.S4: the PLE n-gram hash, the IQ4_NL table read, and the PLE block ---- # `ngram.cpp` is host-only but lives in `strata_kernels` because `ple.cu` shares its geometry constants, and @@ -1586,6 +1621,12 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + # the MoE input quantized per token and scattered to its rows (mmq::quantize_scatter) against the per-row + # gather: the same q8_1 bytes for every MMQ layout (--bench: both at 2K, 8K and 32K tokens) + add_executable(prefill_mmq_scatter_test tests/cuda/prefill_mmq_scatter_test.cpp) + target_link_libraries(prefill_mmq_scatter_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_mmq_scatter_test COMMAND prefill_mmq_scatter_test) + set_tests_properties(prefill_mmq_scatter_test PROPERTIES TIMEOUT 120) endif() if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) @@ -1706,6 +1747,13 @@ if(STRATA_NATIVE_EXPERTS) add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp) target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(q8_gemv_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA) + # EXPDEC (docs/EXPERTDEC.md): the grouped experts' default kernels against STRATA_EXPDEC=1 at T = 1..4, bit for bit + # and in microseconds, on synthetic blobs read cold from DRAM + add_executable(expdec_bench EXCLUDE_FROM_ALL src/kernels/expdec_bench.cpp) + target_include_directories(expdec_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(expdec_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float. diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 12105a25..2185d615 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -2146,3 +2146,27 @@ under `compute-sanitizer --tool memcheck --error-exitcode 86`. Build with signal, early cleanup and `--errors` error-propagation checks. Its `--synchronous` mode is the negative control under memcheck: an eight-second watchdog releases the original launch/service deadlock and the test fails. + +## CUDA opt-in switches measured for 0.1.45 (RTX 3060 and RTX A4000, sm_86; all off unless you set them) + +Ported from open pull requests and A/B'd as whole engine runs against the default (a fresh engine per side, IQ3_XXS, 5 pairs, medians; +bit-exact means the 10-prompt + 4K/20K identity gate with the switch on equals the gate with it off). Decode after a 30K-token prompt +unless noted; the gain is small on these two cards and larger on the Turing cards the authors measured. + +| Switch | What | Answers | RTX 3060 / A4000 | +|---|---|---|---| +| `STRATA_ATTN_DAILY=1` (#2075) | decode attention: two cells per step, a merge that skips empty chunks | bit-exact | +3.2% (5/5) / +0.7% | +| `STRATA_QSA_ROWS=1` (#2059) | block scores of a verify window, queries in registers ([QSAROWS.md](QSAROWS.md)) | bit-exact | -0.3% / +0.3% | +| `STRATA_EXPDEC=1` (#2058) | gate/up of the window's resident experts with the q8_1 rows in shared memory ([EXPERTDEC.md](EXPERTDEC.md)) | bit-exact | +0.5% / +1 to +5% (short context) | +| `STRATA_SIDE_MIXER=1/2` (#1889) | the mixer's input-only work on graph branches | bit-exact | +0.5% / -0.6% (short context) | +| `STRATA_B6_MMVQ_ROWS=1` (#1418) | exact multi-column MMVQ reusing the activation fragment across rows (K-quants, IQ4_XS) | bit-exact | +0.2..1% / +0.5..2% | +| `STRATA_QSA_SPLIT_ATTN=1` (#1888) | decode attention split across blocks on the int8 mma path (sm_80+, int8 KV) | rounding-level (teacher-forced KL 0.0016 against a floor of 0.0012) | +2.8% / +3.5% | +| `STRATA_HC_UPMIX=1` (#1370) | the hyper-connection up projection and `gr_mix_r` in one kernel (sm_80+) | bit-exact here (gate identical) | prompt +0.6% / +0.4% | +| `STRATA_PROMPT_ATTN_IMMA=1` (#1367) | int8-KV prompt attention on INT8 tensor cores | rounding-level (KL at the floor) | prompt read +2.5% | +| `STRATA_HC_REQ8=1` (#1262) | the hyper-connection projections as int8 + a scale per 32 (more expert-cache slots) | rounding-level (KL 0.0018) | decode -0.2% / +2.2% | +| `STRATA_QUANT_GATHER=1` (#1368) | turns the once-per-token MoE input quantization back to the per-row gather | n/a | no difference measured | +| `STRATA_PREFILL_GROUP_GATHER=0` (#1107) | turns the short-prompt grouped gather off | n/a | on is 0.6-1.3% faster | + +`STRATA_DEQUANT_WIDE` (the wide dequantization of Q4_K / Q5_K / Q6_K / IQ4_XS for the prompt's dense weights) is now on by default on +sm_86 as well as sm_61: bit-exact, and the time to the first token of a 150 / 300 / 450-token prompt fell 11-15% on the RTX 3060 and 6-10% on the RTX A4000 (5 of 5 pairs each). +`STRATA_DEQUANT_WIDE=0` turns it off. diff --git a/docs/EXPERTDEC.md b/docs/EXPERTDEC.md new file mode 100644 index 00000000..42563abb --- /dev/null +++ b/docs/EXPERTDEC.md @@ -0,0 +1,107 @@ +# EXPDEC: the verify window's routed experts with the group's activations in shared memory (`STRATA_EXPDEC=1`, opt-in) + +Opt-in: `STRATA_EXPDEC=1`. Unset (or `0`) the engine launches exactly the kernels it launched before. CUDA only; the +output is bitwise the default kernels' (see "Bit for bit" below; `expdec_bench` checks it). + +## What it changes + +`native_expert_grouped` (`src/kernels/cuda/iq_kernels.cu`) computes a verify window's routed experts that are resident +in VRAM: group g is one expert's blob, its entries are the window's rows that picked it (1 to T, T = the window's +tokens). The default gate/up kernel (`native_gu_multi_kernel`) already decodes each weight part once per block and +applies it to the group's entries (`row_dot_80_sub16`), but the apply re-reads each entry's q8_1 block from +global memory with 9 scattered 4-byte loads (36-byte blocks: a warp's load touches 16-32 sectors). On an RTX 2080 Ti +at a 131k decode that makes an extra entry cost about 60% of a whole expert (~1.6 us against ~2.6 us per expert and +layer) although it reads nothing from DRAM. + +`expdec_gu_kernel` (gate/up: IQ2_XXS, IQ2_XS, IQ3_XXS, IQ3_S, IQ2_S at n_embd 2560) and `expdec_down_kernel` (down: +Q2_0 at n_ff 640; IQ4_NL with `STRATA_EXPDEC_D20=1`) instead: + +- stage the group's entries (4 at a time, as the default) in shared memory in a layout where a call's 8 words are two + 16-byte loads with no bank conflicts (the block's two halves in separate planes), the fp16 block scale already a + float (`__low2float(ds)`, the value `apply` computes); for IQ4_NL the words stay together and a call reads two + 8-byte loads; +- compute R rows per lane (`STRATA_EXPDEC_R`, 1 or 2 for gate/up, default 1; `STRATA_EXPDEC_DR` 1/2/4 for down, + default 4): the activation words are loaded once per R rows; +- take `rb` rows per block instead of 16 (`STRATA_EXPDEC_RB` / `_DRB`; 0 = the most that keep `STRATA_EXPDEC_MINBLK`, + default 800, blocks in the launch), so the staging is amortised over 35-140 KB of weights; +- stage the IQ3_XXS and IQ3_S codebooks in shared memory too (the IQ2 ones already were); +- gate/up `__launch_bounds__(256, STRATA_EXPDEC_MINB)`, default 4 (up to 64 registers, 4 blocks per SM like the + default kernels; `2` allows 128). + +Formats outside the list keep the default kernel for that role; `STRATA_OLD_IQ_MMVQ=1` turns EXPDEC off as it turns +the multi kernels off. The down is behind `STRATA_EXPDEC_DOWN=1`: in the engine the Q2_0 down with EXPDEC was about +10% slower than the default kernel although the micro-bench alone had it at 0.78x (the default down already keeps the +group's h rows in shared memory), so by default EXPDEC takes the gate/up only. + +The first time `STRATA_EXPDEC=1` meets a (role, format) the engine writes one line, e.g. +`strata expdec: CUDA1 gate/up type 21: expdec_gu_kernel R 1 MINB 4, 16 rows per block, grid 80 x 10 (cap 10 groups), captured into a graph` +(or `... not covered: the default kernel runs`). + +API (`include/strata/kernels/iq_kernels.hpp`): `native_expert_set_expdec`, `native_expert_set_expdec_params` / +`native_expert_expdec_params` (`NativeExpertExpdecParams`), `native_expert_expdec_takes`. The knobs are read from the +environment at startup; captured graphs keep the kernels they captured. + +## Bit for bit + +For every (row, entry) the sum is the default kernel's tree - `row_dot_80_sub16` for gate/up (lane t of a 16-lane +sub-warp: calls t, t+32, t+64 into `s`, t+16, t+48 into `s16`, `s = __fadd_rn(s, s16)`, butterfly xor 8-4-2-1), +`row_dot_40_sub8` for IQ4_NL, `row_dot_20_sub16` for Q2_0: the same lane does the same calls in the same order, and +`apply_u` is `apply` with the same integer and float operations in the same order on the same words (the q8_1 block +read from shared memory instead of global). The group's entries are independent of each other, so how many are staged +per pass does not matter; R rows per lane and `rb` rows per block only change which lane computes what. The FMA +contraction of `s += d * sumi` is the same compiler decision on the same expression in both kernels. The bench +confirms it: `identical` on every cell (10 format pairs x T 1-4 x 2 window shapes x every variant x 2 cards). + +## Micro-bench: `expdec_bench` + +Not in the default build: `cmake --build --target expdec_bench`. + +``` +expdec_bench [reps=300] [device=-1] [groups=20] [pairs=all] [choices=def,dec,dec:r2,dec:b4,dec:r2:b4] [shape=real] +``` + +Pairs: the model's 5 gate/up x 2 down formats or `21/20,16/42`. Choices: `def` (the reference) and +`dec[:r<1|2>][:d<1|2|4>][:b<2|4>][:w<0|1>][:x<0|1>][:g][:h][:m]` (rows per lane for gate/up and down, min blocks +per SM, EXPDEC for the down too, also IQ4_NL, rows per block, min blocks; a missing field takes the engine's value). +Shapes: `real` = every token picks 10 experts out of `groups` distinct ones (T=1: 10 groups x 1 entry; T=2: 20 x 1; +T=4: 20 groups, 40 entries); `single` = 10 T groups of one entry; `both` also prints the per-expert / per-entry +decomposition. One line per cell: `dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT` (the +whole call, then the gate/up and down phases alone; memcmp of the output against `def`; exit 1 if anything differs). +The blobs rotate over >= 96 MB so every call reads its weights cold from DRAM, as the decode does each layer. + +Gate/up phase, us per call, synthetic blobs, 20 distinct experts (shape `real`); `dec` = the defaults above: + +| card | format | T=1 def / dec | T=2 | T=3 | T=4 | +|---|---|---|---|---|---| +| RTX 2080 Ti | IQ3_S | 72 / 0.73x | 112 / 0.79x | 124 / 0.75x | 138 / 0.74x | +| RTX 2080 Ti | IQ3_XXS | 61 / 0.79x | 95 / 0.84x | 107 / 0.79x | 119 / 0.77x | +| RTX 2080 Ti | IQ2_XXS | 42 / 0.98x | 74 / 0.92x | 86 / 0.86x | 97 / 0.84x | +| RTX 2080 Ti | IQ2_XS | 60 / 0.75x | 80 / 0.92x | 92 / 0.87x | 104 / 0.84x | +| RTX 2080 Ti | IQ2_S | 62 / 0.75x | 83 / 0.92x | 96 / 0.86x | 109 / 0.84x | +| RTX 3060 | IQ3_S | 74 / 1.09x | 144 / 0.99x | 154 / 0.89x | 174 / 0.87x | +| RTX 3060 | IQ3_XXS | 78 / 0.89x | 132 / 0.92x | 143 / 0.90x | 162 / 0.82x | +| RTX 3060 | IQ2_XXS / XS / S | 60-68 / 0.90-1.04x | 112-118 / 0.89-1.00x | 119-136 / 0.89-0.95x | 132-149 / 0.87-0.91x | + +Per-expert / per-entry cost (us per layer call, RTX 2080 Ti, IQ3_S gate/up): 5.20 / 1.26 default, 3.73 / 0.64 with +EXPDEC. Down Q2_0 with `w1` (EXPDEC for the down): 0.65-0.85x in the bench on both cards; down IQ4_NL 0.95-1.07x +(no gain, hence the default kernel). + +## In the engine + +nsys of a 131k decode (layer split: RTX 3060 layers 0-15, RTX 2080 Ti layers 16-47 and the head, `--pipeline-windows +2`, Windows, 96 verify windows), median kernel time per window, T = 1 / 2 / 3 / 4: + +| | default | EXPDEC | +|---|---|---| +| RTX 2080 Ti, gate/up kernel | 1.60 / 2.58 / 3.51 / 4.16 ms | 1.42 / 2.07 / 2.75 / 3.20 ms (-11 / -20 / -22 / -23%) | +| RTX 2080 Ti, gate/up slope per row | +0.86 ms | +0.60 ms | +| RTX 3060, gate/up kernel | 0.77 / 1.43 / 1.97 / 2.23 ms | 0.80 / 1.21 / 1.83 / 1.84 ms | +| RTX 2080 Ti, down Q2_0 with `STRATA_EXPDEC_DOWN=1` | - | ~10% slower than the default (hence off by default) | + +End to end, same machine, a deterministic 131k bench (forced tokens and window sizes, 1024 tokens, B-A-B with the +lever on / off / on): **+1.1%** decode tokens/s (+0.0 and +2.1 in the two B arms, no B below A), the text identical. +The expert kernels are about 20% of the critical stage's time and EXPDEC takes about 20% of that, so the end-to-end +figure is small by construction; the lever is cheap, bitwise and off by default. + +Not done here: the weight side (the 8-9 two-byte loads per call and row of `Split::load`; a weight tile staged in +shared memory with 16-byte loads would be the next step), and the T=1 flat cost. diff --git a/docs/QSAROWS.md b/docs/QSAROWS.md new file mode 100644 index 00000000..cb0d02df --- /dev/null +++ b/docs/QSAROWS.md @@ -0,0 +1,70 @@ +# QSA_ROWS: the decode window's QSA block scores with the queries in registers (`STRATA_QSA_ROWS=1`, opt-in) + +Opt-in: `STRATA_QSA_ROWS=1` (exactly `1`). Unset the engine runs the kernels it ran before. CUDA, the verify window's +decode (calls of `qsa_block_scores` without `active_blocks` and with up to 4 queries); the prompt path and HIP are not +touched. Scores and top-k ids are bitwise the multi kernel's (`qsa_rows_bench --rows` checks it). + +## Why + +In a 131k decode the QSA kernel that grows most with the window's rows is `block_scores_multi_kernel`: about 20 us more +per call for every row of the window on an RTX 2080 Ti and an RTX 3060 (nsys; 8 QSA layers on the second card of a +layer split, 4 on the first). The keys are already read once for all the queries; the cost per row is in the shared +memory and shuffle pipes: per (key block, query) the kernel reads the four query slices from shared memory (4 x +`LDS.128`) and reduces each head's lane products with its own five shuffles (20 per block and query): at 32 769 blocks +that is 15-20 us of issue per query. + +## What it changes + +`block_scores_rows_kernel` (`src/kernels/cuda/qsa_select.cu`, NQ = 1..4): + +1. the NQ queries' slices (4 heads x 4 floats per lane) stay in registers for the whole kernel (44 / 63 / 78 / 94 + registers, no stack, `cuobjdump -res-usage`); +2. the lane products of the 4 heads are reduced with a scatter that keeps `warp_sum`'s pairings: xor 16 and 8 leave + one head per lane, then 4, 2, 1 - six shuffles for the four heads instead of twenty - and gathered on lane 0 in head + order (three shuffles). + +Every addition adds the same two operands of the same `warp_sum` level (float addition commutes), the product +expression is the same text in the same file, the relus are summed in head order: the same bits as the multi kernel +and the per-query kernel. Tail block and the `+1e9` as before. Beyond 4 queries, with `active_blocks`, or without the +variable, the multi kernel runs. + +## Micro-bench: `qsa_rows_bench` + +Not in the default build: `cmake --build --target qsa_rows_bench`. Synthetic data at the real geometry (24 query +heads x 256, 2 KV heads, indexer 4 x 128, blocks of 4 cells, top-k 2048), int8 pools, no model. + +``` +qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] [--rows] [--no-dense] +``` + +Without `--rows` it measures what the T rows of a verification window cost in a QSA layer's decode kernels (block +scores, top-k, attention over each row's selection, indexer append; `--no-dense` skips the drafter's 32768-cell window). +`--rows` runs `block_scores_rows_kernel` against the multi kernel - scores and top-k ids bit for bit (memcmp) at T = +1..4 at 131k and at a short context (cells 100-103, a full tail block), 16 cases per card - and prints both kernels' +microseconds. Exit 0 (77: no GPU; 1: a parity failure). + +`qsa_block_scores`, us per call, 131k context (both kernels read the same pooled keys): + +| | T=1 | T=2 | T=3 | T=4 | per row | +|---|---|---|---|---|---| +| RTX 2080 Ti, multi (reference) | 47.2 | 56.9 | 78.2 | 101.2 | +18.0 | +| RTX 2080 Ti, `STRATA_QSA_ROWS=1` | 36.2 | 38.0 | 49.2 | 54.6 | +6.1 | +| RTX 3060, multi | 73.4 | 109.4 | 151.9 | 193.5 | +40.0 | +| RTX 3060, `STRATA_QSA_ROWS=1` | 63.3 | 75.5 | 98.0 | 130.2 | +22.3 | + +Parity: 8 cases per card, 0 differ. On the RTX 3060 at T=4 the +kernel is at 94 registers (2 CTAs per SM); a two-pass version of 2 queries would stay at 63 if that card matters. + +## In the engine + +Layer split RTX 3060 (layers 0-15) + RTX 2080 Ti (layers 16-47, head), Windows, `--pipeline-windows 2`, 131k context: +per window the second card saves -0.09 ms at T=1 and -0.37 ms at T=4 (8 QSA layers), the first -0.04 / -0.25 (4 +layers). End to end on a deterministic 131k bench (forced tokens and window sizes, 1024 tokens, B-A-B): **+3.2% and ++0.1%** decode tokens/s in the two B arms, the text identical. + +## Not done + +A multi-row attention kernel (K/V of a cell read once for all the rows that selected it) is possible bit for bit only +if every row keeps its own chunk partition; at the decode window's sizes (cap 2051 cells, T <= 4) the blocks of all rows +fit in one wave and the kernel is bound by its block's latency chain, so the gain is bounded by ~0.1-0.2 ms per row on +8 layers: not worth it here. `STRATA_QSA_ROWS` turns on the scores kernel only. diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md index a28df535..75b642a2 100644 --- a/docs/STRIX_HALO.md +++ b/docs/STRIX_HALO.md @@ -92,6 +92,7 @@ they change speed, not answers. Nothing here applies to CUDA or to another AMD a | `STRATA_GDN_HEAD`, `STRATA_GDN_PP=2`, `STRATA_GDN_CONVL2`, `STRATA_GDN_NOY` | the prompt's gated-delta-net recurrence: four lanes per column, two columns per lane, the convolution and the norms fused | | `STRATA_HCD_EXACT` | the hyper-connection down projection (N 320, K 10240) in a WMMA kernel that reproduces hipBLASLt solution 1176 / 1177's summation order (`hip_prefill_hcd_exact_parity` checks it bit for bit); it runs only where the table makes hipBLASLt pick one of those two, and says once if it cannot | | `STRATA_CVEC_FUSE`, `STRATA_PF_PAD` | a steered layer's write, control vector and next norm in one pass; padded GEMM row strides | +| `STRATA_TOPK_REG_MIN_BLOCKS=4096` | the prompt's QSA top-k uses the register kernel from 16K cells of context instead of 28K (the original kernel is slower there; the selected cells are identical, `qsa_topk_parity` checks it) | | `STRATA_Q8_PACKED`, `STRATA_Q6_PACKED`, `STRATA_MMVF_ROWS`, `STRATA_ATTN_LANECELL` | decode layouts and kernels (packed Q8_0 / Q6_K weights, 4-row BF16 GEMV, one-cell-per-thread attention scores) | | `STRATA_EXPERT_V2`, `STRATA_TSUM`, `STRATA_LFUSE` | the grouped decode experts (IQ3_S / IQ4_NL), single-butterfly warp sums, fewer launches around the shared expert and the KV append | | `STRATA_GDN_SPLIT`, `STRATA_QFUSE`, `STRATA_PLE_BATCH` | the GDN step over four blocks per head, activation images written by their producers, the PLE key / value projections of a verify window at once | diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index e3d26155..a3d5fa7f 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -468,6 +468,13 @@ private: 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 + // 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; + cudaEvent_t mfork_ = nullptr, mjoin_ = nullptr; + // fork b063c13 (STRATA_SIDE_MIXER=2): a second branch for the GDN gate projection and the QSA queries' chain + cudaStream_t side2_ = nullptr; + cudaEvent_t pfork_ = nullptr, pjoin_ = nullptr; cudaGraphExec_t commit_exec_ = nullptr; // mapped staging (host pointer, device alias) diff --git a/include/strata/core/weights.hpp b/include/strata/core/weights.hpp index d352ba64..fe372312 100644 --- a/include/strata/core/weights.hpp +++ b/include/strata/core/weights.hpp @@ -96,6 +96,9 @@ struct WeightRef { /// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it /// (native GGUF projections, the native head). The metadata above stays valid; `data` is null. bool resident = true; + /// STRATA_HC_Q8 (experiment): non-null when `data` holds int8 codes [ne1][ne0] of a BF16 hyper-connection + /// projection quantized Q8_0-style (one fp32 scale per 32 contiguous values, `q8_scale[ne1][ne0 / 32]`). + const float* q8_scale = nullptr; }; struct LoadReport { @@ -136,6 +139,12 @@ public: bool read_bf16_host(const std::string& name, std::vector& out, std::string& err) const; const WeightRef* find(const std::string& name) const; + /// STRATA_HC_Q8: the hyper-connection projections (`blk.*.hc_{attn,ffn}_{down,up}.weight`) the loader SKIPPED + /// are read from the pack, quantized to int8 + one fp32 scale per 32 values, and uploaded to their own device + /// allocation (`q8_scale` set). Returns the bytes uploaded in `bytes`. + bool load_hc_q8(const std::string& pack_dir, uint64_t& bytes, std::string& err); + /// The tensor names `load_hc_q8` converts, for the loader's skip set. + static void hc_q8_names(int64_t n_layers, std::set& out); const std::map& all() const { return table_; } const LoadReport& report() const { return report_; } diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index 00324247..95b51016 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -45,9 +45,15 @@ struct FusedGrArgs { /// bytes native_quantize_q8_1 would write); q8_cnt = n_embd / 32 zeroed counters owned by the caller (token 0's) uint8_t* q8_mixed = nullptr; unsigned* q8_cnt = nullptr; + /// STRATA_HC_Q8: non-null when w_down / w_up hold int8 codes (same [row][col] layout) with one fp32 scale per + /// 32 contiguous values here ([row][col / 32]). w_inject stays bf16. + const float* s_down = nullptr; + const float* s_up = nullptr; }; bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr); +/// STRATA_HC_Q8: n int8 codes with one fp32 scale per 32 -> bf16 (the prompt path's GEMMs take bf16). +void hc_q8_to_bf16(const void* codes, const float* scales, uint16_t* out, long long n, void* stream); void fused_gr_read(const FusedGrArgs& a, void* stream); /// STRATA_HC_Q8 on a bf16 pack: `out` (n_blocks * 34 bytes) = the Q8_0 blocks (fp16 d = amax / 127, round(x / d), ggml's /// reference rounding) of `n_blocks * 32` bf16 values on the device. diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 0a39f646..44e706bb 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -83,6 +83,28 @@ void native_grouped_set_v1(bool v1); /// 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). void native_expert_set_mode(int mode, int phase); + +/// EXPDEC (STRATA_EXPDEC=1, docs/EXPERTDEC.md): `native_expert_grouped` stages the group's q8_1 activations in shared +/// memory and computes several rows per lane, the same sums per (row, entry) as the default kernels (bitwise), for +/// gate/up IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S / IQ2_S at n_embd 2560 and down IQ4_NL / Q2_0 at n_ff 640; other layouts +/// keep the default kernels. Set before graph capture; captured graphs keep the kernels they captured. +void native_expert_set_expdec(int on); +int native_expert_expdec(); +/// Its knobs, read from the environment at startup (STRATA_EXPDEC_R 1 | 2, _DR 1 | 2 | 4, _MINB 2 | 4, _D20 0 | 1, +/// _RB, _DRB, _MINBLK): gate/up and down rows per lane, the gate/up kernel's __launch_bounds__ minimum blocks per SM +/// (2 = up to 128 registers, 4 = up to 64), EXPDEC for the IQ4_NL down too, gate/up and down rows per block (0 = auto +/// from the launch's groups), the auto rule's minimum blocks. In the setter a field <= 0 (< 0 for the two rows per +/// block and down_iq4_nl) keeps the current value. +/// `down` (STRATA_EXPDEC_DOWN, default 0): EXPDEC for the down too; by default only the gate/up (in the engine the +/// Q2_0 down was ~10% slower with EXPDEC, docs/EXPERTDEC.md par. 7). +struct NativeExpertExpdecParams { + int gu_rows_per_lane = 0, down_rows_per_lane = 0, gu_min_blocks_per_sm = 0, down_iq4_nl = -1, down = -1; + int gu_rows_per_block = -1, down_rows_per_block = -1, min_blocks = 0; +}; +void native_expert_set_expdec_params(const NativeExpertExpdecParams& p); +NativeExpertExpdecParams native_expert_expdec_params(); +/// Whether EXPDEC has kernels for this layout's gate/up and down (the bench's check). +bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& down); /// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry; /// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give /// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured. diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index fef71027..3c4185f8 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -31,6 +31,12 @@ std::size_t native_q8_1_bytes(int n_in, int ncols = 1); // graph capture; captured graphs keep the kernels they captured. void native_mmvq_set_multi_exact(bool exact); bool native_mmvq_multi_exact(); +// B6 (lab, opt-in STRATA_B6_MMVQ_ROWS=1): the exact multi-column layout with the activation blocks of every column +// loaded once per weight block and reused across the block's rows (bitwise the same sums as the default exact +// layout). 0 = off (default), 1 = 2 rows per block, 2 / 4 / 8 = that many rows. Q4_K, Q5_K, Q6_K and IQ4_XS only. +// Set before graph capture. +void native_mmvq_set_b6_rows(int mode); +int native_mmvq_b6_rows(); // One quantization may serve multiple weight matrices sharing the same input. // Q8_1 stores FP16 scale and FP16 warp sum of the ORIGINAL float inputs; it does diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp index d68bab43..3270d8b6 100644 --- a/include/strata/kernels/qsa_decode_attn.hpp +++ b/include/strata/kernels/qsa_decode_attn.hpp @@ -57,5 +57,16 @@ struct QsaAttnSlotPools { /// (n_q > kQsaAttnMaxSlots, mixed formats, the pre-sm_75 / gfx103x or gfx906 variants): the caller loops instead. bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream); +/// For src/kernels/qsa_merge_daily_parity.cpp only: qsa_decode_attn_batch's two passes apart, whatever the environment +/// says. `chunks_only` runs the chunk pass into `scratch` with `daily_chunk` 0: attn_chunk_kernel (upstream's default), +/// 1: the Daily's (attn_chunk_kernel_pre75, what STRATA_ATTN_DAILY=1 picks on CUDA). `merge_only` merges those +/// partials with `v2` 0: attn_merge_kernel, 1: attn_merge_v2_kernel (STRATA_ATTN_MERGE_V2, on with STRATA_ATTN_DAILY). +/// Width must not exceed an unaligned cap (the chunk pass keeps its upstream contract); for aligned caps the grid +/// bounds widths above cap. One input can go through every pair and the outputs be compared bit for bit. +void qsa_decode_attn_chunks_only(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, int daily_chunk, + void* stream); +void qsa_decode_attn_merge_only(const int32_t* steps, int64_t cap, const QsaShapes& s, const float* scratch, + float* attn, int64_t n_q, int v2, void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/qsa_prompt_attn.hpp b/include/strata/kernels/qsa_prompt_attn.hpp index 2391aaeb..046cd6fc 100644 --- a/include/strata/kernels/qsa_prompt_attn.hpp +++ b/include/strata/kernels/qsa_prompt_attn.hpp @@ -29,4 +29,14 @@ namespace strata::kernels { bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream); +/// STRATA_QSA_SPLIT_ATTN=1 (the idea of fork Eddoursul fd23d91): `qsa_decode_attn_batch`'s decode +/// attention through the int8 tensor-core kernel above with each query's cells split among up to 20 blocks, merged with +/// the log-sum-exp rescale, its partials in `scratch` (`scratch_floats` available). False (nothing +/// launched) unless int8 KV on sm_80+: the caller keeps qsa_decode_attn_batch. Not bitwise the decode kernel: (b). +bool qsa_decode_attn_split(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); +/// Tests: the int8-KV kernel on INT8 tensor cores (1), v2 (0), or as STRATA_PROMPT_ATTN_IMMA says (-1). +void qsa_prompt_attn_set_imma(int on); + } // namespace strata::kernels diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index 3ff769a9..5d1331fe 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -35,6 +35,12 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead, const float* q_idx, const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores, void* stream); +/// QSAROWS (docs/QSAROWS.md): block_scores_multi_kernel's scores for a call of up to 4 queries, bit for bit, with the +/// queries in registers and the four heads reduce-scattered (six shuffles instead of twenty a block and query). +/// qsa_block_scores takes it with STRATA_QSA_ROWS=1; false (nothing launched) above 4 queries or on another geometry. +/// For qsa_rows_bench's parity and timing it is callable on its own. +bool qsa_block_scores_rows(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); /// The same scores on tensor cores (3xTF32, FP32-level accuracy but another summation order: not bitwise; the tail /// block n_bid is the warp kernel's arithmetic). For the prompt path; false (nothing launched) on another geometry. diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f12f34b9..c64d4c79 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -26,7 +26,7 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* /// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as /// the two calls, without reading R back. /// S23 (opt-in STRATA_HC_UPMIX=1): the up projection (lo16 x w_up^T, BF16, FP32 accumulate) with gr_mix_r as its -/// epilogue - `gated` is never written. False (nothing launched) off gfx11. +/// epilogue - `gated` is never written. gfx11 and CUDA sm_80+; false (nothing launched) elsewhere. bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm, float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream); void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index 3d7b4ccd..fee662fc 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -46,6 +46,12 @@ void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, i /// The down product's rows [0, nrows) (`ld` floats each, relative `bounds`) times their expert's s_down - on the FP32 /// output, not folded into up, where the hidden would sit near 1e-5 (FP16-subnormal block scales in q8 formats). void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream); +/// The rows quantize(x, src, ...) writes for tokens x k_used rows in expert order, written token by token: token t's +/// row of x is quantized once and stored at rows slot[t * k_used + k] (`slot` the inverse of `src`) - the same bytes, +/// a k_used-th of the quantizations (llama.cpp's quantize_scatter_mmq_q8_1_cuda). STRATA_QUANT_GATHER=1: quantize() +/// over `src`, as before. +void quantize_scatter(const float* x, const int32_t* slot, const int32_t* src, void* xq, int ggml_type, int64_t cols, + int64_t ld, int64_t tokens, int k_used, void* stream); constexpr int kGatherGroupMax = 16; /// STRATA_MMQ_DIRECT: each expert's own weight address (gate|up or down), in place of `w + z * expert_bytes` - diff --git a/src/core/arch_defaults.cpp b/src/core/arch_defaults.cpp index e8ca7c9b..4cf36daf 100644 --- a/src/core/arch_defaults.cpp +++ b/src/core/arch_defaults.cpp @@ -42,6 +42,7 @@ std::vector> arch_default_env(const char* gc {"STRATA_CVEC_FUSE", "1"}, // a steered layer's write, control vector and next norm in one pass (S23) {"STRATA_HCD_EXACT", "1"}, // the HC down GEMM in hipBLASLt solution 1176's k order: 64K +1.8% (stream S) {"STRATA_PF_PAD", "1"}, // padded GEMM row strides (acts with STRATA_PF_GEMM; inert without it) (S23) + {"STRATA_TOPK_REG_MIN_BLOCKS", "4096"}, // the register top-k from 16K cells, not 28K: same ids; per 2,048 queries the ref takes 1.0 / 2.4 / 3.9 ms at 16K / 20K / 24K cells, the scan 0.87 / 0.93 / 1.00 // decode {"STRATA_Q8_PACKED", "1"}, // the packed Q8_0 decode layout: +2.3% (S26) {"STRATA_Q6_PACKED", "1"}, // the packed Q6_K heads (S26) diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 1e6b3b93..7eeb8a0a 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -1408,11 +1408,11 @@ st_begin(layer, 0, stream); strata::kernels::FusedGrArgs fa; fa.R = R; fa.R_out = R; fa.apply = pending_ffn; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject2; fa.w_norm = (const float*) w_norm[0]->data; fa.w_down = NativeDense::hc_bf16_view(*w_down[0], stream, 0, 1); - fa.w_up = NativeDense::hc_bf16_view(*w_up[0], stream, 1, 1); fa.w_inject = (const uint16_t*) w_inject[0]->data; + fa.w_up = NativeDense::hc_bf16_view(*w_up[0], stream, 1, 1); fa.s_down = w_down[0]->q8_scale; fa.s_up = w_up[0]->q8_scale; fa.w_inject = (const uint16_t*) w_inject[0]->data; fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject; fa.mixed = bb.mixed; strata::kernels::fused_gr_read(fa, stream); } else { - gr_read(R, (const float*) w_norm[0]->data, NativeDense::hc_bf16_view(*w_down[0], stream, 0, 1), NativeDense::hc_bf16_view(*w_up[0], stream, 1, 1), (const uint16_t*) w_inject[0]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); + if (w_down[0]->q8_scale || w_up[0]->q8_scale) { err = "STRATA_HC_REQ8 needs the fused hyper-connection read"; return false; } gr_read(R, (const float*) w_norm[0]->data, NativeDense::hc_bf16_view(*w_down[0], stream, 0, 1), NativeDense::hc_bf16_view(*w_up[0], stream, 1, 1), (const uint16_t*) w_inject[0]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); } st_end(layer, 0, stream); dump_half(bb, g, layer, bb.inject, 2 * g.n_embd, g.hc, stream); } if (run1) { @@ -1431,11 +1431,11 @@ st_begin(layer, 3, stream); strata::kernels::FusedGrArgs fa; fa.R = R; fa.R_out = R; fa.apply = true; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject; fa.w_norm = (const float*) w_norm[1]->data; fa.w_down = NativeDense::hc_bf16_view(*w_down[1], stream, 0, 1); - fa.w_up = NativeDense::hc_bf16_view(*w_up[1], stream, 1, 1); fa.w_inject = (const uint16_t*) w_inject[1]->data; + fa.w_up = NativeDense::hc_bf16_view(*w_up[1], stream, 1, 1); fa.s_down = w_down[1]->q8_scale; fa.s_up = w_up[1]->q8_scale; fa.w_inject = (const uint16_t*) w_inject[1]->data; fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject2; fa.mixed = bb.mixed; strata::kernels::fused_gr_read(fa, stream); } else { - gr_read(R, (const float*) w_norm[1]->data, NativeDense::hc_bf16_view(*w_down[1], stream, 0, 1), NativeDense::hc_bf16_view(*w_up[1], stream, 1, 1), (const uint16_t*) w_inject[1]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); + if (w_down[1]->q8_scale || w_up[1]->q8_scale) { err = "STRATA_HC_REQ8 needs the fused hyper-connection read"; return false; } gr_read(R, (const float*) w_norm[1]->data, NativeDense::hc_bf16_view(*w_down[1], stream, 0, 1), NativeDense::hc_bf16_view(*w_up[1], stream, 1, 1), (const uint16_t*) w_inject[1]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); } st_end(layer, 3, stream); } if (run4) { diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index c36841c6..fb254d35 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -1,5 +1,6 @@ // src/core/mtp.cpp - see include/strata/core/mtp.hpp. #include "strata/core/mtp.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/spec_prob.hpp" #include "strata/core/on_device.hpp" @@ -1026,6 +1027,9 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) { g_mp.stamp(5, cs); const QsaAttnPools pools = qsa_attn_pools(st_); if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); + // STRATA_QSA_SPLIT_ATTN=1: the draft layer's attention over its window, split the same way + static const bool split_attn = [] { const char* v = std::getenv("STRATA_QSA_SPLIT_ATTN"); return v != nullptr && std::atoi(v) != 0; }(); + if (!(split_attn && qsa_decode_attn_split(qcur_, pools, ident_, step, cap_, s, attn_scratch_, (uint64_t) attn_scratch_floats_, attn_, T, cs))) qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs); if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs); g_mp.stamp(6, cs); diff --git a/src/core/remote_expert_opt.cu b/src/core/remote_expert_opt.cu index 7ddb45e2..c92542f9 100644 --- a/src/core/remote_expert_opt.cu +++ b/src/core/remote_expert_opt.cu @@ -98,8 +98,12 @@ void RemoteExpertOpt::prepare(const RemoteExperts& remote, void* metadata) const bool RemoteExpertOpt::reduce(RemoteExperts& remote, const void* metadata, std::string& err) { const auto& p = *std::find_if(peers_.begin(), peers_.end(), [&](const Peer& p) { return p.remote == &remote; }); + // finish() synchronizes this stream before the host reads h_out_. When mapped output is available, + // write the reduced rows there directly, avoiding a separate device-to-host copy for every layer. + float* sum = remote.zero_copy_ ? remote.z_out_ : p.sum; reduce_experts<<>>( - remote.d_out_, (const ReduceMeta*) metadata, p.sum); + remote.d_out_, (const ReduceMeta*) metadata, sum); + if (remote.zero_copy_) return check(cudaGetLastError(), err); return check(cudaMemcpyAsync(remote.h_out_, p.sum, tokens_ * H * sizeof(float), cudaMemcpyDeviceToHost, remote.stream_), err); } diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 9a9830fe..8c945c4e 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -26,6 +26,7 @@ #include "strata/kernels/native_moe.hpp" #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/elementwise.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/route_prior.hpp" #include "strata/kernels/cvec.hpp" @@ -173,6 +174,9 @@ inline bool g_qfuse_hc() { return false; #endif } +// fork 34a35db + b063c13 (Eddoursul), STRATA_SIDE_MIXER=1 / =2 (opt-in): the mixer's work that reads only the layer's +// input on branches of the window's graph (bitwise the same outputs); 0 / unset = in line, and no branch stream is created +inline int g_side_mixer() { static const int m = [] { const char* v = std::getenv("STRATA_SIDE_MIXER"); return v ? std::max(0, std::min(2, std::atoi(v))) : 0; }(); return m; } inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; } #define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) @@ -537,6 +541,10 @@ Verifier::~Verifier() { if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours if (sh_cs_) cudaStreamDestroy(sh_cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } + if (side_) cudaStreamDestroy(side_); + if (side2_) cudaStreamDestroy(side2_); + for (cudaEvent_t e : {mfork_, mjoin_, pfork_, pjoin_}) + if (e) cudaEventDestroy(e); if (commit_done_) cudaEventDestroy(commit_done_); if (ev_done_) cudaEventDestroy(ev_done_); if (ev_commit_) cudaEventDestroy(ev_commit_); @@ -833,6 +841,16 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& all_resident_ = all_ok; } } + if (g_side_mixer() > 0 && + (cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess || + cudaEventCreateWithFlags(&mfork_, cudaEventDisableTiming) != cudaSuccess || + cudaEventCreateWithFlags(&mjoin_, cudaEventDisableTiming) != cudaSuccess || + cudaStreamCreateWithFlags(&side2_, cudaStreamNonBlocking) != cudaSuccess || + cudaEventCreateWithFlags(&pfork_, cudaEventDisableTiming) != cudaSuccess || + cudaEventCreateWithFlags(&pjoin_, cudaEventDisableTiming) != cudaSuccess)) { + err = "verify: the mixer branch's stream / events could not be created"; + return false; + } // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; // exact, but neutral on RIBPC 1-2 GPUs: off by default) { @@ -898,6 +916,17 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // Pipelined windows must wait for the host verdict/snapshot fence before mutating state. const bool self_commit = T == 1 && !always_publish_ && !batch_rec_ && !g_qfuse() && one_token_self_commit(); // see Verifier::commit static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + // fork 34a35db: the GDN gates and the QSA indexer beside the projections (STRATA_SIDE_MIXER=1; 0 / unset = in line) + const int side_mixer_mode = g_side_mixer(); + const bool side_mixer = side_mixer_mode >= 1; + const bool side_proj = side_mixer_mode >= 2 && !batch_rec_; // fork b063c13: the GDN gate projection, the QSA queries + auto branch = [&](cudaEvent_t e, cudaStream_t from, cudaStream_t to, const char* what) { + if (cudaEventRecord(e, from) == cudaSuccess && cudaStreamWaitEvent(to, e, 0) == cudaSuccess) return true; + err = std::string("verify: the mixer branch could not ") + what; + return false; + }; + // a batch window's rows each read their own slot's indexer: in line there + const bool sidem = side_mixer && !batch_rec_; auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs); // #649 @@ -923,7 +952,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // makes side i depend on everything captured on `cs` so far, join(i) makes `cs` depend on everything captured on // side i: a branch never races with what came before its fork or after its join. Not in a split or batch window, // nor under the stage profiler (whose stamps are on `cs`). - const bool br = df_branch_ && G == 1 && !batch_rec_ && !prof_on_; + const bool br = df_branch_ && G == 1 && !batch_rec_ && !prof_on_ && !side_mixer; // STRATA_SIDE_MIXER wins auto fork = [&](int i) { cudaEventRecord(df_fork_, cs); cudaStreamWaitEvent(df_side_[i], df_fork_, 0); @@ -1117,6 +1146,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data; a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8; a.q8_inject = (const uint8_t*) wi[half]->hc_q8; + a.s_down = wd[half]->q8_scale; a.s_up = wu[half]->q8_scale; a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N; if (qcnt_ != nullptr) { // S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself @@ -1170,7 +1200,30 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { float* hb = h_L_ + (size_t) gi * MT * C; float* gate = gate_L_ + (size_t) gi * MT * HV; float* beta = beta_L_ + (size_t) gi * MT * HV; + if (sidem) { // the gates (a few blocks, latency-bound) beside the projections, joined below + if (!branch(mfork_, cs, side_, "fork")) return false; + gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data, + (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, + (int) HV, n, side_); + if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the GDN gates' branch could not join"; return false; } + } if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs); + if (side_proj) { // the gate projection (compute-bound for i-quants) beside qkv and the conv + // the branch reads F4's interleaved copy too (written on cs before the fork; bitwise native_mmvq's + // output), and qkv is recorded before the branch's launch, so its grid is dispatched first and the + // conv / recurrence that wait for it start sooner (z is read only after the recurrence) + const bool g_il = g_mmvq_il() && strata::kernels::native_mmvq_il_supported(wg->native_type, n, (int) ZV); + if (g_il && !il_ready) { + strata::kernels::native_q8_1_interleave(xq_, xil_, (int) N, n, cs); + il_ready = true; + } + if (!branch(pfork_, cs, side2_, "fork")) return false; + mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C); + if (g_il) strata::kernels::native_mmvq_il(wg->native_type, wg->native_data, xq_, xil_, z_ + (size_t) tb * ZV, + (int) N, (int) ZV, n, side2_); + else native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, side2_); + if (cudaEventRecord(pjoin_, side2_) != cudaSuccess) { err = "verify: the gate projection's branch could not join"; return false; } + } if (br) { // STRATA_DF_BRANCH: a/b and z beside q/k/v and the conv; all of them read only this layer's input fork(0); gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data, @@ -1180,8 +1233,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, df_side_[1]); } - const bool fuse_ab = fuse_convab_on() && !br && !batch_rec_ && !prof_on_; - mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C); + const bool fuse_ab = fuse_convab_on() && !br && !batch_rec_ && !prof_on_ && !sidem; // the side mixer computes the gates on its branch + if (!side_proj) mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C); // with side_proj: above, first stamp(l, 2, grp); if (batch_rec_) { // contiguous rows may be proposals for the same slot for (int t = tb; t < te;) { @@ -1209,13 +1262,21 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { join(0); join(1); } else { - if (!fuse_ab) + if (!fuse_ab && !sidem) // the gates: the HIP fused conv kernel (143-amdk) or the side mixer's branch, else here gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data, (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV, n, cs); stamp(l, 4, grp); - mm(wg, z_ + (size_t) tb * ZV, (int) N, (int) ZV); + if (!side_proj) mm(wg, z_ + (size_t) tb * ZV, (int) N, (int) ZV); stamp(l, 5, grp); + if (side_proj && cudaStreamWaitEvent(cs, pjoin_, 0) != cudaSuccess) { + err = "verify: the gate projection's branch could not join"; + return false; + } + if (sidem && cudaStreamWaitEvent(cs, mjoin_, 0) != cudaSuccess) { + err = "verify: the GDN gates' branch could not join"; + return false; + } } // the recurrence from the untouched state over tokens [0, te); outputs only for this group's if (batch_rec_) { // each slot's recurrence over its own proposed-token group @@ -1300,9 +1361,126 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { IQ * ID, N, IQ * ID, n, df_side_[1]); norm_rope_on(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ, df_side_[1]); } - if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs); - else for (int t = tb; t < te; ++t) - bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs); + // STRATA_SIDE_MIXER=1 / =2 (fork Eddoursul 34a35db + b063c13): the indexer's key projection, + // the tail's snapshot, its keys appended, its query projection, norm and RoPE, the block scores and the + // top-k read only the mixer's input and the indexer's own state - =1 runs them on a branch beside the + // attention's projections; =2 also the queries' chain on a second branch. Each step below is + // the in-line code with its stream as a parameter; with the switch off they run on cs in the same order + // as before (STRATA_DF_BRANCH, the same idea for fewer of these steps, is off whenever this is on). + auto norm_rope_s = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos, cudaStream_t ns) { + if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) { + native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS, + rope_scaling(), pos, ns); + return; + } + norm_rope_on(data, norm, rows, cols, pos, ns); + }; + auto idx_key = [&](cudaStream_t ns) { + if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, ns); + else for (int t = tb; t < te; ++t) + bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, ns); + }; + auto idx_snap = [&](cudaStream_t ns) { + if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row + for (int t = tb; t < te && !keep_rows; ++t) + if (t == tb || brow_[t] != brow_[t - 1]) + copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, + slot_ss(t).qsa_states[qi].idx_tail, TS, ns); + } else + if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, ns); + }; + auto idx_append = [&](cudaStream_t ns) { + if (dec_batch && !g_no_batch_kv && !batch_rec_) { + const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; + native_qsa_indexer_append_steps(idx_raw + tb * ID, step_ + tb * kStepCount + kStepPos, kStepCount, + n, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, + rope_scaling(), ns); + } else { + for (int t = tb; t < te; ++t) { + const QsaState& sx = slot_ss(t).qsa_states[qi]; + const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos}; + native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0, + (const float*) wikn->data, EPS, ib, s, sx.max_cells, + rope_scaling(), ns); + } + } + }; + auto idx_query = [&](cudaStream_t ns) { + if (qb) { + bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID, + N, IQ * ID, n, ns); + norm_rope_s(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ, ns); + } else + for (int t = tb; t < te; ++t) { + float* qx = qidx_ + t * IQ * ID; + bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), ns); + norm_rope_s(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH, ns); + } + }; + auto idx_select = [&](cudaStream_t ns) { + 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, + sel_ + (size_t) tb * cap_, ns); + }; + // the attention's queries: the projection (mm on cs, which may read F4's interleaved copy; on a branch + // F4's kernel too, its copy written on cs before the fork - bitwise the same), the q/gate + // split with norm and RoPE, the rotation + const bool q_il = side_proj && g_mmvq_il() && + strata::kernels::native_mmvq_il_supported(wq->native_type, n, (int) (NH * 2 * HD)); + auto q_chain = [&](cudaStream_t ns) -> bool { + if (ns == cs) mm(wq, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD)); + else if (q_il) strata::kernels::native_mmvq_il(wq->native_type, wq->native_data, xq_, xil_, + qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), n, ns); + else native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, + (int) (NH * 2 * HD), n, ns); + if (qb) { + if (fuse_nr) { // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD) + native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, + qcur_ + tb * NH * HD, (int) (n * NH), (int) HD, (int) s.n_rot, EPS, + rope_scaling(), pos_ + tb * NH, ns); + } else { + copy_rows_strided(qcur_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, (int64_t) n * NH, HD, 2 * HD, ns); + norm_rope_s(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH, ns); + } + if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, ns); // = + } else { + for (int t = tb; t < te; ++t) { + float* qc = qcur_ + t * NH * HD; + if (fuse_nr) { + native_qsa_rms_norm_rope(qfull_ + t * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, qc, + (int) NH, (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos_ + t * NH, ns); + } else { + if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, + (size_t) HD * 4, (size_t) NH, cudaMemcpyDeviceToDevice, ns) != cudaSuccess) { + err = "verify: the q/gate split failed"; + return false; + } + norm_rope_s(qc, wqn, (int) NH, (int) HD, pos_ + t * NH, ns); + } + if (st.kv_rot) fwht256_inplace_cuda(qc, NH, ns); // = + } + } + return true; + }; + if (sidem) { + if (!branch(mfork_, cs, side_, "fork")) return false; + idx_key(side_); + idx_snap(side_); + idx_append(side_); + idx_query(side_); + idx_select(side_); + if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the indexer's branch could not join"; return false; } + } + if (side_proj) { // the queries beside the keys and values (fork b063c13) + if (q_il && !il_ready) { // the copy before the fork (mm(wk) / mm(wv) on cs reuse it) + strata::kernels::native_q8_1_interleave(xq_, xil_, (int) N, n, cs); + il_ready = true; + } + if (!branch(pfork_, cs, side2_, "fork") || !q_chain(side2_)) return false; + if (cudaEventRecord(pjoin_, side2_) != cudaSuccess) { err = "verify: the queries' branch could not join"; return false; } + } + if (!sidem) idx_key(cs); stamp(l, 7, grp); mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); mm(wv, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); @@ -1315,13 +1493,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); } stamp(l, 8, grp); - if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row - for (int t = tb; t < te && !keep_rows; ++t) - if (t == tb || brow_[t] != brow_[t - 1]) - copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, - slot_ss(t).qsa_states[qi].idx_tail, TS, cs); - } else - if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); + if (!sidem) idx_snap(cs); // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a // batch's rows each have their own K/V, so that case keeps the loop) if (dec_batch && !g_no_batch_kv && !batch_rec_) { @@ -1369,61 +1541,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host); } - if (dec_batch && !g_no_batch_kv && !batch_rec_) { - const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; - native_qsa_indexer_append_steps(idx_raw + tb * ID, step_ + tb * kStepCount + kStepPos, kStepCount, - n, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - rope_scaling(), cs); - } else { - for (int t = tb; t < te; ++t) { - const QsaState& sx = slot_ss(t).qsa_states[qi]; - const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos}; - native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0, - (const float*) wikn->data, EPS, ib, s, sx.max_cells, - rope_scaling(), cs); - } - } + if (!sidem) idx_append(cs); stamp(l, 9, grp); if (qbr) { join(1); // the indexer query, for the block scores } else { - mm(wq, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD)); - if (qb) { - if (fuse_nr) { // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD) - native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, - qcur_ + tb * NH * HD, (int) (n * NH), (int) HD, (int) s.n_rot, EPS, - rope_scaling(), pos_ + tb * NH, cs); - } else { - // the q/gate split as a copy kernel: the window's chain stays kernel to kernel (PDL) - copy_rows_strided(qcur_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, (int64_t) n * NH, HD, 2 * HD, cs); - norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH); - } - if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // = - bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID, - N, IQ * ID, n, cs); - norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ); - } else { - for (int t = tb; t < te; ++t) { - float* qc = qcur_ + t * NH * HD; - if (fuse_nr) { - native_qsa_rms_norm_rope(qfull_ + t * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, qc, - (int) NH, (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos_ + t * NH, cs); - } else { - if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, - (size_t) HD * 4, (size_t) NH, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { - err = "verify: the q/gate split failed"; - return false; - } - norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH); - } - if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // = - } - for (int t = tb; t < te; ++t) { - float* qx = qidx_ + t * IQ * ID; - bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), cs); - norm_rope(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH); - } - } + if (!side_proj && !q_chain(cs)) return false; + if (!sidem) idx_query(cs); } stamp(l, 10, grp); bool streamed = false; // a streamed KV cache keeps the per-row resolve-then-attend order @@ -1476,16 +1600,27 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { attn_ + t * NH * HD, 1, cs); } } else { - 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_, cs); - qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s, - sel_ + (size_t) tb * cap_, cs); + if (!sidem) idx_select(cs); + else if (cudaStreamWaitEvent(cs, mjoin_, 0) != cudaSuccess) { + err = "verify: the indexer's branch could not join"; + return false; + } + if (side_proj && cudaStreamWaitEvent(cs, pjoin_, 0) != cudaSuccess) { + err = "verify: the queries' branch could not join"; + return false; + } stamp(l, 11, grp); // KV streaming: the n selections' blocks resident (device-side, inside the graph) qsa_kv_resolve(st, *g_, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, n, cap_, cs); stamp(l, 12, grp); if (qbr) join(0); // the query, for attention const QsaAttnPools pools = qsa_attn_pools(st); + // STRATA_QSA_SPLIT_ATTN=1: the split tensor-core attention where it applies (int8 KV, sm_80+) + static const bool split_attn = [] { const char* v = std::getenv("STRATA_QSA_SPLIT_ATTN"); return v != nullptr && std::atoi(v) != 0; }(); + if (!(split_attn && qsa_decode_attn_split(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, + step_ + tb * kStepCount, cap_, s, + attn_scratch_ + (size_t) tb * attn_scratch_floats_, + (uint64_t) n * (uint64_t) attn_scratch_floats_, attn_ + tb * NH * HD, n, cs))) qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); } diff --git a/src/core/weights.cpp b/src/core/weights.cpp index a46c485d..bb28f099 100644 --- a/src/core/weights.cpp +++ b/src/core/weights.cpp @@ -1,5 +1,7 @@ // src/core/weights.cpp - the dense-weight loader. See the header for the engine-vs-pack distinction. #include "strata/core/weights.hpp" +#include +#include #include "strata/kernels/f16_bits.hpp" #include "strata/platform/memory.hpp" @@ -513,4 +515,88 @@ const WeightRef* WeightTable::find(const std::string& name) const { return it == table_.end() ? nullptr : &it->second; } +void WeightTable::hc_q8_names(int64_t n_layers, std::set& out) { + for (int64_t l = 0; l < n_layers; ++l) + for (const char* h : {"hc_attn_", "hc_ffn_"}) + for (const char* m : {"down", "up"}) + out.insert("blk." + std::to_string(l) + "." + h + m + ".weight"); +} + +bool WeightTable::load_hc_q8(const std::string& pack_dir, uint64_t& bytes, std::string& err) { + bytes = 0; + std::vector todo; + for (auto& [name, w] : table_) { + const bool hc = name.find(".hc_attn_down.") != std::string::npos || name.find(".hc_attn_up.") != std::string::npos || + name.find(".hc_ffn_down.") != std::string::npos || name.find(".hc_ffn_up.") != std::string::npos; + if (!hc || w.resident) continue; + // the pack holds BF16 either promoted to f32 (4 B/elem) or as it is in the GGUF (a native pack, 2 B/elem) + if (w.kind != WeightKind::Bf16InF32 || w.ne0 % 32 != 0 || + (w.src_bytes != (uint64_t) w.elements * 4 && w.src_bytes != (uint64_t) w.elements * 2)) { + err = "STRATA_HC_REQ8: " + name + " is not a BF16 tensor of whole 32-value blocks"; + return false; + } + todo.push_back(&w); + } + if (todo.empty()) return true; + auto al = [](uint64_t b) { return (b + 255) & ~(uint64_t) 255; }; + uint64_t total = 0; + for (const WeightRef* w : todo) total += al((uint64_t) w->elements) + al((uint64_t) w->elements / 32 * 4); + uint8_t* dev = nullptr; + if (cudaMalloc((void**) &dev, total) != cudaSuccess) { err = "STRATA_HC_REQ8: cudaMalloc failed"; return false; } + std::vector src; + std::vector q; + std::vector sc; + uint64_t at = 0; + for (WeightRef* w : todo) { + const char* fn = file_name(w->file_id); + const std::string path = pack_dir + "/" + (fn ? fn : "?"); + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) { err = "STRATA_HC_REQ8: cannot open " + path; return false; } + src.resize((size_t) w->elements); + const bool raw16 = w->src_bytes == (uint64_t) w->elements * 2; +#if defined(_WIN32) + bool ok = _fseeki64(f, (long long) w->src_off, SEEK_SET) == 0; +#else + bool ok = fseeko(f, (off_t) w->src_off, SEEK_SET) == 0; // 64-bit: a pack's dense file can pass 2 GiB +#endif + if (ok && raw16) { + std::vector h(src.size()); + ok = std::fread(h.data(), 2, h.size(), f) == h.size(); + for (size_t i = 0; ok && i < h.size(); ++i) { + const uint32_t b = (uint32_t) h[i] << 16; // bf16 -> f32 is exact + std::memcpy(&src[i], &b, 4); + } + } else if (ok) { + ok = std::fread(src.data(), 4, src.size(), f) == src.size(); + } + std::fclose(f); + if (!ok) { err = "STRATA_HC_REQ8: cannot read the source bytes"; return false; } + const size_t nb = src.size() / 32; + q.resize(src.size()); + sc.resize(nb); + for (size_t b = 0; b < nb; ++b) { // Q8_0's rule: d = amax / 127, q = round-to-nearest-even(x / d) + float amax = 0.f; + for (int j = 0; j < 32; ++j) amax = std::max(amax, std::fabs(src[b * 32 + j])); + const float d = amax / 127.f, id = d > 0.f ? 1.f / d : 0.f; + sc[b] = d; + for (int j = 0; j < 32; ++j) q[b * 32 + j] = (int8_t) std::nearbyint(src[b * 32 + j] * id); + } + uint8_t* codes = dev + at; + at += al(q.size()); + float* scales = (float*) (dev + at); + at += al(sc.size() * 4); + if (cudaMemcpy(codes, q.data(), q.size(), cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(scales, sc.data(), sc.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess) { + err = "STRATA_HC_REQ8: upload failed"; + return false; + } + w->data = codes; + w->q8_scale = scales; + w->resident = true; + w->bytes = q.size() + sc.size() * 4; + } + bytes = total; + return true; +} + } // namespace strata::core diff --git a/src/kernels/b6_mmvq_bench.cpp b/src/kernels/b6_mmvq_bench.cpp new file mode 100644 index 00000000..75e136d9 --- /dev/null +++ b/src/kernels/b6_mmvq_bench.cpp @@ -0,0 +1,218 @@ +// src/kernels/b6_mmvq_bench.cpp - B6: what a verify row costs in the dense projections, per kernel, per card. +// +// build/b6_mmvq_bench [reps] [device, -1 = all] [B rows mode: 1 = 2 rows, or 2 / 4 / 8] +// +// The decode's dense projections at the model's own shapes and formats (qwen3.8-flash-next GSQ-RCO IQ3_XXS: +// GDN qkv / gate / out, QSA q / out, shared expert, the head; the BF16 router), called with ncols = 1..5 and 8 as a +// verify window of that many rows calls them. Per call: CUDA events around each launch, every launch queued back to +// back (no host gap inside a measurement), the median of `reps` (default 500) after a warm-up. The weights rotate +// over enough copies to exceed the L2, as the decode reads each layer's weights cold. Synthetic bytes with sane +// block scales (as mmvq_multi_parity): the time does not depend on the values. +// +// Two layouts side by side: the default exact layout (A) and STRATA_B6_MMVQ_ROWS (B, native_mmvq_set_b6_rows). For +// every case and ncols: B's output against A's, bit for bit (memcmp), and both against ncols single-column calls. +// Exit code 1 if any comparison differs. GPU time only: immune to the host and to any generated text. +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace K = strata::kernels; + +namespace { + +struct Case { + const char* name; + int type; // GGML type id; 30 = BF16 (bf16_gemv_fp32_mmvf_multi) + int n_in, n_out; + int block_elems, block_bytes; + int scale_at[2]; // byte offsets of the fp16 scales in a block; -1 = none +}; + +const Case CASES[] = { + {"gdn qkv Q6_K", 14, 2560, 10240, 256, 210, {208, -1}}, + {"gdn qkv Q4_K", 12, 2560, 10240, 256, 144, {0, 2}}, + {"gdn qkv Q5_K", 13, 2560, 10240, 256, 176, {0, 2}}, + {"gdn qkv IQ4_XS", 23, 2560, 10240, 256, 136, {0, -1}}, + {"gdn gate Q6_K", 14, 2560, 6144, 256, 210, {208, -1}}, + {"gdn out Q6_K", 14, 6144, 2560, 256, 210, {208, -1}}, + {"gdn out IQ4_XS", 23, 6144, 2560, 256, 136, {0, -1}}, + {"gdn out Q4_K", 12, 6144, 2560, 256, 144, {0, 2}}, + {"qsa q IQ4_XS", 23, 2560, 12288, 256, 136, {0, -1}}, + {"qsa q Q6_K", 14, 2560, 12288, 256, 210, {208, -1}}, + {"shexp up IQ3_S", 21, 2560, 640, 256, 110, {0, -1}}, + {"shexp gate Q4_K", 12, 2560, 640, 256, 144, {0, 2}}, + {"shexp down IQ4_NL", 20, 640, 2560, 32, 18, {0, -1}}, + {"router BF16", 30, 2560, 512, 1, 2, {-1, -1}}, + {"head Q5_K", 13, 2560, 248320, 256, 176, {0, 2}}, +}; +const int WIDTHS[] = {1, 2, 3, 4, 5, 8}; + +bool ck(cudaError_t e, const char* what) { + if (e == cudaSuccess) return true; + std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); + return false; +} + +uint16_t sane_half(std::mt19937& rng) { + const uint32_t r = rng(); + return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); +} +uint16_t bf16(float x) { + uint32_t u; + std::memcpy(&u, &x, 4); + return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +struct Buf { + std::vector w; // weight copies + std::size_t wbytes = 0; + void* xq = nullptr; // Q8_1 of 8 columns + float* xf = nullptr; // the float activations (BF16 path) + float* y = nullptr; // 8 columns of output +}; + +// one call of the case at `ncols` on weight copy `k` into y +void call(const Case& c, const Buf& b, int k, int ncols, float* y, cudaStream_t s) { + if (c.type == 30) + K::bf16_gemv_fp32_mmvf_multi(b.xf, c.n_in, (const uint16_t*) b.w[(size_t) k], y, c.n_out, c.n_in, c.n_out, ncols, s); + else + K::native_mmvq(c.type, b.w[(size_t) k], b.xq, y, c.n_in, c.n_out, ncols, s); +} +// column j alone (ncols = 1), into y + j * n_out +void call_col(const Case& c, const Buf& b, int j, float* y, cudaStream_t s) { + if (c.type == 30) + K::bf16_gemv_fp32_mmvf_multi(b.xf + (size_t) j * c.n_in, c.n_in, (const uint16_t*) b.w[0], + y + (size_t) j * c.n_out, c.n_out, c.n_in, c.n_out, 1, s); + else + K::native_mmvq(c.type, b.w[0], (const uint8_t*) b.xq + K::native_q8_1_bytes(c.n_in, 1) * (size_t) j, + y + (size_t) j * c.n_out, c.n_in, c.n_out, 1, s); +} + +double median_ms(const Case& c, const Buf& b, int ncols, int reps, cudaStream_t s, std::vector& ev) { + const int nk = (int) b.w.size(); + for (int r = 0; r < 30; ++r) call(c, b, r % nk, ncols, b.y, s); // warm-up + for (int r = 0; r < reps; ++r) { + cudaEventRecord(ev[(size_t) 2 * r], s); + call(c, b, r % nk, ncols, b.y, s); + cudaEventRecord(ev[(size_t) 2 * r + 1], s); + } + cudaStreamSynchronize(s); + std::vector t((size_t) reps); + for (int r = 0; r < reps; ++r) cudaEventElapsedTime(&t[(size_t) r], ev[(size_t) 2 * r], ev[(size_t) 2 * r + 1]); + std::nth_element(t.begin(), t.begin() + reps / 2, t.end()); + return t[(size_t) reps / 2]; +} + +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + const int reps = argc > 1 ? std::max(50, std::atoi(argv[1])) : 500; + int n_dev = 0; + if (!ck(cudaGetDeviceCount(&n_dev), "device count")) return 1; + const int only = argc > 2 ? std::atoi(argv[2]) : -1; + const int bmode = argc > 3 ? std::atoi(argv[3]) : 1; + long long bad = 0; + for (int dev = 0; dev < n_dev; ++dev) { + if (only >= 0 && dev != only) continue; + cudaSetDevice(dev); + cudaDeviceProp pr{}; + cudaGetDeviceProperties(&pr, dev); + std::printf("\n=== device %d: %s (sm_%d%d, L2 %d KB), %d reps, median ms per call, B = rows mode %d ===\n", dev, pr.name, + pr.major, pr.minor, pr.l2CacheSize / 1024, reps, bmode); + std::printf("%-18s %4s %9s %9s %8s %8s %s\n", "case", "cols", "A ms", "B ms", "A +col", "B +col", + "bitwise B=A, A=1col, B=1col"); + cudaStream_t s; + if (!ck(cudaStreamCreate(&s), "stream")) return 1; + std::vector ev((size_t) 2 * reps); + for (auto& e : ev) cudaEventCreate(&e); + for (const Case& c : CASES) { + if (c.type != 30 && !K::native_mmvq_supported(c.type)) { + std::printf("%-18s unsupported type %d\n", c.name, c.type); + continue; + } + std::mt19937 rng(77u + (unsigned) c.type * 131u + (unsigned) c.n_out); + Buf b; + b.wbytes = c.type == 30 ? (size_t) c.n_in * c.n_out * 2 : K::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out); + std::vector w(b.wbytes); + if (c.type == 30) { + std::normal_distribution nd(0.f, 0.05f); + auto* p = (uint16_t*) w.data(); + for (size_t i = 0; i < b.wbytes / 2; ++i) p[i] = bf16(nd(rng)); + } else { + for (auto& x : w) x = (uint8_t) (rng() & 0xff); + const size_t nb = (size_t) c.n_out * (size_t) (c.n_in / c.block_elems); + for (size_t k = 0; k < nb; ++k) + for (int at : c.scale_at) + if (at >= 0) { + const uint16_t h = sane_half(rng); + std::memcpy(&w[k * (size_t) c.block_bytes + (size_t) at], &h, 2); + } + } + const size_t copies = std::max(1, std::min(8, (96u << 20) / b.wbytes + 1)); + bool ok = true; + for (size_t k = 0; k < copies && ok; ++k) { + void* d = nullptr; + ok = ck(cudaMalloc(&d, b.wbytes), "malloc w") && ck(cudaMemcpy(d, w.data(), b.wbytes, cudaMemcpyHostToDevice), "copy w"); + b.w.push_back(d); + } + std::vector x((size_t) 8 * c.n_in); + std::normal_distribution nx(0.f, 1.f); + for (auto& v : x) v = nx(rng); + const size_t ybytes = (size_t) 8 * c.n_out * 4; + ok = ok && ck(cudaMalloc(&b.xf, x.size() * 4), "malloc x") && + ck(cudaMemcpy(b.xf, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x") && + ck(cudaMalloc(&b.y, ybytes), "malloc y"); + if (ok && c.type != 30) { + ok = ck(cudaMalloc(&b.xq, K::native_q8_1_bytes(c.n_in, 8)), "malloc xq"); + if (ok) K::quantize_q8_1_rows(b.xf, 8, c.n_in, b.xq, s); + } + float *ya = nullptr, *yb = nullptr, *y1 = nullptr; + ok = ok && ck(cudaMalloc(&ya, ybytes), "ya") && ck(cudaMalloc(&yb, ybytes), "yb") && ck(cudaMalloc(&y1, ybytes), "y1"); + if (!ok) return 1; + double a1 = 0, b1 = 0; + for (int T : WIDTHS) { + std::vector ha((size_t) T * c.n_out), hb(ha.size()), h1(ha.size()); + K::native_mmvq_set_b6_rows(0); + const double ta = median_ms(c, b, T, reps, s, ev); + call(c, b, 0, T, ya, s); + for (int j = 0; j < T; ++j) call_col(c, b, j, y1, s); + K::native_mmvq_set_b6_rows(bmode); + const double tb = median_ms(c, b, T, reps, s, ev); + call(c, b, 0, T, yb, s); + K::native_mmvq_set_b6_rows(0); + if (!ck(cudaStreamSynchronize(s), "run")) return 1; + cudaMemcpy(ha.data(), ya, ha.size() * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(hb.data(), yb, hb.size() * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(h1.data(), y1, h1.size() * 4, cudaMemcpyDeviceToHost); + const bool ba = std::memcmp(ha.data(), hb.data(), ha.size() * 4) == 0; + const bool a_1 = std::memcmp(ha.data(), h1.data(), ha.size() * 4) == 0; + const bool b_1 = std::memcmp(hb.data(), h1.data(), hb.size() * 4) == 0; + long long nonfinite = 0; + for (uint32_t u : ha) { float f; std::memcpy(&f, &u, 4); if (!std::isfinite(f)) ++nonfinite; } + if (!ba || !b_1 || nonfinite) ++bad; + if (T == 1) { a1 = ta; b1 = tb; } + std::printf("%-18s %4d %9.4f %9.4f %8.4f %8.4f %s %s %s%s\n", c.name, T, ta, tb, + T > 1 ? (ta - a1) / (T - 1) : 0.0, T > 1 ? (tb - b1) / (T - 1) : 0.0, ba ? "ok" : "DIFF", + a_1 ? "ok" : "diff", b_1 ? "ok" : "DIFF", nonfinite ? " NONFINITE" : ""); + } + for (void* d : b.w) cudaFree(d); + cudaFree(b.xq); cudaFree(b.xf); cudaFree(b.y); cudaFree(ya); cudaFree(yb); cudaFree(y1); + } + for (auto& e : ev) cudaEventDestroy(e); + cudaStreamDestroy(s); + } + std::printf("\nb6_mmvq_bench: %s (%lld case/width comparisons failed)\n", bad ? "FAILED" : "ok", bad); + return bad ? 1 : 0; +} diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index 97759ae7..5f9ec4eb 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -269,14 +269,14 @@ bool dequant_wide_on() { static const int env = [] { const char* v = std::getenv("STRATA_DEQUANT_WIDE"); return v != nullptr && v[0] != '\0' ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); if (g_dequant_wide >= 0) return g_dequant_wide != 0; if (env >= 0) return env != 0; - static int per_dev[64]; // 0 unknown, 1 no, 2 yes: sm_61, measured on a Tesla P40 + static int per_dev[64]; // 0 unknown, 1 no, 2 yes: sm_61 (measured on a Tesla P40) and sm_86 (RTX 3060 / A4000, 0.1.45: short-prompt TTFT -12..-17%, bitwise) int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { (void) cudaGetLastError(); return false; } if (!per_dev[dev]) { int major = 0, minor = 0; if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { (void) cudaGetLastError(); return false; } - per_dev[dev] = major == 6 && minor == 1 ? 2 : 1; + per_dev[dev] = (major == 6 && minor == 1) || (major == 8 && minor == 6) ? 2 : 1; } return per_dev[dev] == 2; } diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index c3c2fc8d..8adc141e 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -78,6 +78,38 @@ __device__ __forceinline__ float dot8(const uint4 w, const float* x) { return dot8u_ptr(unpack8(w), x); } +// STRATA_HC_Q8: a weight chunk of 8 values in one uint4 register either way - bf16 (4 words), or Q8 (8 int8 codes in +// .x/.y and the chunk's 32-value block scale in .z), so the kernels keep their register budget. +__device__ __forceinline__ float dot8q(const uint32_t a, const uint32_t b, const float* x) { + float acc = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) acc = fmaf((float) (int8_t) (a >> (8 * i)), x[i], acc); +#pragma unroll + for (int i = 0; i < 4; ++i) acc = fmaf((float) (int8_t) (b >> (8 * i)), x[4 + i], acc); + return acc; +} +/// STRATA_HC_REQ8: the chunk at element `e` (a multiple of 8) of a matrix - bf16 `wb`, or (Q8 and `sq` non-null) +/// int8 codes with scales `sq`, packed into the same uint4 register as 8 int8 codes in .x/.y and the 32-value block's +/// scale in .z. Q8 is a template parameter: the BF16 instantiations compile exactly as before. +template +__device__ __forceinline__ uint4 ldw(const uint16_t* wb, const float* sq, size_t e) { + if constexpr (Q8) { + if (sq != nullptr) { + const uint2 v = __ldg(reinterpret_cast(reinterpret_cast(wb) + e)); + return make_uint4(v.x, v.y, __float_as_uint(__ldg(sq + e / 32)), 0u); + } + } + return __ldg(reinterpret_cast(wb + e)); +} +template +__device__ __forceinline__ float dotw(const bool q8, const uint4 w, const float* x) { + if constexpr (Q8) { + if (q8) return __uint_as_float(w.z) * dot8q(w.x, w.y, x); + } + return dot8(w, x); +} + +template __global__ void __launch_bounds__(THREADS) gr_down_kernel(FusedGrArgs a) { __shared__ __align__(16) float xn[D]; __shared__ float part[WARPS][HC]; @@ -121,11 +153,12 @@ __global__ void __launch_bounds__(THREADS) gr_down_kernel(FusedGrArgs a) { const bool inject_block = blockIdx.x == DOWN_BLOCKS; const int row = inject_block ? warp : blockIdx.x * WARPS + warp; if (inject_block && (a.w_inject == nullptr || warp >= HC)) return; - const uint16_t* wrow = (inject_block ? a.w_inject : a.w_down) + (size_t) row * D; - const uint4* w4 = reinterpret_cast(wrow); + const uint16_t* wmat = inject_block ? a.w_inject : a.w_down; + const float* sq = (Q8 && !inject_block) ? a.s_down : nullptr; // the inject rows stay bf16 + const bool q8 = Q8 && !inject_block; float acc = 0.0f; #pragma unroll 4 - for (int j = lane; j < D / 8; j += 32) acc += dot8(__ldg(w4 + j), xn + j * 8); + for (int j = lane; j < D / 8; j += 32) acc += dotw(q8, ldw(wmat, sq, (size_t) row * D + (size_t) j * 8), xn + j * 8); acc = warp_sum(acc); if (lane != 0) return; if (inject_block) { @@ -136,6 +169,7 @@ __global__ void __launch_bounds__(THREADS) gr_down_kernel(FusedGrArgs a) { } } +template __global__ void __launch_bounds__(THREADS) gr_up_kernel(FusedGrArgs a) { __shared__ __align__(16) float lo[LR]; __shared__ float g[HC][UP_COLS]; @@ -146,9 +180,10 @@ __global__ void __launch_bounds__(THREADS) gr_up_kernel(FusedGrArgs a) { // 128 rows (4 streams x 32 columns), 16 per warp: 320 bf16 = 40 chunks of 8. for (int r = warp; r < HC * UP_COLS; r += WARPS) { const int c = r / UP_COLS, dd = r - c * UP_COLS, i = c * N + d0 + dd; - const uint4* w4 = reinterpret_cast(a.w_up + (size_t) i * LR); - float acc = dot8(__ldg(w4 + lane), lo + lane * 8); - if (lane < LR / 8 - 32) acc += dot8(__ldg(w4 + 32 + lane), lo + (32 + lane) * 8); + const bool q8 = Q8; + float acc = dotw(q8, ldw(a.w_up, a.s_up, (size_t) i * LR + (size_t) lane * 8), lo + lane * 8); + if (lane < LR / 8 - 32) + acc += dotw(q8, ldw(a.w_up, a.s_up, (size_t) i * LR + (size_t) (32 + lane) * 8), lo + (32 + lane) * 8); acc = warp_sum(acc); if (lane == 0) { float rv = a.R[i]; @@ -263,7 +298,7 @@ __global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { // which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held // for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks // of four tokens instead of one on sm_75. -template +template __global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { constexpr int TQ = TILEV / 8 / 32; // uint4 weight chunks per lane per tile extern __shared__ __align__(16) float tile[]; // [T][TILEV] @@ -272,8 +307,10 @@ __global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { const bool inject_block = blockIdx.x == DOWN_BLOCKS; const int row = inject_block ? warp : blockIdx.x * WARPS + warp; const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); - const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; - const uint4* w4 = reinterpret_cast(wrow); + const uint16_t* wmat = inject_block ? m.a[0].w_inject : m.a[0].w_down; + const float* sq = (Q8 && !inject_block) ? m.a[0].s_down : nullptr; // the inject rows stay bf16 + const bool q8 = Q8 && !inject_block; + const size_t row0 = (size_t) (active ? row : 0) * D; float acc[MAX_T]; #pragma unroll for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; @@ -281,7 +318,7 @@ __global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { uint4 wv[TQ]; if (active) { #pragma unroll - for (int q = 0; q < TQ; ++q) wv[q] = __ldg(w4 + base / 8 + lane + 32 * q); + for (int q = 0; q < TQ; ++q) wv[q] = ldw(wmat, sq, row0 + (size_t) base + (size_t) (lane + 32 * q) * 8); } __syncthreads(); // the previous tile is consumed const float4* src4 = reinterpret_cast(m.xn); @@ -297,7 +334,7 @@ __global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { const int j = lane + 32 * q; #pragma unroll for (int k = 0; k < MAX_T; ++k) - if (k < T) acc[k] += dot8(wv[q], tile + k * TILEV + j * 8); + if (k < T) acc[k] += dotw(q8, wv[q], tile + k * TILEV + j * 8); } } if (!active) return; @@ -322,7 +359,7 @@ constexpr int UPM_BLOCKS = N / UPM_COLS; // 160 // `gr_up_kernel` for T tokens: each row of w_up read once; the T dots reduced by xor so every lane holds every // sum, and lane k runs token k's epilogue - the T epilogues in parallel instead of one after another. -template +template __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { __shared__ __align__(16) float lo[MAX_T][LR]; __shared__ float g[MAX_T][HC][UPM_COLS]; @@ -333,9 +370,16 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { __syncthreads(); for (int r = warp; r < HC * UPM_COLS; r += WARPS) { const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; - const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); - const Bf16x8 wa = unpack8(__ldg(w4 + lane)); - const Bf16x8 wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); + uint4 qa = make_uint4(0, 0, 0, 0), qb = make_uint4(0, 0, 0, 0); + Bf16x8 wa{}, wb{}; + if constexpr (Q8) { + qa = ldw(m.a[0].w_up, m.a[0].s_up, (size_t) i * LR + (size_t) lane * 8); + if (lane < LR / 8 - 32) qb = ldw(m.a[0].w_up, m.a[0].s_up, (size_t) i * LR + (size_t) (32 + lane) * 8); + } else { + const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); + wa = unpack8(__ldg(w4 + lane)); + wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); + } // the epilogue inputs of this lane's token, fetched while the dots run float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; bool apply = false; @@ -351,8 +395,14 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { #pragma unroll for (int k = 0; k < MAX_T; ++k) { if (!EXACT_T && k >= T) break; - float acc = dot8u_ptr(wa, lo[k] + lane * 8); - if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); + float acc; + if constexpr (Q8) { + acc = dotw(true, qa, lo[k] + lane * 8); + if (lane < LR / 8 - 32) acc += dotw(true, qb, lo[k] + (32 + lane) * 8); + } else { + acc = dot8u_ptr(wa, lo[k] + lane * 8); + if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); + } acc = warp_sum(acc); if (lane == k) mine = acc; } @@ -941,8 +991,12 @@ int down_chunk(bool staged, int* tile_out) { if (optin > 0 && want > optin) want = optin; if (small_tile) { cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + cudaFuncSetAttribute(gr_down_multi_kernel<1280, kFusedGrMaxT, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + cudaFuncSetAttribute(gr_down_multi_kernel<1280, 4, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); } else { cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + cudaFuncSetAttribute(gr_down_multi_kernel<2560, kFusedGrMaxT, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + cudaFuncSetAttribute(gr_down_multi_kernel<2560, 4, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); } auto set_staged_attr = [&](auto kernel, int max_t) { int ws = (int) (2 * max_t * H_TILE * sizeof(float)); @@ -1031,6 +1085,7 @@ bool qfuse_hc_local() { } void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { const int n_tok = m.T; + const bool q8w = m.a[0].s_down != nullptr; // STRATA_HC_REQ8: w_down / w_up hold int8 codes #if STRATA_GR_FAST_BUILD // gfx906: the latency-hidden norm/up (STRATA_GR_FAST=0: off) - the same sums in the same order as the kernels // they replace (gr_parity checks the multi-token read against single-token calls bitwise) @@ -1047,7 +1102,8 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long } else gr_norm_multi_kernel<<>>(m); #endif if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); - const bool staged = variant >= kHcStaged; + // STRATA_HC_Q8: the staged down kernel reads bf16 only, so Q8 weights take split's down kernel (the plain one) + const bool staged = variant >= kHcStaged && m.a[0].s_down == nullptr; int tv = 2560; const int chunk_tok = down_chunk(staged, &tv); const size_t per_tok = (staged ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); @@ -1083,20 +1139,26 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long else if (max4) gr_down_staged_kernel<4><<>>(c); else gr_down_staged_kernel<><<>>(c); } else if (tv == 1280) { - if (max4) gr_down_multi_kernel<1280, 4><<>>(c); + if (q8w) { // STRATA_HC_REQ8 + if (max4) gr_down_multi_kernel<1280, 4, true><<>>(c); + else gr_down_multi_kernel<1280, kFusedGrMaxT, true><<>>(c); + } else if (max4) gr_down_multi_kernel<1280, 4><<>>(c); else gr_down_multi_kernel<1280><<>>(c); } else { - if (max4) gr_down_multi_kernel<2560, 4><<>>(c); + if (q8w) { // STRATA_HC_REQ8 + if (max4) gr_down_multi_kernel<2560, 4, true><<>>(c); + else gr_down_multi_kernel<2560, kFusedGrMaxT, true><<>>(c); + } else if (max4) gr_down_multi_kernel<2560, 4><<>>(c); else gr_down_multi_kernel<2560><<>>(c); } } if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); #if STRATA_GR_FAST_BUILD - if (fast) gr_up_fast_kernel<<>>(m); + if (fast && !q8w) gr_up_fast_kernel<<>>(m); else #endif #if !STRATA_GR_FAST_BUILD - if (m.a[0].q8_mixed != nullptr && qfuse_hc_local()) { + if (!q8w && m.a[0].q8_mixed != nullptr && qfuse_hc_local()) { switch (no_multi_gr ? kFusedGrMaxT : n_tok) { case 1: gr_up_q32_kernel<1, true><<>>(m); break; case 2: gr_up_q32_kernel<2, true><<>>(m); break; @@ -1109,6 +1171,17 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long return; } #endif + if (q8w) { // STRATA_HC_REQ8: the up kernel on int8 rows + switch (no_multi_gr ? kFusedGrMaxT : n_tok) { + case 1: gr_up_multi_kernel<1, true, true><<>>(m); break; + case 2: gr_up_multi_kernel<2, true, true><<>>(m); break; + case 3: gr_up_multi_kernel<3, true, true><<>>(m); break; + case 4: gr_up_multi_kernel<4, true, true><<>>(m); break; + case 5: gr_up_multi_kernel<5, true, true><<>>(m); break; + case 6: gr_up_multi_kernel<6, true, true><<>>(m); break; + default: gr_up_multi_kernel<<>>(m); break; + } + } else switch (no_multi_gr ? kFusedGrMaxT : n_tok) { case 1: gr_up_multi_kernel<1, true><<>>(m); break; case 2: gr_up_multi_kernel<2, true><<>>(m); break; @@ -2022,7 +2095,7 @@ bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi split3[dev3] = split; } } - const int split = v3 && dev3 >= 0 && dev3 < 64 ? split3[dev3] : -1; + const int split = v3 && dev3 >= 0 && dev3 < 64 && a[0].s_down == nullptr && a[0].s_up == nullptr ? split3[dev3] : -1; if (split > 0) { // 2 kernels; scratch = partials + sums of squares float* part = xn_scratch; float* ssg = xn_scratch + (size_t) n_tok * HC * 2 * PR; // room for S = 2 @@ -2058,7 +2131,7 @@ bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi // fused_gr_read, so the multi-token read is then no longer bitwise equal to T single-token calls (gr_parity's // contract); off by default for that reason. static const bool split_on = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "1"; - if (split_on) { + if (split_on && a[0].s_down == nullptr) { // its K-split down reads bf16 rows (not STRATA_HC_REQ8) const bool fast = gr_fast(); if (fast) gr_norm_fast_kernel<<>>(m); else gr_norm_multi_kernel<<>>(m); @@ -2135,8 +2208,13 @@ void fused_gr_read(const FusedGrArgs& a, void* stream) { std::exit(1); } cudaStream_t st = (cudaStream_t) stream; - gr_down_kernel<<>>(a); - gr_up_kernel<<>>(a); + if (a.s_down != nullptr) { // STRATA_HC_REQ8 + gr_down_kernel<<>>(a); + gr_up_kernel<<>>(a); + } else { + gr_down_kernel<<>>(a); + gr_up_kernel<<>>(a); + } const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "fused_gr_read: %s\n", cudaGetErrorString(e)); @@ -2330,4 +2408,20 @@ void fused_gr_check() { } +namespace { +__global__ void hc_q8_bf16_kernel(const int8_t* __restrict__ q, const float* __restrict__ sc, uint16_t* __restrict__ out, + long long n) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float v = sc[i / 32] * (float) q[i]; + uint32_t b = __float_as_uint(v); + b += 0x7fffu + ((b >> 16) & 1u); // round to nearest even (the values are finite) + out[i] = (uint16_t) (b >> 16); +} +} // namespace + +void hc_q8_to_bf16(const void* codes, const float* scales, uint16_t* out, long long n, void* stream) { + hc_q8_bf16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>((const int8_t*) codes, scales, out, n); +} + } // namespace strata::kernels diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 47e0e76e..6ee46339 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -737,6 +737,16 @@ template<> struct Split<16> { // IQ2_XXS const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); return d * sumi; } + // `apply` with the q8_1 block already in registers: u = its 8 words, d8 = __low2float(ds). Same operations in + // the same order (the EXPDEC kernels, see expdec below). + __device__ static float apply_u(const W& r, const int (&u)[8], float d8) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], u[j], sumi); + sumi = sumi * r.ls / 8; + const float d = r.dw * d8; + return d * sumi; + } }; // IQ2_XS and IQ2_S share the apply: two half sums, two 4-bit scales struct SplitLs2 { @@ -751,6 +761,16 @@ struct SplitLs2 { const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); return d * sumi; } + __device__ static float apply_u(const W& r, const int (&u)[8], float d8) { + int sumi0 = 0, sumi1 = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], u[j], sumi0); +#pragma unroll + for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], u[j], sumi1); + const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = r.dw * d8; + return d * sumi; + } }; template<> inline constexpr bool kSplit<17> = true; template<> struct Split<17> : SplitLs2 { // IQ2_XS @@ -810,15 +830,18 @@ template<> inline constexpr bool kSplit<18> = true; template<> struct Split<18> { // IQ3_XXS struct W { int g[8]; int ls; float dw; }; template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); const uint8_t* q3 = (const uint8_t*) &q3_packed; const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); + const uint32_t* grid_lut; // the same 256 words either way (expdec stages them) + if constexpr (STAGE_GRID) grid_lut = s_grid; + else grid_lut = iq3xxs_grid; W r; #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); + const int2 grid_pos = make_int2(grid_lut[q3[l0 + 0]], grid_lut[q3[l0 + 1]]); const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); const int signs0 = __vcmpne4(signs & 0x08040201, 0); r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); @@ -837,23 +860,34 @@ template<> struct Split<18> { // IQ3_XXS const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); return d * sumi; } + __device__ static float apply_u(const W& r, const int (&u)[8], float d8) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], u[j], sumi); + sumi = (r.ls * sumi + sumi / 2) / 2; + const float d = r.dw * d8; + return d * sumi; + } }; template<> inline constexpr bool kSplit<21> = true; template<> struct Split<21> { // IQ3_S struct W { int g[8]; int ls; float dw; }; template - __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) { + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); const uint8_t* qs = (const uint8_t*) &qs_packed; const int qh = bq3->qh[iqs / 2]; const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + const uint32_t* grid_lut; // the same 512 words either way (expdec stages them) + if constexpr (STAGE_GRID) grid_lut = s_grid; + else grid_lut = iq3s_grid; W r; #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { - const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], - iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + const int2 grid_pos = make_int2(grid_lut[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + grid_lut[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); @@ -871,6 +905,14 @@ template<> struct Split<21> { // IQ3_S const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); return d * sumi; } + __device__ static float apply_u(const W& r, const int (&u)[8], float d8) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], u[j], sumi); + sumi *= r.ls; + const float d = r.dw * d8; + return d * sumi; + } }; template<> inline constexpr bool kSplit<29> = true; template<> struct Split<29> { // IQ1_M @@ -942,6 +984,16 @@ template<> struct Split<20> { // IQ4_NL const float d = r.dw * __low2float(bq8_1->ds); return d * sumi; } + // `apply` with the block's words in registers: p0 = words iqs, iqs + 1; p1 = words iqs + 4, iqs + 5; d8 = __low2float(ds) + __device__ static float apply_u(const W& r, int2 p0, int2 p1, float d8) { + int sumi = 0; + sumi = ggml_cuda_dp4a(r.v[0].x, p0.x, sumi); + sumi = ggml_cuda_dp4a(r.v[0].y, p1.x, sumi); + sumi = ggml_cuda_dp4a(r.v[1].x, p0.y, sumi); + sumi = ggml_cuda_dp4a(r.v[1].y, p1.y, sumi); + const float d = r.dw * d8; + return d * sumi; + } }; template<> inline constexpr bool kSplit<23> = true; template<> struct Split<23> { // IQ4_XS @@ -1002,6 +1054,16 @@ template<> struct Split<42> { // Q2_0 const float d8 = __low2float(bq8_1_chunk->ds); return r.d2 * d8 * sumi; } + // `apply` with the q8_1 block (2 kbx + iqs) in registers: u = its 8 words, d8 = __low2float(ds) + __device__ static float apply_u(const W& r, const int (&u)[8], float d8) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi = ggml_cuda_dp4a(u[j * 2 + 0], r.qx[j], sumi); + sumi = ggml_cuda_dp4a(u[j * 2 + 1], r.qy[j], sumi); + } + return r.d2 * d8 * sumi; + } }; template<> inline constexpr bool kSplit<40> = true; template<> struct Split<40> { // NVFP4: vec_dot_nvfp4_q8_1's two 16-value sub-blocks, weights decoded once per call @@ -1658,6 +1720,369 @@ __global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned l } } +// ---------------------------------------------------------------- EXPDEC (STRATA_EXPDEC=1): the group's activations +// in shared memory, R rows per lane +// +// native_gu_multi_kernel / native_down_multi_kernel decode each weight part once and apply it to every entry of the +// group, but the gate/up apply re-reads the entry's q8_1 block from global memory with 9 scattered 4-byte loads +// (36-byte blocks: a warp's load touches 32 sectors), so an entry costs about 60% of a whole expert (nsys, 2080 Ti, +// L02 at 131k: ~2.6 us per expert and ~1.6 us per entry and layer) although it reads nothing from DRAM. Here a +// block stages its group's entries (ED_NC at a time, as the default) in shared memory laid out so that a call's +// words are two 16-byte loads (gate/up, Q2_0 down: the block's two halves in separate planes, conflict-free) or two +// 8-byte loads (IQ4_NL down), the fp16 block scale already a float; every lane computes R rows at once, so the +// activation words are loaded once per R rows; the IQ3_XXS / IQ3_S codebooks are staged too (IQ2_* already were), +// and a block takes `rb` rows (auto: the most that keep ~STRATA_EXPDEC_MINBLK blocks in flight) instead of 16. +// Each (row, entry) sum is the default kernel's sum tree (row_dot_80_sub16 / row_dot_40_sub8 / row_dot_20_sub16: the +// same lane does the same calls in the same order with the same operations, `apply_u` = `apply` on the block's +// words), so the output is bitwise the same (expdec_bench checks it; docs/EXPERTDEC.md). +#ifndef STRATA_EXPDEC_MINB +#define STRATA_EXPDEC_MINB 4 // gate/up __launch_bounds__ min blocks per SM by default (STRATA_EXPDEC_MINB at runtime): 4 = up to 64 + // registers, as the default kernels (bench: equal on the 2080 Ti, 0.87-0.95 on the 3060); 2 = up to 128 +#endif +constexpr int ED_NC = GRP_NC; // entries staged at once +constexpr int ED_XB = 80; // q8_1 blocks of a gate/up row (n_embd 2560) +constexpr int ED_HB = 20; // q8_1 blocks of a down row (n_ff 640) + +// the codebook of a gate/up format in shared memory: words, and the copy (every thread of the block; sync after) +template struct EdGrid; +template<> struct EdGrid<16> { static constexpr int words = 512; + __device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2xxs_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 256; i += 256) dst[i] = src[i]; } }; +template<> struct EdGrid<17> { static constexpr int words = 1024; + __device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2xs_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 512; i += 256) dst[i] = src[i]; } }; +template<> struct EdGrid<22> { static constexpr int words = 2048; + __device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2s_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 1024; i += 256) dst[i] = src[i]; } }; +template<> struct EdGrid<18> { static constexpr int words = 256; + __device__ static void copy(uint32_t* s, int tid) { for (int i = tid; i < 256; i += 256) s[i] = iq3xxs_grid[i]; } }; +template<> struct EdGrid<21> { static constexpr int words = 512; + __device__ static void copy(uint32_t* s, int tid) { for (int i = tid; i < 512; i += 256) s[i] = iq3s_grid[i]; } }; + +// One entry's q8_1 row (XB blocks of 36 bytes, 4-byte aligned) into shared memory as entry c: the 8 words of block k +// in planes (HALVES: s_u[(2 c + h) XB + k] = words 4h..4h+3, two 16-byte loads per call, conflict-free over 16 +// consecutive k; else s_u[(c XB + k) 2 + h], the block's 32 bytes together, for the IQ4_NL pairs) and the fp16 scale +// as s_ds[c XB + k] = __low2float(ds), the value `apply` computes. All 256 threads. +template +__device__ __forceinline__ void ed_stage_entry(int4* __restrict__ s_u, float* __restrict__ s_ds, int c, + const block_q8_1* __restrict__ src, int tid) { + int* su = (int*) s_u; + const int* w32 = (const int*) src; + for (int w = tid; w < XB * 9; w += 256) { + const int k = w / 9, j = w - k * 9; + const int v = w32[w]; + if (j == 0) { + const half2 h = *reinterpret_cast(&v); + s_ds[c * XB + k] = __low2float(h); + } else { + const int q = j - 1; + if constexpr (HALVES) su[((c * 2 + (q >> 2)) * XB + k) * 4 + (q & 3)] = v; + else su[(c * XB + k) * 8 + q] = v; + } + } +} +template +__device__ __forceinline__ void ed_load_u(const int4* __restrict__ s_u, int c, int k, int (&u)[8]) { + const int4 a = s_u[(c * 2 + 0) * XB + k], b = s_u[(c * 2 + 1) * XB + k]; + u[0] = a.x; u[1] = a.y; u[2] = a.z; u[3] = a.w; + u[4] = b.x; u[5] = b.y; u[6] = b.z; u[7] = b.w; +} + +// R gate/up rows against the NC staged entries, lane t of a 16-lane sub-warp: row_dot_80_sub16's tree (calls t, +// t+32, t+64 into s; t+16, t+48 into s16; s = __fadd_rn(s, s16); xor 8-4-2-1), every call's weight part decoded once +// per row and the entry's block loaded once per NC x R products. +template +__device__ __forceinline__ void ed_gu_rows(const uint8_t* const* wr, const int4* __restrict__ s_u, + const float* __restrict__ s_ds, const uint32_t* __restrict__ s_grid, int t, + float (&s)[R][NC]) { + using F = Fmt; + using S = Split; + float s16[R][NC]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) { s[r][c] = 0.0f; s16[r][c] = 0.0f; } +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int k = t + 32 * j; + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = S::template load(wr[r], kbx, iqs, s_grid); +#pragma unroll + for (int c = 0; c < NC; ++c) { + int u[8]; + ed_load_u(s_u, c, k, u); + const float d8 = s_ds[c * ED_XB + k]; +#pragma unroll + for (int r = 0; r < R; ++r) s[r][c] += S::apply_u(w[r], u, d8); + } + } +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int k = t + 16 + 32 * j; + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = S::template load(wr[r], kbx, iqs, s_grid); +#pragma unroll + for (int c = 0; c < NC; ++c) { + int u[8]; + ed_load_u(s_u, c, k, u); + const float d8 = s_ds[c * ED_XB + k]; +#pragma unroll + for (int r = 0; r < R; ++r) s16[r][c] += S::apply_u(w[r], u, d8); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[r][c] = __fadd_rn(s[r][c], s16[r][c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[r][c] += __shfl_xor_sync(0xffffffffu, s[r][c], o); + } +} + +// gate/up: 16 sub-warps of 16 lanes, R rows each = 16 R rows per pass, `rb` rows per block (a multiple of 16 R; 2 n_ff +// is one too, so a pass is whole or absent for the entire block). Group stride as native_gu_multi_kernel. +template +__global__ void __launch_bounds__(256, MINB) expdec_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, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up, int rb) { + const int ng = *n_groups; + if (blockIdx.y >= ng) return; + __shared__ alignas(16) int4 s_u[ED_NC * 2 * ED_XB]; + __shared__ float s_ds[ED_NC * ED_XB]; + STRATA_SHARED_ALIGN16_U32(s_grid_buf, EdGrid::words); + const int tid = threadIdx.x; + EdGrid::copy(s_grid_buf, tid); // visible after the staging's __syncthreads + const int sw = tid >> 4, t = tid & 15; + const int nrow = 2 * (int) L.n_ff, n_ff = (int) L.n_ff; + const int row_base = blockIdx.x * rb; + for (int g = blockIdx.y; g < ng; g += gridDim.y) { + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += ED_NC) { + const int n = min(ED_NC, e1 - e); + __syncthreads(); + for (int c = 0; c < n; ++c) ed_stage_entry(s_u, s_ds, c, xq + (size_t) ent_tok[e + c] * ED_XB, tid); + __syncthreads(); + for (int p = 0; p * 16 * R < rb; ++p) { + const int row0 = row_base + p * 16 * R + sw * R; + if (row0 >= nrow) break; // uniform over the block + const bool is_up = row0 >= n_ff; + const int r0 = is_up ? row0 - n_ff : row0; + const uint8_t* wr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) wr[r] = blob + (is_up ? L.up_off : 0) + (size_t) (r0 + r) * L.gu_row; + float* dst = is_up ? up : gate; + auto run = [&](auto nc) { + constexpr int NC = decltype(nc)::value; + float s[R][NC]; + ed_gu_rows(wr, s_u, s_ds, s_grid_buf, t, s); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (t == c) +#pragma unroll + for (int r = 0; r < R; ++r) dst[(size_t) (e + c) * n_ff + r0 + r] = s[r][c]; + }; + switch (n) { + case 1: run(std::integral_constant{}); break; + case 2: run(std::integral_constant{}); break; + case 3: run(std::integral_constant{}); break; + default: run(std::integral_constant{}); break; + } + } + } + } +} + +// R IQ4_NL down rows, lane t of an 8-lane sub-warp: row_dot_40_sub8's tree. s_p: the block's 8 words together +// (ed_stage_entry), read as the int2 pairs (iqs, iqs + 1) and (iqs + 4, iqs + 5). +template +__device__ __forceinline__ void ed_d20_rows(const uint8_t* const* wr, const int2* __restrict__ s_p, + const float* __restrict__ s_ds, int t, float (&s)[R][NC]) { + using F = Fmt<20>; + using S = Split<20>; + auto term = [&](int k, int r, int c, const typename S::W& w) -> float { + const int kbx = k / F::ipb, par = k & 1; + const int2 p0 = s_p[(c * ED_HB + kbx) * 4 + par], p1 = s_p[(c * ED_HB + kbx) * 4 + 2 + par]; + return S::apply_u(w, p0, p1, s_ds[c * ED_HB + kbx]); + }; + auto loadw = [&](int k, typename S::W (&w)[R]) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = S::load(wr[r], kbx, iqs); + }; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) s[r][c] = 0.0f; +#pragma unroll + for (int j = 0; j < 2; ++j) { // k = t, t + 32 + const int k = t + 32 * j; + typename S::W w[R]; + loadw(k, w); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int r = 0; r < R; ++r) s[r][c] += term(k, r, c, w[r]); + } + { + const int k = t + 16; + typename S::W w[R]; + loadw(k, w); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int r = 0; r < R; ++r) { + float s16 = 0.0f; + s16 += term(k, r, c, w[r]); + s[r][c] = __fadd_rn(s[r][c], s16); + } + } + float s8[R][NC]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) s8[r][c] = 0.0f; + { + const int k = t + 8; + typename S::W w[R]; + loadw(k, w); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int r = 0; r < R; ++r) s8[r][c] += term(k, r, c, w[r]); + } + { + const int k = t + 24; + typename S::W w[R]; + loadw(k, w); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int r = 0; r < R; ++r) { + float s24 = 0.0f; + s24 += term(k, r, c, w[r]); + s[r][c] = __fadd_rn(s[r][c], __fadd_rn(s8[r][c], s24)); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int o = 4; o > 0; o >>= 1) s[r][c] += __shfl_xor_sync(0xffffffffu, s[r][c], o); +} + +// R Q2_0 down rows, lane t of a 16-lane sub-warp: row_dot_20_sub16's tree (call t; call t + 16 for t < 4 into s16). +template +__device__ __forceinline__ void ed_d42_rows(const uint8_t* const* wr, const int4* __restrict__ s_u, + const float* __restrict__ s_ds, int t, float (&s)[R][NC]) { + using F = Fmt<42>; + using S = Split<42>; + { + const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = S::load(wr[r], kbx, iqs); +#pragma unroll + for (int c = 0; c < NC; ++c) { + int u[8]; + ed_load_u(s_u, c, k, u); + const float d8 = s_ds[c * ED_HB + k]; +#pragma unroll + for (int r = 0; r < R; ++r) { s[r][c] = 0.0f; s[r][c] += S::apply_u(w[r], u, d8); } + } + } + float s16[R][NC]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) s16[r][c] = 0.0f; + if (t < 4) { + const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = S::load(wr[r], kbx, iqs); +#pragma unroll + for (int c = 0; c < NC; ++c) { + int u[8]; + ed_load_u(s_u, c, k, u); + const float d8 = s_ds[c * ED_HB + k]; +#pragma unroll + for (int r = 0; r < R; ++r) s16[r][c] += S::apply_u(w[r], u, d8); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) { + s[r][c] = __fadd_rn(s[r][c], s16[r][c]); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s[r][c] += __shfl_xor_sync(0xffffffffu, s[r][c], o); + } +} + +// down (IQ4_NL: 32 sub-warps of 8 lanes; Q2_0: 16 of 16), R rows per lane, `rb` rows per block (a multiple of the +// rows per pass; n_embd too). The entries' h rows are contiguous in hq (entry e at e * ED_HB). +template +__global__ void __launch_bounds__(256, STRATA_EXPDEC_MINB) expdec_down_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, int rb) { + const int ng = *n_groups; + if (blockIdx.y >= ng) return; + constexpr int LANES = TD == 20 ? 8 : 16; + constexpr int RPP = (256 / LANES) * R; // rows per pass + __shared__ alignas(16) int4 s_u[ED_NC * 2 * ED_HB]; + __shared__ float s_ds[ED_NC * ED_HB]; + const int tid = threadIdx.x; + const int sw = tid / LANES, t = tid % LANES; + const int nrow = (int) L.n_embd; + const int row_base = blockIdx.x * rb; + for (int g = blockIdx.y; g < ng; g += gridDim.y) { + const uint8_t* blob = (const uint8_t*) grp_ptr[g] + L.down_off; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += ED_NC) { + const int n = min(ED_NC, e1 - e); + __syncthreads(); + for (int c = 0; c < n; ++c) ed_stage_entry(s_u, s_ds, c, hq + (size_t) (e + c) * ED_HB, tid); + __syncthreads(); + for (int p = 0; p * RPP < rb; ++p) { + const int row0 = row_base + p * RPP + sw * R; + if (row0 >= nrow) break; // uniform over the block + const uint8_t* wr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) wr[r] = blob + (size_t) (row0 + r) * L.d_row; + auto run = [&](auto nc) { + constexpr int NC = decltype(nc)::value; + float s[R][NC]; + if constexpr (TD == 20) ed_d20_rows(wr, (const int2*) s_u, s_ds, t, s); + else ed_d42_rows(wr, s_u, s_ds, t, s); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (t == c) { + const size_t o = (size_t) ent_dst[e + c] * L.n_embd + row0; +#pragma unroll + for (int r = 0; r < R; ++r) out[o + r] = s[r][c]; + } + }; + switch (n) { + case 1: run(std::integral_constant{}); break; + case 2: run(std::integral_constant{}); break; + case 3: run(std::integral_constant{}); break; + default: run(std::integral_constant{}); break; + } + } + } + } +} + // ---------------------------------------------------------------- q8_1 (quantize.cu) // value i of a q8_1 row set (the warp holds block i / 32, lane = i % 32) __device__ __forceinline__ void q8_1_store(const float xi, block_q8_1* __restrict__ y, const long long i) { @@ -2840,6 +3265,144 @@ void s27_launch_ts(bool ts, const NativeExpertLayout& L, int64_t cap_groups, cud else s27_launch(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh); } +// ---- EXPDEC launch: knobs, shapes, rows per block +int env_int_or(const char* name, int dflt) { + const char* v = std::getenv(name); + return v != nullptr && v[0] != '\0' ? std::atoi(v) : dflt; +} +int g_expdec = env_on("STRATA_EXPDEC") ? 1 : 0; +int g_expdec_r = env_int_or("STRATA_EXPDEC_R", 1); // gate/up rows per lane: 1, 2 (bench: R=1 wins on the 2080 Ti) +int g_expdec_dr = env_int_or("STRATA_EXPDEC_DR", 4); // down rows per lane: 1, 2, 4 (Q2_0: R=4 wins on both cards) +int g_expdec_minb = env_int_or("STRATA_EXPDEC_MINB", STRATA_EXPDEC_MINB); // gate/up __launch_bounds__ min blocks: 2 (<= 128 regs) or 4 (<= 64) +int g_expdec_d20 = env_int_or("STRATA_EXPDEC_D20", 0); // 1: EXPDEC also for the IQ4_NL down (bench: no gain, default kernel) +// 1: EXPDEC for the down too (Q2_0; IQ4_NL with _D20). Default 0: in the engine (nsys of a 131k decode) the Q2_0 down +// with EXPDEC was ~10% slower than the default kernel although the bench alone had it at 0.78, so by default EXPDEC +// takes the gate/up only (-20/-23% at T >= 2 on an RTX 2080 Ti in the engine). +int g_expdec_down = env_int_or("STRATA_EXPDEC_DOWN", 0); +int g_expdec_rb = env_int_or("STRATA_EXPDEC_RB", 0); // gate/up rows per block (0 = auto) +int g_expdec_drb = env_int_or("STRATA_EXPDEC_DRB", 0); // down rows per block (0 = auto) +int g_expdec_minblk = env_int_or("STRATA_EXPDEC_MINBLK", 800); // auto: the most rows per block that keep this many blocks +int expdec_r() { return g_expdec_r == 2 ? 2 : 1; } +int expdec_dr() { return g_expdec_dr == 1 || g_expdec_dr == 2 ? g_expdec_dr : 4; } + +bool expdec_gu_ok(const NativeExpertLayout& L) { + const bool fmt = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22; + return fmt && L.n_embd == 32 * ED_XB && L.n_ff % 64 == 0 && L.n_ff > 0; +} +bool expdec_down_ok(const NativeExpertLayout& L) { + return g_expdec_down && ((L.d_type == 20 && g_expdec_d20) || L.d_type == 42) && L.n_ff == 32 * ED_HB && L.n_embd % 128 == 0 && + L.n_embd > 0; +} +// rows per block: `knob` rounded up to the rows per pass, or (0) doubled from one pass while ceil(nrow / rb) x +// cap_groups blocks stay >= g_expdec_minblk (cap_groups: the launch's group rows; every block row g >= n_groups returns) +int expdec_rows_per_block(int nrow, int rpp, int64_t cap_groups, int knob) { + if (knob > 0) { + int rb = (knob + rpp - 1) / rpp * rpp; + return rb > nrow ? nrow : rb; + } + int rb = rpp; + const int64_t cap = cap_groups > 0 ? cap_groups : 1; + while (rb * 2 <= nrow && ((int64_t) ((nrow + 2 * rb - 1) / (2 * rb))) * cap >= g_expdec_minblk) rb *= 2; + return rb; +} + +template +void expdec_gu_r(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_tok, const block_q8_1* X, const NativeExpertLayout& L, + float* gate, float* up) { + const int nrow = 2 * (int) L.n_ff; + const int rb = expdec_rows_per_block(nrow, 16 * R, cap_groups, g_expdec_rb); + const dim3 grid((unsigned) ((nrow + rb - 1) / rb), (unsigned) gy); + expdec_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, rb); +} +template +void expdec_gu_t(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_tok, const block_q8_1* X, const NativeExpertLayout& L, + float* gate, float* up) { + const bool b4 = g_expdec_minb >= 4; + if (expdec_r() == 2) { + if (b4) expdec_gu_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + else expdec_gu_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + } else { + if (b4) expdec_gu_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + else expdec_gu_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + } +} +// One line on stderr per (role, format, taken or not), the first time STRATA_EXPDEC=1 meets it: the proof in the +// engine's log that the EXPDEC kernels are the ones launched (or captured into the window's graph), with the +// choices in force. +void expdec_note(const NativeExpertLayout& L, bool gu, bool taken, cudaStream_t s, int64_t gy, int64_t cap_groups) { + static bool seen[2][64][2] = {}; + const int ty = gu ? L.gu_type : L.d_type; + if (ty < 0 || ty >= 64 || seen[gu ? 0 : 1][ty][taken ? 1 : 0]) return; + seen[gu ? 0 : 1][ty][taken ? 1 : 0] = true; + cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone; + cudaStreamIsCapturing(s, &cs); + int dev = -1; + cudaGetDevice(&dev); + if (!taken) { + std::fprintf(stderr, "strata expdec: CUDA%d %s type %d (n_embd %lld, n_ff %lld) not covered: the default kernel runs\n", dev, + gu ? "gate/up" : "down", ty, (long long) L.n_embd, (long long) L.n_ff); + return; + } + if (gu) { + const int R = expdec_r(), rb = expdec_rows_per_block(2 * (int) L.n_ff, 16 * R, cap_groups, g_expdec_rb); + std::fprintf(stderr, "strata expdec: CUDA%d gate/up type %d: expdec_gu_kernel R %d MINB %d, %d rows per block, grid %d x %lld " + "(cap %lld groups)%s\n", dev, ty, R, g_expdec_minb >= 4 ? 4 : 2, rb, (2 * (int) L.n_ff + rb - 1) / rb, + (long long) gy, (long long) cap_groups, cs != cudaStreamCaptureStatusNone ? ", captured into a graph" : ""); + } else { + const int R = expdec_dr(), lanes = ty == 20 ? 8 : 16; + const int rb = expdec_rows_per_block((int) L.n_embd, (256 / lanes) * R, cap_groups, g_expdec_drb); + std::fprintf(stderr, "strata expdec: CUDA%d down type %d: expdec_down_kernel R %d, %d rows per block, grid %d x %lld " + "(cap %lld groups)%s\n", dev, ty, R, rb, ((int) L.n_embd + rb - 1) / rb, (long long) gy, + (long long) cap_groups, cs != cudaStreamCaptureStatusNone ? ", captured into a graph" : ""); + } +} + +// false: EXPDEC is off or does not take this layout (the caller launches the default kernels) +bool expdec_gu(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_tok, const block_q8_1* X, float* gate, + float* up) { + if (!g_expdec || g_old_kernels) return false; + if (!expdec_gu_ok(L)) { expdec_note(L, true, false, s, gy, cap_groups); return false; } + expdec_note(L, true, true, s, gy, cap_groups); + switch (L.gu_type) { + case 16: expdec_gu_t<16>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + case 17: expdec_gu_t<17>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + case 18: expdec_gu_t<18>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + case 21: expdec_gu_t<21>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + default: expdec_gu_t<22>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + } + return true; +} +template +void expdec_down_r(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, const NativeExpertLayout& L, float* out) { + constexpr int LANES = TD == 20 ? 8 : 16; + const int nrow = (int) L.n_embd; + const int rb = expdec_rows_per_block(nrow, (256 / LANES) * R, cap_groups, g_expdec_drb); + const dim3 grid((unsigned) ((nrow + rb - 1) / rb), (unsigned) gy); + expdec_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out, rb); +} +template +void expdec_down_t(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, const NativeExpertLayout& L, float* out) { + switch (expdec_dr()) { + case 1: expdec_down_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; + case 2: expdec_down_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; + default: expdec_down_r(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; + } +} +bool expdec_down(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) { + if (!g_expdec || g_old_kernels) return false; + if (!expdec_down_ok(L)) { expdec_note(L, false, false, s, gy, cap_groups); return false; } + expdec_note(L, false, true, s, gy, cap_groups); + if (L.d_type == 20) expdec_down_t<20>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else expdec_down_t<42>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + return true; +} + template void launch_gu(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, const NativeExpertLayout& L, @@ -3638,6 +4201,36 @@ bool g_grouped_v1 = env_on("STRATA_GROUPED_V1"); void native_grouped_set_v1(bool v1) { g_grouped_v1 = v1; } +void native_expert_set_expdec(int on) { g_expdec = on ? 1 : 0; } +int native_expert_expdec() { return g_expdec; } +void native_expert_set_expdec_params(const NativeExpertExpdecParams& p) { + if (p.gu_rows_per_lane > 0) g_expdec_r = p.gu_rows_per_lane; + if (p.down_rows_per_lane > 0) g_expdec_dr = p.down_rows_per_lane; + if (p.gu_min_blocks_per_sm > 0) g_expdec_minb = p.gu_min_blocks_per_sm; + if (p.down_iq4_nl >= 0) g_expdec_d20 = p.down_iq4_nl; + if (p.down >= 0) g_expdec_down = p.down; + if (p.gu_rows_per_block >= 0) g_expdec_rb = p.gu_rows_per_block; + if (p.down_rows_per_block >= 0) g_expdec_drb = p.down_rows_per_block; + if (p.min_blocks > 0) g_expdec_minblk = p.min_blocks; +} +NativeExpertExpdecParams native_expert_expdec_params() { + NativeExpertExpdecParams p; + p.gu_rows_per_lane = expdec_r(); + p.down_rows_per_lane = expdec_dr(); + p.gu_min_blocks_per_sm = g_expdec_minb >= 4 ? 4 : 2; + p.down_iq4_nl = g_expdec_d20 ? 1 : 0; + p.down = g_expdec_down ? 1 : 0; + p.gu_rows_per_block = g_expdec_rb; + p.down_rows_per_block = g_expdec_drb; + p.min_blocks = g_expdec_minblk; + return p; +} +bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& down) { + gu = expdec_gu_ok(L); + down = expdec_down_ok(L); + return gu || down; +} + void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream, @@ -3769,6 +4362,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } else #undef STRATA_GU_AMD #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) { #define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; STRATA_GU_FMTS(STRATA_GU) @@ -3824,6 +4418,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long } else #undef STRATA_D_AMD #endif + if (!expdec_down(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, out)) // STRATA_EXPDEC=1 switch (L.d_type) { #define STRATA_DOWN(T) case T: launch_down(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; STRATA_D_FMTS(STRATA_DOWN) diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index d537fd5f..136eeb60 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -1154,6 +1154,8 @@ struct SmallTraits { // llama.cpp's generic multi-column table (ncols 2-4: 4 warps; 5-8: 2 warps; always 2 rows per block): faster, // equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently). bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured) +// B6 STRATA_B6_MMVQ_ROWS (lab, default 0 = off): see native_mmvq_set_b6_rows +int g_b6_rows = [] { const char* v = std::getenv("STRATA_B6_MMVQ_ROWS"); return v ? std::atoi(v) : 0; }(); // S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same static bool s26_tsum_on() { @@ -1303,10 +1305,174 @@ bool q8_0_rows1(int n_in, int n_out) { } } +// ---- B6 STRATA_B6_MMVQ_ROWS (lab, opt-in): the exact multi-column layout with each column's activation fragment +// loaded ONCE per weight block and reused across ROWS rows of the block (the default kernel reloads it for every row +// it applies it to, and the K-quant scales once per column). A thread keeps the same blocks (kbx = tid / T, stride +// BPI with WARPS warps), each (row, column) sum adds the same per-block values in the same order, and the cross-warp +// and warp reductions are the default kernel's: every output is bitwise the default exact layout's, so bitwise a +// single-column call. Only the formats with a B6X below; the others keep the default kernel. +template struct B6X { static constexpr bool ok = false; }; +template<> struct B6X { + static constexpr bool ok = true; + struct X { int u[2]; float d8[2]; }; + struct W { int vl, vh, sc[2]; float d; }; + __device__ static X xload(const Q81Block* x, int iqs) { + X r; + const int off = 4 * (iqs / 16) + (iqs % 16) / 8; // Q6KTraits::load's bq8_offset +#pragma unroll + for (int i = 0; i < 2; ++i) { + r.u[i] = reinterpret_cast(x[off + 2 * i].qs)[iqs % 8]; + r.d8[i] = __low2float(x[off + 2 * i].ds); + } + return r; + } + __device__ static W wload(const Q6KBlock* __restrict__ w, int iqs) { + const Q6KTraits::W t = Q6KTraits::load(w, iqs); + W r; + r.vl = t.vl; + r.vh = t.vh; + r.sc[0] = t.scales[0]; + r.sc[1] = t.scales[4]; + r.d = t.d; + return r; + } + __device__ static float dot(const W& w, const X& x) { // q6_q8_dot_impl, the scales already in registers + float sumf = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int vil = (w.vl >> (4 * i)) & 0x0f0f0f0f; + const int vih = ((w.vh >> (4 * i)) << 4) & 0x30303030; + const int vi = __vsubss4(vil | vih, 0x20202020); + sumf += x.d8[i] * (STRATA_DP4A(vi, x.u[i], 0) * w.sc[i]); + } + return w.d * sumf; + } +}; +template struct B6XK { // Q4_K (KIND 4) and Q5_K (KIND 5): the same activation fragment + static constexpr bool ok = true; + struct X { int u[4]; float d8[2]; }; + using W = typename T::W; + __device__ static X xload(const Q81Block* bq8, int iqs) { + X r; + const int off = 2 * ((iqs / 2) / 4); // the traits' bq8_offset +#pragma unroll + for (int i = 0; i < 2; ++i) { + const Q81Block* bq8i = bq8 + off + i; + r.d8[i] = __low2float(bq8i->ds); + const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); + r.u[2 * i] = q8[0]; + r.u[2 * i + 1] = q8[4]; + } + return r; + } + __device__ static W wload(const typename T::Block* __restrict__ w, int iqs) { return T::load(w, iqs); } + __device__ static float dot(const W& w, const X& x) { + const uint8_t* sc = reinterpret_cast(w.aux); + if constexpr (KIND == 4) return q4_q8_dot_impl(w.v, x.u, sc, sc + 2, w.dm, x.d8); + else return q5_q8_dot_impl(w.vl, w.vh, x.u, sc, sc + 2, w.dm, x.d8); + } +}; +template<> struct B6X : B6XK {}; +template<> struct B6X : B6XK {}; +template<> struct B6X { + static constexpr bool ok = true; + struct X { int u0[4], u1[4]; float dx; }; + using W = IQ4XSTraits::W; + __device__ static X xload(const Q81Block* x, int iqs) { + X r; +#pragma unroll + for (int j = 0; j < 4; ++j) { + r.u0[j] = reinterpret_cast(x[iqs / 4].qs)[j]; + r.u1[j] = reinterpret_cast(x[iqs / 4].qs)[j + 4]; + } + r.dx = __low2float(x[iqs / 4].ds); + return r; + } + __device__ static W wload(const IQ4XSBlock* __restrict__ w, int iqs) { return IQ4XSTraits::load(w, iqs); } + __device__ static float dot(const W& w, const X& x) { // IQ4XSTraits::apply + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi = STRATA_DP4A(w.v[j].x, x.u0[j], sumi); + sumi = STRATA_DP4A(w.v[j].y, x.u1[j], sumi); + } + sumi *= w.ls - 32; + const float d = w.dw * x.dx; + return d * sumi; + } +}; + +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void b6_mmvq_rows_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + using XB = B6X; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / F::DIV; + const int x_stride = n_in / Q8K; + const int kqs = F::kqs(tid); + float tmp[NCOLS][ROWS] = {}; + for (int kbx = tid / F::T; kbx < blocks_per_row; kbx += F::BPI) { + const int kby = kbx * F::KBY; + typename XB::X xv[NCOLS]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) xv[j] = XB::xload(x + std::size_t(j) * x_stride + kby, kqs); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const typename XB::W wv = XB::wload(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs); +#pragma unroll + for (int j = 0; j < NCOLS; ++j) tmp[j][i] += XB::dot(wv, xv[j]); + } + } + } + __shared__ float partial[WARPS - 1][NCOLS][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][j][i][threadIdx.x] = tmp[j][i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x]; + tmp[j][i] = warp_sum(tmp[j][i]); + if (threadIdx.x == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = tmp[j][i]; + } + } +} + +// the B6 launch for a format that has a B6X: true when it ran. g_b6_rows: 1 = 2 rows per block (the fastest on both +// cards in b6_mmvq_bench), else 2 / 4 / 8 rows. +template +bool b6_launch(const typename F::Block* w, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) { + if constexpr (!B6X::ok) { + return false; + } else { + if (g_b6_rows <= 0 || !g_multi_exact || s26_tsum_on() || n_in / F::DIV < 1) return false; + const int rows = g_b6_rows == 1 ? 2 : g_b6_rows; + const dim3 threads(WARP, WARPS); + if (rows == 2) + b6_mmvq_rows_kernel<<>>(w, x, y, n_in, n_out); + else if (rows == 8) + b6_mmvq_rows_kernel<<>>(w, x, y, n_in, n_out); + else + b6_mmvq_rows_kernel<<>>(w, x, y, n_in, n_out); + return true; + } +} + template void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) { const auto* w = static_cast(weights); const auto* x = static_cast(x_q8_1); + if (b6_launch(w, x, y, n_in, n_out, s)) return; // STRATA_B6_MMVQ_ROWS if (!g_multi_exact) { constexpr int NW = NCOLS <= 4 ? 4 : 2; const unsigned blocks = unsigned((std::size_t(n_out) + 1) / 2); @@ -2151,6 +2317,8 @@ void native_q6_k_unpack(const void* weights) { void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; } bool native_mmvq_multi_exact() { return g_multi_exact; } +void native_mmvq_set_b6_rows(int mode) { g_b6_rows = mode; } +int native_mmvq_b6_rows() { return g_b6_rows; } std::size_t native_q8_1_bytes(int n_in, int ncols) { validate_shape(n_in, ncols); diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 85257e6c..fe1ee65e 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -316,7 +316,11 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float* // run on gfx103x (RDNA2), with 8 cells per step and the butterfly's lane exchanges in registers (DPP / permlanex16) // instead of ds_bpermute: there the score loop is bound by the LDS pipe (the q reads and ds_bpermute share it), not by // occupancy - 8 cells per step at 7 waves/SIMD beat 1 cell at 9. Every other card keeps exactly the kernel above. -#if defined(STRATA_EXPERIMENTAL_SM60) || (defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)) +// Fork (lab/upsync): built on every CUDA build too, for STRATA_ATTN_DAILY=1 (see daily_attn below). With NC 2 and +// no DPP it is the Daily's (be4cf1c) attn_chunk_kernel line for line - the same reduce12 scores, the same cell-major +// probabilities and the same four-cell value fold - except that `spt` shares `sq`'s storage here (no arithmetic +// change). Without the variable nothing selects it on a card at or above sm_75. +#if defined(STRATA_EXPERIMENTAL_SM60) || !defined(__HIPCC__) || !defined(STRATA_HIP_GFX906) #define STRATA_ATTN_PRE75_BUILT 1 #endif #if defined(STRATA_ATTN_PRE75_BUILT) @@ -574,6 +578,86 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_ attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f; } +// attn_merge_kernel's arithmetic in the same chunk order, with two changes that leave every output bit as it was +// (the Daily's 3effa9d5, from Hardin22; qsa_merge_daily_parity compares the two kernels on the same partials, all four +// KV formats): +// +// (1) Bounded by the width. The chunk kernel writes m = -FLT_MAX, l = 0 for every chunk with c0 >= step[kStepWidth] +// (its `n_here <= 0` exit) and the merge skips exactly those, so it can stop at n_act = ceil(width / CHUNK): +// fmaxf with -FLT_MAX never changes M, and a skipped chunk never touches L or acc. The drafter's merge walks its +// whole capacity (--mtp-window 32768: 512 chunks) at every context, where a short context fills one or two. +// (2) Loads batched. attn_merge_kernel loads part_l / part_acc behind its `m == -FLT_MAX` branch, so the compiler +// issues each chunk's l and acc loads inside that chunk's branch: a few dependent L2 round trips per chunk. Here +// the m, l and acc of U chunks are loaded first, guarded only by the chunk index, then consumed in chunk order. +// The skip is a select on the loaded m instead of a branch, so the loads cannot move back behind it. The values +// selected are the very fmaf's attn_merge_kernel computes (same operands, same order), and a skipped chunk leaves +// L and acc as they were, as its `continue` does. +constexpr int kMergeU = 16; + +template +__device__ __forceinline__ void merge_max_block(const float* __restrict__ pm, int c0, int n_act, float& M) { + float mm[U]; +#pragma unroll + for (int u = 0; u < U; ++u) mm[u] = (!TAIL || c0 + u < n_act) ? pm[(size_t) (c0 + u) * G] : -FLT_MAX; +#pragma unroll + for (int u = 0; u < U; ++u) + if (!TAIL || c0 + u < n_act) M = fmaxf(M, mm[u]); +} + +template +__device__ __forceinline__ void merge_sum_block(const float* __restrict__ pm, const float* __restrict__ pl, + const float* __restrict__ pa, int c0, int n_act, float M, float& L, + float& acc) { + float mm[U], ll[U], aa[U]; +#pragma unroll + for (int u = 0; u < U; ++u) { + const bool in = !TAIL || c0 + u < n_act; + mm[u] = in ? pm[(size_t) (c0 + u) * G] : -FLT_MAX; + ll[u] = in ? pl[(size_t) (c0 + u) * G] : 0.0f; + aa[u] = in ? pa[(size_t) (c0 + u) * G * HD] : 0.0f; + } +#pragma unroll + for (int u = 0; u < U; ++u) { + const float w = __expf(mm[u] - M); + const float L_next = fmaf(ll[u], w, L); + const float acc_next = fmaf(aa[u], w, acc); + const bool live = !(mm[u] == -FLT_MAX); // attn_merge_kernel: `if (m == -FLT_MAX) continue;` + L = live ? L_next : L; + acc = live ? acc_next : acc; + } +} + +template +__global__ void __launch_bounds__(HD) attn_merge_v2_kernel(const float* __restrict__ part_acc, + const float* __restrict__ part_m, + const float* __restrict__ part_l, int n_chunks, + const int32_t* __restrict__ steps, + float* __restrict__ attn, long long scratch_stride = 0) { + part_acc += (size_t) blockIdx.y * (size_t) scratch_stride; + part_m += (size_t) blockIdx.y * (size_t) scratch_stride; + part_l += (size_t) blockIdx.y * (size_t) scratch_stride; + attn += (size_t) blockIdx.y * (size_t) gridDim.x * HD; + // the step record the chunk kernel read for this query (attn_chunk_kernel: step + blockIdx.z * kStepCount) + const int width = __ldg(steps + (size_t) blockIdx.y * kStepCount + kStepWidth); + const int n_act = width > 0 ? min(n_chunks, (width - 1) / CHUNK + 1) : 0; + const int h = blockIdx.x; // global query head + const int kvh = h / G, hl = h % G; + const int d = threadIdx.x; + // chunk c of this head: part_m / part_l [(kvh * n_chunks + c) * G + hl], part_acc [that * HD + d] + const size_t base = (size_t) kvh * (size_t) n_chunks * G + (size_t) hl; + const float* pm = part_m + base; + const float* pl = part_l + base; + const float* pa = part_acc + base * HD + (size_t) d; + const int n_full = n_act - n_act % U; + float M = -FLT_MAX; + for (int c0 = 0; c0 < n_full; c0 += U) merge_max_block(pm, c0, n_act, M); + if (n_full < n_act) merge_max_block(pm, n_full, n_act, M); + float L = 0.0f, acc = 0.0f; + for (int c0 = 0; c0 < n_full; c0 += U) merge_sum_block(pm, pl, pa, c0, n_act, M, L, acc); + if (n_full < n_act) merge_sum_block(pm, pl, pa, n_full, n_act, M, L, acc); + attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f; +} + #if defined(STRATA_HIP_GFX906) // The compat backend can target other architectures. Check the calling thread's current device, // caching only its last ordinal so a layer split or another thread cannot reuse the wrong answer. @@ -602,17 +686,40 @@ bool query_swizzle_gfx906_device() { } #endif +// Fork (lab/upsync): STRATA_ATTN_DAILY=1 runs the Daily's (be4cf1c) decode attention on every CUDA card: the chunk +// pass on PR #540's kernel (attn_chunk_kernel_pre75, the Daily's attn_chunk_kernel), bit for bit the +// default kernel's partials. CUDA only; unset or anything but "1" keeps upstream 0.1.42's kernels. +// STRATA_ATTN_PRE75=0 still turns the chunk kernel off (A/B). +[[maybe_unused]] bool daily_attn() { +#if defined(__HIPCC__) + return false; +#else + static const bool on = [] { + const char* v = std::getenv("STRATA_ATTN_DAILY"); + return v != nullptr && v[0] == '1' && v[1] == '\0'; + }(); + return on; +#endif +} + #if defined(STRATA_ATTN_PRE75_BUILT) -// CUDA: the current device is below sm_75; HIP: it is gfx103x (per device: a layer split can mix cards). +// CUDA: the current device is below sm_75 (experimental build) or STRATA_ATTN_DAILY=1 (any card); HIP: it is gfx103x +// (per device: a layer split can mix cards). // STRATA_ATTN_PRE75=0 turns PR #540's kernel off (A/B); on HIP =1 also runs it on another wave32 card. bool pre75_attn() { static const int env = [] { const char* e = std::getenv("STRATA_ATTN_PRE75"); return e == nullptr ? -1 : e[0] == '0' ? 0 : e[0] == '1' ? 1 : -1; }(); + if (env == 0) return false; +#if !defined(__HIPCC__) && !defined(STRATA_EXPERIMENTAL_SM60) + return daily_attn(); // the ready-made engine: upstream's attn_chunk_kernel unless STRATA_ATTN_DAILY=1 +#else +#if !defined(__HIPCC__) + if (daily_attn()) return true; +#endif static int cc[64] = {}; int dev = 0; - if (env == 0) return false; if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } #if defined(__HIPCC__) if (cc[dev] == 0) { // 2: gfx103x, 1: another card @@ -633,13 +740,17 @@ bool pre75_attn() { } return cc[dev] < 75; #endif +#endif // ready-made CUDA engine } +// `PRE` picks PR #540's kernel; the environment's choice is STRATA_ATTN_CHUNK. #if defined(__HIPCC__) -#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75 : attn_chunk_kernel) +#define STRATA_ATTN_CHUNK_SEL(M, PRE) ((PRE) ? attn_chunk_kernel_pre75 : attn_chunk_kernel) #else -#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75 : attn_chunk_kernel) +#define STRATA_ATTN_CHUNK_SEL(M, PRE) ((PRE) ? attn_chunk_kernel_pre75 : attn_chunk_kernel) #endif +#define STRATA_ATTN_CHUNK(M) STRATA_ATTN_CHUNK_SEL(M, pre75_attn()) #else +#define STRATA_ATTN_CHUNK_SEL(M, PRE) attn_chunk_kernel #define STRATA_ATTN_CHUNK(M) attn_chunk_kernel #endif @@ -654,16 +765,33 @@ int attn_kv_mode(const QsaAttnPools& p) { return p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0)); } -} // namespace +// STRATA_ATTN_MERGE_V2: 1 merges with attn_merge_v2_kernel, 0 with attn_merge_kernel. Unset it follows +// STRATA_ATTN_DAILY (the Daily had it on by default on NVIDIA), so upstream's merger stays the default. +int attn_merge_v2() { + static const int on = [] { + int r = daily_attn() ? 1 : 0; + const char* v = std::getenv("STRATA_ATTN_MERGE_V2"); + if (v != nullptr && *v != '\0') r = std::atoi(v) != 0 ? 1 : 0; + return r; + }(); + return on; +} -void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, - int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { - if (n_q <= 0) return; - if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || - !pools.page_table || n_q > 65535) { - std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); - std::exit(1); - } +// the merge of `n_q` queries' partials: v2 = 0 attn_merge_kernel, 1 attn_merge_v2_kernel (bitwise the same output) +void launch_merge(int v2, const float* part_acc, const float* part_m, const float* part_l, int n_chunks, + const int32_t* steps, float* attn, long long stride, unsigned n_head, unsigned n_q, cudaStream_t st) { + if (v2) + attn_merge_v2_kernel<<>>(part_acc, part_m, part_l, n_chunks, steps, + attn, stride); + else + attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, attn, stride); +} + +// qsa_decode_attn_batch's chunk pass: `n_q` queries' partials into `scratch` (one stride each). `kernel` < 0 is the +// environment's choice (lane cell, gfx906 swizzle, STRATA_ATTN_DAILY / PR #540); 0 is attn_chunk_kernel and 1 PR #540's +// kernel where it is built (the parity harness: never the environment). +void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, cudaStream_t st, int kernel) { const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 : (pools.k_q != nullptr ? 1 : 0)); const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); @@ -674,13 +802,17 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 float* part_l = part_m + (size_t) n_chunks * s.n_head; const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); - cudaStream_t st = (cudaStream_t) stream; - const bool lane_cell = lane_cell_attn(); +#if defined(STRATA_ATTN_PRE75_BUILT) + const bool pre = kernel < 0 ? pre75_attn() : kernel == 1; +#endif + // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) + const bool lane_cell = kernel < 0 && lane_cell_attn(); #if defined(STRATA_HIP_GFX906) static const bool query_swizzle = [] { const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1'; }(); - const bool use_query_swizzle = query_swizzle && !lane_cell && kv_mode == 1 && query_swizzle_gfx906_device(); + const bool use_query_swizzle = kernel < 0 && query_swizzle && !lane_cell && kv_mode == 1 && + query_swizzle_gfx906_device(); static const bool query_swizzle_trace = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE_TRACE") != nullptr; static thread_local bool query_swizzle_said = false; if (query_swizzle_trace && !query_swizzle_said) { @@ -728,19 +860,47 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 } else #endif if (kv_mode == 3) - STRATA_ATTN_CHUNK(3)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + STRATA_ATTN_CHUNK_SEL(3, pre)<<>>(q, pools, ids, steps, (int) s.n_head_kv, + (int) s.page_size, scale, part_acc, part_m, part_l, + n_chunks, (int) cap, stride); else if (kv_mode == 2) - STRATA_ATTN_CHUNK(2)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + STRATA_ATTN_CHUNK_SEL(2, pre)<<>>(q, pools, ids, steps, (int) s.n_head_kv, + (int) s.page_size, scale, part_acc, part_m, part_l, + n_chunks, (int) cap, stride); else if (kv_mode == 1) - STRATA_ATTN_CHUNK(1)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + STRATA_ATTN_CHUNK_SEL(1, pre)<<>>(q, pools, ids, steps, (int) s.n_head_kv, + (int) s.page_size, scale, part_acc, part_m, part_l, + n_chunks, (int) cap, stride); else - STRATA_ATTN_CHUNK(0)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, - scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); - attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, - attn, stride); + STRATA_ATTN_CHUNK_SEL(0, pre)<<>>(q, pools, ids, steps, (int) s.n_head_kv, + (int) s.page_size, scale, part_acc, part_m, part_l, + n_chunks, (int) cap, stride); +} + +// qsa_decode_attn_batch's merge pass over the partials launch_chunks_batch wrote; `v2` names the merge kernel +void launch_merge_batch(const int32_t* steps, int64_t cap, const QsaShapes& s, const float* scratch, float* attn, + int64_t n_q, int v2, cudaStream_t st) { + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + const float* part_acc = scratch; + const float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + const float* part_l = part_m + (size_t) n_chunks * s.n_head; + launch_merge(v2, part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head, (unsigned) n_q, st); +} + +} // namespace + +void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || + !pools.page_table || n_q > 65535) { + std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); + std::exit(1); + } + cudaStream_t st = (cudaStream_t) stream; + launch_chunks_batch(q, pools, ids, steps, cap, s, scratch, n_q, st, -1); + launch_merge_batch(steps, cap, s, scratch, attn, n_q, attn_merge_v2(), st); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "qsa_decode_attn_batch: %s\n", cudaGetErrorString(e)); @@ -796,8 +956,8 @@ bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const else STRATA_ATTN_SLOTS(0, false); } #undef STRATA_ATTN_SLOTS - attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, - attn, stride); + launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head, + (unsigned) n_q, st); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "qsa_decode_attn_slots: %s\n", cudaGetErrorString(e)); @@ -845,7 +1005,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 else STRATA_ATTN_CHUNK(0)<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, 0, 0); - attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn); + launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, step, attn, 0, (unsigned) s.n_head, 1u, st); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "qsa_decode_attn: %s\n", cudaGetErrorString(e)); @@ -853,4 +1013,38 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 } } +// qsa_merge_daily_parity: qsa_decode_attn_batch's two passes apart, the chunk kernel and the merge named by the +// arguments (never the environment), so the Daily's kernels and upstream's can be run on the same inputs and the +// outputs compared bit for bit. The engine never calls these. +void qsa_decode_attn_chunks_only(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, int daily_chunk, + void* stream) { + if (n_q <= 0 || n_q > 65535 || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || + !q || !ids || !steps || !pools.page_table || (daily_chunk != 0 && daily_chunk != 1)) { + std::fprintf(stderr, "qsa_decode_attn_chunks_only: unsupported geometry or missing buffers\n"); + std::exit(1); + } + launch_chunks_batch(q, pools, ids, steps, cap, s, scratch, n_q, (cudaStream_t) stream, daily_chunk); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_chunks_only: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +void qsa_decode_attn_merge_only(const int32_t* steps, int64_t cap, const QsaShapes& s, const float* scratch, + float* attn, int64_t n_q, int v2, void* stream) { + if (n_q <= 0 || n_q > 65535 || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || + (v2 != 0 && v2 != 1) || !steps || !attn) { + std::fprintf(stderr, "qsa_decode_attn_merge_only: unsupported geometry or missing buffers\n"); + std::exit(1); + } + launch_merge_batch(steps, cap, s, scratch, attn, n_q, v2, (cudaStream_t) stream); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_merge_only: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + } // namespace strata::kernels diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index bd99609d..43bc917c 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -678,6 +679,251 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __ } } +__global__ void __launch_bounds__(THREADS) decode_attn_i8_split_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, + int page_size, float scale_log2, + float* __restrict__ part, int cap) { + extern __shared__ __align__(16) unsigned char smem_raw[]; + Smem2& S = *reinterpret_cast(smem_raw); + const int qi = blockIdx.x, kvh = blockIdx.y, sp = blockIdx.z, nsp = gridDim.z; + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + // partials of (query, split): acc [n_head][HD] unnormalized, then m / l [n_head][2] + float* pacc = part + (size_t) (qi * nsp + sp) * n_head * (HD + 2) + (size_t) kvh * G * HD; + float* pml = part + (size_t) (qi * nsp + sp) * n_head * (HD + 2) + (size_t) n_head * HD + (size_t) kvh * G * 2; + ids += (size_t) qi * cap; + const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth); + // this split's chunks: [ci0, ci1) of the query's ceil(n / CH2) + const int n_all = (n + CH2 - 1) / CH2, per = (n_all + nsp - 1) / nsp; + const int ci0 = sp * per, ci1 = min(n_all, ci0 + per); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int gid = lane >> 2, tig = lane & 3; + const int dim0 = warp * 64; + + // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments + float qm = 0.0f; + for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); + if (lane == 0) S.qmax[warp] = qm; + if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } + __syncthreads(); + qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); + int qe = 0; + if (qm > 0.0f) frexpf(qm, &qe); + const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); + uint32_t qh[4][4], ql[4][4]; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8; + float2 x = make_float2(0.f, 0.f); + if (row < G) x = *reinterpret_cast(q + (size_t) row * HD + col); + x.x *= qup; + x.y *= qup; + const __half2 hi = __floats2half2_rn(x.x, x.y); + const float2 hf = __half22float2(hi); + const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y); + qh[kk][r] = *reinterpret_cast(&hi); + ql[kk][r] = *reinterpret_cast(&lo); + } + } + + if (ci0 >= ci1) { // an empty split: m = -inf, l = 0, acc = 0 + for (int i = t; i < G * HD; i += THREADS) pacc[(size_t) (i / HD) * HD + i % HD] = 0.0f; + if (t < G) { pml[2 * t] = -INFINITY; pml[2 * t + 1] = 0.0f; } + return; + } + // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead + auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; }; + auto row_of = [&](int cell) -> long long { + if (cell < 0) return -1; + const long long page = (long long) __ldg(p.page_table + cell / page_size); + return (page * n_kv_heads + kvh) * page_size + (cell % page_size); + }; + auto issue = [&](long long r, int st, float& ksr, float& vsr) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3; + const long long rr = __shfl_sync(0xffffffffu, r, cell); + const bool ok = rr >= 0; + const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0; + cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok); + cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok); + } + ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + }; + float ksn, vsn; + issue(row_of(cell_of(ci0 * CH2 + lane)), 0, ksn, vsn); + cp_async_commit(); + S.sc[0][warp][0][lane] = ksn; + S.sc[0][warp][1][lane] = vsn; + long long r_next = row_of(cell_of((ci0 + 1) * CH2 + lane)); + int cell_next2 = cell_of((ci0 + 2) * CH2 + lane); + + float acc[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; + + for (int ci = ci0; ci < ci1; ++ci) { + const int st = (ci - ci0) & 1, c0 = ci * CH2; + const bool more = ci + 1 < ci1; + if (more) issue(r_next, st ^ 1, ksn, vsn); + cp_async_commit(); + r_next = row_of(cell_next2); + cell_next2 = cell_of((ci + 3) * CH2 + lane); + cp_async_wait1(); + __syncwarp(); + const int8_t* K = &S.kv[st][warp][0][0][0]; + const int8_t* V = &S.kv[st][warp][1][0][0]; + // q.k over this warp's 64 dims, times the cell's K scale for this group +#pragma unroll + for (int nt = 0; nt < CH2 / 8; ++nt) { + float tg[4] = {0.f, 0.f, 0.f, 0.f}; + const int cell = nt * 8 + gid; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + uint32_t b[2]; + b[0] = i8x2_to_h2(*reinterpret_cast(K + swz(cell, kk * 16 + 2 * tig))); + b[1] = i8x2_to_h2(*reinterpret_cast(K + swz(cell, kk * 16 + 2 * tig + 8))); + mma16816(tg, qh[kk], b); + mma16816(tg, ql[kk], b); + } + const int c = nt * 8 + 2 * tig; + const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1]; + S.part[warp][gid][c] = tg[0] * s0; + S.part[warp][gid][c + 1] = tg[1] * s1; + S.part[warp][gid + 8][c] = tg[2] * s0; + S.part[warp][gid + 8][c + 1] = tg[3] * s1; + } + __syncthreads(); + // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread + { + const int r = t >> 3, sub = t & 7; + float x[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = sub * 4 + j; + x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown + : -INFINITY; + mx = fmaxf(mx, x[j]); + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); + const float m_old = S.mrow[r]; + const float m_new = fmaxf(m_old, mx); + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); + S.p[r][sub * 4 + j] = e; + sum += e; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + __syncwarp(); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); + S.alpha[r] = a; + S.lsum[r] = fmaf(S.lsum[r], a, sum); + S.mrow[r] = m_new; + } + } + __syncthreads(); + // p.v over this warp's 64 dims (as v1) + { + float vmax = S.sc[st][warp][1][lane]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); + const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); + float tmp[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f; +#pragma unroll + for (int ks = 0; ks < CH2 / 16; ++ks) { + const int cA = ks * 16 + 2 * tig, cB = cA + 8; + const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup, + w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup; + const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1; + const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1; + const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3; + const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3; + uint32_t ah[4], al[4]; + ah[0] = pack_h2(p00, p01); + ah[1] = pack_h2(p10, p11); + ah[2] = pack_h2(p02, p03); + ah[3] = pack_h2(p12, p13); + { + const __half2* h = reinterpret_cast(ah); + float2 f; + f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y); + f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y); + f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y); + f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = j * 8 + gid; + const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8); + const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8); + uint32_t b[2]; + b[0] = i8x2_to_h2(x0); + b[1] = i8x2_to_h2(x1); + mma16816(tmp[j], ah, b); + mma16816(tmp[j], al, b); + } + } + const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown); + acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown); + acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown); + acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown); + } + } + if (more) { + S.sc[st ^ 1][warp][0][lane] = ksn; + S.sc[st ^ 1][warp][1][lane] = vsn; + } + __syncwarp(); + } + __syncthreads(); + // the split's unnormalized sums and each head row's maximum and sum (the merge rescales and divides) +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = dim0 + j * 8 + 2 * tig; + *reinterpret_cast(pacc + (size_t) gid * HD + d) = make_float2(acc[j][0], acc[j][1]); + if (gid + 8 < G) + *reinterpret_cast(pacc + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2], acc[j][3]); + } + if (t < G) { pml[2 * t] = S.mrow[t]; pml[2 * t + 1] = S.lsum[t]; } +} + +// the splits of each (query, head) merged with the log-sum-exp rescale (base 2, as the kernel's online softmax), in +// split order; a block per (query, head), a thread per dimension +__global__ void __launch_bounds__(HD) decode_attn_merge_kernel(const float* __restrict__ part, int n_head, int nsp, + float* __restrict__ attn) { + const int qi = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + const size_t qs = (size_t) qi * nsp * n_head * (HD + 2); + float M = -INFINITY; + for (int s = 0; s < nsp; ++s) M = fmaxf(M, part[qs + (size_t) s * n_head * (HD + 2) + (size_t) n_head * HD + 2 * h]); + float L = 0.0f, o = 0.0f; + for (int s = 0; s < nsp; ++s) { + const float* ps = part + qs + (size_t) s * n_head * (HD + 2); + const float m = ps[(size_t) n_head * HD + 2 * h], l = ps[(size_t) n_head * HD + 2 * h + 1]; + const float w = m == -INFINITY ? 0.0f : exp2f(m - M); + L = fmaf(l, w, L); + o = fmaf(ps[(size_t) h * HD + d], w, o); + } + attn[((size_t) qi * n_head + h) * HD + d] = L > 0.0f ? o * (1.0f / L) : 0.0f; +} + + + bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs this on several) @@ -708,6 +954,354 @@ bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, co return true; } +// ---- v3 (int8 KV, opt-in STRATA_PROMPT_ATTN_IMMA=1): v2's block, pipeline and online softmax, with both products on +// INT8 tensor cores (mma m16n8k32 s8, int32 accumulation). K and V enter as the int8 codes they are - no int8 -> fp16 +// conversion - and the other operand as THREE 8-bit parts: q per (head, 64-dim group) and p * v_scale per (head, chunk) +// scaled to 127, then X = rint(x * 65536) split exactly into h (signed), l (signed) and m (unsigned) bytes - 24 bits, +// as fine as FP32 itself and finer than the FP16 hi + lo split v2 uses (~22 bits). Each part's int32 sum is exact; the three meet in +// FP32 as h + (l * 256 + m) / 65536 (m unsigned: a u8 x s8 MMA). INT8 MMA runs ~3.1x FP16's rate on sm_120 (732 vs 233 measured), so three INT8 +// MMAs cost about one FP16 MMA where v2 spends two. p.v takes each thread's 8 consecutive dims across the 8 n-tiles +// (n-tile j, column n = dim n * 8 + j), so a thread reads 8 bytes of a V row per cell and byte-transposes 4 cells. +__device__ __forceinline__ void imma16832(int* c, const uint32_t* a, const uint32_t* b) { +#if !STRATA_PA_SM80 + __trap(); +#else + asm volatile("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+r"(c[0]), "+r"(c[1]), "+r"(c[2]), "+r"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); +#endif +} +// the low part's MMA: unsigned A (m in 0..255), signed B +__device__ __forceinline__ void imma16832_us(int* c, const uint32_t* a, const uint32_t* b) { +#if !STRATA_PA_SM80 + __trap(); +#else + asm volatile("mma.sync.aligned.m16n8k32.row.col.s32.u8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+r"(c[0]), "+r"(c[1]), "+r"(c[2]), "+r"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); +#endif +} +// x (|x| <= 127) as X = rint(x * 65536) = h * 65536 + l * 256 + m exactly: h, l signed bytes, m an unsigned one +__device__ __forceinline__ void split3(float x, int& h, int& l, int& m) { + const int X = __float2int_rn(x * 65536.0f); + h = (X + 32768) >> 16; + const int r = X - (h << 16); // -32768 .. 32767 + l = r >> 8; // -128 .. 127 + m = r & 255; // 0 .. 255 +} +__device__ __forceinline__ uint32_t pack4(int a, int b, int c, int d) { + return (uint32_t) (a & 0xff) | ((uint32_t) (b & 0xff) << 8) | ((uint32_t) (c & 0xff) << 16) | ((uint32_t) (d & 0xff) << 24); +} +__device__ __forceinline__ float join3(int h, int l, int m) { // the parts' exact int32 sums -> h + (l*256 + m)/65536 + return (float) h + (float) ((l << 8) + m) * (1.0f / 65536.0f); +} +// four words of four bytes each (word i = cell i) -> four words of the same byte position across the cells +__device__ __forceinline__ void tr4x4(uint32_t w0, uint32_t w1, uint32_t w2, uint32_t w3, uint32_t* o) { + const uint32_t t0 = __byte_perm(w0, w1, 0x5140), t1 = __byte_perm(w0, w1, 0x7362); + const uint32_t t2 = __byte_perm(w2, w3, 0x5140), t3 = __byte_perm(w2, w3, 0x7362); + o[0] = __byte_perm(t0, t2, 0x5410); + o[1] = __byte_perm(t0, t2, 0x7632); + o[2] = __byte_perm(t1, t3, 0x5410); + o[3] = __byte_perm(t1, t3, 0x7632); +} + +// v3's shared memory: ONE stage of K and one of V per warp (a warp gathers and reads only its own 64-dim slices, so +// reusing a buffer needs only that warp's own order): K(c + 1) is gathered while the block runs softmax(c) and +// p.v(c), V(c + 1) while it runs q.k(c + 1) and softmax(c + 1); and only the 12 real head rows of the partial sums +// and p. 25.5 KB instead of v2's 45.6 KB: three blocks an SM instead of two (one block an SM ran 1.54x slower than +// two - this kernel waits on latency, not on its MMAs). +struct Smem3 { + int8_t kv[4][2][CH2][64]; // warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell + float sc[4][2][CH2]; // warp, K/V scale of the cell for the warp's group + float part[4][G][CH2 + 1]; // q.k per dim group (the 12 head rows) + float p[G][CH2 + 1]; + float alpha[16]; + float lsum[16]; + float mrow[16]; +}; + +__global__ void __launch_bounds__(THREADS, 3) prompt_attn_i8v3_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, + int page_size, float scale_log2, + float* __restrict__ attn, int cap) { + extern __shared__ __align__(16) unsigned char smem_raw[]; + Smem3& S = *reinterpret_cast(smem_raw); + const int qi = blockIdx.x, kvh = blockIdx.y; + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + ids += (size_t) qi * cap; + const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int gid = lane >> 2, tig = lane & 3; + const int dim0 = warp * 64; + if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; S.alpha[t] = 0.0f; } + + // q: rows gid / gid + 8 (heads; 12..15 are pad), this warp's 64 dims as the A fragments of two k-steps of 32, + // three 8-bit parts with a scale per (row, 64-dim group) + uint32_t qa[3][2][4]; + float qinv[2]; + { + float x[2][2][2][4]; // [row half][k-step][k half][4 dims] + float mx[2] = {0.0f, 0.0f}; +#pragma unroll + for (int rh = 0; rh < 2; ++rh) { + const int row = gid + rh * 8; +#pragma unroll + for (int ks = 0; ks < 2; ++ks) +#pragma unroll + for (int kh = 0; kh < 2; ++kh) { + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + if (row < G) v = *reinterpret_cast(q + (size_t) row * HD + dim0 + ks * 32 + kh * 16 + tig * 4); + x[rh][ks][kh][0] = v.x; x[rh][ks][kh][1] = v.y; x[rh][ks][kh][2] = v.z; x[rh][ks][kh][3] = v.w; + mx[rh] = fmaxf(mx[rh], fmaxf(fmaxf(fabsf(v.x), fabsf(v.y)), fmaxf(fabsf(v.z), fabsf(v.w)))); + } +#pragma unroll + for (int o = 1; o < 4; o <<= 1) mx[rh] = fmaxf(mx[rh], __shfl_xor_sync(0xffffffffu, mx[rh], o)); + } + float up[2]; +#pragma unroll + for (int rh = 0; rh < 2; ++rh) { + up[rh] = mx[rh] > 0.0f ? 127.0f / mx[rh] : 0.0f; + qinv[rh] = mx[rh] * (1.0f / 127.0f); + } +#pragma unroll + for (int ks = 0; ks < 2; ++ks) +#pragma unroll + for (int r = 0; r < 4; ++r) { // a0: row gid, k 0..15 half; a1: row gid + 8; a2: row gid, k 16..31; a3 + const int rh = r & 1, kh = r >> 1; + int hh[4], ll[4], mm[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) split3(x[rh][ks][kh][e] * up[rh], hh[e], ll[e], mm[e]); + qa[0][ks][r] = pack4(hh[0], hh[1], hh[2], hh[3]); + qa[1][ks][r] = pack4(ll[0], ll[1], ll[2], ll[3]); + qa[2][ks][r] = pack4(mm[0], mm[1], mm[2], mm[3]); + } + } + + const int n_chunks = (n + CH2 - 1) / CH2; + auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; }; + auto row_of = [&](int cell) -> long long { + if (cell < 0) return -1; + const long long page = (long long) __ldg(p.page_table + cell / page_size); + return (page * n_kv_heads + kvh) * page_size + (cell % page_size); + }; + // this warp's 64-dim slice of K (kv = 0) or V (1) of the chunk whose rows the lanes hold, and the cells' scales + auto issue = [&](long long r, int kv) { + const int8_t* pool = kv == 0 ? p.k_q : p.v_q; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3; + const long long rr = __shfl_sync(0xffffffffu, r, cell); + const bool ok = rr >= 0; + const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0; + cp_async16(&S.kv[warp][kv][0][0] + swz(cell, pc * 16), pool + off, ok); + } + const uint16_t* sc = kv == 0 ? p.k_scale : p.v_scale; + S.sc[warp][kv][lane] = r >= 0 ? __half2float(__ushort_as_half(__ldg(sc + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + }; + long long r_nxt = row_of(cell_of(lane)); // chunk 0 + issue(r_nxt, 0); + cp_async_commit(); + issue(r_nxt, 1); + cp_async_commit(); + r_nxt = row_of(cell_of(CH2 + lane)); // chunk 1 + int cell_nn = cell_of(2 * CH2 + lane); // chunk 2 + __syncthreads(); + + float acc[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; + const int8_t* K = &S.kv[warp][0][0][0]; + const int8_t* V = &S.kv[warp][1][0][0]; + + for (int ci = 0; ci < n_chunks; ++ci) { + const int c0 = ci * CH2; + const bool more = ci + 1 < n_chunks; + cp_async_wait1(); // K(ci) is in (pending: V(ci)) + __syncwarp(); + // q.k over this warp's 64 dims: n-tile nt holds cells nt * 8 .. + 7 (column n = cell nt * 8 + n) +#pragma unroll + for (int nt = 0; nt < CH2 / 8; ++nt) { + int ch[4] = {0, 0, 0, 0}, cl[4] = {0, 0, 0, 0}, cm[4] = {0, 0, 0, 0}; + const int cell = nt * 8 + gid; +#pragma unroll + for (int ks = 0; ks < 2; ++ks) { + uint32_t b[2]; + b[0] = *reinterpret_cast(K + swz(cell, ks * 32 + tig * 4)); + b[1] = *reinterpret_cast(K + swz(cell, ks * 32 + 16 + tig * 4)); + imma16832(ch, qa[0][ks], b); + imma16832(cl, qa[1][ks], b); + imma16832_us(cm, qa[2][ks], b); + } + const int c = nt * 8 + 2 * tig; + const float s0 = S.sc[warp][0][c], s1 = S.sc[warp][0][c + 1]; + S.part[warp][gid][c] = join3(ch[0], cl[0], cm[0]) * qinv[0] * s0; + S.part[warp][gid][c + 1] = join3(ch[1], cl[1], cm[1]) * qinv[0] * s1; + if (gid + 8 < G) { + S.part[warp][gid + 8][c] = join3(ch[2], cl[2], cm[2]) * qinv[1] * s0; + S.part[warp][gid + 8][c + 1] = join3(ch[3], cl[3], cm[3]) * qinv[1] * s1; + } + } + __syncwarp(); // every lane has read K(ci) and its scales + if (more) issue(r_nxt, 0); + cp_async_commit(); + __syncthreads(); + // online softmax over the four groups' sum (fixed order): rows 0..11, 8 threads a row (warp 3 idles) + if (t < G * 8) { + const int r = t >> 3, sub = t & 7; + float x[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = sub * 4 + j; + x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * scale_log2 + : -INFINITY; + mx = fmaxf(mx, x[j]); + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); + const float m_old = S.mrow[r]; + const float m_new = fmaxf(m_old, mx); + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); + S.p[r][sub * 4 + j] = e; + sum += e; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + __syncwarp(); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); + S.alpha[r] = a; + S.lsum[r] = fmaf(S.lsum[r], a, sum); + S.mrow[r] = m_new; + } + } + __syncthreads(); + cp_async_wait1(); // V(ci) is in (pending: K(ci + 1)) + __syncwarp(); + // p.v over this warp's 64 dims: A = p * v_scale (rows gid / gid + 8, k = the chunk's 32 cells) in three parts + // scaled per row; B = V (k = cells, n-tile j column n = dim n * 8 + j) + { + uint32_t pa[3][4]; + float pinv[2]; + { // a scale per row: a chunk whose p are all small still gets its 24 bits (one per warp and chunk lost + // ~3x of the accuracy against FP64) + float a[4][4], mx[2] = {0.0f, 0.0f}; +#pragma unroll + for (int r = 0; r < 4; ++r) { // a0: row gid, cells tig * 4 ..; a1: row gid + 8; a2 / a3: cells 16 + ... + const int row = gid + (r & 1) * 8, cb = (r >> 1) * 16 + tig * 4; +#pragma unroll + for (int e = 0; e < 4; ++e) { + a[r][e] = row < G ? S.p[row][cb + e] * S.sc[warp][1][cb + e] : 0.0f; + mx[r & 1] = fmaxf(mx[r & 1], a[r][e]); + } + } + float up[2]; +#pragma unroll + for (int rh = 0; rh < 2; ++rh) { +#pragma unroll + for (int o = 1; o < 4; o <<= 1) mx[rh] = fmaxf(mx[rh], __shfl_xor_sync(0xffffffffu, mx[rh], o)); + up[rh] = mx[rh] > 0.0f ? 127.0f / mx[rh] : 0.0f; + pinv[rh] = mx[rh] * (1.0f / 127.0f); + } +#pragma unroll + for (int r = 0; r < 4; ++r) { + int hh[4], ll[4], mm[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) split3(a[r][e] * up[r & 1], hh[e], ll[e], mm[e]); + pa[0][r] = pack4(hh[0], hh[1], hh[2], hh[3]); + pa[1][r] = pack4(ll[0], ll[1], ll[2], ll[3]); + pa[2][r] = pack4(mm[0], mm[1], mm[2], mm[3]); + } + } + // B: this thread's 8 dims (gid * 8 .. + 7) of cells tig * 4 .. + 3 (b0) and 16 + tig * 4 .. + 3 (b1) + uint32_t bv[2][8]; // [k half][dim j] +#pragma unroll + for (int kh = 0; kh < 2; ++kh) { + uint32_t lo[4], hi[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const uint2 w = *reinterpret_cast(V + swz(kh * 16 + tig * 4 + e, gid * 8)); + lo[e] = w.x; + hi[e] = w.y; + } + tr4x4(lo[0], lo[1], lo[2], lo[3], &bv[kh][0]); + tr4x4(hi[0], hi[1], hi[2], hi[3], &bv[kh][4]); + } + __syncwarp(); // every lane has read V(ci) and its scales + if (more) issue(r_nxt, 1); + cp_async_commit(); + const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + int ch[4] = {0, 0, 0, 0}, cl[4] = {0, 0, 0, 0}, cm[4] = {0, 0, 0, 0}; + const uint32_t b[2] = {bv[0][j], bv[1][j]}; + imma16832(ch, pa[0], b); + imma16832(cl, pa[1], b); + imma16832_us(cm, pa[2], b); + acc[j][0] = fmaf(acc[j][0], a0, join3(ch[0], cl[0], cm[0]) * pinv[0]); + acc[j][1] = fmaf(acc[j][1], a0, join3(ch[1], cl[1], cm[1]) * pinv[0]); + acc[j][2] = fmaf(acc[j][2], a1, join3(ch[2], cl[2], cm[2]) * pinv[1]); + acc[j][3] = fmaf(acc[j][3], a1, join3(ch[3], cl[3], cm[3]) * pinv[1]); + } + } + r_nxt = row_of(cell_nn); + cell_nn = cell_of((ci + 3) * CH2 + lane); + } + __syncthreads(); + const float l0 = S.lsum[gid], l1 = gid + 8 < G ? S.lsum[gid + 8] : 0.0f; + const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f; +#pragma unroll + for (int j = 0; j < 8; ++j) { // column 2 * tig is dim 16 * tig + j, column 2 * tig + 1 dim 16 * tig + 8 + j + const int d0 = dim0 + 16 * tig + j, d1 = d0 + 8; + attn[(size_t) gid * HD + d0] = acc[j][0] * i0; + attn[(size_t) gid * HD + d1] = acc[j][1] * i0; + if (gid + 8 < G) { + attn[(size_t) (gid + 8) * HD + d0] = acc[j][2] * i1; + attn[(size_t) (gid + 8) * HD + d1] = acc[j][3] * i1; + } + } +} + +bool launch_i8v3(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { + static bool attr[64] = {}; + int dev = 0; + cudaGetDevice(&dev); + const int bytes = (int) sizeof(Smem3); + if (dev < 0 || dev >= 64) return false; + if (!attr[dev]) { + if (cudaFuncSetAttribute(prompt_attn_i8v3_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != + cudaSuccess) { + cudaGetLastError(); + return false; + } + // the shared-memory side of the L1 split as large as it goes, so three blocks fit an SM + cudaFuncSetAttribute(prompt_attn_i8v3_kernel, cudaFuncAttributePreferredSharedMemoryCarveout, 100); + cudaGetLastError(); + attr[dev] = true; + } + const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + prompt_attn_i8v3_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch (v3): %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} + template bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { @@ -1450,8 +2044,64 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, } #endif +int g_pa_imma = -1; // STRATA_PROMPT_ATTN_IMMA: -1 not read yet; qsa_prompt_attn_set_imma (tests) overrides it } // namespace +// STRATA_QSA_SPLIT_ATTN=1 (the idea of fork Eddoursul fd23d91): the decode attention through the +// prompt path's int8 tensor-core kernel with each query's cells split among up to 20 blocks (one wave), merged with the +// log-sum-exp rescale. int8 KV on sm_80+ only (false otherwise: the caller keeps qsa_decode_attn_batch). The +// partials live in the decode scratch (n_q x splits x n_head x (HD + 2) floats, within qsa_decode_attn_scratch_floats). +bool qsa_decode_attn_split(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 defined(__HIPCC__) + return false; +#else + if (n_q <= 0) return true; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table || + pools.k_q == nullptr || pools.v_q == nullptr || pools.k_scale == nullptr || pools.v_scale == nullptr || + pools.k_q4 != nullptr || pools.v_q4 != nullptr) + return false; + static int cc[64] = {}, sms[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cc[dev] == 0) { + int major = 0, minor = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); + cudaDeviceGetAttribute(&sms[dev], cudaDevAttrMultiProcessorCount, dev); + cc[dev] = 10 * major + minor; + } + if (cc[dev] < 80) return false; + static bool attr[64] = {}; + const int bytes = (int) sizeof(Smem2); + if (!attr[dev]) { + if (cudaFuncSetAttribute(decode_attn_i8_split_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != cudaSuccess) { + cudaGetLastError(); + return false; + } + attr[dev] = true; + } + // splits: up to 20, about two blocks per SM in one wave, never more than the capacity's chunks (the scratch) + const int64_t chunks_cap = (cap + CH2 - 1) / CH2; + int64_t nsp = (2 * (int64_t) sms[dev] + n_q * s.n_head_kv - 1) / (n_q * s.n_head_kv); + nsp = std::max(1, std::min({nsp, 20, chunks_cap})); + if ((uint64_t) (n_q * nsp * s.n_head * (HD + 2)) > scratch_floats) return false; // the caller's scratch + const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); + cudaStream_t st = (cudaStream_t) stream; + decode_attn_i8_split_kernel<<>>( + q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale_log2, scratch, (int) cap); + decode_attn_merge_kernel<<>>(scratch, (int) s.n_head, (int) nsp, attn); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_split: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +#endif +} +void qsa_prompt_attn_set_imma(int on) { g_pa_imma = on < 0 ? -1 : (on ? 1 : 0); } + bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) { if (n_q <= 0) return true; @@ -1517,6 +2167,12 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr; if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st); if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st); + // STRATA_PROMPT_ATTN_IMMA=1 (opt-in, sm_80+): both products on INT8 tensor cores (prompt_attn_i8v3_kernel) + if (g_pa_imma < 0) { + const char* v = std::getenv("STRATA_PROMPT_ATTN_IMMA"); + g_pa_imma = v != nullptr && v[0] == '1' ? 1 : 0; + } + if (g_pa_imma == 1) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st); return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st); } if (!pools.k_pool || !pools.v_pool) return false; diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index d5514172..39db4f65 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -642,14 +642,29 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res hist[0][t] = s; } __syncthreads(); - if (t == 0) { - int cum = above, d = 255; - for (; d > 0; --d) { - if (cum + hist[0][d] >= width) break; - cum += hist[0][d]; + // the digit: the first bin from the top where the count above reaches `width` (bin 0 when none of 255..1 + // does). Threads 0-255 (warps 0-7) prefix-sum the 256 bins in descending order instead of one thread + // walking them: the same digit and count above. + int v = 0, x = 0; + if (t < 256) { + v = hist[0][255 - t]; + x = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, x, o); + if (lane >= o) x += y; + } + if (lane == 31) s_warp[warp] = x; + } + __syncthreads(); + if (t < 256) { + int inc = x; + for (int w2 = 0; w2 < warp; ++w2) inc += s_warp[w2]; + const int before = above + inc - v; + if (before < width && (above + inc >= width || t == 255)) { + s_digit = 255 - t; + s_above = before; } - s_digit = d; - s_above = cum; } __syncthreads(); prefix |= (uint32_t) s_digit << shift; @@ -898,6 +913,82 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(Sc steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit); } +// QSAROWS (docs/QSAROWS.md, STRATA_QSA_ROWS=1): block_scores_multi_kernel's work for NQ <= 4 queries with less issue +// pressure per (block, query). nsys of a 131k decode window (RTX 2080 Ti + RTX 3060): the multi kernel costs ~20 us more a +// call for every row of the window on both cards - per (block, query) it reads the four query slices from shared memory +// (4 x LDS.128) and reduces each head's lane products with its own five shuffles (20 a block and query), and those two +// pipes bound it, not the key reads (the keys are read once for all the queries, as there). Here (1) the lane's slices +// of the NQ queries (4 heads x 4 floats each) live in registers for the whole kernel, (2) the four heads' lane products +// are reduce-scattered with warp_sum's pairing (xor 16, 8, then 4, 2, 1: six shuffles for the four heads) and gathered +// to lane 0 in head order (three more). Every sum adds the same two operands as block_scores_kernel's warp_sum at the +// same level (float add commutes), the dot expression is the same text in the same file, the relu-and-add runs over the +// heads in the same order: the same score bits. The tail block and the +1e9 are as in the multi kernel. +template +__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_rows_kernel(const float* __restrict__ pooled, + const float* __restrict__ dead, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int nq, + int64_t max_blocks, float* __restrict__ out) { + __shared__ int64_t s_nkv[NQ], s_nbid[NQ]; + if (threadIdx.x < nq) { + s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv]; + s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid]; + } + __syncthreads(); + int64_t top = 0; + for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top; + if ((int64_t) blockIdx.x * SCORE_WARPS > top) return; // the multi kernel's early exit (CTA-uniform) + const int lane = threadIdx.x & 31; + float4 qr[NQ][IDX_HEADS]; +#pragma unroll + for (int qi = 0; qi < NQ; ++qi) +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) + qr[qi][h] = qi < nq ? *reinterpret_cast(q_idx + qi * IDX_HEADS * IDX_DIM + h * IDX_DIM + lane * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + const float4 kd = *reinterpret_cast(dead + lane * 4); + const bool hi16 = (lane & 16) != 0, hi8 = (lane & 8) != 0; + const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS; + for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) { + const float4 kp = *reinterpret_cast(pooled + b * IDX_DIM + lane * 4); +#pragma unroll + for (int qi = 0; qi < NQ; ++qi) { + if (qi >= nq) break; + const int64_t n_bid = s_nbid[qi]; + if (b > n_bid) continue; + const float4 k4 = (b == n_bid) ? kd : kp; + float d[IDX_HEADS]; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float4 q4 = qr[qi][h]; + d[h] = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; + } + // reduce-scatter: after xor 16 the lane keeps heads {0,1} (bit 4 clear) or {2,3}; after xor 8 one head + float r2[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) + r2[i] = (hi16 ? d[i + 2] : d[i]) + __shfl_xor_sync(0xffffffffu, hi16 ? d[i] : d[i + 2], 16); + float r = (hi8 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi8 ? r2[0] : r2[1], 8); + r += __shfl_xor_sync(0xffffffffu, r, 4); + r += __shfl_xor_sync(0xffffffffu, r, 2); + r += __shfl_xor_sync(0xffffffffu, r, 1); + // lane 8h holds head h's full sum: gather to lane 0 and add the relus in head order, as the warp kernel + const float s1 = __shfl_sync(0xffffffffu, r, 8); + const float s2 = __shfl_sync(0xffffffffu, r, 16); + const float s3 = __shfl_sync(0xffffffffu, r, 24); + if (lane == 0) { + float score = 0.0f; + score += r > 0.0f ? r : 0.0f; + score += s1 > 0.0f ? s1 : 0.0f; + score += s2 > 0.0f ? s2 : 0.0f; + score += s3 > 0.0f ? s3 : 0.0f; + if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f; + out[qi * max_blocks + b] = score; + } + } + } +} + #if !defined(__HIPCC__) // ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or // block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to @@ -1161,6 +1252,9 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx } // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1) if (scores_multi_on() && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16 + // QSAROWS: STRATA_QSA_ROWS=1 (exactly) takes block_scores_rows_kernel for calls of up to 4 queries - the same bits + static const bool rows_env = [] { const char* v = std::getenv("STRATA_QSA_ROWS"); return v != nullptr && v[0] == '1' && v[1] == '\0'; }(); + if (rows_env && qsa_block_scores_rows(pooled, dead, q_idx, steps, nq, max_blocks, s, scores, stream)) return; block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores, scores_early_exit()); const cudaError_t e = cudaGetLastError(); @@ -1175,6 +1269,21 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores: %s\n", cudaGetErrorString(e)); std::exit(1); } } +bool qsa_block_scores_rows(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) { + if (nq <= 0) return true; + if (nq > 4 || s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R) return false; + cudaStream_t st = (cudaStream_t) stream; + const int n = (int) nq; + if (n == 1) block_scores_rows_kernel<1><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores); + else if (n == 2) block_scores_rows_kernel<2><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores); + else if (n == 3) block_scores_rows_kernel<3><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores); + else block_scores_rows_kernel<4><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores rows: %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +} + bool qsa_block_scores_tc(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 (nq <= 0) return true; @@ -1387,7 +1496,12 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64 const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks; const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER); #if defined(__HIPCC__) - constexpr int64_t kRegMinBlocks = 7168; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref + // gfx1201: below ~28K cells (7,168 blocks) the 1,024-thread kernel's fixed cost loses to the ref. STRATA_TOPK_REG_MIN_BLOCKS + // moves the line (0: the register kernel always); gfx1151's table sets 4096, the crossover with the cooperative scan + static const int64_t kRegMinBlocks = [] { + const char* v = std::getenv("STRATA_TOPK_REG_MIN_BLOCKS"); + return v != nullptr ? (int64_t) std::atoll(v) : (int64_t) 7168; + }(); const bool too_small = counted && reach < kRegMinBlocks; if (old || too_small || reach > fit) { #else diff --git a/src/kernels/expdec_bench.cpp b/src/kernels/expdec_bench.cpp new file mode 100644 index 00000000..a3edf0c3 --- /dev/null +++ b/src/kernels/expdec_bench.cpp @@ -0,0 +1,480 @@ +// src/kernels/expdec_bench.cpp - the VRAM experts of a decode verify window: the default grouped kernels against +// EXPDEC (STRATA_EXPDEC=1, docs/EXPERTDEC.md), bit for bit and in microseconds, per card, per T, per format pair. +// +// build/expdec_bench [reps = 300] [device = -1 (all)] [groups = 20] [pairs = all] [choices = def,dec,dec:r2,dec:b4,dec:r2:b4] [shape = real] +// +// The model's routed expert formats at its geometry (n_embd 2560, n_ff 640): gate/up IQ2_XXS (16), IQ2_XS (17), IQ3_XXS +// (18), IQ3_S (21), IQ2_S (22); down IQ4_NL (20), Q2_0 (42). `pairs` is a comma list of gu/down type ids ("21/20,16/42") +// or "all" (the 10 pairs). `choices` is a comma list of kernel choices: +// def the default kernels (STRATA_EXPDEC off); the reference for the bitwise check +// dec[:r][:d][:b][:w][:x][:g][:h][:m] +// EXPDEC with r = gate/up rows per lane (1, 2), d = down rows per lane (1, 2, 4), b = the +// gate/up kernel's min blocks per SM (2 | 4), w = 1 EXPDEC for the down too (the engine's +// default is the gate/up only), x = 1 also for the IQ4_NL down, g / h = gate/up / down rows +// per block (0 = auto), m = the auto rule's minimum blocks; a missing field takes the +// engine's value (the environment's STRATA_EXPDEC_* or its default) +// `shape`: real = every token picks 10 experts out of `groups` distinct ones (as fp_expert_bench: T=1 10 groups x 1 +// entry, T=2 20 x 1, T=4 20 groups with 40 entries); single = 10 T groups of one entry each (the same entries as `real` +// spread over distinct experts); both = the two, plus the decomposition at the end: per-expert cost a = (single T=4 - +// real T=2) / 20 and per-entry cost b = (real T=4 - real T=2) / 20, in us, for every choice (groups = 20 only). +// +// Per (device, pair, T, shape, choice): the output buffer against `def`'s, bit for bit (memcmp), and the median of +// 5 rounds of `reps` back-to-back `native_expert_grouped` calls with CUDA events: the whole call (gate/up + SwiGLU + +// q8_1 + down), then the gate/up phase and the down phase alone (native_expert_set_mode's phase, 3 rounds each). +// The experts rotate over a pool of >= 96 MB of distinct synthetic blobs (random bytes, sane fp16 block scales), so +// every call reads its weights cold from DRAM as the decode does each layer. +// +// One line per cell: dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT (GB/s = groups x blob +// bytes / all_us; pct = of the peak DRAM bandwidth 2 x memory clock x bus width / 8). Lines starting with '#' are +// context. Exit code 1 if any choice differs or a CUDA error occurred. GPU time only. +#include "strata/kernels/iq_kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace K = strata::kernels; + +namespace { + +constexpr int kEmbd = 2560, kFf = 640, kTop = 10, kMaxT = 4; +constexpr int kMaxEntries = kMaxT * kTop; + +struct Pair { int gu, d; }; +const Pair kModelPairs[] = { {16, 20}, {17, 20}, {18, 20}, {21, 20}, {22, 20}, {16, 42}, {17, 42}, {18, 42}, {21, 42}, {22, 42} }; + +const char* type_name(int t) { + switch (t) { + case 16: return "IQ2_XXS"; case 17: return "IQ2_XS"; case 18: return "IQ3_XXS"; case 21: return "IQ3_S"; + case 22: return "IQ2_S"; case 20: return "IQ4_NL"; case 42: return "Q2_0"; default: return "?"; + } +} +int qk_of(int t) { return t == 20 ? 32 : t == 42 ? 64 : 256; } + +struct Choice { + std::string name; + bool dec = false; + K::NativeExpertExpdecParams p; // every field set: the engine's startup values, then the choice's fields +}; +K::NativeExpertExpdecParams g_engine_params; // the engine's values at startup (environment or defaults) + +// "def" | "dec[:r][:d][:b][:x][:g][:h][:m]"; false on anything else +bool parse_choice(const std::string& s, Choice& c) { + c = Choice{}; + c.name = s; + c.p = g_engine_params; + if (s == "def") return true; + if (s.rfind("dec", 0) != 0) return false; + c.dec = true; + size_t i = 3; + while (i < s.size()) { + if (s[i] != ':') return false; + size_t j = s.find(':', i + 1); + if (j == std::string::npos) j = s.size(); + if (j < i + 3) return false; + const char key = s[i + 1]; + const int v = std::atoi(s.substr(i + 2, j - i - 2).c_str()); + switch (key) { + case 'r': if (v != 1 && v != 2) return false; c.p.gu_rows_per_lane = v; break; + case 'd': if (v != 1 && v != 2 && v != 4) return false; c.p.down_rows_per_lane = v; break; + case 'b': if (v != 2 && v != 4) return false; c.p.gu_min_blocks_per_sm = v; break; + case 'x': if (v != 0 && v != 1) return false; c.p.down_iq4_nl = v; break; + case 'w': if (v != 0 && v != 1) return false; c.p.down = v; break; // EXPDEC for the down (engine default 0) + case 'g': if (v < 0) return false; c.p.gu_rows_per_block = v; break; + case 'h': if (v < 0) return false; c.p.down_rows_per_block = v; break; + case 'm': if (v <= 0) return false; c.p.min_blocks = v; break; + default: return false; + } + i = j; + } + return true; +} + +void apply_choice(const Choice& c) { + K::native_expert_set_expdec(c.dec ? 1 : 0); + K::native_expert_set_expdec_params(c.p); +} + +bool g_cuda_error = false; + +bool ck(cudaError_t e, const char* what) { + if (e == cudaSuccess) return true; + std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); + g_cuda_error = true; + return false; +} + +uint16_t sane_half(std::mt19937& rng) { // a finite fp16 of magnitude ~2^-10 .. 2^-6 + const uint32_t r = rng(); + return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); +} + +// One expert blob [gate rows | up rows | down rows]: random bytes (any qs / qh / signs / scales nibble / grid index / +// IQ4_NL nibble / Q2_0 pair is a valid code) with a sane fp16 `d` in every block (offset 0 of every format's block). +void fill_blob(uint8_t* b, const K::NativeExpertLayout& L, std::mt19937& rng) { + for (size_t i = 0; i + 4 <= L.bytes; i += 4) { + const uint32_t r = rng(); + std::memcpy(b + i, &r, 4); + } + const size_t gu_block = K::iq_row_bytes(L.gu_type, qk_of(L.gu_type)), d_block = K::iq_row_bytes(L.d_type, qk_of(L.d_type)); + const size_t gu_blocks = (size_t) 2 * (size_t) L.n_ff * (size_t) (L.n_embd / qk_of(L.gu_type)); + for (size_t k = 0; k < gu_blocks; ++k) { + const uint16_t h = sane_half(rng); + std::memcpy(b + k * gu_block, &h, 2); + } + const size_t d_blocks = (size_t) L.n_embd * (size_t) (L.n_ff / qk_of(L.d_type)); + for (size_t k = 0; k < d_blocks; ++k) { + const uint16_t h = sane_half(rng); + std::memcpy(b + L.down_off + k * d_block, &h, 2); + } +} + +struct Window { + int groups = 0, entries = 0; + std::vector start, tok, dst; // group g: entries [start[g], start[g + 1]); tok = token, dst = out row +}; + +// real: T tokens, kTop experts each, `groups_req` distinct experts in all (capped at kTop * T, floored at kTop). +// Expert j is forced onto token j % T so that every group has at least one entry; the rest of each token's picks are +// random. +Window build_real(int T, int groups_req, std::mt19937& rng) { + Window w; + const int G = std::min(std::max(groups_req, kTop), kTop * T); + std::vector> picks((size_t) G); + for (int k = 0; k < T; ++k) { + std::vector in((size_t) G, 0); + int cnt = 0; + for (int j = k; j < G; j += T) { in[(size_t) j] = 1; ++cnt; } + std::vector rest; + for (int j = 0; j < G; ++j) + if (!in[(size_t) j]) rest.push_back(j); + std::shuffle(rest.begin(), rest.end(), rng); + for (size_t i = 0; cnt < kTop; ++i, ++cnt) in[(size_t) rest[i]] = 1; + for (int j = 0; j < G; ++j) + if (in[(size_t) j]) picks[(size_t) j].push_back(k); + } + w.groups = G; + w.start.push_back(0); + for (int g = 0; g < G; ++g) { + for (int k : picks[(size_t) g]) { + w.tok.push_back(k); + w.dst.push_back((int32_t) w.dst.size()); + } + w.start.push_back((int32_t) w.dst.size()); + } + w.entries = (int) w.dst.size(); + return w; +} +// single: kTop T groups of one entry each (token g % T) +Window build_single(int T) { + Window w; + w.groups = kTop * T; + w.start.push_back(0); + for (int g = 0; g < w.groups; ++g) { + w.tok.push_back(g % T); + w.dst.push_back(g); + w.start.push_back(g + 1); + } + w.entries = w.groups; + return w; +} + +struct DevMem { + std::vector ptrs; + ~DevMem() { for (void* p : ptrs) cudaFree(p); } + void* alloc(size_t n) { + void* p = nullptr; + if (!ck(cudaMalloc(&p, n), "malloc")) return nullptr; + ptrs.push_back(p); + return p; + } +}; + +struct StreamEvents { + cudaStream_t s = nullptr; + cudaEvent_t a = nullptr, b = nullptr; + ~StreamEvents() { + if (a) cudaEventDestroy(a); + if (b) cudaEventDestroy(b); + if (s) cudaStreamDestroy(s); + } +}; + +// (device, pair gu, pair d, T, shape, choice) -> {all, gu, down} us +using Key = std::tuple; +std::map> g_times; + +bool run_device(int dev, int reps, int groups_req, const std::vector& pool, size_t P, size_t stride, + const std::vector& xh, const K::NativeExpertLayout& L, const Pair& pair, + const std::vector& choices, const std::vector& shapes, long long& bad) { + if (!ck(cudaSetDevice(dev), "set device")) return false; + cudaDeviceProp pr{}; + cudaGetDeviceProperties(&pr, dev); + std::printf("# device %d: %s (sm_%d%d, %d SMs, L2 %d KB), %d reps x 5 rounds, <= %d groups, pool %d blobs x %.2f MB\n", dev, + pr.name, pr.major, pr.minor, pr.multiProcessorCount, pr.l2CacheSize / 1024, reps, groups_req, (int) P, + (double) L.bytes / 1e6); + int mclk_khz = 0, bus_bits = 0; + cudaDeviceGetAttribute(&mclk_khz, cudaDevAttrMemoryClockRate, dev); + cudaDeviceGetAttribute(&bus_bits, cudaDevAttrGlobalMemoryBusWidth, dev); + const double peak = 2.0 * (double) mclk_khz * 1e3 * (double) bus_bits / 8.0; // bytes / s + std::printf("# device %d peak DRAM bandwidth %.1f GB/s (memory clock %d kHz, bus %d bit)\n", dev, peak / 1e9, mclk_khz, bus_bits); + const int gmax = kMaxEntries; + DevMem mem; + auto* dpool = (uint8_t*) mem.alloc(pool.size()); + auto* dx = (float*) mem.alloc(xh.size() * sizeof(float)); + void* dxq = mem.alloc((size_t) kMaxT * kEmbd / 32 * 36); + void* dscr = mem.alloc(K::native_expert_scratch_bytes(kMaxEntries, kFf)); + auto* dout = (float*) mem.alloc((size_t) kMaxEntries * kEmbd * sizeof(float)); + auto* dptr = (unsigned long long*) mem.alloc(P * (size_t) gmax * sizeof(unsigned long long)); + auto* dstart = (int32_t*) mem.alloc((size_t) (gmax + 1) * sizeof(int32_t)); + auto* dn = (int32_t*) mem.alloc(sizeof(int32_t)); + auto* ddst = (int32_t*) mem.alloc((size_t) kMaxEntries * sizeof(int32_t)); + auto* dtok = (int32_t*) mem.alloc((size_t) kMaxEntries * sizeof(int32_t)); + if (!dpool || !dx || !dxq || !dscr || !dout || !dptr || !dstart || !dn || !ddst || !dtok) return false; + StreamEvents se; + if (!ck(cudaStreamCreate(&se.s), "stream") || !ck(cudaEventCreate(&se.a), "event") || + !ck(cudaEventCreate(&se.b), "event")) + return false; + void* stream = (void*) se.s; + if (!ck(cudaMemcpy(dpool, pool.data(), pool.size(), cudaMemcpyHostToDevice), "copy pool") || + !ck(cudaMemcpy(dx, xh.data(), xh.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x")) + return false; + K::quantize_q8_1_rows(dx, kMaxT, kEmbd, dxq, stream); + if (!ck(cudaStreamSynchronize(se.s), "quantize")) return false; + + std::mt19937 rng(20261012u); + bool ok = true; + for (int T = 1; T <= kMaxT && ok; ++T) { + for (const std::string& shape : shapes) { + if (!ok) break; + const Window w = shape == "single" ? build_single(T) : build_real(T, groups_req, rng); + const int G = w.groups, NE = w.entries; + // call i reads G experts starting at blob (i * G) % P: a fresh set until the pool wraps (>= 96 MB later) + std::vector hp(P * (size_t) G); + for (size_t i = 0; i < P; ++i) + for (int g = 0; g < G; ++g) + hp[i * (size_t) G + (size_t) g] = (unsigned long long) (dpool + ((i * (size_t) G + (size_t) g) % P) * stride); + ok = ck(cudaMemcpy(dptr, hp.data(), hp.size() * sizeof(unsigned long long), cudaMemcpyHostToDevice), "copy ptrs") && + ck(cudaMemcpy(dstart, w.start.data(), w.start.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "copy start") && + ck(cudaMemcpy(dn, &G, sizeof(int32_t), cudaMemcpyHostToDevice), "copy n") && + ck(cudaMemcpy(ddst, w.dst.data(), w.dst.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "copy dst") && + ck(cudaMemcpy(dtok, w.tok.data(), w.tok.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "copy tok"); + if (!ok) break; + std::printf("# T=%d %s: %d groups, %d entries, %.1f MB of weights per call\n", T, shape.c_str(), G, NE, + (double) G * (double) L.bytes / 1e6); + auto call = [&](size_t i) { + K::native_expert_grouped(L, dptr + (i % P) * (size_t) G, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, stream, 0); + }; + auto timed = [&](int phase, int rounds, double& out_us) { + K::native_expert_set_mode(-1, phase); + for (size_t i = 0; i < (phase == 0 ? 100u : 20u); ++i) call(i); + std::vector rs((size_t) rounds); + for (double& r : rs) { + cudaEventRecord(se.a, se.s); + for (int i = 0; i < reps; ++i) call((size_t) i); + cudaEventRecord(se.b, se.s); + cudaEventSynchronize(se.b); + float ms = 0.0f; + ok = ok && ck(cudaEventElapsedTime(&ms, se.a, se.b), "elapsed") && ck(cudaGetLastError(), "kernel"); + r = 1000.0 * (double) ms / reps; + } + std::sort(rs.begin(), rs.end()); + out_us = rs[(size_t) rounds / 2]; + K::native_expert_set_mode(-1, 0); + }; + std::vector ref, res((size_t) NE * kEmbd); + for (size_t vi = 0; vi < choices.size() && ok; ++vi) { + const Choice& c = choices[vi]; + apply_choice(c); + K::native_expert_set_mode(-1, 0); + ok = ck(cudaMemset(dout, 0, (size_t) NE * kEmbd * sizeof(float)), "memset out"); + call(0); + ok = ok && ck(cudaStreamSynchronize(se.s), "run") && ck(cudaGetLastError(), "kernel") && + ck(cudaMemcpy(res.data(), dout, res.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy out"); + if (!ok) break; + bool same = true; + if (vi == 0) { + ref = res; + long long nonfinite = 0; + for (float f : ref) nonfinite += std::isfinite(f) ? 0 : 1; + if (nonfinite) std::printf("# T=%d: %s output has %lld non-finite values\n", T, c.name.c_str(), nonfinite); + } else { + same = std::memcmp(ref.data(), res.data(), ref.size() * sizeof(float)) == 0; + } + double us[3] = {0.0, 0.0, 0.0}; + timed(0, 5, us[0]); + timed(1, 3, us[1]); + timed(2, 3, us[2]); + const double gbps = (double) G * (double) L.bytes / (us[0] * 1e-6) / 1e9; + std::printf("%d %d %s %d/%d %s %.1f %.1f %.1f %.1f %.1f%% %s\n", dev, T, shape.c_str(), L.gu_type, L.d_type, + c.name.c_str(), us[0], us[1], us[2], gbps, peak > 0.0 ? 100.0 * gbps * 1e9 / peak : 0.0, + same ? "identical" : "DIFFERENT"); + g_times[Key(dev, L.gu_type, L.d_type, T, shape, c.name)] = {us[0], us[1], us[2]}; + if (!same) ++bad; + } + } + } + Choice off; + off.p = g_engine_params; + apply_choice(off); + K::native_expert_set_mode(-1, 0); + return ok; +} + +// "gu/d,gu/d,..." -> pairs; false on a malformed item +bool parse_pairs(const std::string& spec, std::vector& out) { + size_t i = 0; + while (i < spec.size()) { + size_t j = spec.find(',', i); + if (j == std::string::npos) j = spec.size(); + const std::string item = spec.substr(i, j - i); + i = j + 1; + if (item.empty()) continue; + const size_t s = item.find('/'); + if (s == std::string::npos || s == 0 || s + 1 >= item.size()) return false; + Pair p; + p.gu = std::atoi(item.substr(0, s).c_str()); + p.d = std::atoi(item.substr(s + 1).c_str()); + if (p.gu <= 0 || p.d <= 0) return false; + out.push_back(p); + } + return !out.empty(); +} + +std::vector split_commas(const std::string& s) { + std::vector out; + size_t i = 0; + while (i <= s.size()) { + size_t j = s.find(',', i); + if (j == std::string::npos) j = s.size(); + if (j > i) out.push_back(s.substr(i, j - i)); + i = j + 1; + } + return out; +} + +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + const int reps = argc > 1 ? std::max(20, std::atoi(argv[1])) : 300; + const int only = argc > 2 ? std::atoi(argv[2]) : -1; + const int groups_req = argc > 3 ? std::min(kMaxEntries, std::max(kTop, std::atoi(argv[3]))) : 20; + std::vector pairs; + if (argc > 4 && std::string(argv[4]) != "all") { + if (!parse_pairs(argv[4], pairs)) { + std::printf("expdec_bench: pairs '%s' is not a comma list of gu/down ggml type ids\n", argv[4]); + return 1; + } + } else { + pairs.assign(std::begin(kModelPairs), std::end(kModelPairs)); + } + g_engine_params = K::native_expert_expdec_params(); + std::vector choices; + for (const std::string& s : split_commas(argc > 5 ? argv[5] : "def,dec,dec:r2,dec:b4,dec:r2:b4")) { + Choice c; + if (!parse_choice(s, c)) { + std::printf("expdec_bench: choice '%s' is not def or dec[:r<1|2>][:d<1|2|4>][:b<2|4>][:x<0|1>][:g][:h][:m]\n", s.c_str()); + return 1; + } + choices.push_back(c); + } + if (choices.empty() || choices[0].dec) { + Choice d; + parse_choice("def", d); + choices.insert(choices.begin(), d); // the reference first + } + std::vector shapes; + { + const std::string sh = argc > 6 ? argv[6] : "real"; + if (sh == "both") shapes = {"real", "single"}; + else if (sh == "real" || sh == "single") shapes = {sh}; + else { std::printf("expdec_bench: shape '%s' is not real, single or both\n", sh.c_str()); return 1; } + } + int n_dev = 0; + if (!ck(cudaGetDeviceCount(&n_dev), "device count") || n_dev == 0) { + std::printf("expdec_bench: no CUDA device\n"); + return 1; + } + if (only >= n_dev) { + std::printf("expdec_bench: device %d, only %d present\n", only, n_dev); + return 1; + } + for (const Pair& p : pairs) { + if (!K::native_expert_supported(p.gu, p.d, kEmbd, kFf)) { + std::printf("expdec_bench: native_expert_supported(%d, %d, %d, %d) is false\n", p.gu, p.d, kEmbd, kFf); + return 1; + } + const K::NativeExpertLayout L = K::native_expert_layout(p.gu, p.d, kEmbd, kFf); + bool gu = false, down = false; + K::native_expert_expdec_takes(L, gu, down); + if (!gu || !down) std::printf("# warning: EXPDEC has no %s kernel for pair %d/%d: that phase runs the default\n", + !gu ? "gate/up" : "down", p.gu, p.d); + } + for (const char* name : {"STRATA_NO_SUB16_GU", "STRATA_EXPERT_V2", "STRATA_OLD_IQ_MMVQ", "STRATA_EXP_MODE"}) { + const char* v = std::getenv(name); + if (v != nullptr && v[0] != '\0' && v[0] != '0') std::printf("# warning: %s is set, the kernel choice is bypassed\n", name); + } + K::iq_set_old_kernels(false); + std::printf("# n_embd %d, n_ff %d, %d pair(s), choices:", kEmbd, kFf, (int) pairs.size()); + for (const Choice& c : choices) { + if (c.dec) std::printf(" %s(gu R %d minb %d, down R %d iq4_nl %d, rb %d drb %d, min blocks %d)", c.name.c_str(), + c.p.gu_rows_per_lane, c.p.gu_min_blocks_per_sm, c.p.down_rows_per_lane, c.p.down_iq4_nl, + c.p.gu_rows_per_block, c.p.down_rows_per_block, c.p.min_blocks); + else std::printf(" %s", c.name.c_str()); + } + std::printf("\n# dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT\n"); + long long bad = 0; + bool ok = true; + for (const Pair& p : pairs) { + if (!ok) break; + const K::NativeExpertLayout L = K::native_expert_layout(p.gu, p.d, kEmbd, kFf); + const size_t stride = (L.bytes + 255) / 256 * 256; + const size_t P = std::max((size_t) (96u << 20) / stride + 1, (size_t) 2 * (size_t) kMaxEntries); + std::printf("# pair %d/%d: gate/up %s, down %s: blob %.2f MB (gu_row %d, d_row %d), pool %.0f MB\n", p.gu, p.d, + type_name(p.gu), type_name(p.d), (double) L.bytes / 1e6, (int) L.gu_row, (int) L.d_row, + (double) (P * stride) / 1e6); + std::mt19937 rng(77u + (unsigned) (p.gu * 131 + p.d)); + std::vector pool(P * stride, 0); + for (size_t i = 0; i < P; ++i) fill_blob(pool.data() + i * stride, L, rng); + std::vector xh((size_t) kMaxT * kEmbd); + std::normal_distribution nd(0.0f, 1.0f); + for (float& v : xh) v = nd(rng); + for (int dev = 0; dev < n_dev; ++dev) { + if (only >= 0 && dev != only) continue; + ok = run_device(dev, reps, groups_req, pool, P, stride, xh, L, p, choices, shapes, bad) && ok; + } + } + if (shapes.size() == 2 && groups_req == 20) { + std::printf("\n# decomposition (us per layer call): a = per expert = (single T=4 - real T=2) / 20, b = per entry = (real T=4 - real T=2) / 20\n"); + std::printf("# dev gu/d choice a_all a_gu a_down b_all b_gu b_down\n"); + for (int dev = 0; dev < n_dev; ++dev) { + if (only >= 0 && dev != only) continue; + for (const Pair& p : pairs) + for (const Choice& c : choices) { + auto f2 = g_times.find(Key(dev, p.gu, p.d, 2, "real", c.name)); + auto f4 = g_times.find(Key(dev, p.gu, p.d, 4, "real", c.name)); + auto s4 = g_times.find(Key(dev, p.gu, p.d, 4, "single", c.name)); + if (f2 == g_times.end() || f4 == g_times.end() || s4 == g_times.end()) continue; + std::printf("%d %d/%d %s", dev, p.gu, p.d, c.name.c_str()); + for (int k = 0; k < 3; ++k) std::printf(" %.2f", (s4->second[k] - f2->second[k]) / 20.0); + for (int k = 0; k < 3; ++k) std::printf(" %.2f", (f4->second[k] - f2->second[k]) / 20.0); + std::printf("\n"); + } + } + } + std::printf("\nexpdec_bench: %s (%lld choice comparisons differ%s)\n", (bad || !ok || g_cuda_error) ? "FAILED" : "ok", bad, + (!ok || g_cuda_error) ? ", CUDA error" : ""); + return (bad || !ok || g_cuda_error) ? 1 : 0; +} diff --git a/src/kernels/qsa_merge_daily_parity.cpp b/src/kernels/qsa_merge_daily_parity.cpp new file mode 100644 index 00000000..be473d57 --- /dev/null +++ b/src/kernels/qsa_merge_daily_parity.cpp @@ -0,0 +1,418 @@ +// Recovered from the Claude Daily merge parity harness (lab/wip-0809), extended to the Daily's chunk kernel. +// src/kernels/qsa_merge_daily_parity.cpp - the Daily's decode attention (STRATA_ATTN_DAILY=1: attn_chunk_kernel_pre75 +// and attn_merge_v2_kernel) against upstream's (attn_chunk_kernel, attn_merge_kernel), bitwise (GPU, synthetic, no +// model). +// +// The reference is upstream's pair: one chunk pass with attn_chunk_kernel (qsa_decode_attn_chunks_only, daily_chunk 0) +// and attn_merge_kernel (qsa_decode_attn_merge_only, v2 0). Against it, memcmp of: attn_merge_v2_kernel on the same +// partials; the production entry points (qsa_decode_attn_batch, and _step at n_q 1) as the environment sets them; the +// Daily's chunk kernel (daily_chunk 1, NaN-filled scratch again) merged by both mergers. Kernels are chosen by the +// arguments, never by the environment, except for the production entries. Covers: +// - the four KV formats the chunk kernel reads: fp16, int8, q4_0 (rotated or not, the merge cannot tell), k8v4; +// - page tables with unresident (-1) pages: scattered single pages, and one run of 64 pages (256 consecutive cells) +// that the window-shaped selections land on, so whole chunks inside the width are masked (m = -FLT_MAX, l = 0, +// acc = 0) and some queries are masked entirely (output 0); +// - widths {-1, 0, 1, 63, 64, 65, 1023, 1024, 1025, 2051, 4096, 16383, 16385, 32768, INT_MAX} per query (1023-1025 and 16383 / +// 16385 sit on the v2 merge's 16-chunk block edges), all queries alike and mixed within one batch; a width above +// aligned cap (2112/32768) is bounded by the chunk grid; an unaligned cap2051 keeps width<=cap; +// - n_q 1..6, caps2051/2112 (main selection and its rounded capacity) and32768 (the drafter's +// default --mtp-window); +// - selections shaped like the drafter's window (consecutive cells, window_ids), like the indexer's (ascending, with +// gaps) and unordered with repeats. +// The scratch is filled with NaN before every chunk pass, so a merge that read a partial the chunk pass did not write +// (a chunk past the width, say) would differ from the other one or produce a NaN. ~260 MB of VRAM. +// +// qsa_merge_daily_parity [--device N] the sweep; exit 0 when every case is bit-identical (77: no GPU) +// qsa_merge_daily_parity [--device N] --bench plus each merge's time per call at target/drafter caps2051/32768 +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +#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_merge_daily_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; +} + +// fp16 bits drawn directly: a random sign, exponent 11..15 (|x| in [2^-4, 2)), a random mantissa; finite by +// construction. Scales are positive: INT8 [1/64, 1/32) (codes up to 127 give |x| < 4), Q4_0 [1/4, 1/2). +uint16_t f16_value(uint32_t r) { return (uint16_t) ((r & 0x8000u) | ((11u + (r >> 16) % 5u) << 10) | (r & 0x3FFu)); } +uint16_t f16_scale_q8(uint32_t r) { return (uint16_t) ((9u << 10) | (r & 0x3FFu)); } +uint16_t f16_scale_q4(uint32_t r) { return (uint16_t) ((13u << 10) | (r & 0x3FFu)); } + +constexpr int kFmtF16 = 0, kFmtInt8 = 1, kFmtQ4 = 2, kFmtK8V4 = 3; +const char* fmt_name(int f) { return f == kFmtF16 ? "fp16" : f == kFmtInt8 ? "int8" : f == kFmtQ4 ? "q4_0" : "k8v4"; } + +struct DevicePools { // every format's pools over the same physical rows; `view` picks what a KV mode reads + uint16_t *k16 = nullptr, *v16 = nullptr, *k8s = nullptr, *v8s = nullptr; + int8_t *k8 = nullptr, *v8 = nullptr; + uint8_t *k4 = nullptr, *v4 = nullptr; + k::QsaAttnPools view(int fmt, const int32_t* table) const { + k::QsaAttnPools p; + p.page_table = table; + if (fmt == kFmtF16) { p.k_pool = k16; p.v_pool = v16; } + else if (fmt == kFmtInt8) { p.k_q = k8; p.v_q = v8; p.k_scale = k8s; p.v_scale = v8s; } + else if (fmt == kFmtQ4) { p.k_q4 = k4; p.v_q4 = v4; } + else { p.k_q = k8; p.k_scale = k8s; p.v_q4 = v4; } // K8V4: INT8 K, Q4_0 V (qsa_decode_attn.cu kv_mode 3) + return p; + } +}; + +DevicePools make_pools(int64_t rows, int64_t D, std::mt19937& rng) { + DevicePools p; + { + std::vector h((size_t) (rows * D)); + for (auto& x : h) x = f16_value(rng()); + p.k16 = upload(h); + for (auto& x : h) x = f16_value(rng()); + p.v16 = upload(h); + } + { + std::vector c((size_t) (rows * D)); + for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127); + p.k8 = upload(c); + for (auto& x : c) x = (int8_t) ((int) (rng() % 255u) - 127); + p.v8 = upload(c); + std::vector sc((size_t) (rows * (D / k::KV_Q8_GROUP))); + for (auto& x : sc) x = f16_scale_q8(rng()); + p.k8s = upload(sc); + for (auto& x : sc) x = f16_scale_q8(rng()); + p.v8s = upload(sc); + } + { + const size_t blocks = (size_t) (rows * (D / k::QK4_0)); + std::vector b(blocks * sizeof(k::block_q4_0)); + for (int side = 0; side < 2; ++side) { + for (size_t i = 0; i < blocks; ++i) { + k::block_q4_0 blk; + blk.d = f16_scale_q4(rng()); + for (auto& q : blk.qs) q = (uint8_t) (rng() & 0xFFu); + std::memcpy(b.data() + i * sizeof(k::block_q4_0), &blk, sizeof(blk)); + } + (side == 0 ? p.k4 : p.v4) = upload(b); + } + } + return p; +} + +struct Case { + int fmt = 0; + int64_t cap = 0; + int n_q = 0; + std::vector widths; +}; + +// the cells this harness can address, and where the 64 unresident pages in a row sit (cells [kHole, kHole + 256)) +constexpr int64_t kCells = 40960; +constexpr int64_t kHole = 8192; + +// query `i`'s `cap` selection ids. Every entry is a valid cell: a width above the cap makes the chunk kernel read +// all `cap` of them. +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 (window_ids), often across the unresident run + int64_t start; + if (rng() % 2 == 0) start = std::max(0, kHole - 64 * (int64_t) (rng() % 8)); // chunk-aligned on it + 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(); + DevicePools pools; + int32_t* table = nullptr; + float *q = nullptr, *scratch = nullptr, *attn_old = nullptr, *attn_new = nullptr; + int32_t *ids = nullptr, *steps = nullptr; + int64_t max_q = 0, max_cap = 0; + + 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; + // logical page -> physical page: a permutation, ~3% scattered unresident pages, and the 64-page hole + std::vector tab((size_t) pages); + 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 = upload(tab); + pools = make_pools(pages * H * PS, D, rng); + q = dalloc((size_t) (max_q * s.n_head * D)); + ids = dalloc((size_t) (max_q * max_cap)); + steps = dalloc((size_t) (max_q * k::kStepCount)); + scratch = dalloc((size_t) (k::qsa_decode_attn_scratch_floats(max_cap, s) * (uint64_t) max_q)); + attn_old = dalloc((size_t) (max_q * s.n_head * D)); + attn_new = dalloc((size_t) (max_q * s.n_head * D)); + } + + ~Harness() { + for (void* p : {static_cast(table), static_cast(q), static_cast(ids), + static_cast(steps), static_cast(scratch), static_cast(attn_old), + static_cast(attn_new), static_cast(pools.k16), static_cast(pools.v16), + static_cast(pools.k8), static_cast(pools.v8), static_cast(pools.k8s), + static_cast(pools.v8s), static_cast(pools.k4), static_cast(pools.v4)}) + if (p) ck(cudaFree(p), "free harness"); + } + + // uploads the case's queries, selections and widths, and runs ONE chunk pass into NaN-filled scratch + void prepare(const Case& c, std::mt19937& rng) { + const int64_t D = s.head_dim, NH = s.n_head; + std::normal_distribution nd(0.0f, 1.0f); + std::vector hq((size_t) (c.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) (c.n_q * c.cap)); + std::vector hst((size_t) (c.n_q * k::kStepCount), 0); + for (int i = 0; i < c.n_q; ++i) { + selection(hid.data() + (size_t) i * c.cap, c.cap, c.widths[(size_t) i], (int) (rng() % 3u), rng); + hst[(size_t) i * k::kStepCount + k::kStepWidth] = c.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 scratch_bytes = (size_t) k::qsa_decode_attn_scratch_floats(c.cap, s) * (size_t) c.n_q * 4; + ck(cudaMemset(scratch, 0xFF, scratch_bytes), "scratch NaN fill"); + ck(cudaMemset(attn_old, 0xFF, (size_t) (c.n_q * NH * D) * 4), "attn_old fill"); + ck(cudaMemset(attn_new, 0x7F, (size_t) (c.n_q * NH * D) * 4), "attn_new fill"); + k::qsa_decode_attn_chunks_only(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, c.n_q, 0, nullptr); + } + + // true when the two merges' outputs are bit-identical (and the original's has no NaN) + bool check(const Case& c, long long& nonzero) { + const int64_t D = s.head_dim, NH = s.n_head; + k::qsa_decode_attn_merge_only(steps, c.cap, s, scratch, attn_old, c.n_q, 0, nullptr); + k::qsa_decode_attn_merge_only(steps, c.cap, s, scratch, attn_new, c.n_q, 1, nullptr); + ck(cudaDeviceSynchronize(), "merge sync"); + const size_t n = (size_t) (c.n_q * NH * D); + std::vector a(n), b(n); + ck(cudaMemcpy(a.data(), attn_old, n * 4, cudaMemcpyDeviceToHost), "attn_old"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "attn_new"); + nonzero = 0; + long long nan = 0; + for (size_t i = 0; i < n; ++i) { + if (a[i] != 0.0f) ++nonzero; + if (!std::isfinite(a[i])) ++nan; + } + const bool same = std::memcmp(a.data(), b.data(), n * 4) == 0; + if (!same || nan) { + size_t first = 0; + while (first < n && std::memcmp(&a[first], &b[first], 4) == 0) ++first; + std::printf("FAIL %s cap %lld n_q %d widths", fmt_name(c.fmt), (long long) c.cap, c.n_q); + for (int32_t w : c.widths) std::printf(" %d", w); + if (first < n) { + uint32_t ua, ub; + std::memcpy(&ua, &a[first], 4); + std::memcpy(&ub, &b[first], 4); + std::printf(": first difference at query %lld head %lld dim %lld: %.9g (0x%08x) vs %.9g (0x%08x)", + (long long) (first / (NH * D)), (long long) (first / D % NH), (long long) (first % D), + a[first], ua, b[first], ub); + } + if (nan) std::printf(" (%lld nonfinite values in the original's output)", nan); + std::printf("\n"); + } + // Exercise production entry points too: either selected merger must equal the reference partials. + bool entry_same = true; + k::qsa_decode_attn_batch(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, attn_new, c.n_q, nullptr); + ck(cudaDeviceSynchronize(), "batch entry sync"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "batch entry output"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::puts("FAIL production batch differs from merge reference"); + entry_same = false; + } + if (c.n_q == 1) { + k::qsa_decode_attn_step(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, attn_new, nullptr); + ck(cudaDeviceSynchronize(), "step entry sync"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "step entry output"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::puts("FAIL production step differs from merge reference"); + entry_same = false; + } + } + // The Daily's chunk kernel on the same inputs, into NaN-filled scratch, merged by both mergers. + bool daily_same = true; + const size_t scratch_bytes = (size_t) k::qsa_decode_attn_scratch_floats(c.cap, s) * (size_t) c.n_q * 4; + ck(cudaMemset(scratch, 0xFF, scratch_bytes), "scratch NaN refill"); + k::qsa_decode_attn_chunks_only(q, pools.view(c.fmt, table), ids, steps, c.cap, s, scratch, c.n_q, 1, nullptr); + for (int v2 = 0; v2 < 2; ++v2) { + ck(cudaMemset(attn_new, 0x7F, n * 4), "attn_new refill"); + k::qsa_decode_attn_merge_only(steps, c.cap, s, scratch, attn_new, c.n_q, v2, nullptr); + ck(cudaDeviceSynchronize(), "daily chunk sync"); + ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "daily chunk output"); + if (std::memcmp(a.data(), b.data(), n * 4) != 0) { + std::printf("FAIL Daily chunk kernel + %s differs from upstream reference\n", + v2 ? "attn_merge_v2_kernel" : "attn_merge_kernel"); + daily_same = false; + } + } + return same && nan == 0 && entry_same && daily_same; + } +}; + +void bench(Harness& hx, std::mt19937& rng) { + std::printf("\n--bench: CUDA events over 200 calls per arm, each arm warmed outside timing, same buffers.\n" + "chunks BAB: B1(Daily chunk) -> A(upstream chunk) -> B2(Daily chunk); merges on hot partials:\n" + "BAB: B1(v2) -> A(upstream merger) -> B2(v2).\n"); + std::printf("%-6s %6s %4s %6s | %9s %9s %9s %9s | %9s %9s %9s %9s\n", "fmt", "cap", "n_q", "width", + "chB1 us", "chA us", "chB2 us", "meanB/A", "B1 us", "A us", "B2 us", "meanB/A"); + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "event"); + ck(cudaEventCreate(&e1), "event"); + const int iters = 200; + for (int64_t cap : {(int64_t) 2051, (int64_t) 32768}) + for (int fmt : {kFmtQ4, kFmtInt8, kFmtF16}) { + for (int n_q : {1, 2, 3, 4}) { + for (int width : {64, 2051, 16384, 31000, 32768}) { + Case c; + c.fmt = fmt; + if (width > cap) continue; + c.cap = cap; + c.n_q = n_q; + c.widths.assign((size_t) n_q, width); + hx.prepare(c, rng); + ck(cudaDeviceSynchronize(), "bench prepare"); + double us_ch[3] = {}; + for (int arm = 0; arm < 3; ++arm) { // B1 -> A -> B2: Daily, upstream, Daily chunk kernel + const int daily = arm == 1 ? 0 : 1; + auto chunks = [&] { + k::qsa_decode_attn_chunks_only(hx.q, hx.pools.view(fmt, hx.table), hx.ids, hx.steps, c.cap, + hx.s, hx.scratch, n_q, daily, nullptr); + }; + for (int i = 0; i < iters; ++i) chunks(); + ck(cudaDeviceSynchronize(), "chunk warm"); + ck(cudaEventRecord(e0, nullptr), "record"); + for (int i = 0; i < iters; ++i) chunks(); + ck(cudaEventRecord(e1, nullptr), "record"); + ck(cudaEventSynchronize(e1), "sync"); + float ms_chunks = 0.0f; + ck(cudaEventElapsedTime(&ms_chunks, e0, e1), "elapsed"); + us_ch[arm] = 1000.0 * ms_chunks / iters; + } + const double ratio_ch = us_ch[1] > 0.0 ? (us_ch[0] + us_ch[2]) / (2.0 * us_ch[1]) : std::nan(""); + double us[3] = {}; + for (int arm = 0; arm < 3; ++arm) { // B1 -> A -> B2 at this identical shape + const int v2 = arm == 1 ? 0 : 1; + auto merge = [&] { + k::qsa_decode_attn_merge_only(hx.steps, c.cap, hx.s, hx.scratch, hx.attn_new, n_q, v2, nullptr); + }; + for (int i = 0; i < iters; ++i) merge(); + ck(cudaDeviceSynchronize(), "merge arm warm"); + ck(cudaEventRecord(e0, nullptr), "record"); + for (int i = 0; i < iters; ++i) merge(); + ck(cudaEventRecord(e1, nullptr), "record"); + ck(cudaEventSynchronize(e1), "sync"); + float ms = 0.0f; + ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + us[arm] = 1000.0 * ms / iters; + } + const double ratio = us[1] > 0.0 ? (us[0] + us[2]) / (2.0 * us[1]) : std::nan(""); + std::printf("%-6s %6lld %4d %6d | %9.2f %9.2f %9.2f %9.4f | %9.2f %9.2f %9.2f %9.4f\n", + fmt_name(fmt), (long long) cap, n_q, width, us_ch[0], us_ch[1], us_ch[2], ratio_ch, us[0], + us[1], us[2], ratio); + } + } + } + ck(cudaEventDestroy(e0), "destroy event"); + ck(cudaEventDestroy(e1), "destroy event"); +} +} // namespace + +int main(int argc, char** argv) { + int device = 0; + bool do_bench = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--bench") == 0) do_bench = true; + else if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]); + else { + std::fprintf(stderr, "usage: qsa_merge_daily_parity [--device N] [--bench]\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"); + std::printf("qsa_merge_daily_parity on device %d (%s, %d.%d)\n", device, prop.name, prop.major, prop.minor); + + std::mt19937 rng(20261004u); + Harness hx; + hx.init(rng, 7, 32768); + + // 1023 / 1024 / 1025 and 16383 / 16385: the v2 merge's U = 16 chunks x 64 cells block edges + const int32_t widths[] = {-1, 0, 1, 63, 64, 65, 1023, 1024, 1025, 2051, 4096, 16383, 16384, 16385, 32768, std::numeric_limits::max()}; + const int n_widths = (int) (sizeof(widths) / sizeof(widths[0])); + long long cases = 0, failed = 0, nonzero_total = 0; + for (int fmt = 0; fmt < 4; ++fmt) { + long long fmt_cases = 0, fmt_failed = 0; + for (int64_t cap : {(int64_t) 2051, (int64_t) 2112, (int64_t) 32768}) { + for (int n_q = 1; n_q <= 6; ++n_q) { + // every width for all queries alike, then three batches of mixed widths + for (int wc = 0; wc < n_widths + 3; ++wc) { + Case c; + c.fmt = fmt; + c.cap = cap; + c.n_q = n_q; + for (int i = 0; i < n_q; ++i) + c.widths.push_back(wc < n_widths ? widths[wc] : widths[rng() % (uint32_t) n_widths]); + // The unchanged chunk contract requires width<=cap for an unaligned last chunk. + // Overflow widths remain tested at aligned caps, where the grid bounds the reads. + if (cap % 64 != 0 && std::any_of(c.widths.begin(), c.widths.end(), + [cap](int32_t w) { return (int64_t) w > cap; })) continue; + hx.prepare(c, rng); + long long nz = 0; + const bool ok = hx.check(c, nz); + nonzero_total += nz; + ++cases; + ++fmt_cases; + if (!ok) { ++failed; ++fmt_failed; } + } + } + } + std::printf("[%s] %lld cases, %s (%lld differ)\n", fmt_name(fmt), fmt_cases, fmt_failed ? "FAIL" : "bit-identical", + fmt_failed); + } + std::printf("qsa_merge_daily_parity: %lld cases, %lld differ, %lld nonzero output values in all -> %s\n", cases, failed, + nonzero_total, failed == 0 && nonzero_total > 0 ? "PASS" : "FAIL"); + if (do_bench) bench(hx, rng); + return failed == 0 && nonzero_total > 0 ? 0 : 1; +} diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index 3c8867c5..706fa13b 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -209,16 +209,28 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s, scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr); }; + // int8 KV: v2 here, and the opt-in INT8-MMA kernel (STRATA_PROMPT_ATTN_IMMA) checked and timed below beside it + if (fmt == 1) k::qsa_prompt_attn_set_imma(0); auto new_run = [&]() { if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) { std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n"); std::exit(2); } }; + float* d_im = nullptr; + ck(cudaMalloc(&d_im, nq * NH * HD * 4), "malloc"); + auto imma_run = [&]() { + k::qsa_prompt_attn_set_imma(1); + const bool ok = k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_im, nq, nullptr); + k::qsa_prompt_attn_set_imma(0); + if (!ok) { std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools (imma)\n"); std::exit(2); } + }; old_run(); new_run(); + if (fmt == 1) imma_run(); ck(cudaDeviceSynchronize(), "run"); - std::vector o((size_t) (nq * NH * HD)), nw(o.size()); + std::vector o((size_t) (nq * NH * HD)), nw(o.size()), im(fmt == 1 ? o.size() : 0); + if (fmt == 1) ck(cudaMemcpy(im.data(), d_im, im.size() * 4, cudaMemcpyDeviceToHost), "down"); ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down"); ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down"); { // a hash of the new kernel's output bits (bitwise A/B of two builds / switches) @@ -227,7 +239,7 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 std::printf("NEWHASH %016llx\n", (unsigned long long) hh); } // 1. FP64 reference on a sample of queries - double err_old = 0, err_new = 0, ref_scale = 0; + double err_old = 0, err_new = 0, err_im = 0, ref_scale = 0; for (int64_t i = 0; i < nq; i += std::max(1, nq / 16)) { const int64_t w = steps[i * k::kStepCount + k::kStepWidth]; const int32_t* sel = ids.data() + i * cap; @@ -261,6 +273,7 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 ref_scale = std::max(ref_scale, std::fabs(r)); err_old = std::max(err_old, std::fabs(o[at] - r)); err_new = std::max(err_new, std::fabs(nw[at] - r)); + if (fmt == 1) err_im = std::max(err_im, std::fabs(im[at] - r)); } } } @@ -285,7 +298,31 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 cudaEventRecord(e1); ck(cudaEventSynchronize(e1), "time"); cudaEventElapsedTime(&ms_new, e0, e1); - const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale); + bool ok_im = true; + if (fmt == 1) { // the INT8-MMA kernel: the same bounds as v2's, against FP64 and against v2 + double d_iv = 0; + for (size_t i = 0; i < o.size(); ++i) d_iv = std::max(d_iv, (double) std::fabs(im[i] - nw[i])); + float ms_im = 0, ms_v2 = 0; + for (int round = 0; round < 2; ++round) { // alternating, v2 then imma, twice; the second round counts + cudaEventRecord(e0); + for (int r = 0; r < reps; ++r) new_run(); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "time"); + cudaEventElapsedTime(&ms_v2, e0, e1); + cudaEventRecord(e0); + for (int r = 0; r < reps; ++r) imma_run(); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "time"); + cudaEventElapsedTime(&ms_im, e0, e1); + } + ok_im = err_im <= std::max(4.0 * err_old, 1e-6 * ref_scale) && d_iv <= 1e-4 * scale; + std::printf("%s int8 IMMA ctx %lld, %lld queries: vs FP64 %.3g (v2 %.3g, FP32 %.3g); IMMA vs v2 %.3g (%.2g of scale); " + "v2 %.3f -> IMMA %.3f ms per chunk (%.2fx)\n", ok_im ? "PASS" : "FAIL", (long long) ctx, (long long) nq, + err_im, err_new, err_old, d_iv, d_iv / scale, ms_v2 / reps, ms_im / reps, ms_v2 / ms_im); + } + k::qsa_prompt_attn_set_imma(-1); + cudaFree(d_im); + const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale) && ok_im; const bool ok2 = diff <= 1e-4 * scale; std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of " "scale); %.3f -> %.3f ms per chunk (%.2fx)\n", diff --git a/src/kernels/qsa_rows_bench.cpp b/src/kernels/qsa_rows_bench.cpp new file mode 100644 index 00000000..234f32dd --- /dev/null +++ b/src/kernels/qsa_rows_bench.cpp @@ -0,0 +1,353 @@ +// src/kernels/qsa_rows_bench.cpp - QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA +// layer's decode kernels at a long context, row by row. GPU, synthetic data at the real geometry (24 query heads x +// 256, 2 KV heads, indexer 4 x 128, blocks of 4 cells, top-k 2048), INT8 pools, no model. +// +// The hypothesis under test: "the decode attention of the QSA layers works row by row, re-reading K/V for every row of +// the window, so 8 layers x ~0.25 ms explain the ~2.5 ms a row the stage costs". The kernels measured here are the +// ones verify.cpp launches for a window of T rows at the usual long-context options (--max-context 262144, --kv int8): +// +// scores qsa_block_scores (block_scores_multi_kernel: every pooled key read ONCE for the T queries) +// topk qsa_block_topk (one CTA per query; max_blocks 65538 -> block_topk_wide_kernel) +// attn qsa_decode_attn_batch over each row's own selection, cap 2051 (33 chunks x 2 KV heads x T blocks) +// append native_qsa_indexer_append_steps for the T raw indexer keys (one CTA, the steps in sequence) +// dense qsa_decode_attn_batch over a 32768-cell window per row: the drafter's shape, which the hypothesis's +// "~240 us a query" comes from (the drafter runs it with ONE query per step: capture_round's record_rest) +// +// --rows: block_scores_rows_kernel (STRATA_QSA_ROWS=1, docs/QSAROWS.md) against the multi kernel, scores and ids bit for +// bit, and its microseconds beside the reference's. +// +// qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] [--rows] [--no-dense] +// exit 0 (77: no GPU; 1: a --rows parity failure) +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_select.hpp" +#include "strata/kernels/rope_scaling.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +cudaStream_t st = nullptr; +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_rows_bench: %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; +} +template std::vector download(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return h; +} +uint16_t f16_scale_q8(uint32_t r) { return (uint16_t) ((9u << 10) | (r & 0x3FFu)); } + +struct Timer { + cudaEvent_t e0 = nullptr, e1 = nullptr; + Timer() { ck(cudaEventCreate(&e0), "event"); ck(cudaEventCreate(&e1), "event"); } + ~Timer() { cudaEventDestroy(e0); cudaEventDestroy(e1); } + // microseconds per call over `iters` back-to-back calls, warmed; the median of three such runs + template double us(F&& f, int iters) { + double r[3]; + for (int a = 0; a < 3; ++a) { + for (int i = 0; i < 4; ++i) f(); + ck(cudaDeviceSynchronize(), "warm"); + ck(cudaEventRecord(e0, st), "record"); + for (int i = 0; i < iters; ++i) f(); + ck(cudaEventRecord(e1, st), "record"); + ck(cudaEventSynchronize(e1), "sync"); + float ms = 0.0f; + ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + r[a] = 1000.0 * ms / iters; + } + std::sort(r, r + 3); + return r[1]; + } +}; + +constexpr int NH = 24, HD = 256, NKV = 2, IQ = 4, ID = 128; +constexpr int MAXT = 4; + +struct Table { // us[T] for T = 1..MAXT + double us[MAXT + 1] = {}; + void print(const char* what) const { + std::printf(" %-44s", what); + for (int T = 1; T <= MAXT; ++T) std::printf(" T=%d %8.1f", T, us[T]); + std::printf(" | +%.1f us a row\n", (us[MAXT] - us[1]) / (MAXT - 1)); + } +}; +} // namespace + +int main(int argc, char** argv) { + int device = 0, iters = 100; + int64_t ctx = 131072, max_ctx = 262144; + bool rows = false, dense = true; + 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], "--iters") == 0 && i + 1 < argc) iters = std::atoi(argv[++i]); + else if (std::strcmp(argv[i], "--ctx") == 0 && i + 1 < argc) ctx = std::atoll(argv[++i]); + else if (std::strcmp(argv[i], "--max-context") == 0 && i + 1 < argc) max_ctx = std::atoll(argv[++i]); + else if (std::strcmp(argv[i], "--rows") == 0) rows = true; + else if (std::strcmp(argv[i], "--no-dense") == 0) dense = false; + else { + std::fprintf(stderr, "usage: qsa_rows_bench [--device N] [--iters 100] [--ctx 131072] [--max-context 262144] " + "[--rows] [--no-dense]\n"); + return 2; + } + } + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::puts("SKIP: no GPU"); + return 77; + } + ck(cudaSetDevice(device), "cudaSetDevice"); + ck(cudaStreamCreate(&st), "stream"); + cudaDeviceProp prop{}; + ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties"); + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t PS = s.page_size; + const int64_t max_cells = (max_ctx + PS - 1) / PS * PS; + const int64_t max_blocks = max_cells / s.idx_block + 2; // verify.cpp: max_blocks_ + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); // verify.cpp: cap_ (2051) + const int64_t cells = (ctx + MAXT + 64 + PS - 1) / PS * PS; // the pools' rows: resident cells + const int64_t pages = cells / PS, prows = pages * NKV * PS; + const int64_t dense_win = 32768, dense_cap = dense_win; // the drafter's --mtp-window + std::printf("qsa_rows_bench on device %d (%s, %d.%d), %d iterations: context %lld, capacity %lld cells (max_blocks " + "%lld), selection cap %lld, int8 pools over %lld cells%s\n", + device, prop.name, prop.major, prop.minor, iters, (long long) ctx, (long long) max_cells, + (long long) max_blocks, (long long) cap, (long long) cells, + std::getenv("STRATA_QSA_ROWS") ? ", STRATA_QSA_ROWS set" : ""); + std::mt19937 rng(20261012u); + std::normal_distribution nd(0.0f, 1.0f); + + // ---- INT8 K/V pools, every page resident, identity page table + std::vector c8((size_t) (prows * HD)); + for (auto& x : c8) x = (int8_t) ((int) (rng() % 255u) - 127); + int8_t* k8 = upload(c8); + for (auto& x : c8) x = (int8_t) ((int) (rng() % 255u) - 127); + int8_t* v8 = upload(c8); + c8.clear(); c8.shrink_to_fit(); + std::vector sc((size_t) (prows * (HD / k::KV_Q8_GROUP))); + for (auto& x : sc) x = f16_scale_q8(rng()); + uint16_t* k8s = upload(sc); + for (auto& x : sc) x = f16_scale_q8(rng()); + uint16_t* v8s = upload(sc); + std::vector tab((size_t) pages); + for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i; + int32_t* table = upload(tab); + k::QsaAttnPools pools; + pools.page_table = table; + pools.k_q = k8; pools.v_q = v8; pools.k_scale = k8s; pools.v_scale = v8s; + + // ---- the indexer's state: pooled keys (unit-ish rows), the spare, a tail, the block position + std::vector hp((size_t) (max_blocks * ID)); + for (auto& x : hp) x = nd(rng) * 0.09f; + float* pooled = upload(hp); + hp.clear(); hp.shrink_to_fit(); + std::vector hd((size_t) ID); + for (auto& x : hd) x = nd(rng) * 0.09f; + float* dead = upload(hd); + float* tail = dalloc((size_t) (s.idx_block - 1) * ID); + int32_t* block_pos = dalloc(1); + std::vector hg((size_t) ID, 1.0f); + float* gamma = upload(hg); + // the T rows' indexer queries: one query perturbed a little per row, so the selections overlap as a window's do + std::vector hq0((size_t) (IQ * ID)), hqi((size_t) (MAXT * IQ * ID)); + for (auto& x : hq0) x = nd(rng); + for (int t = 0; t < MAXT; ++t) + for (int i = 0; i < IQ * ID; ++i) hqi[(size_t) t * IQ * ID + i] = hq0[(size_t) i] + 0.15f * nd(rng); + float* q_idx = upload(hqi); + std::vector hraw((size_t) (MAXT * ID)); + for (auto& x : hraw) x = nd(rng); + float* raw = upload(hraw); + // the attention queries [MAXT, NH, HD] + std::vector hq((size_t) (MAXT * NH * HD)); + for (auto& x : hq) x = nd(rng); + float* q = upload(hq); + // step records for rows 0..MAXT-1 at cells ctx .. ctx + MAXT - 1 (verify: pos, n_kv, n_bid, width) + std::vector hst((size_t) (MAXT * k::kStepCount)); + for (int t = 0; t < MAXT; ++t) { + const int64_t pos = ctx + t, n_kv = pos + 1; + hst[(size_t) t * k::kStepCount + k::kStepPos] = (int32_t) pos; + hst[(size_t) t * k::kStepCount + k::kStepNKv] = (int32_t) n_kv; + hst[(size_t) t * k::kStepCount + k::kStepNBid] = (int32_t) (n_kv / s.idx_block); + hst[(size_t) t * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s); + } + int32_t* steps = upload(hst); + // the drafter's dense window: the same cells, width = the window + std::vector hsd(hst); + for (int t = 0; t < MAXT; ++t) hsd[(size_t) t * k::kStepCount + k::kStepWidth] = (int32_t) dense_win; + int32_t* steps_d = upload(hsd); + std::vector hwid((size_t) (MAXT * dense_cap)); + for (int t = 0; t < MAXT; ++t) + for (int64_t j = 0; j < dense_win; ++j) hwid[(size_t) t * dense_cap + j] = (int32_t) (ctx + t + 1 - dense_win + j); + int32_t* ids_d = upload(hwid); + hwid.clear(); hwid.shrink_to_fit(); + + float* scores = dalloc((size_t) (MAXT * max_blocks)); + int32_t* ids = dalloc((size_t) (MAXT * cap)); + const size_t scr_floats = (size_t) k::qsa_decode_attn_scratch_floats(cap, s); + float* scratch = dalloc(scr_floats * MAXT); + float* attn = dalloc((size_t) (MAXT * NH * HD)); + const size_t scr_floats_d = (size_t) k::qsa_decode_attn_scratch_floats(dense_cap, s); + float* scratch_d = dalloc(scr_floats_d * MAXT); + float* attn_d = dalloc((size_t) (MAXT * NH * HD)); + const k::QsaIndexerBuffers ib{tail, dead, pooled, block_pos}; + const k::RopeScaling scaling; + + // ---- the selections once (the attention's inputs), and how much the rows' selections overlap + k::qsa_block_scores(pooled, dead, q_idx, steps, MAXT, max_blocks, s, scores, st); + k::qsa_block_topk(scores, steps, MAXT, max_blocks, cap, s, ids, st); + ck(cudaDeviceSynchronize(), "selection"); + { + const std::vector hid = download(ids, (size_t) (MAXT * cap)); + std::printf(" selections: width %d a row;", hst[k::kStepWidth]); + for (int T = 2; T <= MAXT; ++T) { + std::set u; + for (int t = 0; t < T; ++t) + for (int j = 0; j < hst[(size_t) t * k::kStepCount + k::kStepWidth]; ++j) u.insert(hid[(size_t) t * cap + j]); + std::printf(" union of %d rows %zu cells (%.2fx one row)", T, u.size(), (double) u.size() / hst[k::kStepWidth]); + } + std::puts(""); + } + + Timer tm; + Table t_scores, t_topk, t_attn, t_append, t_layer, t_dense; + for (int T = 1; T <= MAXT; ++T) { + t_scores.us[T] = tm.us([&] { k::qsa_block_scores(pooled, dead, q_idx, steps, T, max_blocks, s, scores, st); }, iters); + t_topk.us[T] = tm.us([&] { k::qsa_block_topk(scores, steps, T, max_blocks, cap, s, ids, st); }, iters); + t_attn.us[T] = tm.us([&] { k::qsa_decode_attn_batch(q, pools, ids, steps, cap, s, scratch, attn, T, st); }, iters); + // the append writes the tail / pooled / block_pos the scores read; its own cells (ctx .. ctx + T - 1) land in + // the tail (ctx % 4 == 0) and, at T == 4, complete block ctx / 4: the same state every call + t_append.us[T] = tm.us([&] { + k::native_qsa_indexer_append_steps(raw, steps + k::kStepPos, (int) k::kStepCount, T, 0, gamma, 1e-6f, ib, s, + max_cells, scaling, st); + }, iters); + t_layer.us[T] = tm.us([&] { + k::native_qsa_indexer_append_steps(raw, steps + k::kStepPos, (int) k::kStepCount, T, 0, gamma, 1e-6f, ib, s, + max_cells, scaling, st); + k::qsa_block_scores(pooled, dead, q_idx, steps, T, max_blocks, s, scores, st); + k::qsa_block_topk(scores, steps, T, max_blocks, cap, s, ids, st); + k::qsa_decode_attn_batch(q, pools, ids, steps, cap, s, scratch, attn, T, st); + }, iters); + if (dense) + t_dense.us[T] = tm.us([&] { + k::qsa_decode_attn_batch(q, pools, ids_d, steps_d, dense_cap, s, scratch_d, attn_d, T, st); + }, iters); + } + std::puts("-- a QSA layer's decode kernels at the verification window's shape (us a call, median of 3 runs)"); + t_scores.print("scores qsa_block_scores (multi)"); + t_topk.print("topk qsa_block_topk"); + t_attn.print("attn qsa_decode_attn_batch cap 2051"); + t_append.print("append native_qsa_indexer_append_steps"); + t_layer.print("layer append + scores + topk + attn"); + if (dense) { + std::puts("-- the drafter's dense window (32768 cells a row): the shape the hypothesis's ~240 us a query comes from"); + t_dense.print("dense qsa_decode_attn_batch cap 32768"); + } + const double per_row = (t_layer.us[MAXT] - t_layer.us[1]) / (MAXT - 1); + std::printf("-- per row: %.1f us a QSA layer -> x4 layers (stage 0) %.2f ms, x8 layers (stage 1) %.2f ms\n", per_row, + 4 * per_row / 1000.0, 8 * per_row / 1000.0); + + bool ok = true; + if (rows) { + // QSAROWS: block_scores_rows_kernel (STRATA_QSA_ROWS=1) against block_scores_multi_kernel, bit for bit on the scores + // and on the ids the top-k draws from them, at every T; then the microseconds of the two + std::puts("-- STRATA_QSA_ROWS: qsa_block_scores_rows against qsa_block_scores (multi), scores and ids bit for bit"); + float* scores_b = dalloc((size_t) (MAXT * max_blocks)); + int32_t* ids_b = dalloc((size_t) (MAXT * cap)); + long long cases = 0, failed = 0; + Table t_rows; + for (int T = 1; T <= MAXT; ++T) { + ck(cudaMemset(scores, 0xFF, (size_t) MAXT * max_blocks * 4), "fill"); + ck(cudaMemset(scores_b, 0xFF, (size_t) MAXT * max_blocks * 4), "fill"); + ck(cudaMemset(ids, 0x7F, (size_t) MAXT * cap * 4), "fill"); + ck(cudaMemset(ids_b, 0x7F, (size_t) MAXT * cap * 4), "fill"); + k::qsa_block_scores(pooled, dead, q_idx, steps, T, max_blocks, s, scores, st); + if (!k::qsa_block_scores_rows(pooled, dead, q_idx, steps, T, max_blocks, s, scores_b, st)) { + std::printf(" FAIL T=%d: qsa_block_scores_rows refused the call\n", T); + ++cases; ++failed; + continue; + } + k::qsa_block_topk(scores, steps, T, max_blocks, cap, s, ids, st); + k::qsa_block_topk(scores_b, steps, T, max_blocks, cap, s, ids_b, st); + ck(cudaDeviceSynchronize(), "rows sync"); + const std::vector a = download(scores, (size_t) T * max_blocks), b = download(scores_b, (size_t) T * max_blocks); + const std::vector ia = download(ids, (size_t) T * cap), ib2 = download(ids_b, (size_t) T * cap); + ++cases; + const bool same_s = std::memcmp(a.data(), b.data(), a.size() * 4) == 0; + const bool same_i = std::memcmp(ia.data(), ib2.data(), ia.size() * 4) == 0; + if (!same_s || !same_i) { + ++failed; + size_t count = 0, first = a.size(); + for (size_t i = 0; i < a.size(); ++i) + if (std::memcmp(&a[i], &b[i], 4) != 0) { if (first == a.size()) first = i; ++count; } + std::printf(" FAIL T=%d: scores %s (%zu of %zu differ, first at query %zu block %zu), ids %s\n", T, + same_s ? "same" : "DIFFER", count, a.size(), first / (size_t) max_blocks, first % (size_t) max_blocks, + same_i ? "same" : "DIFFER"); + } + t_rows.us[T] = tm.us([&] { k::qsa_block_scores_rows(pooled, dead, q_idx, steps, T, max_blocks, s, scores_b, st); }, + iters); + } + // a short context too (n_bid small, the tail block with cells): rows at cells 100..103 + { + std::vector hs2(hst); + for (int t = 0; t < MAXT; ++t) { + const int64_t pos = 100 + t, n_kv = pos + 1; + hs2[(size_t) t * k::kStepCount + k::kStepPos] = (int32_t) pos; + hs2[(size_t) t * k::kStepCount + k::kStepNKv] = (int32_t) n_kv; + hs2[(size_t) t * k::kStepCount + k::kStepNBid] = (int32_t) (n_kv / s.idx_block); + hs2[(size_t) t * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s); + } + int32_t* steps2 = upload(hs2); + for (int T = 1; T <= MAXT; ++T) { + ck(cudaMemset(scores, 0xFF, (size_t) MAXT * max_blocks * 4), "fill"); + ck(cudaMemset(scores_b, 0xFF, (size_t) MAXT * max_blocks * 4), "fill"); + k::qsa_block_scores(pooled, dead, q_idx, steps2, T, max_blocks, s, scores, st); + k::qsa_block_scores_rows(pooled, dead, q_idx, steps2, T, max_blocks, s, scores_b, st); + ck(cudaDeviceSynchronize(), "rows sync"); + const std::vector a = download(scores, (size_t) T * max_blocks), b = download(scores_b, (size_t) T * max_blocks); + ++cases; + if (std::memcmp(a.data(), b.data(), a.size() * 4) != 0) { ++failed; std::printf(" FAIL short context T=%d\n", T); } + } + ck(cudaFree(steps2), "free"); + } + std::printf(" parity: %lld cases, %lld differ -> %s\n", cases, failed, failed ? "FAIL" : "bit-identical"); + ok = failed == 0; + t_scores.print("scores qsa_block_scores (multi, reference)"); + t_rows.print("scores qsa_block_scores_rows"); + ck(cudaFree(scores_b), "free"); + ck(cudaFree(ids_b), "free"); + } + for (void* p : {(void*) k8, (void*) v8, (void*) k8s, (void*) v8s, (void*) table, (void*) pooled, (void*) dead, + (void*) tail, (void*) block_pos, (void*) gamma, (void*) q_idx, (void*) raw, (void*) q, (void*) steps, + (void*) steps_d, (void*) ids_d, (void*) scores, (void*) ids, (void*) scratch, (void*) attn, + (void*) scratch_d, (void*) attn_d}) + ck(cudaFree(p), "free"); + std::printf("qsa_rows_bench: %s\n", ok ? "done" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/src/prefill/gr_upmix_parity.cu b/src/prefill/gr_upmix_parity.cu new file mode 100644 index 00000000..32c15290 --- /dev/null +++ b/src/prefill/gr_upmix_parity.cu @@ -0,0 +1,237 @@ +// src/prefill/gr_upmix_parity.cu - the hyper-connection read's fused up projection + mix (gr_upmix, STRATA_HC_UPMIX=1) +// against the default pair (Gemm::bf16 - cuBLAS - writing `gated`, then gr_mix_r), on synthetic inputs of the model's +// shapes (N = 2560, 4 streams, K = 320). Where cuBLAS's kernel sums K in the fused kernel's order the outputs are the +// same bits (CUDA 13.3 on an RTX 5090 from 33 tokens - the prompt path's default there); elsewhere FP32 rounding: the +// check bounds max |diff| / max |value| of `mixed`, counts the BF16 / FP16 images that differ, and measures both +// against an FP64 reference on sampled tokens (the fused one must be as close to it as cuBLAS). +// gr_upmix_parity the checks (T = 1 .. 32768) +// gr_upmix_parity --bench and the timings of the pair and the fused kernel at T = 2048 / 8192 / 32768 +#include "strata/prefill/gemm.hpp" +#include "strata/prefill/kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int N = 2560, HC = 4, D = N * HC, LR = 320; + +uint16_t to_bf16(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + u += 0x7fffu + ((u >> 16) & 1u); + return (uint16_t) (u >> 16); +} +float from_bf16(uint16_t h) { + const uint32_t u = (uint32_t) h << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} +bool ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e)); + return e == cudaSuccess; +} +template T* dalloc(size_t n) { + T* p = nullptr; + if (!ck(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc")) std::exit(2); + return p; +} + +struct Inputs { + int64_t T; + std::vector lo16, wu; + std::vector R, rs, w; + uint16_t *d_lo16, *d_wu; + float *d_R, *d_rs, *d_w; + Inputs(int64_t t, uint32_t seed) : T(t) { + std::mt19937 g(seed); + std::normal_distribution nd(0.0f, 1.0f); + lo16.resize((size_t) T * LR); + for (auto& x : lo16) x = to_bf16(nd(g) * 0.5f); // silu outputs: O(1) and below + wu.resize((size_t) D * LR); + for (auto& x : wu) x = to_bf16(nd(g) * 0.12f); // gated ~ N(0, ~1): sigmoid in its live range + R.resize((size_t) T * D); + for (auto& x : R) x = nd(g) * 3.0f; + rs.resize((size_t) T * HC); + for (auto& x : rs) x = 0.2f + 0.3f * std::fabs(nd(g)); + w.resize(D); + for (auto& x : w) x = 1.0f + 0.1f * nd(g); + d_lo16 = dalloc(lo16.size()); + d_wu = dalloc(wu.size()); + d_R = dalloc(R.size()); + d_rs = dalloc(rs.size()); + d_w = dalloc(w.size()); + cudaMemcpy(d_lo16, lo16.data(), lo16.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(d_wu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(d_R, R.data(), R.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(d_rs, rs.data(), rs.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice); + } + ~Inputs() { cudaFree(d_lo16); cudaFree(d_wu); cudaFree(d_R); cudaFree(d_rs); cudaFree(d_w); } +}; + +struct Outputs { + float* mixed; + uint16_t *bf, *h; + explicit Outputs(int64_t T) { + mixed = dalloc((size_t) T * N); + bf = dalloc((size_t) T * N); + h = dalloc((size_t) T * N); + } + ~Outputs() { cudaFree(mixed); cudaFree(bf); cudaFree(h); } +}; + +// mixed[t][d] in FP64 from the same BF16 inputs (the exact result both GPU paths round) +double exact_mixed(const Inputs& in, int64_t t, int d) { + double s = 0.0; + for (int c = 0; c < HC; ++c) { + double g = 0.0; + const int j = c * N + d; + for (int k = 0; k < LR; ++k) + g += (double) from_bf16(in.lo16[(size_t) t * LR + k]) * (double) from_bf16(in.wu[(size_t) j * LR + k]); + const double x = (double) in.R[(size_t) t * D + j] * in.rs[(size_t) t * HC + c] * in.w[j]; + s += x / (1.0 + std::exp(-g)); + } + return s / HC; +} + +int check(strata::prefill::Gemm& gm, cudaStream_t st, float* gated, int64_t T, uint32_t seed) { + Inputs in(T, seed); + Outputs ref(T), got(T); + gm.bf16(in.d_lo16, in.d_wu, gated, T, D, LR); + strata::prefill::gr_mix_r(in.d_R, in.d_rs, in.d_w, gated, ref.mixed, ref.bf, T, st, ref.h); + if (!strata::prefill::gr_upmix(in.d_lo16, in.d_wu, in.d_R, in.d_rs, in.d_w, got.mixed, got.bf, got.h, T, st)) { + std::printf("FAIL T=%lld: gr_upmix refused (needs CUDA sm_80+)\n", (long long) T); + return 1; + } + if (!ck(cudaStreamSynchronize(st), "run")) return 1; + const size_t n = (size_t) T * N; + std::vector a(n), b(n); + std::vector abf(n), bbf(n), ah(n), bh(n); + cudaMemcpy(a.data(), ref.mixed, n * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(b.data(), got.mixed, n * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(abf.data(), ref.bf, n * 2, cudaMemcpyDeviceToHost); + cudaMemcpy(bbf.data(), got.bf, n * 2, cudaMemcpyDeviceToHost); + cudaMemcpy(ah.data(), ref.h, n * 2, cudaMemcpyDeviceToHost); + cudaMemcpy(bh.data(), got.h, n * 2, cudaMemcpyDeviceToHost); + double md = 0, mv = 0; + size_t bf_diff = 0, h_diff = 0, bit_diff = 0, nonfinite = 0; + for (size_t i = 0; i < n; ++i) { + if (!std::isfinite(b[i])) ++nonfinite; + md = std::max(md, (double) std::fabs(a[i] - b[i])); + mv = std::max(mv, (double) std::fabs(a[i])); + bf_diff += abf[i] != bbf[i]; + h_diff += ah[i] != bh[i]; + bit_diff += std::memcmp(&a[i], &b[i], 4) != 0; + } + // FP64 on sampled tokens: each path's max |error| / max |value| + std::mt19937 g(seed ^ 0x5a5a); + const int samples = (int) std::min(T, 24); + double ea = 0, eb = 0, ev = 0; + for (int i = 0; i < samples; ++i) { + const int64_t t = T <= 24 ? i : (int64_t) (g() % (uint32_t) T); + for (int d = 0; d < N; d += 37) { + const double x = exact_mixed(in, t, d); + ea = std::max(ea, std::fabs(a[(size_t) t * N + d] - x)); + eb = std::max(eb, std::fabs(b[(size_t) t * N + d] - x)); + ev = std::max(ev, std::fabs(x)); + } + } + const double rel = md / std::max(mv, 1e-30); + const bool bad = nonfinite != 0 || rel > 1e-5 || eb > 2.0 * ea + 1e-6 * ev; + std::printf("%s T=%-6lld %s mixed max |diff| / max |value| %.2e, BF16 / FP16 images differing %.4f%% / %.4f%%; " + "vs FP64 (sampled): cuBLAS + mix %.2e, fused %.2e\n", bad ? "FAIL" : "ok ", (long long) T, + bit_diff == 0 && bf_diff == 0 && h_diff == 0 ? "bitwise " : " ", rel, + 100.0 * (double) bf_diff / (double) n, 100.0 * (double) h_diff / (double) n, ea / ev, eb / ev); + return bad ? 1 : 0; +} + +float median(std::vector v) { + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; +} + +void bench(strata::prefill::Gemm& gm, cudaStream_t st, float* gated, int64_t T) { + Inputs in(T, 7); + Outputs o(T); + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + std::vector tp, tg, tm, tf; + for (int i = 0; i < 23; ++i) { + const bool fused_first = i & 1; // alternate which runs first + for (int k = 0; k < 2; ++k) { + if ((k == 0) == fused_first) { + cudaEventRecord(e0, st); + strata::prefill::gr_upmix(in.d_lo16, in.d_wu, in.d_R, in.d_rs, in.d_w, o.mixed, o.bf, o.h, T, st); + cudaEventRecord(e1, st); + cudaEventSynchronize(e1); + float ms; + cudaEventElapsedTime(&ms, e0, e1); + if (i >= 3) tf.push_back(ms); + } else { + cudaEvent_t em; + cudaEventCreate(&em); + cudaEventRecord(e0, st); + gm.bf16(in.d_lo16, in.d_wu, gated, T, D, LR); + cudaEventRecord(em, st); + strata::prefill::gr_mix_r(in.d_R, in.d_rs, in.d_w, gated, o.mixed, o.bf, T, st, o.h); + cudaEventRecord(e1, st); + cudaEventSynchronize(e1); + float ms, msg; + cudaEventElapsedTime(&ms, e0, e1); + cudaEventElapsedTime(&msg, e0, em); + if (i >= 3) { tp.push_back(ms); tg.push_back(msg); tm.push_back(ms - msg); } + cudaEventDestroy(em); + } + } + } + const float p = median(tp), f = median(tf); + // the fused kernel's bytes: R and the outputs (FP32 + 3 x 16-bit), lo16 and w_up once + const double bytes = (double) T * D * 4 + (double) T * N * (4 + 6) + (double) T * LR * 2 + (double) D * LR * 2; + std::printf(" T=%-6lld default pair %.3f ms (up GEMM %.3f + gr_mix_r %.3f) | fused %.3f ms: %.2fx " + "(fused: %.0f GB/s of its bytes, %.0f TFLOPS of its GEMM)\n", (long long) T, p, median(tg), median(tm), + f, p / f, bytes / f / 1e6, 2.0 * T * D * LR / f / 1e9); + cudaEventDestroy(e0); + cudaEventDestroy(e1); +} + +} // namespace + +int main(int argc, char** argv) { + { // the fused read is sm_80+ (cp.async, BF16 mma): an older card has nothing to compare + int dev = 0, major = 0; + if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) { + std::printf("gr_upmix_parity: no CUDA device, skipped\n"); + return 77; + } + if (major < 8) { std::printf("gr_upmix_parity: sm_%d0, the fused read needs sm_80+: skipped\n", major); return 77; } + } + const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench"; + cudaStream_t st = nullptr; + if (!ck(cudaStreamCreate(&st), "stream")) return 1; + strata::prefill::Gemm gm; + std::string err; + if (!gm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; } + const int64_t Tmax = 32768; + float* gated = dalloc((size_t) Tmax * D); + int fails = 0; + uint32_t seed = 101; + for (const int64_t T : {1, 7, 16, 31, 32, 33, 48, 63, 64, 65, 96, 126, 127, 128, 129, 600, 1000, 2048, 4099, 8192, 32768}) fails += check(gm, st, gated, T, seed++); + if (do_bench) { + std::printf("--bench: the hyper-connection read's up projection + mix (medians of 20 alternating runs)\n"); + for (const int64_t T : {2048, 8192, 32768}) bench(gm, st, gated, T); + } + cudaFree(gated); + std::printf("gr_upmix_parity: %d failures\n", fails); + return fails ? 1 : 0; +} diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index f58a189c..0fb72f3c 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -1804,6 +1804,138 @@ __global__ void __launch_bounds__(256) gr_upmix_kernel(const uint16_t* __restric } } #endif +#if !defined(__HIPCC__) +// S23 on CUDA (sm_80+; opt-in STRATA_HC_UPMIX=1, see hc_upmix in prefill.cpp): the hyper-connection read's up +// projection (lo16 x w_up^T, BF16 in, FP32 accumulate over K = 320) with gr_mix_r as its epilogue, so `gated` +// (T x 10240 FP32, 336 MB for an 8,192-token chunk) is neither written by the GEMM nor read back by the mix - gr_mix_r +// reads R and `gated` at ~96% of the bandwidth already, so only fewer bytes make the read faster. A block: 128 tokens +// x 32 columns x the 4 streams (128 output columns), K staged in 32-deep slices (cp.async, double-buffered), 8 warps of +// 32 tokens x 16 columns x 4 streams on mma.m16n8k16 (ldmatrix); a lane then holds its (token, column) pairs for all 4 +// streams, and the mix runs in registers in gr_mix_r_kernel's order (x_c = R * rs * w; s = fmaf(x_c, sigm(g_c), s); +// s / 4) with the BF16 / FP16 images. The epilogue's R rows are asked into L2 at the start. With cuBLAS's up GEMM +// summing K in the same order (CUDA 13.3 on an RTX 5090 from 33 tokens: gr_upmix_parity) `mixed` is the default pair's +// bits. +constexpr int UC_BM = 128, UC_BD = 32; // tokens, columns a stream +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 // cp.async, bf16 mma: the kernel is empty before sm_80 +constexpr int UC_KC = 32, UC_LD = UC_KC + 8; // k a slice, a staged row +__device__ __forceinline__ void uc_pf_l2(const float* p) { asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); } +__device__ __forceinline__ void uc_cp16(void* s, const void* g) { + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(s)), "l"(g)); +} +__device__ __forceinline__ void uc_ldm4(unsigned (&r)[4], const void* p) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"((unsigned) __cvta_generic_to_shared(p))); +} +__device__ __forceinline__ void uc_mma(float (&d)[4], const unsigned (&a)[4], unsigned b0, unsigned b1) { + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +} +#endif +__global__ void __launch_bounds__(256, 2) gr_upmix_cuda_kernel(const uint16_t* __restrict__ lo16, + const uint16_t* __restrict__ wu, + const float* __restrict__ R, const float* __restrict__ rs, + const float* __restrict__ w, float* __restrict__ mixed, + uint16_t* __restrict__ mixed16, + uint16_t* __restrict__ mixed_h, + int64_t T) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + __shared__ __align__(16) uint16_t sA[2][UC_BM][UC_LD]; + __shared__ __align__(16) uint16_t sB[2][HC * UC_BD][UC_LD]; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, wm = warp >> 1, wn = warp & 1; + // blocks column-tile fastest: the blocks in flight share a token tile (its lo16 rows stay in L2, the epilogue's R + // reads run along rows) + const int64_t t0 = (int64_t) blockIdx.y * UC_BM; + const int d0 = blockIdx.x * UC_BD; + // the epilogue's R rows (128 tokens x 4 streams x 128 bytes) asked into L2 now, so they arrive under the GEMM + for (int i = tid; i < UC_BM * HC; i += 256) { + const int64_t t = t0 + i / HC; + if (t < T) uc_pf_l2(R + t * D + (i % HC) * N + d0); + } + auto stage = [&](int kc, int buf) { + for (int i = tid; i < UC_BM * (UC_KC / 8); i += 256) { + const int r = i / (UC_KC / 8), q = i % (UC_KC / 8); + const int64_t t = t0 + r < T ? t0 + r : T - 1; // the last tile's missing rows read a real row, unused + uc_cp16(&sA[buf][r][q * 8], lo16 + t * LR + kc * UC_KC + q * 8); + } + for (int i = tid; i < HC * UC_BD * (UC_KC / 8); i += 256) { + const int r = i / (UC_KC / 8), q = i % (UC_KC / 8); + uc_cp16(&sB[buf][r][q * 8], wu + ((int64_t) (r / UC_BD) * N + d0 + r % UC_BD) * LR + kc * UC_KC + q * 8); + } + asm volatile("cp.async.commit_group;\n" ::); + }; + float acc[2][HC][2][4]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int c = 0; c < HC; ++c) +#pragma unroll + for (int s = 0; s < 2; ++s) +#pragma unroll + for (int i = 0; i < 4; ++i) acc[mt][c][s][i] = 0.0f; + constexpr int NK = LR / UC_KC; + stage(0, 0); + for (int kc = 0; kc < NK; ++kc) { + const int buf = kc & 1; + if (kc + 1 < NK) { + stage(kc + 1, buf ^ 1); + asm volatile("cp.async.wait_group 1;\n" ::); + } else { + asm volatile("cp.async.wait_group 0;\n" ::); + } + __syncthreads(); +#pragma unroll + for (int ks = 0; ks < UC_KC / 16; ++ks) { + unsigned a[2][4]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) uc_ldm4(a[mt], &sA[buf][wm * 32 + mt * 16 + (lane & 15)][ks * 16 + (lane >> 4) * 8]); +#pragma unroll + for (int c = 0; c < HC; ++c) { + unsigned b[4]; // b[0..1]: columns 0-7 of this warp's 16, b[2..3]: 8-15 (k 0-7, 8-15 each) + uc_ldm4(b, &sB[buf][c * UC_BD + wn * 16 + (lane & 7) + ((lane >> 4) << 3)][ks * 16 + ((lane >> 3) & 1) * 8]); +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + uc_mma(acc[mt][c][0], a[mt], b[0], b[1]); + uc_mma(acc[mt][c][1], a[mt], b[2], b[3]); + } + } + } + __syncthreads(); // every read of `buf` before stage(kc + 2) refills it + } +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int64_t t = t0 + wm * 32 + mt * 16 + (lane >> 2) + h * 8; + if (t >= T) continue; +#pragma unroll + for (int s = 0; s < 2; ++s) { + const int d = d0 + wn * 16 + s * 8 + (lane & 3) * 2; + float sm[2] = {0.0f, 0.0f}; +#pragma unroll + for (int c = 0; c < HC; ++c) { + const float2 r2 = *reinterpret_cast(R + t * D + c * N + d); + const float2 w2 = *reinterpret_cast(w + c * N + d); + const float rsc = rs[t * HC + c]; + const float x0 = r2.x * rsc * w2.x, x1 = r2.y * rsc * w2.y; // gr_mix_r_kernel's order + sm[0] = fmaf(x0, sigm(acc[mt][c][s][h * 2 + 0]), sm[0]); + sm[1] = fmaf(x1, sigm(acc[mt][c][s][h * 2 + 1]), sm[1]); + } + sm[0] /= (float) HC; + sm[1] /= (float) HC; + *reinterpret_cast(mixed + t * N + d) = make_float2(sm[0], sm[1]); + if (mixed16) + *reinterpret_cast(mixed16 + t * N + d) = + (uint32_t) act16(sm[0]) | ((uint32_t) act16(sm[1]) << 16); + if (mixed_h) + *reinterpret_cast(mixed_h + t * N + d) = (uint32_t) hf(sm[0]) | ((uint32_t) hf(sm[1]) << 16); + } + } +#endif +} +#endif } // namespace void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, @@ -1875,9 +2007,20 @@ bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const check("gr_upmix"); return true; #else - (void) lo16; (void) w_up; (void) R; (void) rs; (void) w_norm; (void) mixed; (void) mixed16; (void) mixed_h; - (void) T; (void) stream; - return false; + static int ok_dev[64] = {}; // per device: 0 not asked yet, 1 sm_80+, 2 no + int dev = 0; + if (T <= 0 || cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (ok_dev[dev] == 0) { + int major = 0; + ok_dev[dev] = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + strata::cc_major_of(major) >= 8 ? 1 : 2; + cudaGetLastError(); + } + if (ok_dev[dev] != 1) return false; + gr_upmix_cuda_kernel<<>>( + lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T); + check("gr_upmix"); + return true; #endif } void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 9b78fcc9..0d2a5a50 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -381,6 +381,19 @@ void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, ck(cudaGetLastError(), "quantize"); } +void quantize_scatter(const float* x, const int32_t* slot, const int32_t* src, void* xq, int t, int64_t cols, int64_t ld, + int64_t tokens, int k_used, void* stream) { + if (tokens <= 0 || k_used <= 0) return; + static const bool gather = [] { const char* e = std::getenv("STRATA_QUANT_GATHER"); return e != nullptr && std::atoi(e) != 0; }(); + if (gather) { + quantize(x, src, xq, t, cols, ld, tokens * k_used, stream); + return; + } + quantize_scatter_mmq_q8_1_cuda(x, slot, xq, (ggml_type) t, cols, ld, pad512(cols), tokens, tokens * k_used, k_used, + (cudaStream_t) stream); + ck(cudaGetLastError(), "quantize_scatter"); +} + Context::Context() { int dev = 0; cudaGetDevice(&dev); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 3d6d0ec1..49ea499c 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,4 +1,5 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. +#include "strata/kernels/fused_gr.hpp" #include "strata/prefill/prefill.hpp" #include #if defined(__cpp_lib_atomic_wait) @@ -69,6 +70,7 @@ size_t matrix_bytes(int, int64_t, int64_t) { return 0; } size_t q8_bytes(int64_t, int64_t) { return 0; } void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*, float*) {} bool fp4_activations(int) { return false; } +void quantize_scatter(const float*, const int32_t*, const int32_t*, void*, int, int64_t, int64_t, int64_t, int, void*) {} Context::Context() {} Context::~Context() {} void Context::run(const Product&, void*) {} @@ -128,6 +130,9 @@ constexpr int64_t C = 10240, ZV = 6144, HV = 48; // plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer) inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; } constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min()) +// The staged walk's ring when its MMQ groups take the staged experts too: two groups, so a slot is refilled only after +// the group that read it was gathered (the walk stages at most STAGE_GRP - MMQ_GROUP - 1 entries ahead) +constexpr int STAGE_GRP = 32; constexpr int kSplitHelpRing = 48; // layer split help: the helper stage's ring slots it streams through (at most) // STRATA_PREFILL_STREAM_AHEAD=0 keeps the previous routed-only upload schedule (A/B). inline bool stream_ahead_enabled() { @@ -320,6 +325,9 @@ inline int ring_slots(size_t T) { const int big = r < 16 ? 16 : r > ring_cap() ? ring_cap() : r; return (int64_t) T >= stream_all_min() ? big : STAGE; } +// The staging buffers a layout holds: the ring, and at least STAGE_GRP for the staged walk's grouped gather. Counted +// and taken through this one place, so the bytes the prompt path borrows cover every buffer it writes. +inline int stage_slots(size_t T) { return std::max(ring_slots(T), STAGE_GRP); } constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down) // The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take // BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a @@ -407,7 +415,9 @@ struct HandWorker { } }; -// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11); +// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix: gfx11, +// and CUDA sm_80+ on chunks of 33+ tokens - there, with CUDA 13.3 on an RTX 5090, cuBLAS's up GEMM sums K in the fused +// kernel's order and the read is the default pair's bits: gr_upmix_parity, STRATA_HC_UPMIX_CHECK); // STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` static int64_t pf_switch_min_t() { // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of // N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones) @@ -418,6 +428,15 @@ inline bool hc_upmix() { static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }(); return v; } +// CUDA: the fused read only on chunks of 33+ tokens - below that cuBLAS's up GEMM takes another kernel, rounding-level +// apart, so short chunks keep the default pair +inline int64_t hc_upmix_min_t() { +#if defined(__HIPCC__) + return 0; +#else + return 33; +#endif +} inline bool bf16x2_hc(bool f16_io) { return bf16x2_mode(f16_io) == 1; } // S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass // over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces) @@ -1456,18 +1475,19 @@ bool Prefill::carve(size_t T, void* alloc) { if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); } m.ring = ring_slots(T); + const int nstage = stage_slots(T); // the staged walk may use STAGE_GRP of them if (o.base == nullptr && m.ring > 0) { // OWNED buffers: the ring in ONE allocation. 384 separate 2.7 MiB cudaMallocs each round up to a 2 MiB page // (~1.3 MiB a slot, ~0.5 GiB in all) that no count ever saw. A borrowed region keeps its per-slot layout (and // so its price, `bytes_needed`: the loans' slot counts do not move). - uint8_t* ring_base = o.take((size_t) m.ring * (size_t) MAXBLOB(), ok); - for (int i = 0; ok && i < m.ring; ++i) { + uint8_t* ring_base = o.take((size_t) nstage * (size_t) MAXBLOB(), ok); + for (int i = 0; ok && i < nstage; ++i) { m.stage_dev[i] = ring_base + (size_t) i * (size_t) MAXBLOB(); m.stage_live[i] = false; m.used_of[i] = i; } } else { - for (int i = 0; i < m.ring; ++i) { + for (int i = 0; i < nstage; ++i) { m.stage_dev[i] = o.take((size_t) MAXBLOB(), ok); m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for m.used_of[i] = i; @@ -2060,9 +2080,9 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); } if (owned_pages) { - if (ring_slots(T) > 0) o.take((size_t) ring_slots(T) * (size_t) MAXBLOB(), ok); // one allocation + if (stage_slots(T) > 0) o.take((size_t) stage_slots(T) * (size_t) MAXBLOB(), ok); // one allocation } else { - for (int i = 0; i < ring_slots(T); ++i) o.take((size_t) MAXBLOB(), ok); + for (int i = 0; i < stage_slots(T); ++i) o.take((size_t) MAXBLOB(), ok); } f(T * N); f((size_t) strata::kernels::NG_HC_DIM); @@ -2073,7 +2093,7 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src) { - return bytes_needed(g, ss, chunk, src) - (uint64_t) ring_slots((size_t) chunk) * (uint64_t) MAXBLOB(); + return bytes_needed(g, ss, chunk, src) - (uint64_t) stage_slots((size_t) chunk) * (uint64_t) MAXBLOB(); } int64_t Prefill::ring_default_slots() { @@ -2128,10 +2148,26 @@ bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y return true; } bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0) { + std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0, + void* stream = nullptr) { if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } - gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx); - if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); + const uint16_t* wb = (const uint16_t*) w->data; + if (w->q8_scale != nullptr) { + // STRATA_HC_REQ8: the GEMM takes bf16, so the int8 codes are expanded into one reused scratch on this stream + static uint16_t* scratch = nullptr; + static int64_t cap = 0; + if (w->elements > cap) { + if (scratch) cudaFree(scratch); + if (cudaMalloc((void**) &scratch, (size_t) w->elements * 2) != cudaSuccess) { + scratch = nullptr; cap = 0; err = "prefill: the STRATA_HC_REQ8 scratch"; return false; + } + cap = w->elements; + } + strata::kernels::hc_q8_to_bf16(w->data, w->q8_scale, scratch, (long long) w->elements, stream); + wb = scratch; + } + gm.bf16(X, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx); + if (X_lo) gm.bf16(X_lo, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); return true; } @@ -2786,10 +2822,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri normed = false; bool hcd = false; bool hdown = false; - if (ldx != D && !pf_hcdown()) { // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177 + if (wd->q8_scale == nullptr && ldx != D && !pf_hcdown()) { // not with STRATA_HC_REQ8's int8 rows // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177 hdown = wd->kind == core::WeightKind::Bf16InF32 && wd->data && wd->ne0 == D && wd->ne1 == LR && m.gemm.bf16_hcd_exact(m.xn16, ldx, (const uint16_t*) wd->data, m.lo, T, LR, D); - } else if (ldx != D) { + } else if (wd->q8_scale == nullptr && ldx != D) { if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR || wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC || !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR, @@ -2799,10 +2835,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } hcd = true; } - if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false; + if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs)) return false; gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); bool upmixed = false; - if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && + if (wu->q8_scale == nullptr && hc_upmix() && T >= std::max(pf_switch_min_t(), hc_upmix_min_t()) && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) { static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }(); if (checks > 0) { // the default pair first, kept for the comparison @@ -2828,8 +2864,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri m.mixed, m.mixed_bf, m.mixed_h, T, m.cs); } } - if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; - if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false; + if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo, 0, m.cs)) return false; + if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs)) return false; if (upmixed) { } else if (gr_unfused()) { gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); @@ -3624,8 +3660,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; pt.mark(kPfGather, cs); if (use_mmq) { - // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` - mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale); + // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`: + // each token quantized once and written to its K rows (slot_dev, the inverse of src_dev). + // NVFP4 w4a4 activations carry a per-row scale (Xscale): that mode keeps the gather. + if (mmq::fp4_activations(mmq_gt)) + mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale); + else + mmq::quantize_scatter(m.mixed, m.slot_dev, m.src_dev, m.Xq, mmq_gt, N, N, T, (int) K, m.cs); // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down // reads the group's own quantized H) const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP; @@ -3939,6 +3980,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri p_release_to(l, (int32_t) m.g->n_expert, m.pp->s); cudaSetDevice(pd); } + // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. + static const bool group_env = [] { + const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER"); + return v == nullptr || std::atoi(v) != 0; + }(); + const bool group_gather = group_env && stream_all && use_mmq && lay.native && + MMQ_GROUP <= mmq::kGatherGroupMax; + // The staged walk (a short prompt) groups too, resident and staged experts alike: its ring is + // then STAGE_GRP slots, two groups, and it stages no further ahead than the open group allows, + // so a group's staged slots stay unread-over until its flush (one wait on the last copy, one + // event releasing them all, as in the streamed walk). + const bool group_resident = group_env && !stream_all && use_mmq && lay.native && + MMQ_GROUP <= mmq::kGatherGroupMax; + const bool gg_now = group_gather || group_resident; + const int stage_n = group_resident ? STAGE_GRP : STAGE; // Stage ahead: the copy stream moves blobs host -> device while the compute stream works. int stage_next = 0; std::vector stage_of(order.size(), -1); @@ -3967,7 +4023,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0; if (resident) return true; const int sl = stage_next; - stage_next = (stage_next + 1) % STAGE; + stage_next = (stage_next + 1) % stage_n; const auto th = Clock::now(); const bool pinned = m.src->pinned(l, e); // pinned: never transient const uint8_t* b = pinned ? m.src->blob_stable(l, e) : nullptr; @@ -3998,12 +4054,6 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // entry the routing skipped inside an open group first gathers what the group holds so far // (`flush`), so no more than a group's entries are ever held back from the issuer. // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. - static const bool group_env = [] { - const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER"); - return v == nullptr || std::atoi(v) != 0; - }(); - const bool group_gather = group_env && stream_all && use_mmq && lay.native && - MMQ_GROUP <= mmq::kGatherGroupMax; mmq::GatherGroup gg; int gg_slots[MMQ_GROUP]; int gg_nslots = 0; // ring slots gathered by the next flush @@ -4069,7 +4119,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const int c = ns++; tgu.p[q] = m.grp_gu + (size_t) c * mmq_gub; td.p[q] = m.grp_d + (size_t) c * mmq_db; - if (group_gather) { + if (gg_now) { gg.blob[c] = blob_dev; gg.n = c + 1; if (slot >= 0) gg_slots[gg_nslots++] = slot; @@ -4079,14 +4129,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri m.grp_d + (size_t) c * mmq_db, m.cs); } } - if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } + if (slot >= 0 && !gg_now) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; - if (group_gather) { // also when the last entry was direct (a no-op without gathers) + if (gg_now) { // also when the last entry was direct (a no-op without gathers) flush(0); gg = mmq::GatherGroup{}; } } else { - if (group_gather) { + if (gg_now) { gg.blob[q] = blob_dev; gg.n = (int) q + 1; if (slot >= 0) gg_slots[gg_nslots++] = slot; @@ -4107,7 +4157,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri cudaMemsetAsync(m.grp_d + (size_t) (q + 1) * mmq_db, 0, MMQ_TAIL, m.cs); } } - if (slot >= 0 && !group_gather) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } + if (slot >= 0 && !gg_now) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; } if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; } // the group's products: gate/up, swiglu, the group's H to q8_1, down @@ -4181,7 +4231,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri size_t staged = 0; size_t pending = 0; const bool stream_ahead = stream_ahead_enabled(); - const size_t lookahead = STAGE - 1; + const size_t lookahead = group_resident ? (size_t) (STAGE_GRP - MMQ_GROUP - 1) : STAGE - 1; for (size_t j = 0; j < order.size(); ++j) { // Resident experts occupy no staging slot. Keep STAGE actual transfers ahead, // rather than STAGE positions in the mixed resident/streamed order. @@ -4196,8 +4246,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1, m.host_res[(size_t) l * m.g->n_expert + e])) return false; } else { - pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); + if (!group_resident) { // grouped: the flush waits once, on the group's last copy + pt.mark(kPfWaitCopy, cs); + cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); + } if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j], -1)) return false; --pending; // compute recorded the slot's release event before any reuse } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 638b764c..ed20bbd0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3427,6 +3427,15 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: layer split: CUDA0 loads the dense weights of layers 0-%lld only\n", (long long) split_at[0] - 1); } + // STRATA_HC_REQ8=1 (opt-in, changes the output): the hyper-connection projections are not loaded as BF16; + // load_hc_q8 below requantizes them to int8 + an fp32 scale per 32 values (~0.56x the bytes), and the freed VRAM + // goes to the expert cache like any other. (Upstream's STRATA_HC_Q8 is a different thing: the GGUF's Q8_0 bytes.) + const bool hc_req8_env = std::getenv("STRATA_HC_REQ8") != nullptr && std::atoi(std::getenv("STRATA_HC_REQ8")) != 0; + if (hc_req8_env && multi_gpu) + std::fprintf(stderr, "strata generate: WARNING: STRATA_HC_REQ8 does not support a layer split yet - the BF16 " + "projections are used\n"); + const bool hc_q8 = hc_req8_env && !multi_gpu; + if (hc_q8) strata::core::WeightTable::hc_q8_names(g.n_layers, skip); uint64_t pool_bytes = 0; if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); @@ -3476,6 +3485,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (hc_q8) { + uint64_t qb = 0; + if (!wt.load_hc_q8(o.pack, qb, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + std::fprintf(stderr, "strata generate: STRATA_HC_REQ8: hyper-connection projections as int8 + fp32/32 scales, " + "%llu MiB\n", (unsigned long long) (qb >> 20)); + } std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s in %.1f s (%zu canonical tensors " "skipped: served natively)\n", (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), load_s(), skip.size()); diff --git a/tests/cuda/prefill_mmq_scatter_test.cpp b/tests/cuda/prefill_mmq_scatter_test.cpp new file mode 100644 index 00000000..a3c53b85 --- /dev/null +++ b/tests/cuda/prefill_mmq_scatter_test.cpp @@ -0,0 +1,150 @@ +// prefill_mmq_scatter_test - the prompt path's MoE input quantized per token and scattered to its k rows +// (mmq::quantize_scatter) against the per-row gather (mmq::quantize over the expert-order source rows): the same +// q8_1 bytes, the whole buffer, for every q8_1 layout MMQ uses (D4: Q2_0 Q8_0 IQ2_XS, DS4: Q4_1, D2S6: Q2_K), on a +// routing built the way Prefill builds it (10 of 512 experts a token, rows grouped by expert), with an all-zero +// token and token counts that are not multiples of anything. --bench: both at 2K, 8K and 32K tokens. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#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; +}; + +constexpr int kExperts = 512, kUsed = 10; +constexpr int64_t kCols = 2560; + +// Prefill's maps: slot[t * k + j] = the token's row in expert order, src[row] = the token +void routing(int64_t T, std::mt19937& rng, std::vector& slot, std::vector& src) { + std::vector ids((size_t) (T * kUsed)); + std::vector pick(kExperts); + for (int e = 0; e < kExperts; ++e) pick[(size_t) e] = e; + for (int64_t t = 0; t < T; ++t) { + for (int j = 0; j < kUsed; ++j) std::swap(pick[(size_t) j], pick[(size_t) (j + rng() % (kExperts - j))]); + for (int j = 0; j < kUsed; ++j) ids[(size_t) (t * kUsed + j)] = pick[(size_t) j]; + } + std::vector cnt(kExperts, 0), fill(kExperts, 0); + for (int32_t e : ids) ++cnt[(size_t) e]; + for (int e = 1; e < kExperts; ++e) fill[(size_t) e] = fill[(size_t) e - 1] + cnt[(size_t) e - 1]; + slot.assign(ids.size(), 0); + src.assign(ids.size(), 0); + for (size_t i = 0; i < ids.size(); ++i) { + const int32_t p = fill[(size_t) ids[i]]++; + slot[i] = p; + src[(size_t) p] = (int32_t) (i / kUsed); + } +} + +int check(ggml_type t, int64_t T, uint32_t seed) { + std::mt19937 rng(seed); + std::vector slot, src; + routing(T, rng, slot, src); + std::normal_distribution nd(0.0f, 1.0f); + std::vector x((size_t) (T * kCols)); + for (float& v : x) v = nd(rng) * 0.7f; + if (T > 3) std::fill(x.begin() + 2 * kCols, x.begin() + 3 * kCols, 0.0f); // an all-zero token + const int64_t rows = T * kUsed; + const size_t qb = mmq::q8_bytes(rows, kCols); + Dev dx(x.size() * 4), dslot(slot.size() * 4), dsrc(src.size() * 4), qa(qb), qs(qb); + ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(dslot.p, slot.data(), slot.size() * 4, cudaMemcpyHostToDevice), "slot"); + ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src"); + ck(cudaMemset(qa.p, 0xA5, qb), "memset"); + ck(cudaMemset(qs.p, 0xA5, qb), "memset"); + mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, qa.p, (int) t, kCols, kCols, rows, nullptr); + mmq::quantize_scatter((const float*) dx.p, (const int32_t*) dslot.p, (const int32_t*) dsrc.p, qs.p, (int) t, kCols, + kCols, T, kUsed, nullptr); + ck(cudaDeviceSynchronize(), "quantize"); + std::vector a(qb), b(qb); + ck(cudaMemcpy(a.data(), qa.p, qb, cudaMemcpyDeviceToHost), "back"); + ck(cudaMemcpy(b.data(), qs.p, qb, cudaMemcpyDeviceToHost), "back"); + size_t diff = 0; + for (size_t i = 0; i < qb; ++i) diff += a[i] != b[i]; + std::printf("%s %-7s T=%-5lld %zu of %zu bytes differ\n", diff ? "FAIL" : "ok ", ggml_type_name(t), (long long) T, + diff, qb); + return diff ? 1 : 0; +} + +void bench(ggml_type t, int64_t T) { + std::mt19937 rng(7); + std::vector slot, src; + routing(T, rng, slot, src); + std::vector x((size_t) (T * kCols), 0.25f); + const int64_t rows = T * kUsed; + const size_t qb = mmq::q8_bytes(rows, kCols); + Dev dx(x.size() * 4), dslot(slot.size() * 4), dsrc(src.size() * 4), q(qb); + ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(dslot.p, slot.data(), slot.size() * 4, cudaMemcpyHostToDevice), "slot"); + ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src"); + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "event"); + ck(cudaEventCreate(&e1), "event"); + std::vector tg, ts; + for (int i = 0; i < 23; ++i) + for (int v = 0; v < 2; ++v) { + cudaEventRecord(e0); + if (v == 0) mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, q.p, (int) t, kCols, kCols, rows, nullptr); + else mmq::quantize_scatter((const float*) dx.p, (const int32_t*) dslot.p, (const int32_t*) dsrc.p, q.p, (int) t, + kCols, kCols, T, kUsed, nullptr); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "bench"); + float ms = 0.0f; + cudaEventElapsedTime(&ms, e0, e1); + if (i >= 3) (v == 0 ? tg : ts).push_back(ms); + } + std::sort(tg.begin(), tg.end()); + std::sort(ts.begin(), ts.end()); + const float g = tg[tg.size() / 2], s = ts[ts.size() / 2]; + std::printf(" %-7s T=%lld x %d rows: gather %.3f ms, scatter %.3f ms (%.2fx)\n", ggml_type_name(t), (long long) T, + kUsed, g, s, g / s); + cudaEventDestroy(e0); + cudaEventDestroy(e1); +} +} // namespace + +int main(int argc, char** argv) { + const bool do_bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0; + int fails = 0; + try { + const ggml_type types[] = {GGML_TYPE_Q2_0, GGML_TYPE_Q8_0, GGML_TYPE_IQ2_XS, GGML_TYPE_Q4_1, GGML_TYPE_Q2_K}; + uint32_t seed = 11; + for (ggml_type t : types) + for (int64_t T : {1, 2, 7, 600, 2099}) fails += check(t, T, seed++); + if (do_bench) { + std::printf("--bench (median of 20):\n"); + for (ggml_type t : {GGML_TYPE_IQ2_XS, GGML_TYPE_Q2_0}) { + bench(t, 2048); + bench(t, 8192); + bench(t, 32768); + } + } + } catch (const std::exception& e) { + std::printf("FAIL %s\n", e.what()); + return 1; + } + std::printf("prefill_mmq_scatter_test: %d failures\n", fails); + return fails ? 1 : 0; +}