Merge f-145-havok (#2364 multi-user series, opt-in)
This commit is contained in:
commit
df44bcb712
33 files changed
+3627
-141
No files matched your search
@@ -85,6 +85,15 @@ if(STRATA_Q6K_EXPERTS)
|
||||
add_compile_definitions(STRATA_Q6K_EXPERTS=1)
|
||||
endif()
|
||||
option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF)
|
||||
# CUDA: the pointer-table MMQ behind STRATA_MMQ_DIRECT=1 (the prompt path's MMQ reads resident experts in their cache
|
||||
# slots through a Strata-side copy of llama.cpp's MMQ scheduler, src/prefill/moe_mmq_tab.cuh). Off by default, like
|
||||
# the K-quant options above: the engine loads every kernel when it starts (CUDA_MODULE_LOADING=EAGER), and these nine
|
||||
# instances (+15 MB of binary) take 36-38 MiB of VRAM per GPU on sm_86 - expert slots every model would lose, with
|
||||
# STRATA_MMQ_DIRECT unset too. They also add ~70% of the upstream MMQ instances' compile time per CUDA arch (175 s
|
||||
# of CPU for the nine at sm_86 alone). Off, the build's device code is byte for byte the one without this feature. CUDA
|
||||
# only (not HIP, not gfx906); switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy
|
||||
# was verified against.
|
||||
option(STRATA_MMQ_TAB "Build the pointer-table prompt MMQ for STRATA_MMQ_DIRECT=1 (CUDA; ~37 MiB VRAM per GPU)" OFF)
|
||||
if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP)
|
||||
message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON")
|
||||
endif()
|
||||
@@ -408,6 +417,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
||||
target_link_libraries(qsa_topk_active_parity PRIVATE strata_kernels CUDA::cudart)
|
||||
add_test(NAME qsa_topk_active_parity COMMAND qsa_topk_active_parity)
|
||||
set_tests_properties(qsa_topk_active_parity PROPERTIES SKIP_RETURN_CODE 77)
|
||||
# STRATA_QSA_SLOTS: a batch window's scores, top-k and attention as one launch over rows of different slots
|
||||
# against one call per row, bitwise (synthetic, no model)
|
||||
add_executable(qsa_slots_parity src/kernels/qsa_slots_parity.cpp)
|
||||
target_include_directories(qsa_slots_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
|
||||
target_link_libraries(qsa_slots_parity PRIVATE strata_kernels CUDA::cudart)
|
||||
add_test(NAME qsa_slots_parity COMMAND qsa_slots_parity)
|
||||
add_test(NAME qsa_slots_parity_lanecell COMMAND qsa_slots_parity)
|
||||
set_tests_properties(qsa_slots_parity qsa_slots_parity_lanecell PROPERTIES SKIP_RETURN_CODE 77)
|
||||
set_tests_properties(qsa_slots_parity_lanecell PROPERTIES ENVIRONMENT "STRATA_ATTN_LANECELL=1")
|
||||
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
|
||||
@@ -577,6 +595,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
||||
target_link_libraries(expert_cache_segmented_test PRIVATE strata_engine)
|
||||
add_test(NAME expert_cache_segmented_test COMMAND expert_cache_segmented_test)
|
||||
set_tests_properties(expert_cache_segmented_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
|
||||
# STRATA_MMQ_DIRECT: slot_guard / slot_room / slot_tail on the uniform and the sized cache, and the default
|
||||
# (no guard) sized layout unchanged
|
||||
add_executable(expert_cache_slot_guard_test tests/core/expert_cache_slot_guard_test.cpp)
|
||||
target_link_libraries(expert_cache_slot_guard_test PRIVATE strata_engine)
|
||||
add_test(NAME expert_cache_slot_guard_test COMMAND expert_cache_slot_guard_test)
|
||||
set_tests_properties(expert_cache_slot_guard_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
|
||||
endif()
|
||||
if(STRATA_BUILD_CONVERSATION_TESTS)
|
||||
add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp)
|
||||
@@ -1462,6 +1486,47 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
endif()
|
||||
target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target})
|
||||
target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4)
|
||||
# STRATA_MMQ_TAB: the pointer-table copy of MMQ's scheduler mirrors mmq.cuh from mul_mat_q_process_tile through
|
||||
# mul_mat_q_case (struct mmq_args included). A fingerprint of that text instead of a compile probe: nothing is
|
||||
# compiled at configure time, and a llama.cpp tree with another scheduler turns the feature off instead of
|
||||
# failing the build. _strata_mmq_tab_known: the hashes moe_mmq_tab.cuh was verified against (3cf03257, the
|
||||
# fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh).
|
||||
set(_strata_mmq_tab_on OFF)
|
||||
if(STRATA_MMQ_TAB AND NOT STRATA_HIP_GFX906) # gfx906 compiles no .cu from here (its HIP glob): no tab at all
|
||||
set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0)
|
||||
set(_strata_mmq_tab_hash "")
|
||||
if(EXISTS ${_strata_mmq}/mmq.cuh)
|
||||
file(READ ${_strata_mmq}/mmq.cuh _strata_mmq_src)
|
||||
string(REPLACE "\r\n" "\n" _strata_mmq_src "${_strata_mmq_src}")
|
||||
string(FIND "${_strata_mmq_src}" "static __device__ __forceinline__ void mul_mat_q_process_tile" _strata_tab_a)
|
||||
string(FIND "${_strata_mmq_src}" "#define DECL_MMQ_CASE" _strata_tab_b)
|
||||
if(_strata_tab_a GREATER -1 AND _strata_tab_b GREATER _strata_tab_a)
|
||||
math(EXPR _strata_tab_len "${_strata_tab_b} - ${_strata_tab_a}")
|
||||
string(SUBSTRING "${_strata_mmq_src}" ${_strata_tab_a} ${_strata_tab_len} _strata_tab_region)
|
||||
string(SHA256 _strata_mmq_tab_hash "${_strata_tab_region}")
|
||||
endif()
|
||||
unset(_strata_mmq_src)
|
||||
unset(_strata_tab_region)
|
||||
endif()
|
||||
if(_strata_mmq_tab_hash AND _strata_mmq_tab_hash IN_LIST _strata_mmq_tab_known)
|
||||
set(_strata_mmq_tab_on ON)
|
||||
else()
|
||||
message(STATUS "STRATA_MMQ_TAB off: mmq.cuh differs from the mirrored scheduler (${_strata_mmq_tab_hash})")
|
||||
endif()
|
||||
endif()
|
||||
if(_strata_mmq_tab_on)
|
||||
set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh)
|
||||
# the native packs' nine types, the ones prefill_mmq_tab_test checks bit for bit; the optional Q5_0 / K-quant
|
||||
# instances (STRATA_ORCA_Q4KS_MMQ, STRATA_MMQ_KQUANTS) get no pointer table and keep the gather
|
||||
set(_strata_mmq_tab_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0)
|
||||
foreach(_t IN LISTS _strata_mmq_tab_types)
|
||||
string(TOUPPER ${_t} _strata_tab_T)
|
||||
configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu @ONLY)
|
||||
target_sources(strata_mmq PRIVATE ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu)
|
||||
endforeach()
|
||||
target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TAB=1)
|
||||
message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_tab_types}")
|
||||
endif()
|
||||
target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}
|
||||
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_compile_options(strata_mmq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
|
||||
@@ -1522,6 +1587,13 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
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)
|
||||
endif()
|
||||
if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on)
|
||||
# STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80)
|
||||
add_executable(prefill_mmq_tab_test tests/cuda/prefill_mmq_tab_test.cu)
|
||||
target_link_libraries(prefill_mmq_tab_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target})
|
||||
add_test(NAME prefill_mmq_tab_test COMMAND prefill_mmq_tab_test)
|
||||
set_tests_properties(prefill_mmq_tab_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600)
|
||||
endif()
|
||||
if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS)
|
||||
# the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds)
|
||||
add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp)
|
||||
|
||||
+47
-3
@@ -87,15 +87,59 @@ With a layer split, the engine options go into the config's `args`:
|
||||
|
||||
| Option | What it does |
|
||||
| --- | --- |
|
||||
| `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. |
|
||||
| `"parallel": N` / `--batch N` / `--slots N` (2..8 normally; with a layer split up to 8 per group, see below) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. |
|
||||
| `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. |
|
||||
| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--adapt-async 1` and no `--batch-groups` the default is one group (the adaptive tier between batch windows does not run in pipelined groups) and the log says so; with `--batch-mtp` and no `--batch-groups` the pipeline wins and `--batch-mtp` is left off (`--batch-groups 1` or `STRATA_BATCH_MTP_SERIAL=1` keeps it); `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). |
|
||||
| `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. |
|
||||
|
||||
The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by
|
||||
default (a window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads
|
||||
The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots without a
|
||||
layer split (a window holds 8 rows; with a layer split and pipelined groups, 8 per group), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads
|
||||
the count the engine reports (`INFO batch_slots=N`), and `GET /v1/status` says it (`concurrency.serving`).
|
||||
|
||||
## More than 8 slots on a layer split, and the opt-in admission and decode switches
|
||||
|
||||
(From havok2-htwo's patch series, PR #2364.)
|
||||
|
||||
**More than 8 slots.** With a layer split a pipelined window holds at most 8 rows, but each group of the pipeline is its
|
||||
own window, so `--batch 16` on 4 GPUs runs 4 groups of 4 slots (`--batch-groups auto`), `--batch 32` runs 4 groups of 8.
|
||||
Until 0.1.44.1 the engine cut such a request down to 8 slots and said so; it now runs what is asked for, as many slots
|
||||
as fit in VRAM and at most 8 per group (`INFO batch_slots=N`). `--batch-mtp` keeps its limit (rows per window are
|
||||
doubled by the proposals). Nothing changes for 8 slots or fewer. Every slot of a 16-slot pipelined batch decodes
|
||||
exactly the tokens it decodes alone (`tools/batch_test.py --n 16`, which now takes up to 32 prompts).
|
||||
|
||||
**Opt-in switches** (environment of the engine, i.e. `"env"` in the config; none is on by default). Each one changes
|
||||
how the work is scheduled or copied, not what is computed; the identity gates and `tools/batch_test.py` are in
|
||||
`phaseA-tests/review-havok.md`.
|
||||
|
||||
| Switch | What it does |
|
||||
|---|---|
|
||||
| `STRATA_SLOT_COPY_DIRECT=1` | an admission (and a slot's resume) copies the running state and the QSA K/V device to device, instead of through host images |
|
||||
| `STRATA_SLOT_COPY_BATCHSYNC=1` | with the above: queue the ~116 copies and synchronize each device once |
|
||||
| `STRATA_SLOT_CKPT_MOVE=1` | the admission's turn checkpoint moves into the slot (no 112 MB copy); it also keeps the dropped checkpoints' storage, as `STRATA_CKPT_POOL` does; a session SAVE or parked conversation taken right after an admission lacks the moved checkpoint (the slot holds it) |
|
||||
| `STRATA_CKPT_POOL=1`, `STRATA_CKPT_THREADS=1` | a checkpoint is saved into the vectors of a dropped one; a split's stage parts are saved at once |
|
||||
| `STRATA_ADMIT_MERGE_FIRST=1` | an admission reads its last prompt tokens and its first token in one window (all experts resident only) |
|
||||
| `STRATA_PIPE_BYIELD_NODRAIN=1` | a BYIELD that reaches a pipelined batch is dropped without draining the groups |
|
||||
| `STRATA_BATCH_SELF_COMMIT=1` | a one-row-per-slot window advances the GDN state itself, no commit graph |
|
||||
| `STRATA_QSA_SLOTS=1` | a window's QSA block scores, top-k and attention run as one launch over its rows |
|
||||
| `STRATA_HANDOFF_PIPE=P` | a layer split hands a prompt chunk to the next card in P pieces (2..16), gated by events, on a persistent thread |
|
||||
| `STRATA_ADMIT_SHORT_FIRST=N` (server) | a new prompt of at most N tokens takes the control lines before longer ones (a longer one that waited `STRATA_ADMIT_MAX_WAIT_S`, default 30, counts as short) |
|
||||
| `STRATA_TRACE=1` | one line per admission with its phases (drain, prompt, first window, slot copy, checkpoint copy) |
|
||||
| `STRATA_MMQ_DIRECT=1`, `STRATA_MMQ_GROUP_SORT=1` | CUDA, needs the build option `-DSTRATA_MMQ_TAB=ON`: the prompt MMQ reads resident experts in their cache slots; full MMQ groups sorted by row count (docs/DETAILS.md) |
|
||||
|
||||
Measured (4x R9700 32 GB, HIP, IQ3_S all experts resident, layer split 12,25,37, 3 interleaved rounds per arm, 0.1.44.1
|
||||
with 8 slots against the same build with 16 slots and the switches above; aggregate output tok/s, TTFT p50 in seconds):
|
||||
|
||||
| users (prompt) | 0.1.44.1, 8 slots | 16 slots, no switch | 16 slots, all switches |
|
||||
|---|---|---|---|
|
||||
| 8 (147 tokens) | 209 / 2.70 s | 209 / 2.72 s | 251 / 1.82 s |
|
||||
| 16 (147 tokens) | 208 / 20.6 s | 252 / 5.4 s | 324 / 2.0 s |
|
||||
| 16 (1.2K tokens) | 145 / 23.9 s | 167 / 10.6 s | 204 / 5.3 s |
|
||||
| 16 agents x 3 turns, follow-up TTFT | 50 tok/s / 21.2 s | 53 / 7.1 s | 56 / 5.7 s |
|
||||
|
||||
One user alone is unchanged (73-74 tok/s). Each slot's session takes VRAM from the expert cache, so on a card or split
|
||||
where the experts do not all fit, 16 slots cost the single-user speed (see docs above on what a slot costs).
|
||||
|
||||
|
||||
### What a slot costs, and what setup recommends
|
||||
|
||||
Every slot's session takes VRAM that the expert cache would otherwise hold: 0.56 GiB at a 32K context with 8-bit
|
||||
|
||||
@@ -1793,6 +1793,44 @@ the pairs in which the switched arm won). They are here so you can try them on y
|
||||
instead of 512: prefill 292.5 -> 667.1 tok/s on a 29,854-token prompt (medians of 12 and 6 fresh-engine trials).
|
||||
Reads of up to 512 fresh tokens cost about 0.6-0.75 s more per request, and the card had 0 MiB free while decoding.
|
||||
Details, limits and the measurement: [PREFILL_HEAD_ALIAS.md](PREFILL_HEAD_ALIAS.md).
|
||||
`STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`; otherwise the log says why it is off. RTX A4000, 6 interleaved pairs each,
|
||||
decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%),
|
||||
IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time.
|
||||
- **`STRATA_MMQ_DIRECT=1`: the prompt's MMQ reads resident experts in their cache slots** (CUDA, native packs; needs an
|
||||
engine built with `-DSTRATA_MMQ_TAB=ON`, which is off by default). The prompt path multiplies its experts in groups of
|
||||
16 with llama.cpp's MMQ, which wants a group's weights in one buffer at a fixed stride, so every expert a chunk routes
|
||||
to is copied there first (2.3-3.1 MB each, per chunk and layer), resident ones too. With this on, a Strata-side copy of
|
||||
MMQ's outer scheduler (`src/prefill/moe_mmq_tab.cuh`) takes one pointer per expert instead, and a resident expert is
|
||||
read where it is; streamed, peer-GPU and other experts are still copied. The launch (tile size, stream-k split,
|
||||
fixup) is the one MMQ makes for the copied group and the tile code is llama.cpp's own, so the answers are the same
|
||||
bits (`prefill_mmq_tab_test`: 874 products bitwise equal to the copied path, all nine types - Q2_0, IQ2_XXS, IQ2_XS,
|
||||
IQ2_S, IQ3_XXS, IQ3_S, IQ4_NL, IQ4_XS, Q8_0 - and every tile size; the optional Q5_0 and K-quant experts get no
|
||||
pointer table and keep the copy). Each sized cache slot keeps 256 bytes after its expert, because MMQ reads up to
|
||||
136 bytes past a 640-wide down matrix; they are zeroed before each group. That is about 2.3 MiB over 9,300 slots (one
|
||||
slot fewer out of 6,998 on one RTX 3090). `STRATA_MMQ_DIRECT=2` keeps that layout but copies as before (an A/B
|
||||
reference); 0 or unset is the default path, byte for byte. `STRATA_MMQ_DIRECT_LOG=1` adds each stage's count of experts
|
||||
read in place to the log after every prompt. Under HIP, on a build without `STRATA_MMQ_TAB`, or when CMake turned
|
||||
that option off (it does so, with a message, when the llama.cpp tree's `mmq.cuh` differs from the one the copy
|
||||
mirrors), the variable is ignored.
|
||||
**Why the build option is off:** the engine loads every kernel at start (`CUDA_MODULE_LOADING=EAGER`), and the nine
|
||||
pointer-table instances (+15 MB of binary) take 36-38 MiB of VRAM on every GPU (sm_86), with the variable unset too -
|
||||
expert slots every model would lose, as with `STRATA_MMQ_KQUANTS`. They also cost ~70% of the upstream MMQ instances'
|
||||
compile time per CUDA arch (175 s of CPU at sm_86). Without the option the device code is byte for byte that of a
|
||||
build without the feature.
|
||||
Measured on 4x RTX 3090, UD-IQ4_XS, split `12,24,36` with `--trim-stage-weights` and `--batch 16` (every expert
|
||||
resident), the engine driven directly, its "read in" time, medians of 8: a 170-token prompt 331 -> 251 ms (-24%) and
|
||||
369 -> 290 ms (-21%) in two series, a 1,217-token prompt 773 -> 634 ms (-18%) and 838 -> 675 ms (-19%). A hack that
|
||||
skipped the copies altogether ran 225 and 577 ms, but it is no bound for an exact implementation: it changes the
|
||||
routing (12,003 expert-layer entries fell to 777 on one prompt) and so does less work. On one RTX 3090 with most
|
||||
experts streamed from RAM the copies of streamed experts stay, and the prompt time did not move (within 1.5%).
|
||||
Exactness, with `STRATA_PREFILL_CPU_SHARE=0` and no adaptive swaps: the first decode window's logits after the prompt
|
||||
(`STRATA_DUMP_FIRST_LOGITS`, fp32) and 32 greedy tokens were byte-identical between 2 and 1 (and 0) for prompts of
|
||||
180-2,619 tokens - on the 4-GPU split with `--prefill 2048` (chunks of 1,024 tokens and more: the streamed walk),
|
||||
the same with 9 GB less expert cache per GPU (20-31% of the expert reads streamed, so groups mix in-place, copied and
|
||||
mid-group flushed experts), and on one GPU with `--expert-cache-per-layer`; the 150 greedy tokens of each of
|
||||
`tools/batch_test.py --n 16` prompts (solo and batch) were identical too, and to those of a build without the
|
||||
option. The uniform cache (no profile) holds no resident expert when a native pack's prompt is read (serve needs the
|
||||
profile, and a one-shot run fills the cache only while it decodes), so `expert_cache_slot_guard_test` covers it.
|
||||
|
||||
## Thread placement: `--aux-cpus` (Linux, off by default)
|
||||
|
||||
|
||||
@@ -25,6 +25,12 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& state
|
||||
int64_t upto, bool include_index, std::string& error);
|
||||
bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, std::string& error);
|
||||
// conversation_kv_save(from) + conversation_kv_restore(to) without a host image, for two states of the same layout.
|
||||
// The copies are complete on return; the residency refresh is queued on the legacy stream like the restore's.
|
||||
// `queued`: the copies are only queued on the private copy stream, the refresh is ordered after them on the device,
|
||||
// and the caller synchronizes the device before it reads or writes either state.
|
||||
bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, std::string& error, bool queued = false);
|
||||
// Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack
|
||||
// workspace, compares authoritative bytes and resident draft-ring pages, and
|
||||
// fingerprints the authoritative payload only. Never changes model state.
|
||||
@@ -60,6 +66,11 @@ bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const Sess
|
||||
const ModelGeometry& g, std::string& error);
|
||||
bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session,
|
||||
const ModelGeometry& g, std::string& error);
|
||||
// conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two
|
||||
// sessions carved alike on the same device; the caller synchronizes the device before (as for the restore).
|
||||
// `queued`: the copies are only queued (the private copy stream), and the caller synchronizes the device after too.
|
||||
bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector<int32_t>& ids,
|
||||
const ModelGeometry& g, std::string& error, bool queued = false);
|
||||
|
||||
struct ConversationView {
|
||||
const std::vector<int32_t>& ids;
|
||||
|
||||
@@ -119,6 +119,16 @@ public:
|
||||
/// always. CUDA only: a HIP build refuses it at open. The slots past `slots()` after a shrink must hold no
|
||||
/// resident expert and no loan: the CALLER evicts them first (they become CPU misses).
|
||||
void set_segment_bytes(int64_t seg_bytes) { seg_req_ = seg_bytes > 0 ? seg_bytes : 0; }
|
||||
/// STRATA_MMQ_DIRECT: `open_sized` leaves at least `g` bytes of room after each slot's blob (the prompt MMQ
|
||||
/// reads a little past a down matrix when it reads an expert in its slot). Set before opening, like
|
||||
/// `set_segment_bytes`; `close` keeps it. 0 (the default): no guard. The uniform `open` ignores it, and so does
|
||||
/// the SYCL engine's open_sized (its slots then have no guard, and `slot_tail` finds no room).
|
||||
void set_slot_guard(int64_t g) { guard_req_ = g > 0 ? g : 0; }
|
||||
/// The guard the open slots were laid out with: what `open_sized` applied (0 for uniform slots, when closed, and
|
||||
/// on SYCL, whose open_sized applies none).
|
||||
int64_t slot_guard() const { return guard_; }
|
||||
/// A sized slot's arena bytes: the blob plus the guard, 256-byte aligned.
|
||||
static int64_t slot_stride(int64_t blob, int64_t guard = 0) { return (blob + guard + 255) / 256 * 256; }
|
||||
bool segmented() const { return !segs_.empty(); }
|
||||
int64_t segment_bytes() const { return seg_; }
|
||||
/// Bytes of the arena backed by VRAM now (a whole number of segments; the arena when not segmented).
|
||||
@@ -208,6 +218,14 @@ public:
|
||||
VmmRange* vmm_range() { return vmm_.get(); }
|
||||
/// Byte offset of slot `s` in the arena (s == slots(): the end).
|
||||
uint64_t slot_offset(int64_t s) const { return off_.empty() ? (uint64_t) s * (uint64_t) blob_ : off_[(size_t) s]; }
|
||||
/// The arena bytes of slot `s` (its blob, any slack and the guard).
|
||||
uint64_t slot_room(int32_t s) const { return slot_offset(s + 1) - slot_offset(s); }
|
||||
/// STRATA_MMQ_DIRECT: the address `blob` bytes into slot `s` when the slot has room for `need` more bytes there
|
||||
/// (null otherwise, or for a bad slot). Uniform slots too: their stride is the largest blob.
|
||||
uint8_t* slot_tail(int32_t s, uint64_t blob, uint64_t need) const {
|
||||
if (s < 0 || s >= slots_ || base_ == nullptr) return nullptr;
|
||||
return slot_room(s) >= blob + need ? base_ + slot_offset(s) + blob : nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
#if defined(STRATA_USE_HIP)
|
||||
@@ -221,6 +239,8 @@ private:
|
||||
uint8_t* base_ = nullptr;
|
||||
int64_t live_slots_ = 0; ///< #533: slots() - all of them unless shrunk
|
||||
int64_t seg_req_ = 0; ///< #533: the segment size asked for (0: one cudaMalloc)
|
||||
int64_t guard_req_ = 0; ///< STRATA_MMQ_DIRECT: bytes kept after each sized slot's blob (set_slot_guard)
|
||||
int64_t guard_ = 0; ///< ...the guard open_sized applied to the open slots (0: none)
|
||||
int64_t seg_ = 0; ///< #533: the segment size used (a multiple of the driver's granularity)
|
||||
uint64_t reserved_ = 0; ///< #533: the reserved address range's size
|
||||
std::vector<unsigned long long> segs_; ///< #533: each segment's physical handle (0: unmapped)
|
||||
|
||||
@@ -120,6 +120,8 @@ public:
|
||||
return t >= 0 && t < 32 && ((nf_mask_ >> t) & 1u) != 0;
|
||||
}
|
||||
static bool nan_guard_on();
|
||||
/// The most tokens one window holds (`init`'s `max_t`; 0 before it).
|
||||
int max_t() const { return max_t_; }
|
||||
/// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per
|
||||
/// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its
|
||||
/// parameters would otherwise be baked forever - so this can change between requests freely.
|
||||
@@ -170,6 +172,12 @@ public:
|
||||
void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) {
|
||||
lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out;
|
||||
}
|
||||
/// The rows the hand-off buffers of `set_stage` hold (0: kVerifyMaxT, the default). More than --batch's 8 slots on a
|
||||
/// layer split: the pipelined slot groups write their rows at hbase = group * rows-per-group, one row per slot.
|
||||
void set_handoff_rows(int rows) { handoff_rows_ = rows; }
|
||||
/// Is the zero-doorbell graph the one a batch window would run now (every expert of the stage in VRAM by the host
|
||||
/// table)? Looks at the table, as each window does. (STRATA_ADMIT_MERGE_FIRST's gate.)
|
||||
bool ar_live() { refresh_ar(); return ar_on(); }
|
||||
/// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings
|
||||
/// and `final_R` are the last stage's.
|
||||
void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; }
|
||||
@@ -412,6 +420,7 @@ private:
|
||||
unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32)
|
||||
unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device
|
||||
int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last)
|
||||
int handoff_rows_ = 0; ///< set_handoff_rows (0: kVerifyMaxT)
|
||||
const float* hand_in_ = nullptr;
|
||||
float* hand_out_ = nullptr;
|
||||
Verifier* next_ = nullptr;
|
||||
|
||||
@@ -43,4 +43,19 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32
|
||||
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);
|
||||
|
||||
/// Up to this many queries of different slots in one qsa_decode_attn_slots call.
|
||||
constexpr int kQsaAttnMaxSlots = 8;
|
||||
|
||||
/// One KV pool set per query of a qsa_decode_attn_slots call (passed by value as a kernel argument).
|
||||
struct QsaAttnSlotPools {
|
||||
QsaAttnPools p[kQsaAttnMaxSlots];
|
||||
};
|
||||
|
||||
/// qsa_decode_attn_batch for `n_q` queries that each attend over their OWN pools (`pools.p[i]`, one KV cache per batch
|
||||
/// slot): one launch instead of one call per query, every block computing exactly what the per-query call computes.
|
||||
/// The pools must all have one KV format. False (nothing launched) where the per-query call would run another kernel
|
||||
/// (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);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -29,6 +29,13 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
|
||||
int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the
|
||||
///< batch's largest n_bid + 1; not for a captured graph)
|
||||
|
||||
/// qsa_block_scores for `nq` queries of different slots, query i scoring its own slot's keys (pooled[i], dead[i]; host
|
||||
/// arrays of device pointers): one launch whose blocks each compute exactly what the single-query call computes.
|
||||
/// False (nothing launched) where that call would run another kernel (nq > 8, STRATA_SCORES_MULTI=0): loop instead.
|
||||
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);
|
||||
|
||||
/// 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.
|
||||
/// On AMD it is the gfx12 (RDNA4) WMMA kernel (a three-way bf16 split, six products); false on any other AMD target.
|
||||
|
||||
@@ -47,6 +47,14 @@ void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, i
|
||||
/// 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);
|
||||
|
||||
constexpr int kGatherGroupMax = 16;
|
||||
/// STRATA_MMQ_DIRECT: each expert's own weight address (gate|up or down), in place of `w + z * expert_bytes` -
|
||||
/// expert z < n <= kGatherGroupMax starts at p[z]. The launch (tiles, stream-k split, fixup) is the same as
|
||||
/// with `w`: only the base address of each expert's matrix changes.
|
||||
struct WeightTab {
|
||||
const void* p[kGatherGroupMax] = {};
|
||||
};
|
||||
|
||||
/// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows
|
||||
/// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into
|
||||
/// dst rows of the same indices (`ld_dst` floats apart, via `ids`: dst row = ids[row], an identity table works).
|
||||
@@ -64,6 +72,9 @@ struct Product {
|
||||
float* dst = nullptr;
|
||||
int64_t ld_dst = 0;
|
||||
const float* y_scale = nullptr; ///< NVFP4 w4a4: the per-row activation scales (fp4_activations)
|
||||
/// set: expert z's matrix starts at tab->p[z] (w and expert_bytes are not used for addressing). CUDA only,
|
||||
/// and only where `tab_fits` said so.
|
||||
const WeightTab* tab = nullptr;
|
||||
};
|
||||
|
||||
/// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path.
|
||||
@@ -91,7 +102,6 @@ void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const
|
||||
/// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time).
|
||||
/// NVFP4: `tail_off` (0 = none) is each blob's 16-byte tail, copied to tail_dst + 16 q; `zero_bytes` are zeroed after
|
||||
/// the last expert's gu and d slots (the MMQ tail).
|
||||
constexpr int kGatherGroupMax = 16;
|
||||
struct GatherGroup {
|
||||
const uint8_t* blob[kGatherGroupMax] = {};
|
||||
int first = 0, n = 0;
|
||||
@@ -120,4 +130,35 @@ void f16_to_f32(const uint16_t* x, float* y, int64_t n, void* stream);
|
||||
/// dst = {0, rows} (the bounds of one matrix; dst on the device).
|
||||
void set_bounds(int32_t* dst, int32_t rows, void* stream);
|
||||
|
||||
// ---- STRATA_MMQ_DIRECT: the prompt MMQ reads resident experts in place (docs/DETAILS.md, "STRATA_MMQ_DIRECT") ----
|
||||
/// This build has the pointer-table MMQ (CUDA, the build option STRATA_MMQ_TAB on - off by default - and the
|
||||
/// llama.cpp tree matched the mirrored scheduler's fingerprint). false under HIP, gfx906, SYCL and builds without MMQ.
|
||||
bool tab_built();
|
||||
/// `tab_built`, `fits`, rows a multiple of 128 (no fallback tiles) and a pointer-table instance for the type (the
|
||||
/// native packs' nine: Q2_0 IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_NL IQ4_XS Q8_0; not Q5_0 or the K-quants).
|
||||
bool tab_fits(int ggml_type, int64_t w_rows);
|
||||
/// The bytes past a [rows, cols] matrix that its last row's final K tile reads (the largest over-read of any
|
||||
/// config on any visible GPU): 72 for IQ4_NL and 136 for Q8_0 at 640 columns, 0 for IQ3_S at 2560 (sm_86). 0 without MMQ.
|
||||
size_t overread_bytes(int ggml_type, int64_t cols);
|
||||
/// The room kept after each sized expert slot's blob for that over-read (the guard).
|
||||
constexpr size_t kSlotGuard = 256;
|
||||
/// Every launch of `n_experts` experts of [w_rows, *] `ggml_type` weights computes each output tile in one block
|
||||
/// with no stream-k K split, and every tile width has the same I/K tiles and SRAM layout, on every visible GPU - so an
|
||||
/// expert's rows get the same bits in any such launch, whatever its group-mates and max_rows (STRATA_MMQ_GROUP_SORT).
|
||||
/// 160 or 320 tiles per column tile on 82 SMs: yes; 108 or 128 SMs: no (stream-k splits the few-tile launches).
|
||||
bool whole_tiles(int ggml_type, int64_t w_rows, int n_experts);
|
||||
/// STRATA_MMQ_DIRECT, read once: 0 (default) today's gather; 1 the guard layout and resident experts read in
|
||||
/// place; 2 the guard layout with today's gather (the bitwise A/B reference). 0 whenever !tab_built().
|
||||
int direct_mode();
|
||||
/// kSlotGuard when direct_mode() != 0, else 0 (no CUDA call).
|
||||
size_t direct_slot_guard();
|
||||
/// The guards a group's direct experts' down over-reads land in (each `guard_bytes` long).
|
||||
struct GuardTab {
|
||||
uint8_t* p[kGatherGroupMax] = {};
|
||||
int n = 0;
|
||||
};
|
||||
/// One launch: zeroes `guard_bytes` at each g.p[i] and `tail_bytes` at tail_gu and tail_d (null: skipped). It
|
||||
/// replaces the two tail memsets of a group in direct mode. Nothing is launched when there is nothing to zero.
|
||||
void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream);
|
||||
|
||||
} // namespace strata::prefill::mmq
|
||||
@@ -35,6 +35,7 @@ struct PrefillStats {
|
||||
int64_t experts_streamed = 0; ///< expert blobs copied host -> device
|
||||
int64_t experts_dma = 0; ///< ...of which straight from the pinned arena (no CPU copy)
|
||||
int64_t experts_resident = 0; ///< expert-layer groups served from the VRAM tier
|
||||
int64_t experts_direct = 0; ///< ...of which MMQ read in their cache slots, not gathered (STRATA_MMQ_DIRECT=1)
|
||||
int64_t experts_cpu = 0; ///< ...computed on the CPU pool instead of streamed (STRATA_PREFILL_CPU_SHARE)
|
||||
double cpu_share = 0; ///< ...the share of the streamed ones it took last (measured by default)
|
||||
double ms_ple = 0;
|
||||
@@ -124,6 +125,11 @@ public:
|
||||
/// keeps the ring full. STRATA_RING_BYTES=0: 0.1.39's ring, loan and chunk list.
|
||||
static bool ring_bytes_enabled();
|
||||
|
||||
/// STRATA_MMQ_DIRECT: the guard each sized expert-cache slot keeps after its blob (ExpertCache::set_slot_guard),
|
||||
/// so the prompt MMQ can read a resident expert in its slot. 0 unless STRATA_MMQ_DIRECT is 1 or 2 on a CUDA
|
||||
/// build with the pointer-table MMQ (STRATA_MMQ_TAB).
|
||||
static size_t slot_guard_bytes();
|
||||
|
||||
/// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest
|
||||
/// first, -1 for none) and is advanced to the last two of these.
|
||||
bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err);
|
||||
@@ -202,6 +208,10 @@ private:
|
||||
bool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before)
|
||||
bool bind_stage_helper(int64_t T); // binds the helper's buffers for a one-chunk prompt of T tokens
|
||||
const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned)
|
||||
/// STRATA_HANDOFF_PIPE: the previous stage's per-piece "landed in hand_in_" events (cudaEvent_t[hand_pieces_],
|
||||
/// on its device) when it copies the chunk in pieces without a host wait; null with the one-copy hand-off
|
||||
const void* hand_ev_ = nullptr;
|
||||
int hand_pieces_ = 0;
|
||||
|
||||
std::string next_err_;
|
||||
std::future<bool> next_run_;
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
#include "strata/kernels/cpu/nvfp4_avx512.hpp"
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
#include "strata/kernels/native_qsa_indexer.hpp"
|
||||
#include "strata/kernels/qsa_decode_attn.hpp"
|
||||
#include "strata/kernels/qsa_select.hpp"
|
||||
#include "strata/kernels/verify_kernels.hpp"
|
||||
#include "strata/prefill/kernels.hpp"
|
||||
|
||||
@@ -51,3 +53,12 @@ void nvfp4_512_rows(const uint8_t*, size_t, int, const void* const*, int, float*
|
||||
strata::metal_engine::missing("strata::kernels::cpu::nvfp4_512_rows");
|
||||
}
|
||||
} // namespace strata::kernels::cpu
|
||||
|
||||
// STRATA_QSA_SLOTS (PR #2364): the one-launch-over-the-rows QSA launchers have no Metal kernel; false = "run the per-row calls",
|
||||
// which is what Verifier::record_window does on a decline.
|
||||
namespace strata::kernels {
|
||||
bool qsa_block_scores_slots(const float* const*, const float* const*, const float*, const int32_t*, int64_t, int64_t,
|
||||
const QsaShapes&, float*, void*) { return false; }
|
||||
bool qsa_decode_attn_slots(const float*, const QsaAttnSlotPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&,
|
||||
float*, float*, int64_t, void*) { return false; }
|
||||
} // namespace strata::kernels
|
||||
+36
-4
@@ -254,6 +254,15 @@ def _timeout_env(name: str, default: float) -> float | None:
|
||||
# still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable).
|
||||
# STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended.
|
||||
ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0)
|
||||
# --batch: new requests take the control lines (one prompt read at a time) short prompts first: a prompt of at most
|
||||
# STRATA_ADMIT_SHORT_FIRST tokens goes before longer ones (opt-in; unset or 0: whoever gets the lock first), and a
|
||||
# longer one that waited STRATA_ADMIT_MAX_WAIT_S (default 30) counts as short. A chat question then waits for the one
|
||||
# read in progress, not for every agent read that came before it.
|
||||
try:
|
||||
ADMIT_SHORT_FIRST = max(0, int(os.environ.get("STRATA_ADMIT_SHORT_FIRST") or 0))
|
||||
except ValueError:
|
||||
ADMIT_SHORT_FIRST = 0
|
||||
ADMIT_MAX_WAIT_S = _timeout_env("STRATA_ADMIT_MAX_WAIT_S", 30.0) or 0.0
|
||||
STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen
|
||||
STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window
|
||||
|
||||
@@ -1416,10 +1425,11 @@ class StrataEngine:
|
||||
|
||||
YIELDS_MAX = 2 # #656: how often one request's prompt read gives way to a shorter waiting one
|
||||
|
||||
def _take_control(self, cancel, plen: int, after_epoch: int | None = None):
|
||||
def _take_control(self, cancel, plen: int, after_epoch: int | None = None, new: bool = False):
|
||||
"""Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled.
|
||||
`after_epoch`: a request whose read gave way lets the requests waiting then go first."""
|
||||
entry = [plen]
|
||||
`after_epoch`: a request whose read gave way lets the requests waiting then go first.
|
||||
`new`: the request's first admission (STRATA_ADMIT_SHORT_FIRST orders only these)."""
|
||||
entry = [plen, time.monotonic(), new] # (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST)
|
||||
with self.slot_cv:
|
||||
self.waiting += 1
|
||||
self.wait_lens.append(entry)
|
||||
@@ -1433,7 +1443,17 @@ class StrataEngine:
|
||||
raise EngineDied("the engine stopped while this request waited; it was not sent")
|
||||
with self.slot_cv:
|
||||
turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1
|
||||
if turn and new and ADMIT_SHORT_FIRST > 0:
|
||||
turn = self._admit_next() is entry
|
||||
if turn and self.ctl.acquire(timeout=0.5):
|
||||
if new and ADMIT_SHORT_FIRST > 0:
|
||||
with self.slot_cv: # a shorter one came while this one waited in acquire()
|
||||
first = self._admit_next() is entry
|
||||
if not first:
|
||||
self.ctl.release()
|
||||
with self.slot_cv:
|
||||
self.slot_cv.notify_all()
|
||||
continue
|
||||
if self.alive():
|
||||
break
|
||||
self.ctl.release() # it died (or is being restarted) while this one was getting
|
||||
@@ -1456,6 +1476,18 @@ class StrataEngine:
|
||||
self.slot_cv.notify_all()
|
||||
return True
|
||||
|
||||
def _admit_next(self):
|
||||
"""STRATA_ADMIT_SHORT_FIRST=<tokens> (the caller holds slot_cv): the new request that takes the control lines
|
||||
next - one whose prompt is at most that long (it reads little) before a longer one, in arrival order within
|
||||
each; a longer one that has waited STRATA_ADMIT_MAX_WAIT_S counts as short (it is never held back for good).
|
||||
Off (unset or 0): whoever gets the lock first, as before. Only the order changes, never what is read."""
|
||||
now = time.monotonic()
|
||||
ordered = [e for e in self.wait_lens if len(e) > 2 and e[2]]
|
||||
if not ordered:
|
||||
return None
|
||||
return min(ordered, key=lambda e: (0 if e[0] <= ADMIT_SHORT_FIRST or now - e[1] >= ADMIT_MAX_WAIT_S else 1,
|
||||
e[1]))
|
||||
|
||||
SOLO_AGAIN_MAX = 2 # how often a request left alone in a slot goes back to the solo path
|
||||
SOLO_AGAIN_MIN_LEFT = 32 # ... only with at least this many tokens still allowed (max_tokens)
|
||||
|
||||
@@ -1493,7 +1525,7 @@ class StrataEngine:
|
||||
prompt, left = list(ids), int(max_new)
|
||||
reused0 = None # the first read's reused tokens: a continued leg's count includes this request's own output
|
||||
carry = {} # #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them)
|
||||
ok = yield from self._take_control(cancel, len(prompt))
|
||||
ok = yield from self._take_control(cancel, len(prompt), new=True)
|
||||
if not ok:
|
||||
return
|
||||
holding, born = True, self.gen # (the engine it now has the control lines of)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""serve/test_admit_order.py - STRATA_ADMIT_SHORT_FIRST: new requests take the control lines short prompts first
|
||||
(StrataEngine._take_control / _admit_next; no process, no GPU).
|
||||
|
||||
python -m unittest serve.test_admit_order -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import serve.server as server # noqa: E402
|
||||
from serve.server import StrataEngine # noqa: E402
|
||||
|
||||
|
||||
def engine_without_process(n=2):
|
||||
"""A StrataEngine with the admission state of a started one and no process: alive() is `e.up`."""
|
||||
e = StrataEngine("missing-executable", [], lazy=True)
|
||||
e.batch = n
|
||||
e.slot_busy = [False] * n
|
||||
e.slot_claims, e.slot_releasing, e._orphan_seen = set(), set(), {}
|
||||
e.slot_cv = threading.Condition()
|
||||
e.waiting, e.admitting, e.wait_lens, e.ctl_epoch = 0, 0, [], 0
|
||||
e.ctl = threading.Lock()
|
||||
e.gen = 1
|
||||
e.up = True
|
||||
e.alive = lambda: e.up
|
||||
return e
|
||||
|
||||
|
||||
class AdmitOrderTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.e = engine_without_process(16)
|
||||
self.order, self.cancels = [], []
|
||||
self.order_lock = threading.Lock()
|
||||
|
||||
def tearDown(self):
|
||||
for c in self.cancels:
|
||||
c.set()
|
||||
|
||||
def take(self, name, plen, **kw):
|
||||
"""A request waiting for the control lines; once it has them it notes its name and gives them back."""
|
||||
c = threading.Event()
|
||||
self.cancels.append(c)
|
||||
|
||||
def go():
|
||||
gen = self.e._take_control(c, plen, **kw)
|
||||
try:
|
||||
while True:
|
||||
next(gen)
|
||||
except StopIteration as s:
|
||||
if s.value:
|
||||
with self.order_lock:
|
||||
self.order.append(name)
|
||||
time.sleep(0.05) # its read
|
||||
self.e.ctl.release()
|
||||
threading.Thread(target=go, daemon=True).start()
|
||||
|
||||
def until(self, cond, s=5.0):
|
||||
end = time.time() + s
|
||||
while time.time() < end and not cond():
|
||||
time.sleep(0.01)
|
||||
self.assertTrue(cond())
|
||||
|
||||
def queue(self, *reqs):
|
||||
"""While a long read holds the control lines, the requests arrive in this order; then the read ends."""
|
||||
self.assertTrue(self.e.ctl.acquire(timeout=1))
|
||||
for name, plen in reqs:
|
||||
self.take(name, plen, new=True)
|
||||
self.until(lambda n=len(self.order) + sum(1 for _ in self.e.wait_lens): self.e.waiting >= 1)
|
||||
time.sleep(0.02) # (distinct arrival times)
|
||||
self.until(lambda: self.e.waiting == len(reqs))
|
||||
self.e.ctl.release()
|
||||
self.until(lambda: len(self.order) == len(reqs), s=15.0)
|
||||
return self.order
|
||||
|
||||
def test_short_first_puts_the_chat_before_the_agent_reads(self):
|
||||
with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0):
|
||||
order = self.queue(("agent1", 120000), ("agent2", 190000), ("chat", 500), ("agent3", 150000))
|
||||
self.assertEqual(order[0], "chat")
|
||||
self.assertEqual(order[1:], ["agent1", "agent2", "agent3"]) # arrival order among the long ones
|
||||
|
||||
def test_a_long_request_that_waited_too_long_goes_first(self):
|
||||
with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 0.2):
|
||||
self.assertTrue(self.e.ctl.acquire(timeout=1))
|
||||
self.take("agent", 120000, new=True)
|
||||
self.until(lambda: self.e.waiting == 1)
|
||||
time.sleep(0.4) # past STRATA_ADMIT_MAX_WAIT_S
|
||||
self.take("chat", 500, new=True)
|
||||
self.until(lambda: self.e.waiting == 2)
|
||||
self.e.ctl.release()
|
||||
self.until(lambda: len(self.order) == 2, s=15.0)
|
||||
self.assertEqual(self.order, ["agent", "chat"])
|
||||
|
||||
def test_off_by_default(self):
|
||||
self.assertEqual(server.ADMIT_SHORT_FIRST if "STRATA_ADMIT_SHORT_FIRST" not in __import__("os").environ
|
||||
else 0, 0)
|
||||
with mock.patch.object(server, "ADMIT_SHORT_FIRST", 0):
|
||||
order = self.queue(("agent1", 120000), ("chat", 500))
|
||||
self.assertEqual(sorted(order), ["agent1", "chat"]) # both get their turn, in any order
|
||||
|
||||
def test_a_continuation_is_not_held_back(self):
|
||||
"""A request already admitted once (new=False: promoted from the solo path) is not part of the order."""
|
||||
with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0):
|
||||
self.assertTrue(self.e.ctl.acquire(timeout=1))
|
||||
self.take("chat", 500, new=True)
|
||||
self.take("continuation", 190000)
|
||||
self.until(lambda: self.e.waiting == 2)
|
||||
self.e.ctl.release()
|
||||
self.until(lambda: len(self.order) == 2, s=15.0)
|
||||
self.assertEqual(sorted(self.order), ["chat", "continuation"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -19,7 +19,8 @@ namespace strata::core::conversation_detail {
|
||||
/// device, and while another thread captures a graph on one (a drafter or a stage worker), HIP refuses it with
|
||||
/// "operation would make the legacy stream depend on a capturing blocking stream". The caller's contract is
|
||||
/// unchanged: the device was synchronized before the copy (the copy itself is complete on return).
|
||||
inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) {
|
||||
/// private_stream: this thread's stream on the current device, created on first use.
|
||||
inline cudaError_t private_stream(cudaStream_t& s) {
|
||||
int dev = 0;
|
||||
cudaError_t e = cudaGetDevice(&dev);
|
||||
if (e != cudaSuccess) return e;
|
||||
@@ -30,9 +31,18 @@ inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes) {
|
||||
e = cudaStreamCreateWithFlags(&streams[(size_t) dev], cudaStreamNonBlocking);
|
||||
if (e != cudaSuccess) { streams[(size_t) dev] = nullptr; return e; }
|
||||
}
|
||||
cudaStream_t s = streams[(size_t) dev];
|
||||
e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s);
|
||||
s = streams[(size_t) dev];
|
||||
return cudaSuccess;
|
||||
}
|
||||
|
||||
/// `queued`: the copy is only queued on the private stream, and the caller synchronizes the device (or orders a
|
||||
/// later launch after it with order_after_queued) before anything reads the target or writes the source.
|
||||
inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes, bool queued = false) {
|
||||
cudaStream_t s = nullptr;
|
||||
cudaError_t e = private_stream(s);
|
||||
if (e != cudaSuccess) return e;
|
||||
e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s);
|
||||
if (e != cudaSuccess || queued) return e;
|
||||
e = cudaStreamSynchronize(s);
|
||||
core::progress_beat(); // #2049: a parked conversation is many of these; each one that lands is progress
|
||||
return e;
|
||||
@@ -87,4 +97,25 @@ inline std::vector<ConversationCheckpoint> copy_checkpoints_beating(const std::v
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Work queued on the legacy stream after this call starts after every copy this thread queued on the current
|
||||
/// device's private stream (an event the legacy stream waits for; no host wait).
|
||||
inline cudaError_t order_after_queued() {
|
||||
cudaStream_t s = nullptr;
|
||||
cudaError_t e = private_stream(s);
|
||||
if (e != cudaSuccess) return e;
|
||||
int dev = 0;
|
||||
e = cudaGetDevice(&dev);
|
||||
if (e != cudaSuccess) return e;
|
||||
thread_local std::vector<cudaEvent_t> events;
|
||||
if (dev < 0) dev = 0;
|
||||
if ((size_t) dev >= events.size()) events.resize((size_t) dev + 1, nullptr); // never destroyed: process lifetime
|
||||
if (!events[(size_t) dev]) {
|
||||
e = cudaEventCreateWithFlags(&events[(size_t) dev], cudaEventDisableTiming);
|
||||
if (e != cudaSuccess) { events[(size_t) dev] = nullptr; return e; }
|
||||
}
|
||||
e = cudaEventRecord(events[(size_t) dev], s);
|
||||
if (e != cudaSuccess) return e;
|
||||
return cudaStreamWaitEvent(nullptr, events[(size_t) dev], 0);
|
||||
}
|
||||
|
||||
} // namespace strata::core::conversation_detail
|
||||
@@ -201,17 +201,10 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, c
|
||||
return true;
|
||||
}
|
||||
|
||||
bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
|
||||
int64_t upto, bool index, std::string& error) {
|
||||
if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
|
||||
const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
|
||||
const auto dst = pools(st);
|
||||
for (size_t i = 0; i < src.size(); ++i)
|
||||
if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
|
||||
return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);
|
||||
})) return false;
|
||||
// VRAM slots still contain the outgoing conversation. Resolve must refill
|
||||
// them from the restored authoritative pools before any attention reads.
|
||||
namespace {
|
||||
// After the authoritative pools were rewritten: the VRAM slots of a streamed state still hold the outgoing
|
||||
// conversation, so resolve must refill them before any attention reads (shared by restore and direct copy).
|
||||
bool refresh_residency(const QsaState& st, const ModelGeometry& g, int64_t upto, std::string& error) {
|
||||
if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr);
|
||||
if (st.kv_mode == 2 && upto > 0) {
|
||||
auto shapes = strata::kernels::qsa_real_shapes();
|
||||
@@ -225,6 +218,50 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co
|
||||
error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status);
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool conversation_kv_copy(const QsaState& from, const QsaState& to, const ModelGeometry& g,
|
||||
int64_t upto, bool index, std::string& error, bool queued) {
|
||||
Layout lf{}, lt{};
|
||||
if (!layout(from, g, upto, index, lf, error) || !valid(from, lf, upto, error) ||
|
||||
!layout(to, g, upto, index, lt, error) || !valid(to, lt, upto, error)) return false;
|
||||
if (lf.format != lt.format || lf.cells != lt.cells || lf.page_size != lt.page_size ||
|
||||
lf.pooled_rows != lt.pooled_rows || lf.data != lt.data || lf.value_data != lt.value_data ||
|
||||
lf.scales != lt.scales || lf.value_scales != lt.value_scales || lf.pooled != lt.pooled) {
|
||||
error = "conversation snapshot: direct K/V copy between different layouts";
|
||||
return false;
|
||||
}
|
||||
// The same bytes conversation_kv_save + conversation_kv_restore move, without the host image: each part
|
||||
// straight from the source's authoritative pool into the target's (device or mapped host memory), through the
|
||||
// private non-blocking stream the other snapshot copies use (complete on return, before the residency refresh).
|
||||
// `queued`: the copies are only queued, and a streamed state's refresh waits for them on the device (an event).
|
||||
const auto src = pools(from);
|
||||
const auto dst = pools(to);
|
||||
const std::array<size_t,5> sizes = {lf.data, lf.value_data, lf.scales, lf.value_scales, lf.pooled};
|
||||
for (size_t i = 0; i < sizes.size(); ++i) {
|
||||
if (!sizes[i]) continue;
|
||||
if (!src[i] || !dst[i]) { error = "conversation snapshot: missing state buffer"; return false; }
|
||||
const cudaError_t e = conversation_detail::copy_nonblocking(dst[i], src[i], sizes[i], queued);
|
||||
if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; }
|
||||
}
|
||||
if (queued && to.kv_mode != 0) {
|
||||
const cudaError_t e = conversation_detail::order_after_queued();
|
||||
if (e != cudaSuccess) { error = std::string("conversation snapshot direct copy: ") + cudaGetErrorString(e); return false; }
|
||||
}
|
||||
return refresh_residency(to, g, upto, error);
|
||||
}
|
||||
|
||||
bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
|
||||
int64_t upto, bool index, std::string& error) {
|
||||
if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
|
||||
const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
|
||||
const auto dst = pools(st);
|
||||
for (size_t i = 0; i < src.size(); ++i)
|
||||
if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
|
||||
return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);
|
||||
})) return false;
|
||||
return refresh_residency(st, g, upto, error);
|
||||
}
|
||||
|
||||
bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index,
|
||||
std::array<uint64_t, 5>& sizes, std::string& error) {
|
||||
|
||||
@@ -30,10 +30,10 @@ bool sync(std::string& error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool copy(void* dst, const void* src, size_t bytes, std::string& error) {
|
||||
bool copy(void* dst, const void* src, size_t bytes, std::string& error, bool queued = false) {
|
||||
if (!bytes) return true;
|
||||
if (!dst || !src) return fail(error, "missing running-state buffer");
|
||||
const auto status = conversation_detail::copy_nonblocking(dst, src, bytes);
|
||||
const auto status = conversation_detail::copy_nonblocking(dst, src, bytes, queued);
|
||||
if (status == cudaSuccess) return true;
|
||||
error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status);
|
||||
return false;
|
||||
@@ -215,6 +215,37 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionSta
|
||||
return sync(error);
|
||||
}
|
||||
|
||||
bool conversation_checkpoint_copy(const SessionState& from, SessionState& to, const std::vector<int32_t>& ids,
|
||||
const ModelGeometry& g, std::string& error, bool queued) {
|
||||
// conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) without the host image, for two
|
||||
// sessions carved alike on the same device (a stage's own session and its batch slots): the same bytes into
|
||||
// the same places, through copy() like the restore (the private non-blocking stream, complete on return unless
|
||||
// `queued`: then the caller synchronizes the device).
|
||||
ConversationStateSizes zf, zt;
|
||||
if (!checkpoint_targets(from, g, ids.size(), zf, error) || !checkpoint_targets(to, g, ids.size(), zt, error))
|
||||
return false;
|
||||
if (zf.gdn != zt.gdn || zf.tail != zt.tail || zf.dead != zt.dead || zf.block_pos != zt.block_pos ||
|
||||
owned_qsa(from) != owned_qsa(to) || (from.ple_hist != nullptr) != (to.ple_hist != nullptr))
|
||||
return fail(error, "direct copy between differently carved sessions");
|
||||
auto acopy = [&](void* dst, const void* src, size_t bytes) { return copy(dst, src, bytes, error, queued); };
|
||||
if (!acopy(to.gdn_state, from.gdn_state, zf.gdn) ||
|
||||
!acopy(to.ple_hist, from.ple_hist, from.ple_hist ? zf.ple : 0)) return false;
|
||||
for (size_t j = 0; j < owned_qsa(from); ++j) {
|
||||
const auto& a = owned(from, j);
|
||||
const auto& b = owned(to, j);
|
||||
if (!acopy(b.idx_tail, a.idx_tail, zf.tail) || !acopy(b.idx_dead, a.idx_dead, zf.dead) ||
|
||||
!acopy(b.idx_block_pos, a.idx_block_pos, zf.block_pos)) return false;
|
||||
if (!ids.empty()) { // restore writes the saved `dead` row into the pooled row the next token fills
|
||||
const size_t row = ids.size() / strata::kernels::qsa_real_shapes().idx_block;
|
||||
if (!acopy(b.idx_pooled + row * g.idx_key_dim, a.idx_dead, zf.dead)) return false;
|
||||
}
|
||||
}
|
||||
const size_t tokens = ids.size();
|
||||
to.ple_prev[0] = tokens >= 2 ? ids[tokens - 2] : -1;
|
||||
to.ple_prev[1] = tokens >= 1 ? ids[tokens - 1] : -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss,
|
||||
const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error) {
|
||||
bytes = 0;
|
||||
|
||||
@@ -564,8 +564,9 @@ bool ExpertCache::open_sized(const std::vector<int64_t>& slot_bytes, int64_t n_l
|
||||
int64_t mx = 0;
|
||||
std::vector<uint64_t> off(slot_bytes.size() + 1, 0);
|
||||
for (size_t i = 0; i < slot_bytes.size(); ++i) {
|
||||
// 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it
|
||||
off[i + 1] = off[i] + ((uint64_t) slot_bytes[i] + 255) / 256 * 256;
|
||||
// 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it (and the
|
||||
// STRATA_MMQ_DIRECT guard after each blob, 0 by default)
|
||||
off[i + 1] = off[i] + (uint64_t) slot_stride(slot_bytes[i], guard_req_);
|
||||
mx = slot_bytes[i] > mx ? slot_bytes[i] : mx;
|
||||
}
|
||||
// one allocation of the summed size, through the uniform path's checks: n "slots" of 1 byte
|
||||
@@ -574,6 +575,7 @@ bool ExpertCache::open_sized(const std::vector<int64_t>& slot_bytes, int64_t n_l
|
||||
live_slots_ = slots_;
|
||||
blob_ = mx;
|
||||
off_ = std::move(off);
|
||||
guard_ = guard_req_;
|
||||
#if defined(STRATA_USE_HIP)
|
||||
if (!ensure_blocking_staging((std::size_t) blob_, err)) {
|
||||
close();
|
||||
@@ -598,6 +600,7 @@ void ExpertCache::close() {
|
||||
blocking_staging_bytes_ = 0;
|
||||
#endif
|
||||
off_.clear();
|
||||
guard_ = 0;
|
||||
if (!segs_.empty()) {
|
||||
release_segmented();
|
||||
} else if (vmm_) {
|
||||
|
||||
+77
-14
@@ -200,6 +200,26 @@ const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE");
|
||||
const bool g_trace = env_on("STRATA_VERIFY_TRACE");
|
||||
const bool g_no_multi_gr = env_on("STRATA_NO_MULTI_GR"); // #783 PR-g: per-token GR reads/writes and generic-T kernels again
|
||||
const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP"); // #783 PR-d: per-token K/V and indexer appends again
|
||||
// STRATA_BATCH_SELF_COMMIT=1 (opt-in): a batch window whose rows are each another slot's one token keeps them itself,
|
||||
// as a one-token window does (record_window): the GDN conv histories and states advance inside the window graph, and
|
||||
// no commit graph runs after it. Such a window's commit is unconditional (each slot keeps its one row), and the rest
|
||||
// of the commit graph only repeats what the window wrote: the indexer tails are put back and appended again from the
|
||||
// same rows, the PLE histories are put back to the window's own snapshot.
|
||||
const bool g_batch_self_commit = env_on("STRATA_BATCH_SELF_COMMIT");
|
||||
// STRATA_QSA_SLOTS=1 (opt-in): in a batch window, a QSA layer's block scores, top-k and attention run as one launch
|
||||
// each over the window's rows (up to 8 per launch, each row reading its own slot's indexer keys and K/V) instead of
|
||||
// one call per row; every row is computed by the same kernel with the same arithmetic as its own call. Not with a
|
||||
// streamed KV cache (a row's block resolve could evict the blocks an earlier row of the same slot selected).
|
||||
const bool g_qsa_slots = env_on("STRATA_QSA_SLOTS");
|
||||
|
||||
// every row of a batch window is another slot's (no slot has proposal rows)
|
||||
bool one_row_per_slot(const int* rows, int S) {
|
||||
for (int i = 0; i < S; ++i)
|
||||
for (int j = i + 1; j < S; ++j)
|
||||
if (rows[i] == rows[j]) return false;
|
||||
return S >= 1;
|
||||
}
|
||||
bool batch_self_commits(const int* rows, int S) { return g_batch_self_commit && one_row_per_slot(rows, S); }
|
||||
|
||||
// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The
|
||||
// overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the
|
||||
@@ -916,6 +936,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
// a batch window: row t is slot t, whose state lives in its own session
|
||||
auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; };
|
||||
const int hrow0 = batch_rec_ ? row_base_ : 0; // a slot group's own hand-off rows
|
||||
// STRATA_BATCH_SELF_COMMIT: the window keeps its rows (no commit graph, nothing to snapshot for one)
|
||||
const bool keep_rows = batch_rec_ && batch_self_commits(brow_, T);
|
||||
|
||||
// ---- the window's inputs, from mapped staging. With branches the steps and positions (first read by the first
|
||||
// layer's mixer) cross PCIe on side 1 beside the embedding and the first hyper-connection read.
|
||||
@@ -1081,7 +1103,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
err = std::string("verify PLE: ") + e.what();
|
||||
return false;
|
||||
}
|
||||
copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs);
|
||||
if (!keep_rows) copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs);
|
||||
}
|
||||
pending = false;
|
||||
}
|
||||
@@ -1169,7 +1191,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats +
|
||||
(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
|
||||
gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data,
|
||||
hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0);
|
||||
hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0,
|
||||
keep_rows);
|
||||
}
|
||||
} else
|
||||
// a one-token window keeps its token: it advances the conv history and the state itself (commit)
|
||||
@@ -1204,7 +1227,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV,
|
||||
beta + (size_t) first * HV, z_ + (size_t) first * ZV,
|
||||
(const float*) wnm->data, EPS, y_ + (size_t) first * ZV,
|
||||
(int) HK, (int) HV, t - first, nullptr, cs, 0);
|
||||
(int) HK, (int) HV, t - first, keep_rows ? one_ : nullptr, cs, 0);
|
||||
}
|
||||
} else
|
||||
gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
|
||||
@@ -1293,7 +1316,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
}
|
||||
stamp(l, 8, grp);
|
||||
if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row
|
||||
for (int t = tb; t < te; ++t)
|
||||
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);
|
||||
@@ -1403,7 +1426,43 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
}
|
||||
}
|
||||
stamp(l, 10, grp);
|
||||
if (batch_rec_) { // each row selects and attends over its own slot's K/V
|
||||
bool streamed = false; // a streamed KV cache keeps the per-row resolve-then-attend order
|
||||
if (batch_rec_ && g_qsa_slots)
|
||||
for (int t = tb; t < te; ++t) streamed = streamed || slot_ss(t).qsa_states[qi].kv_mode == 1;
|
||||
if (batch_rec_ && g_qsa_slots && !streamed) {
|
||||
// the rows' block scores, top-k and attention, up to 8 rows per launch. The rows only read
|
||||
// their slots' keys and K/V here and write their own scores/sel/scratch/attn rows, so running
|
||||
// each step for all rows before the next is the per-row loop's result
|
||||
for (int t0 = tb; t0 < te; t0 += kQsaAttnMaxSlots) {
|
||||
const int m = std::min(te - t0, kQsaAttnMaxSlots);
|
||||
const float* pooled[kQsaAttnMaxSlots];
|
||||
const float* dead[kQsaAttnMaxSlots];
|
||||
QsaAttnSlotPools px;
|
||||
for (int i = 0; i < m; ++i) {
|
||||
const QsaState& sx = slot_ss(t0 + i).qsa_states[qi];
|
||||
pooled[i] = sx.idx_pooled;
|
||||
dead[i] = sx.idx_dead;
|
||||
px.p[i] = qsa_attn_pools(sx);
|
||||
}
|
||||
// a launcher that would not run the per-row call's kernel launches nothing: per-row calls
|
||||
if (!qsa_block_scores_slots(pooled, dead, qidx_ + t0 * IQ * ID, step_ + t0 * kStepCount, m,
|
||||
max_blocks_, s, scores_ + (size_t) t0 * max_blocks_, cs))
|
||||
for (int t = t0; t < t0 + m; ++t)
|
||||
qsa_block_scores(pooled[t - t0], dead[t - t0], qidx_ + t * IQ * ID, step_ + t * kStepCount,
|
||||
1, max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs);
|
||||
qsa_block_topk(scores_ + (size_t) t0 * max_blocks_, step_ + t0 * kStepCount, m, max_blocks_,
|
||||
cap_, s, sel_ + (size_t) t0 * cap_, cs);
|
||||
if (!qsa_decode_attn_slots(qcur_ + t0 * NH * HD, px, sel_ + (size_t) t0 * cap_,
|
||||
step_ + t0 * kStepCount, cap_, s,
|
||||
attn_scratch_ + (size_t) t0 * attn_scratch_floats_,
|
||||
attn_ + t0 * NH * HD, m, cs))
|
||||
for (int t = t0; t < t0 + m; ++t)
|
||||
qsa_decode_attn_batch(qcur_ + t * NH * HD, px.p[t - t0], sel_ + (size_t) t * cap_,
|
||||
step_ + t * kStepCount, cap_, s,
|
||||
attn_scratch_ + (size_t) t * attn_scratch_floats_,
|
||||
attn_ + t * NH * HD, 1, cs);
|
||||
}
|
||||
} else if (batch_rec_) { // each row selects and attends over its own slot's K/V
|
||||
for (int t = tb; t < te; ++t) {
|
||||
const QsaState& sx = slot_ss(t).qsa_states[qi];
|
||||
qsa_block_scores(sx.idx_pooled, sx.idx_dead, qidx_ + t * IQ * ID, step_ + t * kStepCount, 1,
|
||||
@@ -2754,8 +2813,8 @@ bool Verifier::init_slots(const std::vector<SessionState*>& slots, std::string&
|
||||
tail_snap_b_ = (float*) ((uint8_t*) d + a);
|
||||
slots_ = slots;
|
||||
slot_sp_.assign(slots.size(), sampling_); // greedy until set_slot_sampling
|
||||
std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))\n", (long long) S,
|
||||
(long long) lb_, (long long) le_);
|
||||
std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))%s\n", (long long) S,
|
||||
(long long) lb_, (long long) le_, g_batch_self_commit ? ", one-row windows keep their rows" : "");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2792,6 +2851,7 @@ bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err
|
||||
}
|
||||
|
||||
bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::string& err) {
|
||||
if (batch_self_commits(rows, S)) return true; // the window keeps its rows: no commit graph
|
||||
cudaGraphExec_t& cex = commit_bm_[bkey(rows, S, hbase)];
|
||||
if (cex != nullptr) return true;
|
||||
using namespace strata::kernels;
|
||||
@@ -2940,9 +3000,9 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok
|
||||
std::string& err) {
|
||||
using namespace strata::kernels;
|
||||
// the row layout: a slot may own a contiguous group of rows (--batch-mtp), also across the stages of a layer split,
|
||||
// whose hand-off buffers hold kVerifyMaxT rows (a stage that hands rows on or takes them)
|
||||
// whose hand-off buffers hold kVerifyMaxT rows, or set_handoff_rows' (a stage that hands rows on or takes them)
|
||||
if (const char* why = batch_rows_error(rows, S, pos, (int) slots_.size(), max_t_, hbase,
|
||||
next_ != nullptr || lb_ > 0, kVerifyMaxT)) {
|
||||
next_ != nullptr || lb_ > 0, handoff_rows_ > 0 ? handoff_rows_ : kVerifyMaxT)) {
|
||||
err = why;
|
||||
return false;
|
||||
}
|
||||
@@ -3152,10 +3212,12 @@ bool Verifier::commit_slot_prefixes(const int* keep, std::string& err) {
|
||||
c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1;
|
||||
}
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_);
|
||||
if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; }
|
||||
const cudaError_t se = cudaStreamSynchronize(cs_);
|
||||
if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; }
|
||||
if (!batch_self_commits(last_rows_, S)) { // (else the window has kept its rows)
|
||||
const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_);
|
||||
if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; }
|
||||
const cudaError_t se = cudaStreamSynchronize(cs_);
|
||||
if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; }
|
||||
}
|
||||
if (ple_stage())
|
||||
for (int t = 0; t < S;) {
|
||||
const int first = t;
|
||||
@@ -3192,7 +3254,8 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_
|
||||
for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t;
|
||||
if (!stage_batch(rows, S, base, tokens, pos, err)) return false;
|
||||
cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_);
|
||||
if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_); // right behind it: every row is kept
|
||||
if (le == cudaSuccess && !batch_self_commits(rows, S)) // (else the window has kept its rows itself)
|
||||
le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_); // right behind it: every row is kept
|
||||
if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; }
|
||||
(void) cudaStreamQuery(cs_);
|
||||
if (ple_stage()) // the host's side of the commit (the hash's last two tokens)
|
||||
|
||||
@@ -116,13 +116,14 @@ __device__ __forceinline__ int reduce12_head_of_lane(int lane) {
|
||||
return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);
|
||||
}
|
||||
|
||||
template <int KV_MODE, bool LANE_CELL = false, bool QUERY_SWIZZLE = false, bool REDUCE12 = false>
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ step, int n_kv_heads,
|
||||
int page_size, float scale, float* __restrict__ part_acc,
|
||||
float* __restrict__ part_m, float* __restrict__ part_l,
|
||||
int n_chunks, int cap = 0, long long scratch_stride = 0) {
|
||||
// The chunk kernel's body; `p` is the query's KV pools (the call's one set, or blockIdx.z's slot's set).
|
||||
template <int KV_MODE, bool LANE_CELL, bool QUERY_SWIZZLE, bool REDUCE12>
|
||||
__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids, const int32_t* __restrict__ step,
|
||||
int n_kv_heads, int page_size, float scale,
|
||||
float* __restrict__ part_acc, float* __restrict__ part_m,
|
||||
float* __restrict__ part_l, int n_chunks, int cap,
|
||||
long long scratch_stride) {
|
||||
// batched form: query blockIdx.z, with its own q row, selection, step and scratch
|
||||
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
|
||||
ids += (size_t) blockIdx.z * (size_t) cap;
|
||||
@@ -281,6 +282,33 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
|
||||
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
|
||||
}
|
||||
|
||||
template <int KV_MODE, bool LANE_CELL = false, bool QUERY_SWIZZLE = false, bool REDUCE12 = false>
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ step, int n_kv_heads,
|
||||
int page_size, float scale, float* __restrict__ part_acc,
|
||||
float* __restrict__ part_m, float* __restrict__ part_l,
|
||||
int n_chunks, int cap = 0, long long scratch_stride = 0) {
|
||||
attn_chunk_body<KV_MODE, LANE_CELL, QUERY_SWIZZLE, REDUCE12>(q, p, ids, step, n_kv_heads, page_size, scale,
|
||||
part_acc, part_m, part_l, n_chunks, cap,
|
||||
scratch_stride);
|
||||
}
|
||||
|
||||
// The same blocks for queries of different slots: query blockIdx.z reads its own slot's pools, everything else is
|
||||
// attn_chunk_kernel's batched form (qsa_decode_attn_slots).
|
||||
template <int KV_MODE, bool LANE_CELL>
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float* __restrict__ q, QsaAttnSlotPools ps,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ step, int n_kv_heads,
|
||||
int page_size, float scale,
|
||||
float* __restrict__ part_acc,
|
||||
float* __restrict__ part_m,
|
||||
float* __restrict__ part_l, int n_chunks, int cap,
|
||||
long long scratch_stride) {
|
||||
attn_chunk_body<KV_MODE, LANE_CELL, false, false>(q, ps.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale,
|
||||
part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
|
||||
}
|
||||
|
||||
// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
|
||||
// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It
|
||||
// uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the
|
||||
@@ -615,6 +643,17 @@ bool pre75_attn() {
|
||||
#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
|
||||
#endif
|
||||
|
||||
// S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)
|
||||
bool lane_cell_attn() {
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
|
||||
return on;
|
||||
}
|
||||
|
||||
// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V
|
||||
int attn_kv_mode(const QsaAttnPools& p) {
|
||||
return p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
|
||||
@@ -636,8 +675,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
const float scale = 1.0f / sqrtf((float) HD);
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
// S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)
|
||||
static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
|
||||
const bool lane_cell = 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';
|
||||
@@ -710,6 +748,64 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
if (n_q <= 0) return true;
|
||||
if (n_q > kQsaAttnMaxSlots) return false;
|
||||
if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps) {
|
||||
std::fprintf(stderr, "qsa_decode_attn_slots: unsupported geometry or missing buffers\n");
|
||||
std::exit(1);
|
||||
}
|
||||
const int kv_mode = attn_kv_mode(pools.p[0]);
|
||||
for (int64_t z = 0; z < n_q; ++z) {
|
||||
if (!pools.p[z].page_table) {
|
||||
std::fprintf(stderr, "qsa_decode_attn_slots: missing page table\n");
|
||||
std::exit(1);
|
||||
}
|
||||
if (attn_kv_mode(pools.p[z]) != kv_mode) return false;
|
||||
}
|
||||
const bool lane_cell = lane_cell_attn();
|
||||
// only where qsa_decode_attn_batch runs attn_chunk_kernel; its other variants keep the per-query calls
|
||||
#if defined(STRATA_ATTN_PRE75_BUILT)
|
||||
if (!lane_cell && pre75_attn()) return false;
|
||||
#endif
|
||||
#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';
|
||||
}();
|
||||
if (query_swizzle && !lane_cell && kv_mode == 1 && query_swizzle_gfx906_device()) return false;
|
||||
#endif
|
||||
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
|
||||
const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
|
||||
float* part_acc = scratch;
|
||||
float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
|
||||
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;
|
||||
#define STRATA_ATTN_SLOTS(M, LC) attn_chunk_slots_kernel<M, LC><<<grid, THREADS, 0, st>>>(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)
|
||||
if (lane_cell) {
|
||||
if (kv_mode == 3) STRATA_ATTN_SLOTS(3, true);
|
||||
else if (kv_mode == 2) STRATA_ATTN_SLOTS(2, true);
|
||||
else if (kv_mode == 1) STRATA_ATTN_SLOTS(1, true);
|
||||
else STRATA_ATTN_SLOTS(0, true);
|
||||
} else {
|
||||
if (kv_mode == 3) STRATA_ATTN_SLOTS(3, false);
|
||||
else if (kv_mode == 2) STRATA_ATTN_SLOTS(2, false);
|
||||
else if (kv_mode == 1) STRATA_ATTN_SLOTS(1, false);
|
||||
else STRATA_ATTN_SLOTS(0, false);
|
||||
}
|
||||
#undef STRATA_ATTN_SLOTS
|
||||
attn_merge_kernel<<<dim3((unsigned) s.n_head, (unsigned) n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks,
|
||||
attn, stride);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "qsa_decode_attn_slots: %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
|
||||
const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
|
||||
return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
|
||||
|
||||
@@ -816,12 +816,11 @@ __global__ void __launch_bounds__(TK_T) block_topk_wide_kernel(const float* __re
|
||||
// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode
|
||||
// window, the uncaptured decode, and prefill's pooled16 call.
|
||||
constexpr int MQ = 8;
|
||||
__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_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,
|
||||
bool early_exit) {
|
||||
__device__ __forceinline__ void block_scores_multi_body(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, bool early_exit) {
|
||||
__shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM];
|
||||
__shared__ int64_t s_nkv[MQ], s_nbid[MQ];
|
||||
if (!early_exit)
|
||||
@@ -868,6 +867,37 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_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,
|
||||
bool early_exit) {
|
||||
block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit);
|
||||
}
|
||||
|
||||
// Queries of different slots, each with its own indexer keys: blockIdx.y is the query, and its CTAs run exactly the
|
||||
// single-query call of block_scores_multi_kernel (qsa_block_scores_slots).
|
||||
struct ScoreSlotKeys {
|
||||
const float* pooled[MQ];
|
||||
const float* dead[MQ];
|
||||
};
|
||||
__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(ScoreSlotKeys keys,
|
||||
const float* __restrict__ q_idx,
|
||||
const int32_t* __restrict__ steps,
|
||||
int64_t max_blocks, float* __restrict__ out,
|
||||
bool early_exit) {
|
||||
const unsigned z = blockIdx.y;
|
||||
// the slot's pointers picked by unrolled selects: indexing the argument array by z would copy it to local memory
|
||||
const float* pooled = keys.pooled[0];
|
||||
const float* dead = keys.dead[0];
|
||||
#pragma unroll
|
||||
for (unsigned i = 1; i < MQ; ++i)
|
||||
if (z == i) { pooled = keys.pooled[i]; dead = keys.dead[i]; }
|
||||
block_scores_multi_body(pooled, dead, q_idx + (size_t) z * IDX_HEADS * IDX_DIM,
|
||||
steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit);
|
||||
}
|
||||
|
||||
#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
|
||||
@@ -1090,8 +1120,38 @@ __global__ void __launch_bounds__(CL_T) block_topk_cluster_kernel(const float* _
|
||||
#endif
|
||||
}
|
||||
#endif // !__HIPCC__
|
||||
bool scores_multi_on() {
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();
|
||||
return on;
|
||||
}
|
||||
// STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits
|
||||
bool scores_early_exit() {
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
|
||||
return on;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
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) {
|
||||
if (nq <= 0) return true;
|
||||
if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R) {
|
||||
std::fprintf(stderr, "qsa_block_scores_slots: unsupported indexer geometry\n");
|
||||
std::exit(1);
|
||||
}
|
||||
if (nq > MQ || !scores_multi_on()) return false; // the single-query call would not run the multi kernel
|
||||
ScoreSlotKeys keys{};
|
||||
for (int64_t z = 0; z < nq; ++z) {
|
||||
keys.pooled[z] = pooled[z];
|
||||
keys.dead[z] = dead[z];
|
||||
}
|
||||
block_scores_slots_kernel<<<dim3(256, (unsigned) nq), SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(
|
||||
keys, q_idx, steps, max_blocks, scores, scores_early_exit());
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_slots: %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return true;
|
||||
}
|
||||
|
||||
void qsa_block_scores(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;
|
||||
@@ -1100,12 +1160,9 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
|
||||
std::exit(1);
|
||||
}
|
||||
// a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)
|
||||
static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();
|
||||
if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16
|
||||
// STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits
|
||||
static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
|
||||
if (scores_multi_on() && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16
|
||||
block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq,
|
||||
max_blocks, scores, early);
|
||||
max_blocks, scores, scores_early_exit());
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
// src/kernels/qsa_slots_parity.cpp - STRATA_QSA_SLOTS: a batch window's block scores, top-k and attention as one
|
||||
// launch over rows of different slots (qsa_block_scores_slots, qsa_block_topk over the rows, qsa_decode_attn_slots)
|
||||
// against one call per row, as verify.cpp makes them without the switch. Every slot has its own indexer keys, page
|
||||
// table and K/V pools (fp16, int8, q4_0 and int8-K/q4_0-V) and its own context length; scores, selected ids and the
|
||||
// attention output must be bitwise identical. Synthetic data, no model. Run it once more with
|
||||
// STRATA_ATTN_LANECELL=1 for the lane-cell kernels. Where a launcher declines by design (STRATA_SCORES_MULTI=0, the
|
||||
// pre-sm_75 attention, the gfx906 query swizzle) the engine keeps its per-row calls and the test skips (77).
|
||||
#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 "strata/kernels/qsa_select.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <numeric>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace k = strata::kernels;
|
||||
namespace {
|
||||
|
||||
void ck(cudaError_t e) {
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e));
|
||||
std::exit(2);
|
||||
}
|
||||
}
|
||||
template <typename T> T* up(const std::vector<T>& h) {
|
||||
T* d = nullptr;
|
||||
ck(cudaMalloc(&d, h.size() * sizeof(T)));
|
||||
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice));
|
||||
return d;
|
||||
}
|
||||
template <typename T> std::vector<T> down(const T* d, size_t n) {
|
||||
std::vector<T> h(n);
|
||||
ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost));
|
||||
return h;
|
||||
}
|
||||
// a finite fp16 of magnitude 2^-5 .. 2^2
|
||||
uint16_t rnd_half(std::mt19937& r) {
|
||||
const uint32_t x = r();
|
||||
return (uint16_t) (((x & 1u) << 15) | ((10u + (x >> 1) % 7u) << 10) | ((x >> 4) & 0x3ffu));
|
||||
}
|
||||
|
||||
constexpr int64_t kMaxCells = 32768;
|
||||
|
||||
struct Slot {
|
||||
float *pooled = nullptr, *dead = nullptr;
|
||||
int32_t* page_table = nullptr;
|
||||
void* bufs[6] = {};
|
||||
k::QsaAttnPools pools;
|
||||
};
|
||||
|
||||
Slot make_slot(int fmt, const k::QsaShapes& s, int64_t max_blocks, std::mt19937& r) {
|
||||
Slot sl;
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::vector<float> pooled((size_t) (max_blocks * s.idx_dim)), dead((size_t) s.idx_dim);
|
||||
for (auto& v : pooled) v = nd(r);
|
||||
for (auto& v : dead) v = nd(r);
|
||||
sl.pooled = up(pooled);
|
||||
sl.dead = up(dead);
|
||||
const int64_t pages = kMaxCells / s.page_size;
|
||||
std::vector<int32_t> pt((size_t) pages);
|
||||
std::iota(pt.begin(), pt.end(), 0);
|
||||
std::shuffle(pt.begin(), pt.end(), r);
|
||||
for (int i = 0; i < 3; ++i) pt[(size_t) (r() % pages)] = -1; // a few non-resident pages (masked cells)
|
||||
sl.page_table = up(pt);
|
||||
sl.pools.page_table = sl.page_table;
|
||||
const size_t rows = (size_t) (pages * s.n_head_kv * s.page_size), hd = (size_t) s.head_dim;
|
||||
auto halves = [&](size_t n) { std::vector<uint16_t> h(n); for (auto& v : h) v = rnd_half(r); return h; };
|
||||
auto codes = [&](size_t n) { std::vector<int8_t> h(n); for (auto& v : h) v = (int8_t) (r() & 0xff); return h; };
|
||||
auto q4 = [&](size_t n_rows) {
|
||||
std::vector<uint8_t> h(n_rows * (size_t) k::kv_q4_bytes_per_head((int) hd));
|
||||
k::block_q4_0* b = reinterpret_cast<k::block_q4_0*>(h.data());
|
||||
for (size_t i = 0; i < h.size() / sizeof(k::block_q4_0); ++i) {
|
||||
b[i].d = rnd_half(r);
|
||||
for (auto& q : b[i].qs) q = (uint8_t) (r() & 0xff);
|
||||
}
|
||||
return h;
|
||||
};
|
||||
if (fmt == 0) {
|
||||
sl.pools.k_pool = (const uint16_t*) (sl.bufs[0] = up(halves(rows * hd)));
|
||||
sl.pools.v_pool = (const uint16_t*) (sl.bufs[1] = up(halves(rows * hd)));
|
||||
} else if (fmt == 1 || fmt == 3) {
|
||||
sl.pools.k_q = (const int8_t*) (sl.bufs[0] = up(codes(rows * hd)));
|
||||
sl.pools.k_scale = (const uint16_t*) (sl.bufs[1] = up(halves(rows * hd / k::KV_Q8_GROUP)));
|
||||
if (fmt == 1) {
|
||||
sl.pools.v_q = (const int8_t*) (sl.bufs[2] = up(codes(rows * hd)));
|
||||
sl.pools.v_scale = (const uint16_t*) (sl.bufs[3] = up(halves(rows * hd / k::KV_Q8_GROUP)));
|
||||
} else {
|
||||
sl.pools.v_q4 = (const uint8_t*) (sl.bufs[2] = up(q4(rows)));
|
||||
}
|
||||
} else {
|
||||
sl.pools.k_q4 = (const uint8_t*) (sl.bufs[0] = up(q4(rows)));
|
||||
sl.pools.v_q4 = (const uint8_t*) (sl.bufs[1] = up(q4(rows)));
|
||||
}
|
||||
return sl;
|
||||
}
|
||||
|
||||
void free_slot(Slot& sl) {
|
||||
ck(cudaFree(sl.pooled)); ck(cudaFree(sl.dead)); ck(cudaFree(sl.page_table));
|
||||
for (void* b : sl.bufs) if (b) ck(cudaFree(b));
|
||||
}
|
||||
|
||||
enum Result { kPass, kFail, kSkip };
|
||||
|
||||
// one case: `m` rows of different slots, KV format `fmt`, contexts `ctx[i]`
|
||||
Result check(int fmt, int m, const int64_t* ctx, uint32_t seed) {
|
||||
const k::QsaShapes s = k::qsa_real_shapes();
|
||||
const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);
|
||||
const int64_t max_blocks = kMaxCells / s.idx_block + 2;
|
||||
const int64_t NH = s.n_head, HD = s.head_dim, QI = s.idx_n_head * s.idx_dim;
|
||||
const int64_t sf = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s);
|
||||
std::mt19937 r(seed);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::vector<Slot> slots;
|
||||
for (int i = 0; i < m; ++i) slots.push_back(make_slot(fmt, s, max_blocks, r));
|
||||
std::vector<float> qidx((size_t) (m * QI)), qcur((size_t) (m * NH * HD));
|
||||
for (auto& v : qidx) v = nd(r);
|
||||
for (auto& v : qcur) v = nd(r);
|
||||
std::vector<int32_t> steps((size_t) (m * k::kStepCount));
|
||||
for (int i = 0; i < m; ++i) k::qsa_step_fill(steps.data() + i * k::kStepCount, ctx[i] - 1, s);
|
||||
float* d_qidx = up(qidx);
|
||||
float* d_qcur = up(qcur);
|
||||
int32_t* d_steps = up(steps);
|
||||
float *sc[2], *scratch[2], *attn[2];
|
||||
int32_t* sel[2];
|
||||
for (int v = 0; v < 2; ++v) {
|
||||
ck(cudaMalloc(&sc[v], (size_t) (m * max_blocks) * 4));
|
||||
ck(cudaMalloc(&sel[v], (size_t) (m * cap) * 4));
|
||||
ck(cudaMalloc(&scratch[v], (size_t) (m * sf) * 4));
|
||||
ck(cudaMalloc(&attn[v], (size_t) (m * NH * HD) * 4));
|
||||
ck(cudaMemset(sc[v], 0, (size_t) (m * max_blocks) * 4));
|
||||
ck(cudaMemset(sel[v], 0, (size_t) (m * cap) * 4));
|
||||
ck(cudaMemset(attn[v], 0, (size_t) (m * NH * HD) * 4));
|
||||
}
|
||||
// 0: one call per row (verify.cpp's batch-window loop)
|
||||
for (int t = 0; t < m; ++t) {
|
||||
k::qsa_block_scores(slots[t].pooled, slots[t].dead, d_qidx + t * QI, d_steps + t * k::kStepCount, 1,
|
||||
max_blocks, s, sc[0] + t * max_blocks, nullptr);
|
||||
k::qsa_block_topk(sc[0] + t * max_blocks, d_steps + t * k::kStepCount, 1, max_blocks, cap, s, sel[0] + t * cap,
|
||||
nullptr);
|
||||
k::qsa_decode_attn_batch(d_qcur + t * NH * HD, slots[t].pools, sel[0] + t * cap, d_steps + t * k::kStepCount,
|
||||
cap, s, scratch[0] + t * sf, attn[0] + t * NH * HD, 1, nullptr);
|
||||
}
|
||||
// 1: one launch per step over the rows
|
||||
const float* pooled[k::kQsaAttnMaxSlots];
|
||||
const float* dead[k::kQsaAttnMaxSlots];
|
||||
k::QsaAttnSlotPools px;
|
||||
for (int t = 0; t < m; ++t) { pooled[t] = slots[t].pooled; dead[t] = slots[t].dead; px.p[t] = slots[t].pools; }
|
||||
// a declined launch is no failure: the engine runs the per-row calls there (STRATA_SCORES_MULTI=0, the pre-sm_75
|
||||
// attention, the gfx906 query swizzle)
|
||||
Result res = kPass;
|
||||
if (!k::qsa_block_scores_slots(pooled, dead, d_qidx, d_steps, m, max_blocks, s, sc[1], nullptr)) {
|
||||
std::puts("SKIP: qsa_block_scores_slots declined (STRATA_SCORES_MULTI=0); the engine keeps the per-row calls");
|
||||
res = kSkip;
|
||||
} else {
|
||||
k::qsa_block_topk(sc[1], d_steps, m, max_blocks, cap, s, sel[1], nullptr);
|
||||
if (!k::qsa_decode_attn_slots(d_qcur, px, sel[1], d_steps, cap, s, scratch[1], attn[1], m, nullptr)) {
|
||||
std::puts("SKIP: qsa_decode_attn_slots declined (the pre-sm_75 or gfx906 query-swizzle attention); the "
|
||||
"engine keeps the per-row calls");
|
||||
res = kSkip;
|
||||
}
|
||||
}
|
||||
ck(cudaDeviceSynchronize());
|
||||
bool ok = res == kPass;
|
||||
const auto s0 = down(sc[0], (size_t) (m * max_blocks)), s1 = down(sc[1], (size_t) (m * max_blocks));
|
||||
const auto i0 = down(sel[0], (size_t) (m * cap)), i1 = down(sel[1], (size_t) (m * cap));
|
||||
const auto a0 = down(attn[0], (size_t) (m * NH * HD)), a1 = down(attn[1], (size_t) (m * NH * HD));
|
||||
for (int t = 0; t < m && ok; ++t) {
|
||||
const int64_t nb = steps[(size_t) (t * k::kStepCount + k::kStepNBid)] + 1;
|
||||
const int64_t w = steps[(size_t) (t * k::kStepCount + k::kStepWidth)];
|
||||
const char* what = nullptr;
|
||||
if (std::memcmp(&s0[(size_t) (t * max_blocks)], &s1[(size_t) (t * max_blocks)], (size_t) nb * 4)) what = "scores";
|
||||
else if (std::memcmp(&i0[(size_t) (t * cap)], &i1[(size_t) (t * cap)], (size_t) w * 4)) what = "ids";
|
||||
else if (std::memcmp(&a0[(size_t) (t * NH * HD)], &a1[(size_t) (t * NH * HD)], (size_t) (NH * HD) * 4))
|
||||
what = "attention";
|
||||
if (what) {
|
||||
std::fprintf(stderr, "FAIL fmt=%d rows=%d row=%d ctx=%lld: %s differ\n", fmt, m, t, (long long) ctx[t], what);
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
double mag = 0; // the attention output is not trivially zero
|
||||
for (float v : a0) mag += std::fabs(v);
|
||||
if (ok && !(mag > 0)) { std::fprintf(stderr, "FAIL fmt=%d rows=%d: attention output is zero\n", fmt, m); ok = false; }
|
||||
if (res == kPass && !ok) res = kFail;
|
||||
for (int v = 0; v < 2; ++v) { ck(cudaFree(sc[v])); ck(cudaFree(sel[v])); ck(cudaFree(scratch[v])); ck(cudaFree(attn[v])); }
|
||||
ck(cudaFree(d_qidx)); ck(cudaFree(d_qcur)); ck(cudaFree(d_steps));
|
||||
for (auto& sl : slots) free_slot(sl);
|
||||
return res;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
int devices = 0;
|
||||
if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
|
||||
std::puts("SKIP: no CUDA device");
|
||||
return 77;
|
||||
}
|
||||
if (const char* v = std::getenv("STRATA_SCORES_MULTI"); v && std::atoi(v) == 0) {
|
||||
std::puts("SKIP: STRATA_SCORES_MULTI=0 (the slots launch is off; the engine keeps the per-row calls)");
|
||||
return 77;
|
||||
}
|
||||
// contexts per row: under and over the selection width (2048 cells), partial and complete indexer blocks
|
||||
const int64_t ctx[8] = {1500, 37, 9000, 2049, 32768, 300, 20001, 4096};
|
||||
int cases = 0, skipped = 0; // the gfx906 query swizzle declines only the int8 K/V format
|
||||
for (int fmt = 0; fmt < 4; ++fmt)
|
||||
for (int m : {1, 2, 4, 8}) {
|
||||
const Result res = check(fmt, m, ctx, 1000u * (uint32_t) fmt + (uint32_t) m);
|
||||
if (res == kFail) return 1;
|
||||
++(res == kSkip ? skipped : cases);
|
||||
}
|
||||
if (cases == 0) return 77;
|
||||
std::printf("PASS: %d cases (4 KV formats x 1/2/4/8 rows of different slots%s, %d declined): scores, ids and "
|
||||
"attention bitwise identical to one call per row\n", cases,
|
||||
std::getenv("STRATA_ATTN_LANECELL") ? ", lane-cell" : "", skipped);
|
||||
return 0;
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -18,6 +19,22 @@ inline bool mmq_resident_sort_requested() {
|
||||
return on;
|
||||
}
|
||||
|
||||
// STRATA_MMQ_GROUP_SORT=1: the same row-count order for the full 16-expert groups only; the last, partial group keeps
|
||||
// its experts in ID order. A full group's launch has 160 * ntx (gate/up) or 320 * ntx (down) tiles, at or above the
|
||||
// 90 % tile efficiency on the cards' SM counts, so it runs one block per tile with no stream-k K split whatever its tile
|
||||
// width: each expert's rows get the same bits in any full group. The partial group can take the stream-k split, whose
|
||||
// K boundaries depend on the group's tile count - leaving it unchanged keeps the prompt's bits.
|
||||
inline bool mmq_group_sort_requested() {
|
||||
static const bool on = mmq_resident_sort_flag(std::getenv("STRATA_MMQ_GROUP_SORT"));
|
||||
return on;
|
||||
}
|
||||
|
||||
// How many of `n` ordered experts the sort may move: all of them (STRATA_MMQ_RESIDENT_SORT_NE), or the full groups
|
||||
// of `group` experts (STRATA_MMQ_GROUP_SORT).
|
||||
inline size_t mmq_resident_sort_span(size_t n, size_t group, bool keep_tail) {
|
||||
return keep_tail && group > 0 ? n - n % group : n;
|
||||
}
|
||||
|
||||
inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native_layout, bool has_cache,
|
||||
const int32_t* layer_resident, int64_t n_expert,
|
||||
bool stream_all, bool layer_stream_empty) {
|
||||
@@ -35,10 +52,12 @@ inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native
|
||||
// order contains each positive-count expert once in ID order; off has count.size()+1 entries;
|
||||
// routes fits its original int32 offsets, and slot/src each have routes writable entries.
|
||||
// After sorting, off[e] is an expert-indexed START, not an ID-prefix end at off[e+1].
|
||||
// Only order[0, span) is sorted (span >= order.size(): all of it); the entries after it keep their positions.
|
||||
inline void mmq_resident_sort_rows(const int32_t* ids, int64_t routes, int32_t k,
|
||||
const std::vector<int32_t>& count, std::vector<int32_t>& off,
|
||||
std::vector<int32_t>& order, int32_t* slot, int32_t* src) {
|
||||
std::stable_sort(order.begin(), order.end(), [&](int32_t a, int32_t b) {
|
||||
std::vector<int32_t>& order, int32_t* slot, int32_t* src,
|
||||
size_t span = SIZE_MAX) {
|
||||
std::stable_sort(order.begin(), order.begin() + (ptrdiff_t) std::min(span, order.size()), [&](int32_t a, int32_t b) {
|
||||
return count[(size_t) a] != count[(size_t) b]
|
||||
? count[(size_t) a] < count[(size_t) b] : a < b;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// Generated by CMake from src/prefill/mmq_tab_instance.cu.in (STRATA_MMQ_TAB): the pointer-table MMQ for one type,
|
||||
// in its own TU so nvcc builds the types in parallel and each object stays small.
|
||||
#include "@_strata_tab_cuh@"
|
||||
|
||||
namespace strata::prefill::mmq {
|
||||
template bool mul_mat_q_tab_case<GGML_TYPE_@_strata_tab_T@>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&,
|
||||
cudaStream_t);
|
||||
} // namespace strata::prefill::mmq
|
||||
+181
-1
@@ -6,9 +6,13 @@
|
||||
#include "common.cuh"
|
||||
#include "mmq.cuh"
|
||||
#include "quantize.cuh"
|
||||
#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
|
||||
#include "moe_mmq_tab.hpp" // declarations only: the tab kernels live in the per-type mmq-tab-*.cu TUs
|
||||
#endif
|
||||
|
||||
#include "strata/prefill/mmq_kq_abi.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -173,6 +177,59 @@ __global__ void set_bounds_kernel(int32_t* d, int32_t rows) {
|
||||
|
||||
unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); }
|
||||
|
||||
#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
|
||||
// STRATA_MMQ_DIRECT: a group's guards (y < g.n, byte stores) and its two zero tails (y == g.n: gate/up, y == g.n + 1:
|
||||
// down; uint4 stores when `tail16`, which the host checked: both pointers and the size 16-byte aligned). Only in a
|
||||
// STRATA_MMQ_TAB build: the engine loads every kernel at start (EAGER), so a build without it keeps today's image.
|
||||
__global__ void prep_group_kernel(GuardTab g, int64_t guard, uint8_t* tail_gu, uint8_t* tail_d, int64_t tail, bool tail16) {
|
||||
const int y = (int) blockIdx.y;
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (y < g.n) {
|
||||
if (i < guard) g.p[y][i] = 0;
|
||||
return;
|
||||
}
|
||||
uint8_t* t = y == g.n ? tail_gu : tail_d;
|
||||
if (t == nullptr) return;
|
||||
if (tail16) {
|
||||
if (i < tail / 16) ((uint4*) t)[i] = make_uint4(0, 0, 0, 0);
|
||||
} else if (i < tail) {
|
||||
t[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// the pointer-table MMQ per type: the native packs' nine types (CMake's _strata_mmq_tab_types, all of them checked
|
||||
// bit for bit by prefill_mmq_tab_test). false: no instance - the optional Q5_0 and K-quant experts keep the gather
|
||||
bool run_tab(ggml_backend_cuda_context* ctx, const mmq_args* a, const mmq_x_tab* tab, cudaStream_t s) {
|
||||
const ggml_type t = a ? a->type_x : GGML_TYPE_COUNT;
|
||||
#define STRATA_TAB_CASE(T) case T: return ctx == nullptr || mul_mat_q_tab_case<T>(*ctx, *a, *tab, s)
|
||||
switch (t) {
|
||||
STRATA_TAB_CASE(GGML_TYPE_Q2_0);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ2_XXS);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ2_XS);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ2_S);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ3_XXS);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ3_S);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ4_NL);
|
||||
STRATA_TAB_CASE(GGML_TYPE_IQ4_XS);
|
||||
STRATA_TAB_CASE(GGML_TYPE_Q8_0);
|
||||
default: return false;
|
||||
}
|
||||
#undef STRATA_TAB_CASE
|
||||
}
|
||||
// whether run_tab has an instance for type t (no launch)
|
||||
bool tab_has_type(int t) {
|
||||
mmq_args a{};
|
||||
a.type_x = (ggml_type) t;
|
||||
return run_tab(nullptr, &a, nullptr, nullptr);
|
||||
}
|
||||
#else
|
||||
bool run_tab(ggml_backend_cuda_context*, const mmq_args*, const void*, cudaStream_t) {
|
||||
std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n");
|
||||
std::exit(1);
|
||||
}
|
||||
bool tab_has_type(int) { return false; }
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
// mmq_nvfp4_w4a8.cu: mmq.cuh's int8 NVFP4 path, compiled for this GPU with Blackwell's FP4 MMA hidden
|
||||
@@ -337,11 +394,30 @@ void Context::run(const Product& p, void* stream) {
|
||||
const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk;
|
||||
const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, p.y_scale,
|
||||
p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst,
|
||||
p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0,
|
||||
p.n, p.n, p.tab ? 0 : (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0,
|
||||
1, 1, 0, 0, 0,
|
||||
p.max_rows, p.max_rows};
|
||||
auto& ctx = *(ggml_backend_cuda_context*) ctx_;
|
||||
const cudaStream_t s = (cudaStream_t) stream;
|
||||
if (p.tab) {
|
||||
if (p.n > kGatherGroupMax) {
|
||||
std::fprintf(stderr, "prefill mmq: a pointer table holds at most %d experts (got %d)\n", kGatherGroupMax, p.n);
|
||||
std::exit(1);
|
||||
}
|
||||
#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
|
||||
mmq_x_tab tab{};
|
||||
for (int z = 0; z < p.n; ++z) tab.p[z] = (const char*) p.tab->p[z];
|
||||
if (!run_tab(&ctx, &a, &tab, s)) {
|
||||
std::fprintf(stderr, "prefill mmq: no pointer-table MMQ for %s with %lld rows\n", ggml_type_name(t),
|
||||
(long long) p.w_rows);
|
||||
std::exit(1);
|
||||
}
|
||||
#else
|
||||
run_tab(&ctx, &a, nullptr, s);
|
||||
#endif
|
||||
ck(cudaGetLastError(), "mul_mat_q (pointer table)");
|
||||
return;
|
||||
}
|
||||
switch (t) {
|
||||
#ifdef STRATA_ORCA_Q4KS_MMQ
|
||||
case GGML_TYPE_Q5_0: mul_mat_q_case<GGML_TYPE_Q5_0>(ctx, a, s); break;
|
||||
@@ -383,6 +459,110 @@ void Context::run(const Product& p, void* stream) {
|
||||
ck(cudaGetLastError(), "mul_mat_q");
|
||||
}
|
||||
|
||||
// ---- STRATA_MMQ_DIRECT ----
|
||||
bool tab_built() {
|
||||
#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool tab_fits(int t, int64_t w_rows) {
|
||||
return tab_built() && w_rows % 128 == 0 && tab_has_type(t) && fits(t, w_rows);
|
||||
}
|
||||
|
||||
size_t overread_bytes(int t, int64_t cols) {
|
||||
if (!supported(t)) return 0;
|
||||
// the K tile's over-read for each (fallback=false) config on any visible GPU, the largest of them: the over-read
|
||||
// is not monotonic in the tile length (20 blocks: 12 more with a 16-block tile, 4 with a 24-block one), so each
|
||||
// config's own; MMQ_ITER_K's is the floor (it is the tile when no config is known)
|
||||
const int64_t qk = ggml_blck_size((ggml_type) t), bpn = cols / qk;
|
||||
auto over = [&](int64_t k_vram) -> int64_t {
|
||||
const int64_t bpi = k_vram / qk;
|
||||
return bpi > 0 ? (bpi - bpn % bpi) % bpi : 0;
|
||||
};
|
||||
int64_t blocks = over(MMQ_ITER_K);
|
||||
const ggml_cuda_device_info& info = ggml_cuda_info();
|
||||
for (int id = 0; id < info.device_count; ++id)
|
||||
for (int J = 8; J <= 128; J += 8) {
|
||||
const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, info.devices[id].cc);
|
||||
if (c.type != GGML_TYPE_COUNT) blocks = std::max<int64_t>(blocks, over(c.K_vram));
|
||||
}
|
||||
return (size_t) blocks * ggml_type_size((ggml_type) t);
|
||||
}
|
||||
|
||||
bool whole_tiles(int t, int64_t w_rows, int n_experts) {
|
||||
if (!supported(t) || w_rows % 128 != 0 || n_experts <= 0) return false;
|
||||
// launch_mul_mat_q's grid: without stream-k one block per tile; with it one block per tile when the tiles fill
|
||||
// their waves to >= 90 % (NVIDIA), else nsm blocks that split tiles along K at boundaries set by the tile count.
|
||||
// The tile count is nty * n_experts * ntx, ntx = any positive count of J-wide column tiles (max_rows decides),
|
||||
// and ntiles >= 9 * nsm always fills its waves to >= 90 %: the ntx below that are checked one by one.
|
||||
const ggml_cuda_device_info& info = ggml_cuda_info();
|
||||
for (int id = 0; id < info.device_count; ++id) {
|
||||
const int cc = info.devices[id].cc, nsm = info.devices[id].nsm;
|
||||
const size_t smpbo = info.devices[id].smpbo;
|
||||
bool any = false, stream_k = false;
|
||||
ggml_cuda_mmq_config c0 = ggml_cuda_mmq_get_config((ggml_type) t, 8, false, cc);
|
||||
for (int J = 8; J <= 128; J += 8) {
|
||||
const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, cc);
|
||||
if (c.type == GGML_TYPE_COUNT || mmq_get_nbytes_shared(c, cc) > smpbo) continue;
|
||||
if (!any) c0 = c;
|
||||
any = true;
|
||||
// every tile width accumulates each output over the same K tiles in the same order
|
||||
if (c.I != c0.I || c.K_vram != c0.K_vram || c.sram_layout != c0.sram_layout) return false;
|
||||
stream_k = stream_k || c.stream_k;
|
||||
}
|
||||
if (!any) return false;
|
||||
if (!stream_k) continue;
|
||||
if (!GGML_CUDA_CC_IS_NVIDIA(cc) || nsm <= 0) return false;
|
||||
const int64_t per_ntx = (w_rows / c0.I) * n_experts;
|
||||
for (int64_t ntx = 1; per_ntx * ntx < 9 * (int64_t) nsm + per_ntx; ++ntx) {
|
||||
const int64_t tiles = per_ntx * ntx, waves = (tiles + nsm - 1) / nsm;
|
||||
if (100 * tiles / (nsm * waves) < 90) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int direct_mode() {
|
||||
static const int mode = [] {
|
||||
const char* v = std::getenv("STRATA_MMQ_DIRECT");
|
||||
const int m = v ? std::atoi(v) : 0;
|
||||
if (m != 1 && m != 2) return 0;
|
||||
if (!tab_built()) {
|
||||
std::fprintf(stderr, "strata: STRATA_MMQ_DIRECT=%d is ignored: this build has no pointer-table MMQ "
|
||||
"(CUDA with STRATA_MMQ_TAB only)\n", m);
|
||||
return 0;
|
||||
}
|
||||
return m;
|
||||
}();
|
||||
return mode;
|
||||
}
|
||||
|
||||
size_t direct_slot_guard() { return direct_mode() != 0 ? kSlotGuard : 0; }
|
||||
|
||||
void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream) {
|
||||
#if !defined(STRATA_MMQ_TAB) || defined(__HIPCC__)
|
||||
// never reached: only a direct group calls it, and direct_mode() is 0 without the pointer-table MMQ
|
||||
(void) g; (void) guard_bytes; (void) tail_gu; (void) tail_d; (void) tail_bytes; (void) stream;
|
||||
std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n");
|
||||
std::exit(1);
|
||||
#else
|
||||
const int n = g.n > 0 ? std::min(g.n, kGatherGroupMax) : 0;
|
||||
const size_t guard = n > 0 ? guard_bytes : 0;
|
||||
const size_t tail = tail_gu || tail_d ? tail_bytes : 0;
|
||||
if (guard == 0 && tail == 0) return;
|
||||
GuardTab gt = g;
|
||||
gt.n = guard > 0 ? n : 0;
|
||||
const bool tail16 = ((uintptr_t) tail_gu | (uintptr_t) tail_d | tail_bytes) % 16 == 0;
|
||||
const size_t span = std::max(guard, tail);
|
||||
prep_group_kernel<<<dim3(blocks((int64_t) span), (unsigned) (gt.n + 2)), 256, 0, (cudaStream_t) stream>>>(
|
||||
gt, (int64_t) guard, (uint8_t*) tail_gu, (uint8_t*) tail_d, (int64_t) tail, tail16);
|
||||
ck(cudaGetLastError(), "prep_group");
|
||||
#endif
|
||||
}
|
||||
|
||||
void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes,
|
||||
void* gu_dst, void* d_dst, void* stream, const void* tail, void* tail_dst, size_t zero_bytes) {
|
||||
const cudaStream_t s = (cudaStream_t) stream;
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
// src/prefill/moe_mmq_tab.cuh - STRATA_MMQ_DIRECT: llama.cpp's MMQ outer scheduler (ggml-cuda mmq.cuh, MIT) with a
|
||||
// per-expert pointer table, so the prompt path's MMQ reads resident experts in their expert-cache slots instead of
|
||||
// a gathered copy. Included only by the per-type instance TUs (CMake: mmq_tab_instance.cu.in); moe_mmq.cu sees
|
||||
// the declarations in moe_mmq_tab.hpp.
|
||||
//
|
||||
// Mirrored from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d (the fetched pin; the vendored third_party tree's
|
||||
// mmq.cuh is byte-identical to it), ggml/src/ggml-cuda/mmq.cuh:
|
||||
// mul_mat_q lines 953-1238 -> mul_mat_q_tab
|
||||
// launch_mul_mat_q lines 1395-1475 -> launch_mul_mat_q_tab
|
||||
// mul_mat_q_switch_J lines 1477-1558 -> mul_mat_q_tab_switch_J
|
||||
// fallback = false only (mul_mat_q_tab_case refuses rows % 128 != 0). Everything else is the upstream text, and
|
||||
// mul_mat_q_process_tile, the tile loaders, vec_dot, write_back and mul_mat_q_stream_k_fixup are upstream's own
|
||||
// templates from the same mmq.cuh, compiled in the same target with the same flags. Deliberate deviations:
|
||||
// 1. upstream's `const char * __restrict__ x` parameter becomes 16 such parameters x0..x15 (the table, see
|
||||
// STRATA_MMQ_TAB_PARAMS); at the three offset_x sites the expert's base is the one picked by
|
||||
// fastdiv(zt, channel_ratio), and the fastdiv(zt, channel_ratio)*stride_channel_x term leaves offset_x
|
||||
// (stride_channel_x is still passed, unused);
|
||||
// 2. the launcher raises the shared-memory limit of mul_mat_q_tab<type, J> only - upstream's line for
|
||||
// mul_mat_q<type, J, true> is dropped, so no fallback=true kernel is instantiated.
|
||||
// The launch geometry (J, tiles, the stream-k grid and k split, the fixup) is computed from the same mmq_args as
|
||||
// upstream's, so every output tile is summed in the same order: the results are bitwise the same as gathering the
|
||||
// experts `stride_channel_x` apart (tests/cuda/prefill_mmq_tab_test.cu checks it per type and J).
|
||||
// CMake turns STRATA_MMQ_TAB off unless the SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through
|
||||
// mul_mat_q_case, which includes struct mmq_args) is one this copy was verified against; when the llama.cpp pin
|
||||
// moves, re-sync this file, re-run the test and record the new hash in CMakeLists.txt (_strata_mmq_tab_known).
|
||||
//
|
||||
// MIT License
|
||||
// Copyright (c) 2023-2026 The ggml authors
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
#pragma once
|
||||
|
||||
#include "mmq.cuh"
|
||||
#include "moe_mmq_tab.hpp"
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
namespace strata::prefill::mmq {
|
||||
|
||||
// A second net behind the configure fingerprint: the upstream templates this copy calls keep their signatures.
|
||||
static_assert(std::is_same<decltype(&mul_mat_q_process_tile<GGML_TYPE_Q8_0, 8, false, false>),
|
||||
void (*)(const char*, int, const int*, const int*, float*, float*, const float*, int, int, int,
|
||||
int, int, int, int)>::value,
|
||||
"mmq.cuh: mul_mat_q_process_tile changed - re-sync src/prefill/moe_mmq_tab.cuh");
|
||||
static_assert(std::is_same<decltype(&mul_mat_q_stream_k_fixup<GGML_TYPE_Q8_0, 8, false>),
|
||||
void (*)(const int32_t*, const int32_t*, float*, float*, uint3, int, int, int, uint3, int,
|
||||
uint3, int, uint3)>::value,
|
||||
"mmq.cuh: mul_mat_q_stream_k_fixup changed - re-sync src/prefill/moe_mmq_tab.cuh");
|
||||
|
||||
// The table reaches the kernel as 16 separate `const char * __restrict__` parameters, like upstream's `x`, and an
|
||||
// expert's entry is picked with a select chain: a pointer picked from read-only kernel parameters keeps upstream's
|
||||
// non-coherent global loads (LDG.CONSTANT) of the weights; a dynamically indexed array parameter would be copied to
|
||||
// local memory and its pointers read through generic loads (measured ~1.2-2.5x slower products).
|
||||
#define STRATA_MMQ_TAB_PARAMS \
|
||||
const char * __restrict__ x0, const char * __restrict__ x1, const char * __restrict__ x2, \
|
||||
const char * __restrict__ x3, const char * __restrict__ x4, const char * __restrict__ x5, \
|
||||
const char * __restrict__ x6, const char * __restrict__ x7, const char * __restrict__ x8, \
|
||||
const char * __restrict__ x9, const char * __restrict__ x10, const char * __restrict__ x11, \
|
||||
const char * __restrict__ x12, const char * __restrict__ x13, const char * __restrict__ x14, \
|
||||
const char * __restrict__ x15
|
||||
#define STRATA_MMQ_TAB_PICK(z) \
|
||||
((z) == 0 ? x0 : (z) == 1 ? x1 : (z) == 2 ? x2 : (z) == 3 ? x3 : (z) == 4 ? x4 : (z) == 5 ? x5 : \
|
||||
(z) == 6 ? x6 : (z) == 7 ? x7 : (z) == 8 ? x8 : (z) == 9 ? x9 : (z) == 10 ? x10 : (z) == 11 ? x11 : \
|
||||
(z) == 12 ? x12 : (z) == 13 ? x13 : (z) == 14 ? x14 : x15)
|
||||
#define STRATA_MMQ_TAB_ARGS(t) \
|
||||
(t).p[0], (t).p[1], (t).p[2], (t).p[3], (t).p[4], (t).p[5], (t).p[6], (t).p[7], (t).p[8], (t).p[9], \
|
||||
(t).p[10], (t).p[11], (t).p[12], (t).p[13], (t).p[14], (t).p[15]
|
||||
|
||||
// ---- mirrored: mul_mat_q (fallback = false, per-expert base from `tab`) ----
|
||||
template <ggml_type type, int J>
|
||||
__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, false), ggml_cuda_mmq_get_occupancy(type, J, false))
|
||||
static __global__ void mul_mat_q_tab(
|
||||
STRATA_MMQ_TAB_PARAMS, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
|
||||
const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
|
||||
const float * __restrict__ y_scale,
|
||||
const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
|
||||
const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
|
||||
const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
|
||||
const uint3 ntx) {
|
||||
constexpr bool fallback = false; // STRATA: the tab copy has no fallback (rows % 128 == 0) instantiation
|
||||
|
||||
// Skip unused template specializations for faster compilation:
|
||||
if (ggml_cuda_mmq_get_config(type, J, fallback).type == GGML_TYPE_COUNT) {
|
||||
NO_DEVICE_CODE;
|
||||
return;
|
||||
}
|
||||
|
||||
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
|
||||
constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size;
|
||||
constexpr int qk = ggml_cuda_type_traits<type>::qk;
|
||||
constexpr int I = ggml_cuda_mmq_get_I(type, J, fallback);
|
||||
|
||||
const uint32_t nty = (nrows_x + I - 1) / I; // Number of tiles y
|
||||
|
||||
// Initialize the ids for writing back data with just the index.
|
||||
// For regular matrix multiplications this is never changed.
|
||||
// For MoE the correct indices are loaded from ids_dst.
|
||||
extern __shared__ int ids_dst_shared[]; // Stored at beginning of shared memory.
|
||||
#pragma unroll
|
||||
for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
|
||||
const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
|
||||
|
||||
if (j0 + nwarps*warp_size > J && j >= J) {
|
||||
break;
|
||||
}
|
||||
|
||||
ids_dst_shared[j] = j;
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
if constexpr (!ggml_cuda_mmq_get_stream_k(type, J, fallback)) {
|
||||
const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y);
|
||||
const int wt = tmp2.x;
|
||||
const int zt = tmp2.y;
|
||||
const int jt = blockIdx.y;
|
||||
const int it = blockIdx.x;
|
||||
|
||||
// Defaults for regular matrix multiplication:
|
||||
int col_low = 0;
|
||||
int col_high = ncols_dst;
|
||||
int col_diff = ncols_dst;
|
||||
int offset_y = wt*stride_sample_y + zt*stride_channel_y;
|
||||
int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
|
||||
int offset_y_scale;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
|
||||
} else {
|
||||
GGML_UNUSED(offset_y_scale);
|
||||
}
|
||||
|
||||
if (ids_dst) {
|
||||
col_low = expert_bounds[zt + 0];
|
||||
col_high = expert_bounds[zt + 1];
|
||||
col_diff = col_high - col_low;
|
||||
|
||||
offset_y = 0;
|
||||
offset_dst = 0;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale = 0;
|
||||
}
|
||||
|
||||
if (jt*J >= col_diff) {
|
||||
return;
|
||||
}
|
||||
|
||||
// __syncthreads(); // There is no previous tile that could cause a race condition.
|
||||
#pragma unroll
|
||||
for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
|
||||
const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
|
||||
|
||||
if (j0 + nwarps*warp_size > J && j >= J) {
|
||||
break;
|
||||
}
|
||||
|
||||
ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
offset_y += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int));
|
||||
offset_dst += it*I;
|
||||
const float * y_scale_tile = nullptr;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale += col_low + jt*J;
|
||||
y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
|
||||
}
|
||||
|
||||
const int tile_x_max_i = nrows_x - it*I - 1;
|
||||
const int tile_y_max_j = col_diff - jt*J - 1;
|
||||
|
||||
const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio)); // STRATA: per-expert base
|
||||
const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x;
|
||||
|
||||
constexpr bool fixup = false;
|
||||
mul_mat_q_process_tile<type, J, fallback, fixup>
|
||||
(xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
|
||||
stride_row_x, ncols_y, stride_col_dst,
|
||||
tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z);
|
||||
return;
|
||||
}
|
||||
|
||||
constexpr int ITER_K = ggml_cuda_mmq_get_K_vram(type, J, fallback);
|
||||
constexpr int blocks_per_iter = ITER_K / qk;
|
||||
|
||||
// kbc == k block continuous, current index in continuous ijk space.
|
||||
int kbc = int64_t(blockIdx.x) *(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
|
||||
int kbc_stop = int64_t(blockIdx.x + 1)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
|
||||
|
||||
kbc -= fastmodulo(kbc, blocks_per_ne00) % blocks_per_iter;
|
||||
kbc_stop -= fastmodulo(kbc_stop, blocks_per_ne00) % blocks_per_iter;
|
||||
|
||||
// kb0 == k index when doing the matrix multiplication for an output tile.
|
||||
int kb0_start = fastmodulo(kbc, blocks_per_ne00);
|
||||
int kb0_stop = min(blocks_per_ne00.z, uint32_t(kb0_start + kbc_stop - kbc));
|
||||
while (kbc < kbc_stop && kb0_stop == int(blocks_per_ne00.z)) {
|
||||
int tmp = fastdiv(kbc, blocks_per_ne00);
|
||||
uint2 tmp2 = fast_div_modulo(tmp, ntx);
|
||||
const int jt = tmp2.y;
|
||||
tmp = tmp2.x;
|
||||
tmp2 = fast_div_modulo(tmp, nchannels_y);
|
||||
const int zt = tmp2.y;
|
||||
tmp = tmp2.x;
|
||||
tmp2 = fast_div_modulo(tmp, nsamples_y);
|
||||
const int wt = tmp2.y;
|
||||
const int it = tmp2.x;
|
||||
|
||||
// Defaults for regular matrix multiplication:
|
||||
int col_low = 0;
|
||||
int col_high = ncols_dst;
|
||||
int col_diff = ncols_dst;
|
||||
int offset_y = wt*stride_sample_y + zt*stride_channel_y;
|
||||
int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
|
||||
int offset_y_scale;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
|
||||
} else {
|
||||
GGML_UNUSED(offset_y_scale);
|
||||
}
|
||||
|
||||
if (ids_dst) {
|
||||
col_low = expert_bounds[zt + 0];
|
||||
col_high = expert_bounds[zt + 1];
|
||||
col_diff = col_high - col_low;
|
||||
|
||||
offset_y = 0;
|
||||
offset_dst = 0;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale = 0;
|
||||
}
|
||||
|
||||
if (jt*J >= col_diff) {
|
||||
kbc += blocks_per_ne00.z;
|
||||
kbc -= fastmodulo(kbc, blocks_per_ne00);
|
||||
|
||||
kb0_start = 0;
|
||||
kb0_stop = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
|
||||
const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
|
||||
|
||||
if (j0 + nwarps*warp_size > J && j >= J) {
|
||||
break;
|
||||
}
|
||||
|
||||
ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int));
|
||||
offset_dst += it*I;
|
||||
const float * y_scale_tile = nullptr;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale += col_low + jt * J;
|
||||
y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
|
||||
}
|
||||
|
||||
const int tile_x_max_i = nrows_x - it*I - 1;
|
||||
const int tile_y_max_j = col_diff - jt*J - 1;
|
||||
|
||||
const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio)); // STRATA: per-expert base
|
||||
const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x;
|
||||
|
||||
constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
|
||||
mul_mat_q_process_tile<type, J, fallback, fixup>
|
||||
(xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
|
||||
stride_row_x, ncols_y, stride_col_dst,
|
||||
tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop);
|
||||
|
||||
kbc += blocks_per_ne00.z;
|
||||
kbc -= fastmodulo(kbc, blocks_per_ne00);
|
||||
|
||||
kb0_start = 0;
|
||||
kb0_stop = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc));
|
||||
}
|
||||
|
||||
if (kbc >= kbc_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
int tmp = fastdiv(kbc, blocks_per_ne00);
|
||||
uint2 tmp2 = fast_div_modulo(tmp, ntx);
|
||||
const int jt = tmp2.y;
|
||||
tmp = tmp2.x;
|
||||
tmp2 = fast_div_modulo(tmp, nchannels_y);
|
||||
const int zt = tmp2.y;
|
||||
tmp = tmp2.x;
|
||||
tmp2 = fast_div_modulo(tmp, nsamples_y);
|
||||
const int wt = tmp2.y;
|
||||
const int it = tmp2.x;
|
||||
|
||||
// Defaults for regular matrix multiplication:
|
||||
int col_low = 0;
|
||||
int col_high = ncols_dst;
|
||||
int col_diff = ncols_dst;
|
||||
int offset_y = wt*stride_sample_y + zt*stride_channel_y;
|
||||
int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
|
||||
int offset_y_scale;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
|
||||
} else {
|
||||
GGML_UNUSED(offset_y_scale);
|
||||
}
|
||||
|
||||
if (ids_dst) {
|
||||
col_low = expert_bounds[zt + 0];
|
||||
col_high = expert_bounds[zt + 1];
|
||||
col_diff = col_high - col_low;
|
||||
|
||||
offset_y = 0;
|
||||
offset_dst = 0;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale = 0;
|
||||
}
|
||||
|
||||
if (jt*J >= col_diff) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The memory layout for the fixup buffer is always contiguous, therefore reset ids:
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
|
||||
const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
|
||||
|
||||
if (j0 + nwarps*warp_size > J && j >= J) {
|
||||
break;
|
||||
}
|
||||
|
||||
ids_dst_shared[j] = j;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int));
|
||||
offset_dst += it*I;
|
||||
const float * y_scale_tile = nullptr;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
offset_y_scale += col_low + jt * J;
|
||||
y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
|
||||
}
|
||||
|
||||
const int tile_x_max_i = nrows_x - it*I - 1;
|
||||
const int tile_y_max_j = col_diff - jt*J - 1;
|
||||
|
||||
const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio)); // STRATA: per-expert base
|
||||
const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x;
|
||||
|
||||
constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
|
||||
mul_mat_q_process_tile<type, J, fallback, fixup>
|
||||
(xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
|
||||
stride_row_x, ncols_y, stride_col_dst,
|
||||
tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop);
|
||||
}
|
||||
|
||||
// ---- mirrored: launch_mul_mat_q (fallback = false) ----
|
||||
template <ggml_type type, int J>
|
||||
static void launch_mul_mat_q_tab(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) {
|
||||
constexpr bool fallback = false;
|
||||
const int id = ggml_cuda_get_device();
|
||||
const int cc = ggml_cuda_info().devices[id].cc;
|
||||
const int nsm = ggml_cuda_info().devices[id].nsm;
|
||||
const int warp_size = ggml_cuda_info().devices[id].warp_size;
|
||||
|
||||
const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc);
|
||||
GGML_ASSERT(config.nthreads % warp_size == 0);
|
||||
const int nwarps = config.nthreads / warp_size;
|
||||
const int nbytes_shared = mmq_get_nbytes_shared(config, cc);
|
||||
|
||||
const dim3 block_dims(warp_size, nwarps, 1);
|
||||
|
||||
CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_tab<type, J>), nbytes_shared); // STRATA: no fallback=true line
|
||||
|
||||
const int nty = (args.nrows_x + config.I - 1) / config.I;
|
||||
const int ntx = (args.ncols_max + config.J - 1) / config.J;
|
||||
const int ntzw = args.nchannels_y * args.nsamples_y;
|
||||
const dim3 block_nums_xy_tiling(nty, ntx, ntzw);
|
||||
|
||||
GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0);
|
||||
GGML_ASSERT(args.nsamples_y % args.nsamples_x == 0);
|
||||
const int channel_ratio = args.nchannels_y / args.nchannels_x;
|
||||
const int sample_ratio = args.nsamples_y / args.nsamples_x;
|
||||
|
||||
const uint3 blocks_per_ne00_fd = init_fastdiv_values(args.ncols_x / ggml_cuda_type_traits<type>::qk);
|
||||
const uint3 ntx_fd = init_fastdiv_values(ntx);
|
||||
const uint3 nchannels_y_fd = init_fastdiv_values(args.nchannels_y);
|
||||
const uint3 nsamples_y_fd = init_fastdiv_values(args.nsamples_y);
|
||||
const uint3 channel_ratio_fd = init_fastdiv_values(channel_ratio);
|
||||
const uint3 sample_ratio_fd = init_fastdiv_values(sample_ratio);
|
||||
|
||||
if (!ggml_cuda_mmq_get_stream_k(type, J, fallback, cc)) {
|
||||
mul_mat_q_tab<type, J><<<block_nums_xy_tiling, block_dims, nbytes_shared, stream>>>
|
||||
(STRATA_MMQ_TAB_ARGS(tab), args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale,
|
||||
blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
|
||||
channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
|
||||
sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
|
||||
ntx_fd);
|
||||
return;
|
||||
}
|
||||
|
||||
// For the stream-k kernel it is possible to run it with tiling by setting the number of CUDA blocks equal to the number of tiles.
|
||||
// This is worthwhile if the efficiency of tiling is high and skipping the fixup kernel is more important.
|
||||
const int ntiles_dst = ntx * nty * ntzw;
|
||||
const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm;
|
||||
const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves);
|
||||
const dim3 block_nums_stream_k(GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm, 1, 1);
|
||||
|
||||
GGML_ASSERT(ntiles_dst * blocks_per_ne00_fd.z < (1 << 30)); // Assert that variable kbc will not overflow.
|
||||
|
||||
const bool fixup_needed = ntiles_dst % block_nums_stream_k.x != 0;
|
||||
|
||||
ggml_cuda_pool & pool = ctx.pool(id);
|
||||
ggml_cuda_pool_alloc<float> tmp_fixup(pool);
|
||||
if (fixup_needed) {
|
||||
tmp_fixup.alloc(block_nums_stream_k.x * config.J*config.I);
|
||||
}
|
||||
|
||||
const dim3 block_nums_fixup(block_nums_stream_k.x, config.I/warp_size, 1);
|
||||
const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z);
|
||||
|
||||
mul_mat_q_tab<type, J><<<block_nums_stream_k, block_dims, nbytes_shared, stream>>>
|
||||
(STRATA_MMQ_TAB_ARGS(tab), args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale,
|
||||
blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
|
||||
channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
|
||||
sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
|
||||
ntx_fd);
|
||||
|
||||
if (!fixup_needed) {
|
||||
return;
|
||||
}
|
||||
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
mul_mat_q_stream_k_fixup<type, J, fallback><<<block_nums_fixup, block_dims_fixup, 0, stream>>>
|
||||
(args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
|
||||
args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst,
|
||||
ntx_fd);
|
||||
}
|
||||
|
||||
// ---- mirrored: mul_mat_q_switch_J (fallback = false) ----
|
||||
template <ggml_type type>
|
||||
static void mul_mat_q_tab_switch_J(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) {
|
||||
constexpr bool fallback = false;
|
||||
const int id = ggml_cuda_get_device();
|
||||
const int cc = ggml_cuda_info().devices[id].cc;
|
||||
const size_t smpbo = ggml_cuda_info().devices[id].smpbo;
|
||||
|
||||
int J_best = 0;
|
||||
int ntiles_J_best = INT_MAX;
|
||||
|
||||
for (int J = 8; J <= 128 && ntiles_J_best > 1; J += 8) {
|
||||
const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc);
|
||||
if (config.type == GGML_TYPE_COUNT) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (mmq_get_nbytes_shared(config, cc) > smpbo) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const int ntiles_x = (args.ncols_opt + config.J - 1) / config.J;
|
||||
|
||||
if (ntiles_x < ntiles_J_best) {
|
||||
J_best = J;
|
||||
ntiles_J_best = ntiles_x;
|
||||
}
|
||||
}
|
||||
|
||||
switch (J_best) {
|
||||
case 8:
|
||||
launch_mul_mat_q_tab<type, 8>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 16:
|
||||
launch_mul_mat_q_tab<type, 16>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 24:
|
||||
launch_mul_mat_q_tab<type, 24>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 32:
|
||||
launch_mul_mat_q_tab<type, 32>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 40:
|
||||
launch_mul_mat_q_tab<type, 40>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 48:
|
||||
launch_mul_mat_q_tab<type, 48>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 56:
|
||||
launch_mul_mat_q_tab<type, 56>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 64:
|
||||
launch_mul_mat_q_tab<type, 64>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 72:
|
||||
launch_mul_mat_q_tab<type, 72>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 80:
|
||||
launch_mul_mat_q_tab<type, 80>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 88:
|
||||
launch_mul_mat_q_tab<type, 88>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 96:
|
||||
launch_mul_mat_q_tab<type, 96>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 104:
|
||||
launch_mul_mat_q_tab<type, 104>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 112:
|
||||
launch_mul_mat_q_tab<type, 112>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 120:
|
||||
launch_mul_mat_q_tab<type, 120>(ctx, args, tab, stream);
|
||||
break;
|
||||
case 128:
|
||||
launch_mul_mat_q_tab<type, 128>(ctx, args, tab, stream);
|
||||
break;
|
||||
default:
|
||||
fprintf(stderr, "J_best=%d\n", J_best);
|
||||
GGML_ABORT("fatal error");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
template <ggml_type T>
|
||||
bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s) {
|
||||
if (a.nrows_x % 128 != 0) return false; // upstream would take the fallback configs: not mirrored
|
||||
mul_mat_q_tab_switch_J<T>(ctx, a, tab, s);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace strata::prefill::mmq
|
||||
@@ -0,0 +1,30 @@
|
||||
// src/prefill/moe_mmq_tab.hpp - STRATA_MMQ_DIRECT: declarations of the pointer-table MMQ (moe_mmq_tab.cuh).
|
||||
// moe_mmq.cu includes only this header, so the tab kernels are instantiated once, in the per-type TUs that CMake
|
||||
// generates from mmq_tab_instance.cu.in (STRATA_MMQ_TAB on), never implicitly in moe_mmq.cu.
|
||||
#pragma once
|
||||
|
||||
#include "mmq.cuh"
|
||||
|
||||
namespace strata::prefill::mmq {
|
||||
|
||||
/// Expert z's weight matrix starts at p[z] (z < the launch's nchannels <= 16).
|
||||
struct mmq_x_tab {
|
||||
const char* p[16];
|
||||
};
|
||||
|
||||
/// llama.cpp's mul_mat_q_case<T> for fallback=false, with the per-expert base address from `tab` instead of
|
||||
/// x + z * stride_channel_x. false (nothing launched) when the rows are not a multiple of 128.
|
||||
template <ggml_type T>
|
||||
bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s);
|
||||
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_Q2_0>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ2_XXS>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ2_XS>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ2_S>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ3_XXS>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ3_S>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ4_NL>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_IQ4_XS>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
extern template bool mul_mat_q_tab_case<GGML_TYPE_Q8_0>(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t);
|
||||
|
||||
} // namespace strata::prefill::mmq
|
||||
+277
-12
@@ -47,6 +47,7 @@
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <atomic>
|
||||
@@ -79,6 +80,13 @@ void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
|
||||
void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {}
|
||||
void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {}
|
||||
void iota(int32_t*, int64_t, void*) {}
|
||||
bool tab_built() { return false; }
|
||||
bool tab_fits(int, int64_t) { return false; }
|
||||
size_t overread_bytes(int, int64_t) { return 0; }
|
||||
bool whole_tiles(int, int64_t, int) { return false; }
|
||||
int direct_mode() { return 0; }
|
||||
size_t direct_slot_guard() { return 0; }
|
||||
void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {}
|
||||
} // namespace strata::prefill::mmq
|
||||
#endif
|
||||
#ifndef STRATA_PREFILL_FUSED
|
||||
@@ -328,6 +336,77 @@ inline int bf16x2_mode(bool f16_io) {
|
||||
return f16_io ? 0 : v;
|
||||
}
|
||||
inline bool bf16x2(bool f16_io) { return bf16x2_mode(f16_io) != 0; }
|
||||
// STRATA_HANDOFF_PIPE=P (opt-in, 2..16; unset/0/1 = the one copy): a layer split hands a chunk's rows on in P row pieces.
|
||||
// The stage records an event when its chunk's work is done and one after each piece's copy into the pinned hand-off
|
||||
// buffer, waits on the host only for the first (what on_stage_chunk's checkpoint parts and the error check need), and
|
||||
// starts the next stage at once: that stage's upload of piece i waits on piece i's event on the GPU, so its uploads
|
||||
// overlap the remaining downloads (separate PCIe links; the 3090s here have no P2P) and the thread start is hidden
|
||||
// behind them. The same bytes land in the same rows before the next stage's first kernel: exact. No device memory;
|
||||
// the events and the existing two pinned buffers per stage only.
|
||||
static constexpr int kHandPiecesMax = 16;
|
||||
static int handoff_pipe_pieces() {
|
||||
static const int v = [] {
|
||||
const char* e = std::getenv("STRATA_HANDOFF_PIPE");
|
||||
const int p = e ? std::atoi(e) : 0;
|
||||
return p >= 2 ? std::min(p, kHandPiecesMax) : 0;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
// rows [r0, r0 + nr) of piece i of a T-row chunk in P pieces (the same split on both sides of a hand-off)
|
||||
static void handoff_piece(int64_t T, int P, int i, int64_t& r0, int64_t& nr) {
|
||||
const int64_t per = (T + P - 1) / P;
|
||||
r0 = std::min<int64_t>(T, (int64_t) i * per);
|
||||
nr = std::min<int64_t>(T, r0 + per) - r0;
|
||||
}
|
||||
// STRATA_HANDOFF_PIPE: the next stage's chunks run on one thread of the stage's own, started once and pinned once
|
||||
// (std::async started a thread per chunk: ~1 ms from the hand-off to the next stage's first call, measured with nsys).
|
||||
// The futures are the same (run_impl's result, or what it threw), so the chain's waits do not change.
|
||||
// (STRATA_HANDOFF_PIPE_WORKER=0: a thread per chunk again, for an A/B of the two halves.)
|
||||
static bool handoff_pipe_worker() {
|
||||
static const bool v = [] { const char* e = std::getenv("STRATA_HANDOFF_PIPE_WORKER"); return !e || std::atoi(e) != 0; }();
|
||||
return handoff_pipe_pieces() > 0 && v;
|
||||
}
|
||||
struct HandWorker {
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::deque<std::packaged_task<bool()>> jobs;
|
||||
bool stop = false;
|
||||
std::thread th;
|
||||
HandWorker() {
|
||||
th = std::thread([this] {
|
||||
strata::aux_cpus::pin_current_thread();
|
||||
for (;;) {
|
||||
std::packaged_task<bool()> job;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(mu);
|
||||
cv.wait(lk, [this] { return stop || !jobs.empty(); });
|
||||
if (jobs.empty()) return; // stopped, and every job taken has run (no broken promise)
|
||||
job = std::move(jobs.front());
|
||||
jobs.pop_front();
|
||||
}
|
||||
job();
|
||||
}
|
||||
});
|
||||
}
|
||||
std::future<bool> submit(std::packaged_task<bool()> job) {
|
||||
std::future<bool> f = job.get_future();
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
jobs.push_back(std::move(job));
|
||||
}
|
||||
cv.notify_one();
|
||||
return f;
|
||||
}
|
||||
~HandWorker() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
stop = true;
|
||||
}
|
||||
cv.notify_one();
|
||||
if (th.joinable()) th.join();
|
||||
}
|
||||
};
|
||||
|
||||
// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11);
|
||||
// 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
|
||||
@@ -875,6 +954,11 @@ struct Prefill::Impl {
|
||||
// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)
|
||||
int device = -1;
|
||||
float* hand[2] = {};
|
||||
// STRATA_HANDOFF_PIPE: per hand-off buffer, "the chunk's work is done" and one "landed" event per piece
|
||||
int hand_pieces = 0;
|
||||
cudaEvent_t hand_done[2] = {};
|
||||
cudaEvent_t hand_ev[2][kHandPiecesMax] = {};
|
||||
std::unique_ptr<HandWorker> hand_worker; // STRATA_HANDOFF_PIPE: the next stage's chunks' thread (lazily)
|
||||
// C-4: the chunk's token ids on the device, for one batched embedding gather
|
||||
int32_t* tok_dev = nullptr;
|
||||
std::vector<int32_t> tok_host;
|
||||
@@ -938,6 +1022,7 @@ void Prefill::reset() {
|
||||
|
||||
void Prefill::release() {
|
||||
if (!impl_) return;
|
||||
impl_->hand_worker.reset(); // idle here (run drains the chain before it returns); joins its thread
|
||||
if (impl_->cs) cudaStreamSynchronize(impl_->cs);
|
||||
if (impl_->copy) cudaStreamSynchronize(impl_->copy);
|
||||
if (impl_->kv_copy) cudaStreamSynchronize(impl_->kv_copy);
|
||||
@@ -947,6 +1032,9 @@ void Prefill::release() {
|
||||
}
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
if (impl_->hand[b]) cudaFreeHost(impl_->hand[b]);
|
||||
if (impl_->hand_done[b]) cudaEventDestroy(impl_->hand_done[b]);
|
||||
for (cudaEvent_t& e : impl_->hand_ev[b])
|
||||
if (e) cudaEventDestroy(e);
|
||||
if (impl_->ple_copied[b]) cudaEventDestroy(impl_->ple_copied[b]);
|
||||
if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]);
|
||||
}
|
||||
@@ -1008,6 +1096,13 @@ struct MmqPlan {
|
||||
std::vector<char> fo; // per layer: no MMQ here but the native fused kernels cover its formats
|
||||
// (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1)
|
||||
size_t gu_max = 0, d_max = 0;
|
||||
// STRATA_MMQ_DIRECT=1: per layer, whether resident experts are read in their cache slots (pointer-table MMQ),
|
||||
// and the bytes the down product reads past its matrix there (zeroed in the slot's guard before each group)
|
||||
std::vector<char> direct;
|
||||
std::vector<uint32_t> d_over;
|
||||
// STRATA_MMQ_GROUP_SORT=1 (without STRATA_MMQ_RESIDENT_SORT_NE): per MMQ layer, whether both products' 16-expert
|
||||
// launches run whole tiles on every visible GPU (mmq::whole_tiles), so its full groups may be taken in row-count order
|
||||
std::vector<char> group_sort;
|
||||
};
|
||||
const MmqPlan& mmq_plan() {
|
||||
static const MmqPlan plan = [] {
|
||||
@@ -1033,6 +1128,41 @@ const MmqPlan& mmq_plan() {
|
||||
p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N));
|
||||
p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640));
|
||||
}
|
||||
// STRATA_MMQ_DIRECT=1: a native layer's resident experts are read in place when the pointer-table MMQ covers
|
||||
// both products, gate/up reads nothing past its matrix, the down over-read fits the slot guard, and the blob
|
||||
// is exactly [gate | up | down] in MMQ's matrix sizes (the bytes a gather would copy)
|
||||
p.direct.assign(p.layer.size(), 0);
|
||||
p.d_over.assign(p.layer.size(), 0);
|
||||
if (on && lay.native && mmq::direct_mode() == 1) {
|
||||
int64_t nd = 0;
|
||||
for (int64_t l = 0; l < layers; ++l) {
|
||||
if (!p.layer[(size_t) l]) continue;
|
||||
const auto& f = lay.fmt[(size_t) l];
|
||||
const int gt = f.gu_type, dt = f.d_type;
|
||||
if (!mmq::tab_fits(gt, 1280) || !mmq::tab_fits(dt, N)) continue;
|
||||
if (mmq::overread_bytes(gt, N) != 0 || mmq::overread_bytes(dt, 640) > mmq::kSlotGuard) continue;
|
||||
if (f.up_off != mmq::matrix_bytes(gt, 1280, N) / 2 || f.down_off != 2 * f.up_off) continue;
|
||||
if (mmq::matrix_bytes(dt, N, 640) != f.bytes - f.down_off) continue;
|
||||
p.direct[(size_t) l] = 1;
|
||||
p.d_over[(size_t) l] = (uint32_t) mmq::overread_bytes(dt, 640);
|
||||
++nd;
|
||||
}
|
||||
std::fprintf(stderr, "strata: prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1): %lld of %lld "
|
||||
"layers\n", (long long) nd, (long long) layers);
|
||||
}
|
||||
// the verdict depends only on the layer's formats and the visible GPUs: taken once here, not per chunk
|
||||
p.group_sort.assign(p.layer.size(), 0);
|
||||
if (on && detail::mmq_group_sort_requested() && !detail::mmq_resident_sort_requested()) {
|
||||
int64_t ns = 0;
|
||||
for (int64_t l = 0; l < layers; ++l) {
|
||||
if (!p.layer[(size_t) l]) continue;
|
||||
const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
|
||||
p.group_sort[(size_t) l] = mmq::whole_tiles(gt, 1280, MMQ_GROUP) && mmq::whole_tiles(dt, N, MMQ_GROUP);
|
||||
ns += p.group_sort[(size_t) l];
|
||||
}
|
||||
std::fprintf(stderr, "strata: prompt MMQ sorts the full expert groups (STRATA_MMQ_GROUP_SORT=1): %lld of %lld "
|
||||
"layers\n", (long long) ns, (long long) layers);
|
||||
}
|
||||
return p;
|
||||
}();
|
||||
return plan;
|
||||
@@ -1107,6 +1237,16 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
|
||||
err = "prefill: the layer split's hand-off buffers";
|
||||
return false;
|
||||
}
|
||||
if (next_ != nullptr && handoff_pipe_pieces() > 0 && m.hand_pieces == 0) { // events only: no device memory
|
||||
bool ok = true;
|
||||
auto make = [](cudaEvent_t& e) { return e != nullptr || cudaEventCreateWithFlags(&e, cudaEventDisableTiming) == cudaSuccess; };
|
||||
for (int b = 0; b < 2; ++b) { // (a retry after a failed init keeps the events it made)
|
||||
ok = ok && make(m.hand_done[b]);
|
||||
for (int i = 0; ok && i < handoff_pipe_pieces(); ++i) ok = make(m.hand_ev[b][i]);
|
||||
}
|
||||
if (!ok) { err = "prefill: the layer split's hand-off events (STRATA_HANDOFF_PIPE)"; return false; }
|
||||
m.hand_pieces = handoff_pipe_pieces();
|
||||
}
|
||||
if (m.tok_dev == nullptr) {
|
||||
if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) {
|
||||
err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")";
|
||||
@@ -1972,6 +2112,7 @@ void Prefill::arm_cpu_share(bool applies, bool by_default) {
|
||||
}
|
||||
|
||||
bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); }
|
||||
size_t Prefill::slot_guard_bytes() { return mmq::direct_slot_guard(); }
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -2185,7 +2326,30 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
const auto tsetup = Clock::now();
|
||||
// ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the
|
||||
// previous stage handed on
|
||||
if (hand_in_ != nullptr) {
|
||||
if (hand_in_ != nullptr && hand_ev_ != nullptr) {
|
||||
// STRATA_HANDOFF_PIPE: each piece's upload waits on the GPU for its download on the stage before. The
|
||||
// stage before split the chunk it handed on (n rows); one chunk here is all of it, otherwise (a smaller
|
||||
// chunk here) every piece is waited for before the one copy.
|
||||
const auto* ev = static_cast<const cudaEvent_t*>(hand_ev_);
|
||||
const bool whole = c0 == 0 && T == n;
|
||||
bool ok = true;
|
||||
for (int i = 0; ok && i < hand_pieces_; ++i) {
|
||||
int64_t r0 = 0, nr = 0;
|
||||
handoff_piece(n, hand_pieces_, i, r0, nr);
|
||||
ok = cudaStreamWaitEvent(m.cs, ev[i], 0) == cudaSuccess;
|
||||
if (ok && whole && nr > 0)
|
||||
ok = cudaMemcpyAsync(m.R + (size_t) r0 * D, hand_in_ + (size_t) r0 * D, (size_t) nr * D * 4,
|
||||
cudaMemcpyHostToDevice, m.cs) == cudaSuccess;
|
||||
}
|
||||
if (ok && !whole)
|
||||
ok = cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice,
|
||||
m.cs) == cudaSuccess;
|
||||
if (!ok) {
|
||||
err = std::string("prefill: the layer split's hand-off upload failed (STRATA_HANDOFF_PIPE): ") +
|
||||
cudaGetErrorString(cudaGetLastError());
|
||||
return false;
|
||||
}
|
||||
} else if (hand_in_ != nullptr) {
|
||||
if (cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice, m.cs) !=
|
||||
cudaSuccess) {
|
||||
err = "prefill: the layer split's hand-off upload failed";
|
||||
@@ -3344,10 +3508,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
// run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows
|
||||
// (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently
|
||||
// before the upload, the routed ids, weights and the within-expert row order stay as they are.
|
||||
if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested() && on_peer.empty(), use_mmq, lay.native,
|
||||
// STRATA_MMQ_GROUP_SORT=1 (opt-in, exact): the same order for the full groups only, where each
|
||||
// tile is one block's whole K (MmqPlan::group_sort); the partial group keeps its ID order and bits.
|
||||
// STRATA_MMQ_RESIDENT_SORT_NE=1 takes precedence (it sorts the partial group too).
|
||||
const bool sort_all = detail::mmq_resident_sort_requested();
|
||||
const bool sort_full = !sort_all && use_mmq && mmq_plan().group_sort[(size_t) l] &&
|
||||
order.size() >= (size_t) MMQ_GROUP;
|
||||
if (detail::mmq_resident_sort_eligible((sort_all || sort_full) && on_peer.empty(), use_mmq, lay.native,
|
||||
m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr,
|
||||
m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]))
|
||||
detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h);
|
||||
detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h,
|
||||
detail::mmq_resident_sort_span(order.size(), MMQ_GROUP, sort_full));
|
||||
if (grp_mapped) {
|
||||
copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);
|
||||
copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);
|
||||
@@ -3836,7 +4007,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
mmq::GatherGroup gg;
|
||||
int gg_slots[MMQ_GROUP];
|
||||
int gg_nslots = 0; // ring slots gathered by the next flush
|
||||
// `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush)
|
||||
// STRATA_MMQ_DIRECT=1: a resident expert with guard room in its slot is not gathered - the
|
||||
// group's pointer tables give MMQ each expert's own address (group position q), the others are
|
||||
// gathered at compact positions c = 0..ns-1 of the group buffers, as before (same bytes)
|
||||
const bool direct = use_mmq && lay.native && m.cache && mmq_plan().direct[(size_t) l];
|
||||
mmq::WeightTab tgu, td;
|
||||
mmq::GuardTab gd;
|
||||
int ns = 0;
|
||||
// `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush); a direct
|
||||
// group's tail is zeroed by prep_group
|
||||
auto flush = [&](size_t zero) {
|
||||
if (gg.n <= gg.first) return;
|
||||
const auto& f = lay.fmt[(size_t) l];
|
||||
@@ -3866,8 +4045,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
gg.first = gg.n;
|
||||
};
|
||||
// one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident
|
||||
// expert) is released once the blob is read
|
||||
auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {
|
||||
// expert) is released once the blob is read; `cslot`: the expert-cache slot the blob is in (-1:
|
||||
// a ring slot or the peer's), which STRATA_MMQ_DIRECT reads in place
|
||||
auto compute = [&](size_t j, const uint8_t* blob_dev, int slot, int32_t cslot) -> bool {
|
||||
const int32_t e = order[j];
|
||||
pt.mark(kPfDequant, cs);
|
||||
if (use_mmq) {
|
||||
@@ -3875,6 +4055,37 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
const size_t q = j % MMQ_GROUP;
|
||||
// the group's last expert also zeroes the MMQ tail after its slot (see MMQ_TAIL)
|
||||
const bool last_of_group = q + 1 == MMQ_GROUP || j + 1 == order.size();
|
||||
if (direct) {
|
||||
const auto& f = lay.fmt[(size_t) l];
|
||||
uint8_t* gp = cslot >= 0 && ((uintptr_t) blob_dev | (uintptr_t) f.down_off) % 16 == 0
|
||||
? m.cache->slot_tail(cslot, f.bytes, mmq_plan().d_over[(size_t) l])
|
||||
: nullptr;
|
||||
if (gp) { // read in its slot: the guard after the blob is zeroed at the group end
|
||||
tgu.p[q] = blob_dev;
|
||||
td.p[q] = blob_dev + f.down_off;
|
||||
gd.p[gd.n++] = gp;
|
||||
++stats_.experts_direct;
|
||||
} else {
|
||||
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) {
|
||||
gg.blob[c] = blob_dev;
|
||||
gg.n = c + 1;
|
||||
if (slot >= 0) gg_slots[gg_nslots++] = slot;
|
||||
} else {
|
||||
mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
|
||||
mmq_db, m.grp_gu + (size_t) c * mmq_gub,
|
||||
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 (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)
|
||||
flush(0);
|
||||
gg = mmq::GatherGroup{};
|
||||
}
|
||||
} else {
|
||||
if (group_gather) {
|
||||
gg.blob[q] = blob_dev;
|
||||
gg.n = (int) q + 1;
|
||||
@@ -3898,6 +4109,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
}
|
||||
if (slot >= 0 && !group_gather) { 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
|
||||
const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size();
|
||||
const int ngx = (int) (q + 1);
|
||||
@@ -3905,11 +4117,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
int64_t maxr = 0;
|
||||
for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
|
||||
pt.mark(kPfGemmGU, cs);
|
||||
if (direct) {
|
||||
// one launch: the direct experts' guards (their down over-read) and the zeroed tail
|
||||
// after the last gathered expert (see MMQ_TAIL)
|
||||
mmq::prep_group(gd, mmq_plan().d_over[(size_t) l],
|
||||
ns ? m.grp_gu + (size_t) ns * mmq_gub : nullptr,
|
||||
ns ? m.grp_d + (size_t) ns * mmq_db : nullptr, MMQ_TAIL, m.cs);
|
||||
}
|
||||
mmq::Product gu;
|
||||
gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
|
||||
gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
|
||||
gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
|
||||
gu.y_scale = mmq::fp4_activations(mmq_gt) ? m.Xscale : nullptr;
|
||||
if (direct) gu.tab = &tgu;
|
||||
m.mmq_ctx->run(gu, m.cs);
|
||||
if (lay.native && lay.fmt[(size_t) l].tail_off) // gate/up scales applied as read
|
||||
mmq::swiglu_scaled(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, m.bounds_dev + j0, ngx,
|
||||
@@ -3924,9 +4144,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
|
||||
dn.ld_dst = N;
|
||||
dn.y_scale = mmq::fp4_activations(mmq_dt) ? m.Hscale : nullptr;
|
||||
if (direct) dn.tab = &td;
|
||||
m.mmq_ctx->run(dn, m.cs);
|
||||
if (lay.native && lay.fmt[(size_t) l].tail_off) // s_down: applied by the combine
|
||||
mmq::down_row_scales(m.row_sd + r0, dn.bounds, ngx, m.grp_tail, nr, m.cs);
|
||||
if (direct) {
|
||||
tgu = mmq::WeightTab{};
|
||||
td = mmq::WeightTab{};
|
||||
gd = mmq::GuardTab{};
|
||||
ns = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const int q = (int) (j % DQ);
|
||||
@@ -3966,11 +4193,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
const int32_t e = order[j];
|
||||
if (stage_of[j] < 0) {
|
||||
++stats_.experts_resident;
|
||||
if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
|
||||
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 (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -3999,7 +4227,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
pt.mark(kPfWaitCopy, cs);
|
||||
cudaStreamWaitEvent(m.cs, m.copied[sl], 0);
|
||||
}
|
||||
if (!compute(j, m.stage_dev[sl], sl)) return false;
|
||||
if (!compute(j, m.stage_dev[sl], sl, -1)) return false;
|
||||
consumed = ++k;
|
||||
if (!group_gather || gg_nslots == 0) give_back(consumed); // its group was gathered
|
||||
} else {
|
||||
@@ -4008,7 +4236,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
: (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr); // over the cap: P2P
|
||||
if (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; }
|
||||
++stats_.experts_resident;
|
||||
if (!compute(j, bp, -1)) return false;
|
||||
if (!compute(j, bp, -1, r0 ? m.host_res[(size_t) l * m.g->n_expert + e] : -1)) return false;
|
||||
if (group_gather && gg_nslots == 0) give_back(consumed);
|
||||
}
|
||||
}
|
||||
@@ -4158,8 +4386,25 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
if (next_ != nullptr) {
|
||||
// The current hand-off slot was used two chunks ago.
|
||||
float* h = m.hand[hand_buf_];
|
||||
if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
|
||||
cudaStreamSynchronize(m.cs) != cudaSuccess) {
|
||||
const int hp = m.hand_pieces;
|
||||
if (hp > 0) {
|
||||
// STRATA_HANDOFF_PIPE: the pieces' downloads stay queued; the host waits for the chunk's work only (the
|
||||
// state on_stage_chunk saves, the error check), the next stage's uploads wait on the pieces' events
|
||||
bool ok = cudaEventRecord(m.hand_done[hand_buf_], m.cs) == cudaSuccess;
|
||||
for (int i = 0; ok && i < hp; ++i) {
|
||||
int64_t r0 = 0, nr = 0;
|
||||
handoff_piece(T, hp, i, r0, nr);
|
||||
if (nr > 0)
|
||||
ok = cudaMemcpyAsync(h + (size_t) r0 * D, m.R + (size_t) r0 * D, (size_t) nr * D * 4,
|
||||
cudaMemcpyDeviceToHost, m.cs) == cudaSuccess;
|
||||
ok = ok && cudaEventRecord(m.hand_ev[hand_buf_][i], m.cs) == cudaSuccess;
|
||||
}
|
||||
if (!ok || cudaEventSynchronize(m.hand_done[hand_buf_]) != cudaSuccess) {
|
||||
err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError());
|
||||
return false;
|
||||
}
|
||||
} else if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
|
||||
cudaStreamSynchronize(m.cs) != cudaSuccess) {
|
||||
err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError());
|
||||
return false;
|
||||
}
|
||||
@@ -4169,7 +4414,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
if (next_run_.valid() && !next_run_.get()) { err = next_err_; return false; }
|
||||
next_err_.clear();
|
||||
next_->hand_in_ = h;
|
||||
next_->hand_ev_ = hp > 0 ? static_cast<const void*>(m.hand_ev[hand_buf_]) : nullptr;
|
||||
next_->hand_pieces_ = hp;
|
||||
next_->single_chunk_ = single_chunk;
|
||||
if (handoff_pipe_worker()) {
|
||||
if (!m.hand_worker) m.hand_worker = std::make_unique<HandWorker>();
|
||||
next_run_ = m.hand_worker->submit(std::packaged_task<bool()>([this, tokens, c0, T, p0] {
|
||||
const bool r = next_->run_impl(tokens + c0, T, p0, next_err_);
|
||||
(void) cudaGetLastError(); // clear what a thread's end cleared (std::async)
|
||||
return r;
|
||||
}));
|
||||
} else
|
||||
next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] {
|
||||
strata::aux_cpus::pin_current_thread();
|
||||
return next_->run_impl(tokens + c0, T, p0, next_err_);
|
||||
@@ -4356,6 +4611,16 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
||||
err = drain_err;
|
||||
return false;
|
||||
}
|
||||
// STRATA_MMQ_DIRECT=1 with STRATA_MMQ_DIRECT_LOG=1 (a check, not a default): each stage's totals so far - how many
|
||||
// resident experts its prompt MMQ read in their slots, of all its resident and streamed ones
|
||||
if (mmq::direct_mode() == 1) {
|
||||
static const bool log = [] { const char* v = std::getenv("STRATA_MMQ_DIRECT_LOG"); return v && std::atoi(v) != 0; }();
|
||||
for (const Prefill* p = this; log && p != nullptr; p = p->next_)
|
||||
std::fprintf(stderr, "strata prefill: layers %lld..%lld: %lld of %lld resident experts read in place, %lld "
|
||||
"streamed (STRATA_MMQ_DIRECT, totals)\n", (long long) p->stage_lb_,
|
||||
(long long) p->stage_le_, (long long) p->stats_.experts_direct,
|
||||
(long long) p->stats_.experts_resident, (long long) p->stats_.experts_streamed);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+655
-53
File diff suppressed because it is too large.
Load diff
@@ -308,4 +308,13 @@ void iota(int32_t* dst, int64_t n, void* stream) {
|
||||
ck(0, "iota");
|
||||
}
|
||||
|
||||
// STRATA_MMQ_DIRECT (include/strata/prefill/moe_mmq.hpp): the pointer-table MMQ is CUDA only, so SYCL keeps the
|
||||
// gather - these say so, for a prefill.cpp migrated from a tree that calls them
|
||||
bool tab_built() { return false; }
|
||||
bool tab_fits(int, int64_t) { return false; }
|
||||
size_t overread_bytes(int, int64_t) { return 0; }
|
||||
int direct_mode() { return 0; }
|
||||
size_t direct_slot_guard() { return 0; }
|
||||
void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {}
|
||||
|
||||
} // namespace strata::prefill::mmq
|
||||
@@ -0,0 +1,117 @@
|
||||
// STRATA_MMQ_DIRECT: the expert cache's slot guard (set_slot_guard), slot_room and slot_tail on the uniform cache
|
||||
// (open: off_ empty, the stride is the largest blob) and on the sized one (open_sized: off_ holds each slot's start).
|
||||
// No guard asked (the default) must give today's sized layout byte for byte. Needs a CUDA device (exits 77 without).
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
int g_fail = 0;
|
||||
|
||||
void check(bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "FAIL: %s\n", what);
|
||||
++g_fail;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
int n = 0;
|
||||
if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) {
|
||||
std::puts("no CUDA device: skipped");
|
||||
return 77;
|
||||
}
|
||||
using strata::core::ExpertCache;
|
||||
std::string err;
|
||||
|
||||
// slot_stride: the blob plus the guard, 256-byte aligned; guard 0 is the old (b + 255) / 256 * 256
|
||||
for (int64_t b : {1, 255, 256, 257, 1000, 2457600, 2949120, 3047424}) {
|
||||
check(ExpertCache::slot_stride(b) == (b + 255) / 256 * 256, "slot_stride without a guard is today's stride");
|
||||
check(ExpertCache::slot_stride(b, 256) == (b + 256 + 255) / 256 * 256, "slot_stride with a 256 B guard");
|
||||
check(ExpertCache::slot_stride(b, 256) - b >= 256, "a guarded slot has at least the guard after its blob");
|
||||
}
|
||||
|
||||
// 1. uniform: off_ is empty; the guard is asked for but not applied (every slot is the largest blob)
|
||||
{
|
||||
ExpertCache c;
|
||||
c.set_slot_guard(256);
|
||||
if (!c.open(6, 3, 4, 1024, err)) { std::fprintf(stderr, "open: %s\n", err.c_str()); return 1; }
|
||||
check(c.slot_guard() == 0, "uniform: no guard applied");
|
||||
for (int32_t s = 0; s < 6; ++s) {
|
||||
check(c.slot_room(s) == 1024, "uniform: slot_room is the blob size");
|
||||
check(c.slot_offset(s) == (uint64_t) s * 1024, "uniform: slot_offset");
|
||||
}
|
||||
// the last slot reads slot_offset(slots) - the end - without indexing an empty off_
|
||||
check(c.slot_tail(5, 1000, 24) == c.device_slot(5) + 1000, "uniform: the last slot's slack covers 24 B");
|
||||
check(c.slot_tail(5, 1000, 25) == nullptr, "uniform: the last slot has no room for 25 B past 1000");
|
||||
check(c.slot_tail(0, 1024, 0) == c.device_slot(0) + 1024, "uniform: need 0 at the slot's end");
|
||||
check(c.slot_tail(0, 1024, 1) == nullptr, "uniform: a full slot has no room");
|
||||
check(c.slot_tail(3, 512, 136) == c.device_slot(3) + 512, "uniform: a smaller blob's slack");
|
||||
check(c.slot_tail(-1, 10, 10) == nullptr && c.slot_tail(6, 10, 10) == nullptr, "uniform: a bad slot is null");
|
||||
c.close();
|
||||
check(c.slot_guard() == 0 && c.slot_tail(0, 10, 10) == nullptr, "uniform: closed");
|
||||
}
|
||||
|
||||
// 2. sized without a guard (the default): today's layout, and slot_tail sees only the 256-byte rounding
|
||||
const std::vector<int64_t> blobs = {1000, 2457600, 700, 3047424, 256, 2949120};
|
||||
std::vector<uint64_t> plain(blobs.size() + 1, 0);
|
||||
for (size_t i = 0; i < blobs.size(); ++i) plain[i + 1] = plain[i] + ((uint64_t) blobs[i] + 255) / 256 * 256;
|
||||
{
|
||||
ExpertCache c;
|
||||
if (!c.open_sized(blobs, 3, 4, err)) { std::fprintf(stderr, "open_sized: %s\n", err.c_str()); return 1; }
|
||||
check(c.slot_guard() == 0, "sized, no guard: slot_guard 0");
|
||||
for (size_t s = 0; s <= blobs.size(); ++s) check(c.slot_offset((int64_t) s) == plain[s], "sized, no guard: today's offsets");
|
||||
check(c.slot_tail(0, 1000, 24) == c.device_slot(0) + 1000, "sized, no guard: the rounding's 24 B");
|
||||
check(c.slot_tail(0, 1000, 25) == nullptr, "sized, no guard: no more than the rounding");
|
||||
check(c.slot_tail(4, 256, 1) == nullptr, "sized, no guard: a blob of 256 has no room");
|
||||
check(c.slot_tail(5, 2949120, 1) == nullptr, "sized, no guard: the last slot (offset of the end)");
|
||||
}
|
||||
|
||||
// 3. sized with the 256 B guard: every slot has >= 256 B after its blob; close() drops the applied guard and a
|
||||
// reopen applies the kept request again
|
||||
{
|
||||
ExpertCache c;
|
||||
c.set_slot_guard(256);
|
||||
for (int round = 0; round < 2; ++round) {
|
||||
if (!c.open_sized(blobs, 3, 4, err)) { std::fprintf(stderr, "open_sized: %s\n", err.c_str()); return 1; }
|
||||
check(c.slot_guard() == 256, "sized, guard: slot_guard 256");
|
||||
uint64_t off = 0;
|
||||
for (size_t s = 0; s < blobs.size(); ++s) {
|
||||
const int32_t si = (int32_t) s;
|
||||
check(c.slot_offset(si) == off, "sized, guard: offsets");
|
||||
off += (uint64_t) ExpertCache::slot_stride(blobs[s], 256);
|
||||
check(c.slot_room(si) == (uint64_t) ExpertCache::slot_stride(blobs[s], 256), "sized, guard: slot_room");
|
||||
check(c.device_slot(si) == c.device_slot(0) + c.slot_offset(si), "sized, guard: device_slot");
|
||||
uint8_t* t = c.slot_tail(si, (uint64_t) blobs[s], 256);
|
||||
check(t == c.device_slot(si) + blobs[s], "sized, guard: slot_tail at the blob's end");
|
||||
check(c.slot_tail(si, (uint64_t) blobs[s], c.slot_room(si) - (uint64_t) blobs[s] + 1) == nullptr,
|
||||
"sized, guard: no room past the slot");
|
||||
}
|
||||
check(c.slot_offset((int64_t) blobs.size()) == off, "sized, guard: the end");
|
||||
// the guard is writable device memory inside the arena (the prompt path zeroes it)
|
||||
uint8_t* t = c.slot_tail((int32_t) blobs.size() - 1, (uint64_t) blobs.back(), 256);
|
||||
check(t != nullptr && cudaMemset(t, 0, 256) == cudaSuccess && cudaDeviceSynchronize() == cudaSuccess,
|
||||
"sized, guard: the last slot's guard can be zeroed");
|
||||
c.close();
|
||||
check(c.slot_guard() == 0 && c.slot_tail(0, 10, 10) == nullptr, "sized, guard: closed");
|
||||
}
|
||||
// asked for 0 again: today's layout
|
||||
c.set_slot_guard(0);
|
||||
if (!c.open_sized(blobs, 3, 4, err)) { std::fprintf(stderr, "open_sized: %s\n", err.c_str()); return 1; }
|
||||
check(c.slot_guard() == 0 && c.slot_offset((int64_t) blobs.size()) == plain.back(), "sized: guard reset to 0");
|
||||
}
|
||||
|
||||
if (g_fail != 0) {
|
||||
std::fprintf(stderr, "expert cache slot guard: %d checks failed\n", g_fail);
|
||||
return 1;
|
||||
}
|
||||
std::puts("expert cache slot guard: uniform and sized caches, with and without the guard, passed");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
// prefill_mmq_tab_test - STRATA_MMQ_DIRECT: the pointer-table MMQ (src/prefill/moe_mmq_tab.cuh, Product::tab) bit for
|
||||
// bit against the gathered MMQ the prompt path runs today (experts copied `expert_bytes` apart, a zeroed 4096-byte
|
||||
// tail after the last one).
|
||||
//
|
||||
// Part 1, per product type (IQ3_S gate/up [1280, 2560], IQ4_NL and Q8_0 down [2560, 640], and every other type with a
|
||||
// pointer-table instance, at its pack shape): random valid expert matrices at scattered 256-aligned addresses, each
|
||||
// followed by a guard filled with an fp16 NaN pattern (0xFF 0x7C); prep_group zeroes the over-read bytes, then the
|
||||
// table launch; memcmp of the whole output (pre-filled with a NaN pattern in both runs) against the gathered launch.
|
||||
// Sweep: 1..16 experts with mixed row counts {0,1,7,8,9,31,64,100,512,1000}; max_rows from 1 to 1000 so that every
|
||||
// tile width J from 8 to 128 is taken (and max_rows above the largest count); few-tile launches (stream-k grid of
|
||||
// nsm blocks with the fixup kernel) and many-tile ones (one block per tile).
|
||||
// Part 2, negative control: the same table launch with the guards NOT zeroed must give non-finite values in a down
|
||||
// product (proves the guard handling is load-bearing; skipped for types that read nothing past a matrix).
|
||||
// Part 3, mixed groups as prefill.cpp's walk builds them: native expert blobs (gate|up|down) for IQ3_S + IQ4_NL and
|
||||
// IQ3_S + Q8_0, some read in place (direct), the others gathered at compact positions c != q - one at a time
|
||||
// (gather_native) or by gather_native_group with a mid-group flush (first > 0) - including groups whose last entry is
|
||||
// direct and groups with no gathered entry; both products bitwise equal to all-gathered.
|
||||
// Part 4, STRATA_MMQ_GROUP_SORT: a layer's experts in groups of 16 as prefill.cpp runs them (activations quantized
|
||||
// in group order through the src map, absolute bounds, max_rows = the group's largest count), once in ID order and
|
||||
// once with the full groups in row-count order (mmq_resident_sort_rows, the partial group kept): every token's
|
||||
// product row bitwise equal, when mmq::whole_tiles says so for this card (else only reported). Sorting the partial
|
||||
// group too (STRATA_MMQ_RESIDENT_SORT_NE) is reported, not required.
|
||||
// Exit 77 without a CUDA device of sm_80 or newer or without the pointer-table build.
|
||||
#include "strata/prefill/moe_mmq.hpp"
|
||||
|
||||
#include "ggml.h"
|
||||
|
||||
#include "../../src/prefill/mmq_resident_sort.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
namespace mmq = strata::prefill::mmq;
|
||||
|
||||
constexpr int G = mmq::kGatherGroupMax;
|
||||
constexpr size_t TAIL = 4096;
|
||||
constexpr int64_t kIdsPad = 2048 + 128; // > the largest max_rows of the sweep plus one tile
|
||||
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
|
||||
}
|
||||
|
||||
struct Dev {
|
||||
void* p = nullptr;
|
||||
size_t n = 0;
|
||||
explicit Dev(size_t bytes) : n(bytes) { ck(cudaMalloc(&p, bytes), "cudaMalloc"); }
|
||||
~Dev() { cudaFree(p); }
|
||||
Dev(const Dev&) = delete;
|
||||
Dev& operator=(const Dev&) = delete;
|
||||
uint8_t* b() const { return (uint8_t*) p; }
|
||||
};
|
||||
|
||||
// random blocks with a sane fp16 scale at each block's start (every format here begins with it)
|
||||
void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) {
|
||||
const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t));
|
||||
std::uniform_int_distribution<int> byte(0, 255);
|
||||
const float lo = t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f
|
||||
: t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f;
|
||||
std::uniform_real_distribution<float> sc(lo, 6.0f * lo);
|
||||
for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng);
|
||||
for (size_t b = 0; b < nb; ++b) {
|
||||
const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng));
|
||||
std::memcpy(m + b * bs, &h, 2);
|
||||
}
|
||||
}
|
||||
|
||||
// host -> device, finished before any work on the (non-blocking) test stream starts: a pageable cudaMemcpy returns
|
||||
// before its DMA lands, and the legacy stream does not order it against a cudaStreamNonBlocking stream
|
||||
void upload(void* dst, const void* src, size_t n, const char* what) {
|
||||
ck(cudaMemcpy(dst, src, n, cudaMemcpyHostToDevice), what);
|
||||
ck(cudaDeviceSynchronize(), what);
|
||||
}
|
||||
|
||||
// the fp16 NaN pattern a guard holds before prep_group (0x7CFF little-endian at every even offset)
|
||||
void fill_nan(uint8_t* dev, size_t n) {
|
||||
std::vector<uint8_t> h(n);
|
||||
for (size_t i = 0; i < n; ++i) h[i] = (i & 1) ? 0x7C : 0xFF;
|
||||
upload(dev, h.data(), n, "fill_nan");
|
||||
}
|
||||
|
||||
struct Shape {
|
||||
ggml_type t;
|
||||
int64_t rows, cols; // the weight matrix [rows, cols]
|
||||
const char* role;
|
||||
};
|
||||
|
||||
// activations for `total` rows of `cols`, quantized for type t (q8_1), plus an identity map and the bounds
|
||||
struct Acts {
|
||||
Dev x, xq, ids, bounds;
|
||||
int64_t total;
|
||||
Acts(ggml_type t, int64_t cols, const std::vector<int>& cnt, std::mt19937& rng, cudaStream_t s)
|
||||
: x((size_t) std::max<int64_t>(1, sum(cnt)) * cols * 4), xq(mmq::q8_bytes(std::max<int64_t>(1, sum(cnt)), cols)),
|
||||
ids((size_t) (sum(cnt) + kIdsPad) * 4), bounds((cnt.size() + 1) * 4), total(sum(cnt)) {
|
||||
std::vector<float> hx((size_t) std::max<int64_t>(1, total) * cols);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
for (auto& v : hx) v = nd(rng);
|
||||
upload(x.p, hx.data(), hx.size() * 4, "x");
|
||||
std::vector<int32_t> hb(cnt.size() + 1, 0);
|
||||
for (size_t i = 0; i < cnt.size(); ++i) hb[i + 1] = hb[i] + cnt[i];
|
||||
upload(bounds.p, hb.data(), hb.size() * 4, "bounds");
|
||||
// MMQ loads a whole tile's J ids from an expert's first row, and its stream-k fixup does so for every column
|
||||
// tile of max_rows, also past the last row (upstream behaviour, harmless values): padded for memcheck
|
||||
mmq::iota((int32_t*) ids.p, total + kIdsPad, s);
|
||||
if (total > 0) mmq::quantize((const float*) x.p, nullptr, xq.p, (int) t, cols, cols, total, s);
|
||||
ck(cudaStreamSynchronize(s), "acts");
|
||||
}
|
||||
static int64_t sum(const std::vector<int>& c) {
|
||||
int64_t n = 0;
|
||||
for (int v : c) n += v;
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
mmq::Product product(const Shape& sh, const Acts& a, int n, int64_t max_rows, float* dst) {
|
||||
mmq::Product p;
|
||||
p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols;
|
||||
p.n = n; p.xq = a.xq.p; p.bounds = (const int32_t*) a.bounds.p; p.ids = (const int32_t*) a.ids.p;
|
||||
p.total_rows = a.total; p.max_rows = max_rows; p.dst = dst; p.ld_dst = sh.rows;
|
||||
return p;
|
||||
}
|
||||
|
||||
int g_cases = 0, g_fail = 0;
|
||||
|
||||
bool same_bits(const Dev& a, const Dev& b, size_t n, const char* what) {
|
||||
std::vector<uint8_t> ha(n), hb(n);
|
||||
ck(cudaMemcpy(ha.data(), a.p, n, cudaMemcpyDeviceToHost), "dtoh a");
|
||||
ck(cudaMemcpy(hb.data(), b.p, n, cudaMemcpyDeviceToHost), "dtoh b");
|
||||
++g_cases;
|
||||
if (std::memcmp(ha.data(), hb.data(), n) == 0) return true;
|
||||
size_t i = 0;
|
||||
while (i < n && ha[i] == hb[i]) ++i;
|
||||
std::printf(" FAIL %s: first differing byte %zu of %zu\n", what, i, n);
|
||||
if (std::getenv("TAB_TEST_DEBUG")) {
|
||||
const float* fa = (const float*) ha.data();
|
||||
const float* fb = (const float*) hb.data();
|
||||
size_t nd = 0;
|
||||
for (size_t k = 0; k < n / 4; ++k)
|
||||
if (std::memcmp(fa + k, fb + k, 4) != 0) {
|
||||
if (nd < 6) std::printf(" float %zu: %.9g vs %.9g\n", k, fa[k], fb[k]);
|
||||
++nd;
|
||||
}
|
||||
std::printf(" %zu floats differ\n", nd);
|
||||
}
|
||||
++g_fail;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool any_nonfinite(const Dev& d, size_t floats) {
|
||||
std::vector<float> h(floats);
|
||||
ck(cudaMemcpy(h.data(), d.p, floats * 4, cudaMemcpyDeviceToHost), "dtoh");
|
||||
for (float v : h)
|
||||
if (!std::isfinite(v)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Part 1 + 2: one product, `cnt` rows per expert
|
||||
void product_case(mmq::Context& ctx, const Shape& sh, const std::vector<int>& cnt, int64_t max_rows, std::mt19937& rng,
|
||||
cudaStream_t s, bool negative, const char* label) {
|
||||
const int n = (int) cnt.size();
|
||||
const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols);
|
||||
const size_t over = mmq::overread_bytes((int) sh.t, sh.cols);
|
||||
Acts a(sh.t, sh.cols, cnt, rng, s);
|
||||
// the experts' matrices on the host
|
||||
std::vector<std::vector<uint8_t>> w((size_t) n, std::vector<uint8_t>(eb));
|
||||
for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng);
|
||||
// gathered: back to back, a zeroed tail, the space after it NaN-patterned
|
||||
Dev grp((size_t) n * eb + TAIL + 4096);
|
||||
fill_nan(grp.b(), grp.n);
|
||||
for (int z = 0; z < n; ++z) upload(grp.b() + (size_t) z * eb, w[(size_t) z].data(), eb, "grp");
|
||||
ck(cudaMemset(grp.b() + (size_t) n * eb, 0, TAIL), "tail");
|
||||
ck(cudaDeviceSynchronize(), "tail");
|
||||
// in place: scattered 256-aligned slots in one arena (shuffled order, random gaps), each with a NaN guard
|
||||
const size_t stride = (eb + mmq::kSlotGuard + 255) / 256 * 256;
|
||||
std::vector<size_t> pos((size_t) n);
|
||||
for (int z = 0; z < n; ++z) pos[(size_t) z] = (size_t) z;
|
||||
std::shuffle(pos.begin(), pos.end(), rng);
|
||||
std::uniform_int_distribution<int> gap(0, 8);
|
||||
Dev arena((size_t) n * (stride + 8 * 256) + 4096);
|
||||
fill_nan(arena.b(), arena.n);
|
||||
mmq::WeightTab tab;
|
||||
mmq::GuardTab guards;
|
||||
size_t at = 0;
|
||||
std::vector<size_t> where((size_t) n);
|
||||
for (int k = 0; k < n; ++k) {
|
||||
at += (size_t) gap(rng) * 256;
|
||||
where[pos[(size_t) k]] = at;
|
||||
at += stride;
|
||||
}
|
||||
for (int z = 0; z < n; ++z) {
|
||||
uint8_t* p = arena.b() + where[(size_t) z];
|
||||
upload(p, w[(size_t) z].data(), eb, "arena");
|
||||
tab.p[z] = p;
|
||||
guards.p[guards.n++] = p + eb;
|
||||
}
|
||||
const size_t out = (size_t) std::max<int64_t>(1, a.total) * (size_t) sh.rows * 4;
|
||||
Dev ref(out), got(out);
|
||||
fill_nan(ref.b(), out);
|
||||
fill_nan(got.b(), out);
|
||||
mmq::Product pr = product(sh, a, n, max_rows, (float*) ref.p);
|
||||
pr.w = grp.p; pr.expert_bytes = eb;
|
||||
ctx.run(pr, s);
|
||||
if (!negative) mmq::prep_group(guards, over, nullptr, nullptr, 0, s);
|
||||
mmq::Product pt = product(sh, a, n, max_rows, (float*) got.p);
|
||||
pt.w = nullptr; pt.expert_bytes = 0; pt.tab = &tab;
|
||||
ctx.run(pt, s);
|
||||
ck(cudaStreamSynchronize(s), "run");
|
||||
char what[256];
|
||||
std::snprintf(what, sizeof what, "%s %s n=%d rows=%lld max_rows=%lld (%s)", ggml_type_name(sh.t), sh.role, n,
|
||||
(long long) a.total, (long long) max_rows, label);
|
||||
if (!negative) {
|
||||
same_bits(ref, got, out, what);
|
||||
return;
|
||||
}
|
||||
++g_cases;
|
||||
if (!any_nonfinite(got, out / 4)) {
|
||||
std::printf(" FAIL negative control %s: no non-finite value with the guards left as NaN\n", what);
|
||||
++g_fail;
|
||||
} else if (any_nonfinite(ref, (size_t) a.total * (size_t) sh.rows)) {
|
||||
std::printf(" FAIL negative control %s: the gathered reference is not finite\n", what);
|
||||
++g_fail;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<int> random_counts(int n, std::mt19937& rng) {
|
||||
static const int kRows[] = {0, 1, 7, 8, 9, 31, 64, 100, 512, 1000};
|
||||
std::uniform_int_distribution<int> pick(0, 9);
|
||||
std::vector<int> c((size_t) n);
|
||||
for (auto& v : c) v = kRows[pick(rng)];
|
||||
return c;
|
||||
}
|
||||
int64_t max_of(const std::vector<int>& c) {
|
||||
int64_t m = 0;
|
||||
for (int v : c) m = std::max<int64_t>(m, v);
|
||||
return m;
|
||||
}
|
||||
|
||||
void sweep(mmq::Context& ctx, const Shape& sh, bool full, std::mt19937& rng, cudaStream_t s) {
|
||||
const int f0 = g_fail, c0 = g_cases;
|
||||
// 1..16 experts, mixed counts (max_rows = the largest count, as prefill.cpp passes it)
|
||||
for (int n = 1; n <= G; ++n) {
|
||||
if (!full && n != 1 && n != 3 && n != 8 && n != G) continue;
|
||||
for (int rep = 0; rep < (full ? 3 : 1); ++rep) {
|
||||
std::vector<int> c = random_counts(n, rng);
|
||||
if (max_of(c) == 0) c[0] = 1;
|
||||
product_case(ctx, sh, c, max_of(c), rng, s, false, "mixed");
|
||||
}
|
||||
}
|
||||
// every J: one expert with m rows, the others fewer; and max_rows above the largest count
|
||||
static const int kMax[] = {1, 7, 8, 9, 16, 17, 24, 25, 32, 33, 40, 41, 48, 56, 64, 65, 72, 80, 88, 96, 100, 104,
|
||||
112, 120, 127, 128, 129, 300, 1000};
|
||||
for (int m : kMax) {
|
||||
if (!full && m % 8 != 0 && m != 1 && m != 129) continue;
|
||||
for (int n : {1, 5, 16}) {
|
||||
if (!full && n == 5) continue;
|
||||
std::uniform_int_distribution<int> fewer(0, m);
|
||||
std::vector<int> c((size_t) n);
|
||||
for (auto& v : c) v = fewer(rng);
|
||||
c[(size_t) (rng() % (unsigned) n)] = m;
|
||||
product_case(ctx, sh, c, m, rng, s, false, "J sweep");
|
||||
}
|
||||
}
|
||||
for (int n : {1, 4, 16}) {
|
||||
std::vector<int> c = random_counts(n, rng);
|
||||
if (max_of(c) == 0) c[0] = 9;
|
||||
product_case(ctx, sh, c, max_of(c) + 37, rng, s, false, "max_rows above the largest count");
|
||||
}
|
||||
// experts with 0 rows at the ends and in the middle
|
||||
product_case(ctx, sh, {0, 0, 5, 0, 1000, 0, 0}, 1000, rng, s, false, "empty experts");
|
||||
product_case(ctx, sh, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 1, rng, s, false, "only the last expert");
|
||||
std::printf("%-8s %-7s %4d cases, %s\n", ggml_type_name(sh.t), sh.role, g_cases - c0,
|
||||
g_fail == f0 ? "all bitwise identical" : "FAILURES");
|
||||
// negative control: a down product that reads past its matrix, guards not zeroed
|
||||
if (mmq::overread_bytes((int) sh.t, sh.cols) > 0) {
|
||||
const int f1 = g_fail;
|
||||
product_case(ctx, sh, {3, 64, 0, 17}, 64, rng, s, true, "negative");
|
||||
product_case(ctx, sh, {200}, 200, rng, s, true, "negative");
|
||||
std::printf("%-8s %-7s negative control (guards not zeroed): %s\n", ggml_type_name(sh.t), sh.role,
|
||||
g_fail == f1 ? "non-finite output, as required" : "FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
// Part 3: groups as prefill.cpp's walk builds them, both products
|
||||
struct Pair {
|
||||
ggml_type gu, d;
|
||||
};
|
||||
void group_case(mmq::Context& ctx, const Pair& pr, const std::vector<int>& cnt, const std::vector<char>& direct,
|
||||
bool group_gather, int flush_at, std::mt19937& rng, cudaStream_t s, const char* label) {
|
||||
const int n = (int) cnt.size();
|
||||
const Shape gs{pr.gu, 1280, 2560, "gate/up"}, ds{pr.d, 2560, 640, "down"};
|
||||
const size_t gub = mmq::matrix_bytes((int) pr.gu, 1280, 2560), db = mmq::matrix_bytes((int) pr.d, 2560, 640);
|
||||
const size_t up_off = gub / 2, down_off = gub, bytes = gub + db;
|
||||
const size_t over = mmq::overread_bytes((int) pr.d, 640);
|
||||
// native blobs, each in its own place: direct ones in "cache slots" with a guard, gathered ones elsewhere
|
||||
std::vector<std::vector<uint8_t>> blob((size_t) n, std::vector<uint8_t>(bytes));
|
||||
for (auto& b : blob) {
|
||||
fill_matrix(b.data(), pr.gu, 1280, 2560, rng);
|
||||
fill_matrix(b.data() + down_off, pr.d, 2560, 640, rng);
|
||||
}
|
||||
const size_t stride = (bytes + mmq::kSlotGuard + 255) / 256 * 256;
|
||||
Dev arena((size_t) n * (stride + 4 * 256) + 4096);
|
||||
fill_nan(arena.b(), arena.n);
|
||||
std::vector<uint8_t*> at((size_t) n);
|
||||
size_t o = 0;
|
||||
for (int z = 0; z < n; ++z) {
|
||||
o += (size_t) (rng() % 4) * 256;
|
||||
at[(size_t) z] = arena.b() + o;
|
||||
o += stride;
|
||||
upload(at[(size_t) z], blob[(size_t) z].data(), bytes, "blob");
|
||||
}
|
||||
Acts ag(pr.gu, 2560, cnt, rng, s), ad(pr.d, 640, cnt, rng, s);
|
||||
const int64_t mr = std::max<int64_t>(1, max_of(cnt));
|
||||
const size_t out_g = (size_t) std::max<int64_t>(1, ag.total) * 1280 * 4, out_d = (size_t) std::max<int64_t>(1, ad.total) * 2560 * 4;
|
||||
// reference: today's walk (gather at q, two tail memsets)
|
||||
Dev rgu((size_t) G * gub + TAIL), rd((size_t) G * db + TAIL), ref_g(out_g), ref_d(out_d);
|
||||
fill_nan(rgu.b(), rgu.n);
|
||||
fill_nan(rd.b(), rd.n);
|
||||
fill_nan(ref_g.b(), out_g);
|
||||
fill_nan(ref_d.b(), out_d);
|
||||
for (int q = 0; q < n; ++q) {
|
||||
const uint8_t* b = at[(size_t) q];
|
||||
mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, rgu.b() + (size_t) q * gub, rd.b() + (size_t) q * db, s);
|
||||
}
|
||||
ck(cudaMemsetAsync(rgu.b() + (size_t) n * gub, 0, TAIL, s), "memset");
|
||||
ck(cudaMemsetAsync(rd.b() + (size_t) n * db, 0, TAIL, s), "memset");
|
||||
mmq::Product p = product(gs, ag, n, mr, (float*) ref_g.p);
|
||||
p.w = rgu.p; p.expert_bytes = gub;
|
||||
ctx.run(p, s);
|
||||
p = product(ds, ad, n, mr, (float*) ref_d.p);
|
||||
p.w = rd.p; p.expert_bytes = db;
|
||||
ctx.run(p, s);
|
||||
// direct: prefill.cpp's compute() in direct mode
|
||||
Dev tgu_buf((size_t) G * gub + TAIL), td_buf((size_t) G * db + TAIL), got_g(out_g), got_d(out_d);
|
||||
fill_nan(tgu_buf.b(), tgu_buf.n);
|
||||
fill_nan(td_buf.b(), td_buf.n);
|
||||
fill_nan(got_g.b(), out_g);
|
||||
fill_nan(got_d.b(), out_d);
|
||||
mmq::WeightTab tgu, td;
|
||||
mmq::GuardTab gd;
|
||||
mmq::GatherGroup gg;
|
||||
int ns = 0;
|
||||
auto flush = [&]() {
|
||||
if (gg.n <= gg.first) return;
|
||||
if (!mmq::gather_native_group(gg, up_off, gub / 2, down_off, db, tgu_buf.p, gub, td_buf.p, db, s))
|
||||
throw std::runtime_error("gather_native_group refused an aligned group");
|
||||
gg.first = gg.n;
|
||||
};
|
||||
for (int q = 0; q < n; ++q) {
|
||||
uint8_t* b = at[(size_t) q];
|
||||
if (direct[(size_t) q]) {
|
||||
tgu.p[q] = b;
|
||||
td.p[q] = b + down_off;
|
||||
gd.p[gd.n++] = b + bytes;
|
||||
} else {
|
||||
const int c = ns++;
|
||||
tgu.p[q] = tgu_buf.b() + (size_t) c * gub;
|
||||
td.p[q] = td_buf.b() + (size_t) c * db;
|
||||
if (group_gather) {
|
||||
gg.blob[c] = b;
|
||||
gg.n = c + 1;
|
||||
} else {
|
||||
mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, tgu_buf.b() + (size_t) c * gub,
|
||||
td_buf.b() + (size_t) c * db, s);
|
||||
}
|
||||
}
|
||||
if (group_gather && q == flush_at) flush(); // release_to's mid-group flush
|
||||
}
|
||||
if (group_gather) flush();
|
||||
mmq::prep_group(gd, over, ns ? tgu_buf.b() + (size_t) ns * gub : nullptr, ns ? td_buf.b() + (size_t) ns * db : nullptr,
|
||||
TAIL, s);
|
||||
p = product(gs, ag, n, mr, (float*) got_g.p);
|
||||
p.tab = &tgu;
|
||||
ctx.run(p, s);
|
||||
p = product(ds, ad, n, mr, (float*) got_d.p);
|
||||
p.tab = &td;
|
||||
ctx.run(p, s);
|
||||
ck(cudaStreamSynchronize(s), "group");
|
||||
char what[256];
|
||||
std::snprintf(what, sizeof what, "%s+%s group n=%d direct=%d %s (%s)", ggml_type_name(pr.gu), ggml_type_name(pr.d), n,
|
||||
gd.n, group_gather ? "gather_native_group" : "gather_native", label);
|
||||
std::string w1 = std::string(what) + " gate/up", w2 = std::string(what) + " down";
|
||||
same_bits(ref_g, got_g, out_g, w1.c_str());
|
||||
same_bits(ref_d, got_d, out_d, w2.c_str());
|
||||
}
|
||||
|
||||
|
||||
// Part 4: one layer's experts in groups of G; `span` as mmq_resident_sort_span gives it (0: ID order)
|
||||
struct Layer {
|
||||
std::vector<int32_t> ids, count, off, order, slot, src;
|
||||
};
|
||||
Layer route(const std::vector<int>& cnt, std::mt19937& rng) {
|
||||
Layer L;
|
||||
for (size_t e = 0; e < cnt.size(); ++e)
|
||||
for (int r = 0; r < cnt[e]; ++r) L.ids.push_back((int32_t) e);
|
||||
std::shuffle(L.ids.begin(), L.ids.end(), rng); // one route per token (K = 1), experts interleaved
|
||||
L.count.assign(cnt.begin(), cnt.end());
|
||||
L.off.assign(cnt.size() + 1, 0);
|
||||
for (size_t e = 0; e < cnt.size(); ++e) L.off[e + 1] = L.off[e] + cnt[e];
|
||||
for (size_t e = 0; e < cnt.size(); ++e)
|
||||
if (cnt[e] > 0) L.order.push_back((int32_t) e);
|
||||
L.slot.assign(L.ids.size(), 0);
|
||||
L.src.assign(L.ids.size(), 0);
|
||||
std::vector<int32_t> fill(L.off.begin(), L.off.end() - 1);
|
||||
for (size_t i = 0; i < L.ids.size(); ++i) {
|
||||
const int32_t p = fill[(size_t) L.ids[i]]++;
|
||||
L.slot[i] = p;
|
||||
L.src[(size_t) p] = (int32_t) i;
|
||||
}
|
||||
return L;
|
||||
}
|
||||
|
||||
// the layer's product rows in the layer's row order (row p = token src[p])
|
||||
std::vector<float> run_layer(mmq::Context& ctx, const Shape& sh, const Layer& L, const std::vector<std::vector<uint8_t>>& w,
|
||||
const Dev& x, cudaStream_t s) {
|
||||
const int64_t T = (int64_t) L.ids.size();
|
||||
const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols), n = L.order.size();
|
||||
Dev src((size_t) T * 4), xq(mmq::q8_bytes(T, sh.cols)), ids((size_t) (T + kIdsPad) * 4), bounds((n + 1) * 4);
|
||||
Dev grp((size_t) G * eb + TAIL), out((size_t) T * sh.rows * 4);
|
||||
upload(src.p, L.src.data(), (size_t) T * 4, "src");
|
||||
std::vector<int32_t> hb(n + 1);
|
||||
for (size_t j = 0; j < n; ++j) hb[j] = L.off[(size_t) L.order[j]];
|
||||
hb[n] = (int32_t) T;
|
||||
upload(bounds.p, hb.data(), hb.size() * 4, "bounds");
|
||||
fill_nan(out.b(), out.n);
|
||||
mmq::iota((int32_t*) ids.p, T + kIdsPad, s);
|
||||
mmq::quantize((const float*) x.p, (const int32_t*) src.p, xq.p, (int) sh.t, sh.cols, sh.cols, T, s);
|
||||
for (size_t j0 = 0; j0 < n; j0 += G) {
|
||||
const int ng = (int) std::min<size_t>(G, n - j0);
|
||||
int64_t maxr = 0;
|
||||
ck(cudaStreamSynchronize(s), "group"); // grp is rewritten below
|
||||
for (int q = 0; q < ng; ++q) {
|
||||
const int32_t e = L.order[j0 + (size_t) q];
|
||||
maxr = std::max<int64_t>(maxr, L.count[(size_t) e]);
|
||||
upload(grp.b() + (size_t) q * eb, w[(size_t) e].data(), eb, "grp");
|
||||
}
|
||||
ck(cudaMemset(grp.b() + (size_t) ng * eb, 0, TAIL), "tail");
|
||||
ck(cudaDeviceSynchronize(), "tail");
|
||||
mmq::Product p;
|
||||
p.w = grp.p; p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols; p.expert_bytes = eb;
|
||||
p.n = ng; p.xq = xq.p; p.bounds = (const int32_t*) bounds.p + j0; p.ids = (const int32_t*) ids.p;
|
||||
p.total_rows = T; p.max_rows = maxr; p.dst = (float*) out.p; p.ld_dst = sh.rows;
|
||||
ctx.run(p, s);
|
||||
}
|
||||
ck(cudaStreamSynchronize(s), "layer");
|
||||
std::vector<float> h((size_t) T * sh.rows);
|
||||
ck(cudaMemcpy(h.data(), out.p, h.size() * 4, cudaMemcpyDeviceToHost), "dtoh layer");
|
||||
return h;
|
||||
}
|
||||
|
||||
// tokens whose product row differs between two orders of the same layer
|
||||
int64_t rows_differing(const Layer& a, const std::vector<float>& ra, const Layer& b, const std::vector<float>& rb, int64_t cols) {
|
||||
int64_t nd = 0;
|
||||
for (size_t t = 0; t < a.ids.size(); ++t)
|
||||
if (std::memcmp(ra.data() + (size_t) a.slot[t] * cols, rb.data() + (size_t) b.slot[t] * cols, (size_t) cols * 4) != 0) ++nd;
|
||||
return nd;
|
||||
}
|
||||
|
||||
void order_case(mmq::Context& ctx, const Shape& sh, const std::vector<int>& cnt, bool whole, std::mt19937& rng, cudaStream_t s,
|
||||
const char* label) {
|
||||
const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols);
|
||||
std::vector<std::vector<uint8_t>> w(cnt.size(), std::vector<uint8_t>(eb));
|
||||
for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng);
|
||||
Layer id = route(cnt, rng);
|
||||
const int64_t T = (int64_t) id.ids.size();
|
||||
Dev x((size_t) T * sh.cols * 4);
|
||||
{
|
||||
std::vector<float> hx((size_t) T * sh.cols);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
for (auto& v : hx) v = nd(rng);
|
||||
upload(x.p, hx.data(), hx.size() * 4, "x");
|
||||
}
|
||||
Layer full = id, all = id;
|
||||
namespace d = strata::prefill::detail;
|
||||
d::mmq_resident_sort_rows(full.ids.data(), T, 1, full.count, full.off, full.order, full.slot.data(), full.src.data(),
|
||||
d::mmq_resident_sort_span(full.order.size(), G, true));
|
||||
d::mmq_resident_sort_rows(all.ids.data(), T, 1, all.count, all.off, all.order, all.slot.data(), all.src.data(),
|
||||
d::mmq_resident_sort_span(all.order.size(), G, false));
|
||||
const size_t n = id.order.size(), tail = n % G;
|
||||
// the partial group's entries and row range stay where they were
|
||||
bool kept = std::equal(id.order.end() - (ptrdiff_t) tail, id.order.end(), full.order.end() - (ptrdiff_t) tail);
|
||||
for (size_t j = n - tail; j < n && kept; ++j) kept = full.off[(size_t) full.order[j]] == id.off[(size_t) id.order[j]];
|
||||
const std::vector<float> r_id = run_layer(ctx, sh, id, w, x, s);
|
||||
const std::vector<float> r_full = run_layer(ctx, sh, full, w, x, s);
|
||||
const std::vector<float> r_all = run_layer(ctx, sh, all, w, x, s);
|
||||
const int64_t d_full = rows_differing(id, r_id, full, r_full, sh.rows), d_all = rows_differing(id, r_id, all, r_all, sh.rows);
|
||||
++g_cases;
|
||||
const bool ok = kept && (!whole || d_full == 0);
|
||||
if (!ok) ++g_fail;
|
||||
std::printf(" %s %-7s %s: %zu experts (%zu in the partial group), %lld rows: full groups sorted %lld rows differ%s, "
|
||||
"all sorted %lld rows differ%s\n", ggml_type_name(sh.t), sh.role, label, n, tail, (long long) T,
|
||||
(long long) d_full, ok ? "" : (kept ? " FAIL" : " FAIL (partial group moved)"), (long long) d_all,
|
||||
whole ? "" : " (whole_tiles false on this card: reported only)");
|
||||
}
|
||||
|
||||
std::vector<int> skewed_counts(int n, int lo, int hi, std::mt19937& rng) {
|
||||
// prompt-like: most experts few rows, some many (log-uniform)
|
||||
std::uniform_real_distribution<double> u(std::log((double) lo), std::log((double) hi + 1));
|
||||
std::vector<int> c((size_t) n);
|
||||
for (auto& v : c) v = std::max(lo, (int) std::exp(u(rng)));
|
||||
return c;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
try {
|
||||
int dev = 0;
|
||||
cudaDeviceProp prop{};
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess || prop.major < 8) {
|
||||
std::printf("needs a CUDA device of sm_80 or newer: skipped\n");
|
||||
return 77;
|
||||
}
|
||||
if (!mmq::built() || !mmq::tab_built()) {
|
||||
std::printf("no pointer-table MMQ in this build: skipped\n");
|
||||
return 77;
|
||||
}
|
||||
std::printf("%s (sm_%d%d, %d SMs)\n", prop.name, prop.major, prop.minor, prop.multiProcessorCount);
|
||||
cudaStream_t s;
|
||||
ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
|
||||
mmq::Context ctx;
|
||||
std::mt19937 rng(20261011);
|
||||
// the pack's three formats, fully; every other type with an instance, a shorter sweep
|
||||
const Shape main_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"},
|
||||
{GGML_TYPE_IQ4_NL, 2560, 640, "down"},
|
||||
{GGML_TYPE_Q8_0, 2560, 640, "down"}};
|
||||
// the types without a pointer table (the optional Q5_0 / K-quant instances) must keep the gather
|
||||
for (const ggml_type t : {GGML_TYPE_Q5_0, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, GGML_TYPE_Q6_K}) {
|
||||
if (mmq::tab_fits((int) t, 1280) || mmq::tab_fits((int) t, 2560)) {
|
||||
std::printf("FAIL: %s reports a pointer table (only the nine tested types have one)\n", ggml_type_name(t));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
// the over-read each guard must cover: within kSlotGuard, and on sm_86 the values the guards were sized for
|
||||
// (256-value K tiles: 640 columns are 20 blocks of 32, so the last tile reads 4 blocks more - 4 x 18 B of
|
||||
// IQ4_NL, 4 x 34 B of Q8_0; 2560 columns end on a tile)
|
||||
const size_t want_over[] = {0, 72, 136};
|
||||
for (size_t i = 0; i < 3; ++i) {
|
||||
const Shape& sh = main_shapes[i];
|
||||
const size_t ov = mmq::overread_bytes((int) sh.t, sh.cols);
|
||||
if (ov > mmq::kSlotGuard || (prop.major == 8 && prop.minor == 6 && ov != want_over[i])) {
|
||||
std::printf("FAIL: %s over-read %zu B (want %zu, at most %zu)\n", ggml_type_name(sh.t), ov, want_over[i],
|
||||
mmq::kSlotGuard);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
for (const Shape& sh : main_shapes) {
|
||||
if (!mmq::tab_fits((int) sh.t, sh.rows)) {
|
||||
std::printf("FAIL: no pointer-table MMQ for %s\n", ggml_type_name(sh.t));
|
||||
return 1;
|
||||
}
|
||||
std::printf("%-8s %-7s over-read past the matrix: %zu B\n", ggml_type_name(sh.t), sh.role,
|
||||
mmq::overread_bytes((int) sh.t, sh.cols));
|
||||
sweep(ctx, sh, true, rng, s);
|
||||
}
|
||||
const Shape other[] = {{GGML_TYPE_IQ2_XXS, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ2_XS, 1280, 2560, "gate/up"},
|
||||
{GGML_TYPE_IQ2_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ3_XXS, 1280, 2560, "gate/up"},
|
||||
{GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"}, {GGML_TYPE_Q8_0, 1280, 2560, "gate/up"},
|
||||
{GGML_TYPE_IQ4_NL, 1280, 2560, "gate/up"}, {GGML_TYPE_Q2_0, 2560, 640, "down"}};
|
||||
for (const Shape& sh : other) {
|
||||
if (!mmq::tab_fits((int) sh.t, sh.rows)) { // all nine types have an instance (CMake's tab types)
|
||||
std::printf("FAIL: no pointer-table MMQ for %s %s\n", ggml_type_name(sh.t), sh.role);
|
||||
return 1;
|
||||
}
|
||||
sweep(ctx, sh, false, rng, s);
|
||||
}
|
||||
// Part 3
|
||||
const int f0 = g_fail, c0 = g_cases;
|
||||
for (const Pair pr : {Pair{GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL}, Pair{GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0}}) {
|
||||
for (int gg = 0; gg < 2; ++gg) {
|
||||
const bool group_gather = gg == 1;
|
||||
// alternating direct / gathered, last entry direct
|
||||
group_case(ctx, pr, {5, 0, 31, 64, 1, 100, 8, 9}, {0, 1, 0, 1, 1, 0, 0, 1}, group_gather, 3, rng, s,
|
||||
"interleaved, last direct");
|
||||
// a full group, the first entries gathered, then mostly direct; flush after entry 5
|
||||
group_case(ctx, pr, {7, 8, 9, 31, 64, 100, 1, 0, 512, 3, 17, 33, 2, 64, 90, 128},
|
||||
{0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0}, group_gather, 5, rng, s,
|
||||
"full group, last gathered");
|
||||
// every entry direct (ns == 0: no tails), and every entry gathered
|
||||
group_case(ctx, pr, {12, 40, 0, 7}, {1, 1, 1, 1}, group_gather, -1, rng, s, "all direct");
|
||||
group_case(ctx, pr, {12, 40, 0, 7}, {0, 0, 0, 0}, group_gather, 1, rng, s, "all gathered");
|
||||
// one entry
|
||||
group_case(ctx, pr, {1000}, {1}, group_gather, -1, rng, s, "one direct entry");
|
||||
// random mixes
|
||||
for (int r = 0; r < 4; ++r) {
|
||||
const int n = 1 + (int) (rng() % G);
|
||||
std::vector<int> c = random_counts(n, rng);
|
||||
if (max_of(c) == 0) c[0] = 1;
|
||||
std::vector<char> d((size_t) n);
|
||||
for (auto& v : d) v = (char) (rng() & 1);
|
||||
group_case(ctx, pr, c, d, group_gather, (int) (rng() % (unsigned) n), rng, s, "random mix");
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf("mixed groups: %d comparisons, %s\n", g_cases - c0, g_fail == f0 ? "all bitwise identical" : "FAILURES");
|
||||
// Part 4
|
||||
const int f4 = g_fail, c4 = g_cases;
|
||||
const Shape order_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"},
|
||||
{GGML_TYPE_IQ4_NL, 2560, 640, "down"}, {GGML_TYPE_Q8_0, 2560, 640, "down"}};
|
||||
for (const Shape& sh : order_shapes) {
|
||||
const bool whole = mmq::whole_tiles((int) sh.t, sh.rows, G);
|
||||
std::printf("%-8s %-7s whole_tiles(%d experts): %s\n", ggml_type_name(sh.t), sh.role, G, whole ? "yes" : "no");
|
||||
order_case(ctx, sh, skewed_counts(147, 1, 40, rng), whole, rng, s, "150-token prompt");
|
||||
order_case(ctx, sh, skewed_counts(219, 1, 160, rng), whole, rng, s, "512-token chunk");
|
||||
order_case(ctx, sh, skewed_counts(48, 1, 300, rng), whole, rng, s, "no partial group");
|
||||
order_case(ctx, sh, skewed_counts(11, 1, 300, rng), whole, rng, s, "partial group only");
|
||||
}
|
||||
std::printf("group order: %d comparisons, %s\n", g_cases - c4, g_fail == f4 ? "all bitwise identical" : "FAILURES");
|
||||
cudaStreamDestroy(s);
|
||||
std::printf("%d comparisons, %d failed\n", g_cases, g_fail);
|
||||
return g_fail == 0 ? 0 : 1;
|
||||
} catch (const std::exception& e) {
|
||||
std::printf("error: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
+110
-13
@@ -7,12 +7,17 @@ chunks interleaved with their windows), and a conversation's next turn continued
|
||||
tokens must equal its solo tokens
|
||||
3. A's next turn (BGEN into slot 0, which still holds A): read from the slot, its tokens must equal the solo next turn
|
||||
4. a long prompt D gives way (BYIELD) at its first chunk boundary, a short E is admitted, D goes on from its slot
|
||||
while E decodes: both equal their solo tokens
|
||||
while E decodes: both equal their solo tokens. On a pipelined batch (a layer split, more than one group) a read
|
||||
never gives way: D is then read whole into slot 2 and E admitted into slot 1 beside it; both must still equal
|
||||
solo, only the give-way is not required (--yield auto; --yield expect requires it anyway)
|
||||
6. A in a slot, stopped after 50 tokens and continued on the solo path (GEN of A + its tokens, from the slot): the
|
||||
whole equals solo A (what the server does with a request left alone in a slot)
|
||||
5. (a measurement) a solo next turn continued from a slot: the drafts accepted
|
||||
7. F, A's history as a client sends it back without the reply's thinking, from slot 1's turn checkpoint: equal to
|
||||
F solo (which continues from the same checkpoint of the live chain)
|
||||
(after step 6 the solo path holds A's start, so F's start comes from the live chain or the prompt cache here)
|
||||
7b. A in slot 1 to its end, --flush unrelated solo GENs, then F2 (A's question, another reply) into slot 2: its
|
||||
start can only come from slot 1's turn checkpoint; equal to F2 solo. The engine log line says which source was used.
|
||||
|
||||
Exact comparisons need the same settings as batch_test.py (this script sets STRATA_IQ_MT_MIN=1):
|
||||
python tools/batch_interleave_test.py --exe build/strata --config strata-<model>.json \\
|
||||
@@ -20,7 +25,7 @@ Exact comparisons need the same settings as batch_test.py (this script sets STRA
|
||||
Without --no-prefill-borrow the slots decoding during C's read see the expert cache without the slots C's prompt
|
||||
borrowed (those experts run on the CPU, which rounds differently): A's and B's text may then drift from solo.
|
||||
"""
|
||||
import argparse, json, os, sys, time
|
||||
import argparse, json, os, re, sys, time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
@@ -48,6 +53,18 @@ def run(eng, out, line, slot=None):
|
||||
raise SystemExit(f"the engine ended during: {line[:40]} (see {eng.log_path})")
|
||||
|
||||
|
||||
def engine_pipelined(eng, extra):
|
||||
"""Does the engine run the batch in pipelined groups (a layer split, more than one group)? Then a BYIELD is
|
||||
dropped: a pipelined read never gives way."""
|
||||
if "--batch-groups" in extra:
|
||||
v = extra[extra.index("--batch-groups") + 1] if extra.index("--batch-groups") + 1 < len(extra) else ""
|
||||
if v.isdigit():
|
||||
return int(v) > 1
|
||||
eng.log.flush()
|
||||
m = re.search(r"--batch-groups auto: (\d+) groups? of", Path(eng.log_path).read_text(errors="replace"))
|
||||
return bool(m) and int(m.group(1)) > 1
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--exe", required=True)
|
||||
@@ -55,6 +72,13 @@ def main():
|
||||
ap.add_argument("--max-new", type=int, default=200)
|
||||
ap.add_argument("--long", type=int, default=5000, help="tokens of the long prompt C (several prompt chunks)")
|
||||
ap.add_argument("--extra", default="")
|
||||
ap.add_argument("--yield", dest="yield_mode", choices=("auto", "expect", "skip"), default="auto",
|
||||
help="step 4's give-way: auto = expect a YIELDED unless the batch is pipelined (the engine log "
|
||||
"says '--batch-groups auto: N groups' with N > 1, or --extra has --batch-groups N > 1), "
|
||||
"where a read never gives way; expect = always required; skip = never required")
|
||||
ap.add_argument("--flush", type=int, default=8,
|
||||
help="7b: unrelated solo GENs between A in slot 1 and F, so only the slot holds A's start (0: off)")
|
||||
ap.add_argument("--dump", default="", help="write every solo and slot token list as JSON: an A/B of two builds")
|
||||
a = ap.parse_args()
|
||||
cfg = json.loads(Path(a.config).read_text())
|
||||
tok = tokenizer(cfg["tokenizer"])
|
||||
@@ -85,6 +109,10 @@ def main():
|
||||
F = A[:turn_at] + tok.encode("<|im_start|>assistant\nA short answer.<|im_end|>\n", parse_special=True) + \
|
||||
chat("Now in Go.")
|
||||
sF, _ = run(eng, out, f"GEN {M} {ids(F)}")
|
||||
# F2 (step 7b): another reply to A's question - it too shares A only up to A's turn checkpoint
|
||||
F2 = A[:turn_at] + tok.encode("<|im_start|>assistant\nAnother short answer.<|im_end|>\n", parse_special=True) + \
|
||||
chat("Now in C.")
|
||||
sF2, _ = run(eng, out, f"GEN {M} {ids(F2)}") if a.flush > 0 else ([], None)
|
||||
sB, _ = run(eng, out, f"GEN {M} {ids(B)}")
|
||||
sC, _ = run(eng, out, f"GEN {M} {ids(C)}")
|
||||
sD, _ = run(eng, out, f"GEN {M} {ids(D)}")
|
||||
@@ -139,36 +167,58 @@ def main():
|
||||
d = next((k for k in range(min(len(got2), len(sA2))) if got2[k] != sA2[k]), None)
|
||||
print(f"A's next turn from its slot: {len(got2)} tokens, solo {len(sA2)}: "
|
||||
f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
|
||||
# 4. a long prompt D gives way (BYIELD) to a short E at its first chunk boundary, then goes on from its slot
|
||||
# 4. a long prompt D gives way (BYIELD) to a short E at its first chunk boundary, then goes on from its slot.
|
||||
# On a pipelined batch (a layer split with more than one group) a read never gives way (generate.cpp: the BYIELD
|
||||
# is dropped): D is then admitted whole into slot 2 and E goes into the free slot 1 while D decodes - both must
|
||||
# still equal solo, only the give-way itself is not checked (--yield)
|
||||
pipelined = engine_pipelined(eng, a.extra.split())
|
||||
expect_yield = a.yield_mode == "expect" or (a.yield_mode == "auto" and not pipelined)
|
||||
eng.send(f"BGEN 2 {M} {ids(D)}")
|
||||
eng.send("BYIELD 2")
|
||||
yielded = None
|
||||
yielded, firstD, contD = None, [], None
|
||||
for l in out:
|
||||
if l.startswith("YIELDED "):
|
||||
if l.startswith("T "):
|
||||
firstD.append(int(l.split()[1]))
|
||||
elif l.startswith("YIELDED "):
|
||||
yielded = l
|
||||
elif l.startswith(("BT ", "BDONE ")):
|
||||
eng.pending.append(l)
|
||||
elif l.startswith("ERR"):
|
||||
raise SystemExit("engine: " + l)
|
||||
elif l.startswith("BADM 2 "):
|
||||
contD = l.split()[2] == "1"
|
||||
break
|
||||
print(f"D gave way: {yielded}", flush=True)
|
||||
ok &= yielded is not None
|
||||
if yielded is not None:
|
||||
print(f"D gave way: {yielded}", flush=True)
|
||||
elif expect_yield:
|
||||
print(f"D gave way: None (expected a YIELDED: batch {'pipelined' if pipelined else 'not pipelined'})",
|
||||
flush=True)
|
||||
ok = False
|
||||
else:
|
||||
print(f"D gave way: None - the batch is pipelined ({pipelined}), where a read never gives way; D stays in "
|
||||
f"slot 2 ({len(firstD)} first tokens, {'continues' if contD else 'done'}), E goes into slot 1 beside it",
|
||||
flush=True)
|
||||
got4 = {1: [], 2: []}
|
||||
first, cont1 = run(eng, out, f"BGEN 1 {M} {ids(E)}", slot=1)
|
||||
got4[1] += first
|
||||
first, cont2 = run(eng, out, f"BGEN 2 {M} {ids(D)}", slot=2)
|
||||
got4[2] += first
|
||||
if yielded is not None:
|
||||
first, cont2 = run(eng, out, f"BGEN 2 {M} {ids(D)}", slot=2)
|
||||
got4[2] += first
|
||||
else: # D never left slot 2: its tokens so far are the read's first ones plus the BT 2 lines kept in pending
|
||||
got4[2] += firstD
|
||||
cont2 = contD
|
||||
done4 = {s for s, c in ((1, cont1), (2, cont2)) if not c}
|
||||
while len(done4) < 2:
|
||||
l = eng.pending.pop(0) if eng.pending else next(out)
|
||||
if l.startswith("BT "):
|
||||
_, s, y = l.split()
|
||||
if int(s) in got4:
|
||||
if int(s) in got4 and int(s) not in done4:
|
||||
got4[int(s)].append(int(y))
|
||||
elif l.startswith("BDONE "):
|
||||
done4.add(int(l.split()[1]))
|
||||
for s, ref, name in ((1, sE, "E (short, admitted while D waited)"), (2, sD, "D (gave way, then went on)")):
|
||||
elif l.startswith("ERR"):
|
||||
raise SystemExit("engine: " + l)
|
||||
for s, ref, name in ((1, sE, "E (short, admitted while D waited)"), (2, sD, "D (gave way, then went on)" if yielded else "D (read whole, E admitted beside it)")):
|
||||
same = got4[s] == ref
|
||||
ok &= same
|
||||
d = next((k for k in range(min(len(got4[s]), len(ref))) if got4[s][k] != ref[k]), None)
|
||||
@@ -208,7 +258,8 @@ def main():
|
||||
print(f"solo next turn from a slot: drafts accepted {f[6]} of {f[7]} ({f[1]} tokens in {f[4]} ms)",
|
||||
flush=True)
|
||||
break
|
||||
# 7. F from slot 1's turn checkpoint (slot 1 holds A since step 6): the engine log says "(its turn checkpoint)"
|
||||
# 7. F, A's history without the reply's thinking, into slot 2 (its start comes from the live chain or the prompt
|
||||
# cache: step 6's solo continuation took slot 1's contents back; 7b below makes a slot the only source)
|
||||
first, cont = run(eng, out, f"BGEN 2 {M} {ids(F)}", slot=2)
|
||||
got7 = list(first)
|
||||
while cont:
|
||||
@@ -220,8 +271,54 @@ def main():
|
||||
same = got7 == sF
|
||||
ok &= same
|
||||
d = next((k for k in range(min(len(got7), len(sF))) if got7[k] != sF[k]), None)
|
||||
print(f"F (A's history without the reply's thinking) from slot 1's turn checkpoint: {len(got7)} tokens, solo "
|
||||
print(f"F (A's history without the reply's thinking) in slot 2: {len(got7)} tokens, solo "
|
||||
f"{len(sF)}: {'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
|
||||
# 7b. step 7 where only a SLOT can give the start: after step 6 the solo path took slot 1's contents back, so the
|
||||
# live chain (or the prompt cache) held A's start in step 7 and F came from there. Here A runs to its end in
|
||||
# slot 1, then --flush unrelated solo GENs push A out of the live session and the prompt cache's checkpoints; F2
|
||||
# (A's question, another reply) into slot 2 can then only start from slot 1's turn checkpoint (slot 2 holds F,
|
||||
# which shares no more with F2 than A does; the engine log line is printed) - its tokens must equal F2 solo
|
||||
got7b = []
|
||||
if a.flush > 0:
|
||||
first, cont = run(eng, out, f"BGEN 1 {M} {ids(A)}", slot=1)
|
||||
gotA = list(first)
|
||||
while cont:
|
||||
l = eng.pending.pop(0) if eng.pending else next(out)
|
||||
if l.startswith("BT 1 "):
|
||||
gotA.append(int(l.split()[2]))
|
||||
elif l.startswith("BDONE 1 "):
|
||||
break
|
||||
same = gotA == sA
|
||||
ok &= same
|
||||
print(f"7b: A in slot 1 to its end: {len(gotA)} tokens, solo {len(sA)}: {'IDENTICAL' if same else 'DIFFERS'}",
|
||||
flush=True)
|
||||
for k in range(a.flush):
|
||||
run(eng, out, f"GEN 8 {ids(chat(f'Unrelated question {k}: name one prime number above {100 * k}.'))}")
|
||||
eng.log.flush()
|
||||
mark = len(Path(eng.log_path).read_text(errors="replace"))
|
||||
first, cont = run(eng, out, f"BGEN 2 {M} {ids(F2)}", slot=2)
|
||||
got7b = list(first)
|
||||
while cont:
|
||||
l = eng.pending.pop(0) if eng.pending else next(out)
|
||||
if l.startswith("BT 2 "):
|
||||
got7b.append(int(l.split()[2]))
|
||||
elif l.startswith("BDONE 2 "):
|
||||
break
|
||||
tail = Path(eng.log_path).read_text(errors="replace")[mark:]
|
||||
src = [l for l in tail.splitlines() if "gave back" in l or "strata serve: prompt" in l][:2]
|
||||
same = got7b == sF2
|
||||
ok &= same
|
||||
d = next((k for k in range(min(len(got7b), len(sF2))) if got7b[k] != sF2[k]), None)
|
||||
print(f"7b: F2 after {a.flush} unrelated GENs, from slot 1: {len(got7b)} tokens, solo {len(sF2)}: "
|
||||
f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
|
||||
for l in src:
|
||||
print(" 7b log:", l.split("strata ")[-1][:160], flush=True)
|
||||
if a.dump:
|
||||
Path(a.dump).write_text(json.dumps({
|
||||
"solo": {"A": sA, "A2": sA2, "B": sB, "C": sC, "D": sD, "E": sE, "F": sF, "F2": sF2},
|
||||
"slots": {"A": got[0], "B": got[1], "C": got[2], "A2": got2, "E": got4[1], "D": got4[2],
|
||||
"A_slot_then_solo": got6 + tail6, "F": got7, "F2": got7b},
|
||||
"yielded": yielded is not None, "pipelined": pipelined}), encoding="utf-8")
|
||||
eng.send("QUIT")
|
||||
eng.p.wait(timeout=180)
|
||||
log = Path(eng.log_path).read_text(errors="replace")
|
||||
|
||||
@@ -20,7 +20,17 @@ QUESTIONS = [
|
||||
"Explain how a transformer's attention works, step by step.",
|
||||
"Donne une recette de tarte aux pommes, etape par etape.",
|
||||
"Describe the life cycle of a star like the Sun.",
|
||||
"Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.",
|
||||
"Write a Rust function that parses a CSV line with quoted fields, then explain it.",
|
||||
"What were the main consequences of the invention of the printing press?",
|
||||
"Explique le theoreme de Pythagore avec trois demonstrations differentes.",
|
||||
"Describe how the immune system responds to a viral infection.",
|
||||
"Explain the difference between processes and threads in an operating system.",
|
||||
"Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.",
|
||||
"How does public-key cryptography work? Give an example with RSA.",
|
||||
]
|
||||
# more than 16 slots: the same questions again, asked to answer in German
|
||||
QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS]
|
||||
|
||||
|
||||
def tokenizer(path):
|
||||
|
||||
Reference in new issue
Block a user