Author SHA1 Message Date
lotherk 93e0566581 Front end: shorten a request's max_tokens instead of refusing it (--fit-max-tokens)
The engine keeps 8 cells of the context for itself, so the earlier check
(prompt + 1 <= ctx) promised more room than the engine would accept.  A request
whose max_tokens would run past the room left is now shortened to fit, or
refused with --no-fit-max-tokens (default: fit).
2026-10-13 13:18:53 +01:00
lotherk 89f025cc66 Container: build the unittest image in a Dockerfile; add a P40 compose example
Multi-stage Dockerfile: build (nvidia/cuda 12.8.1 devel, PASCAL=1) then a
runtime stage (nvidia/cuda 12.8.1 runtime), one binary (build/unbiased-strata),
a /health check. examples/compose/p40.yml shows a one-card Tesla P40 service
with the model, pack and MTP mounted read-only.
2026-10-13 13:18:50 +01:00
lotherk 1002fd0823 Build: PASCAL=1 for the experimental sm_61/sm_60 (GTX 10-series, P40) build
Compiles CMAKE_CUDA_ARCHITECTURES=61 and passes -DSTRATA_EXPERIMENTAL_SM60=ON,
with an early error when nvcc is 13+ (which dropped sm_60/sm_70). Default
build is unchanged.
2026-10-11 21:19:28 +01:00
158 changed files with 1233 additions and 26469 deletions

No files matched your search

+8 -186
View File
@@ -231,33 +231,6 @@ if(STRATA_BUILD_TESTS)
add_executable(gguf_split_test tests/core/gguf_split_test.cpp)
target_link_libraries(gguf_split_test PRIVATE strata_artifact)
add_test(NAME gguf_split_test COMMAND gguf_split_test)
# Qwen3.6 port, step 2: ModelGeometry from the model file's metadata (strata/core/model_geometry.hpp) on the
# synthetic qwen35moe GGUFs tools/qwen36_synth_gguf.py writes (python3 with numpy and the vendored gguf-py; the
# fixture test skips without them, and so does the test that needs the files)
add_executable(model_geometry_test tests/core/model_geometry_test.cpp)
target_link_libraries(model_geometry_test PRIVATE strata_artifact)
find_package(Python3 COMPONENTS Interpreter QUIET)
set(_q36_python "")
foreach(_cand ${Python3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/.venv/bin/python" /usr/bin/python3 python3)
if(_cand STREQUAL "" OR NOT _q36_python STREQUAL "")
continue()
endif()
execute_process(COMMAND ${_cand} -c "import numpy" OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE _q36_probe)
if(_q36_probe EQUAL 0)
set(_q36_python "${_cand}")
endif()
endforeach()
if(NOT _q36_python STREQUAL "")
add_test(NAME qwen36_synth_fixtures
COMMAND ${CMAKE_COMMAND} -DPYTHON=${_q36_python} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}
-DOUT=${CMAKE_CURRENT_BINARY_DIR}/qwen36_synth -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/qwen36_synth_fixtures.cmake)
set_tests_properties(qwen36_synth_fixtures PROPERTIES FIXTURES_SETUP qwen36_synth_data)
add_test(NAME model_geometry_test COMMAND model_geometry_test ${CMAKE_CURRENT_BINARY_DIR}/qwen36_synth)
set_tests_properties(model_geometry_test PROPERTIES FIXTURES_REQUIRED qwen36_synth_data SKIP_RETURN_CODE 3)
else()
message(STATUS "STRATA tests: no python3 with numpy - the qwen36 synthetic fixtures and model_geometry_test are "
"not registered")
endif()
endif()
# ---- strata_plan ----------------------------------------------------------
@@ -269,12 +242,6 @@ target_link_libraries(strata_plan INTERFACE strata_warnings)
add_executable(strata-plan src/plan/plan_main.cpp)
target_link_libraries(strata-plan PRIVATE strata_plan)
if(STRATA_BUILD_TESTS)
# Qwen3.6 port, step 2: the VRAM planner's arithmetic (strata/plan/vram_plan.hpp) against the study's table 4.3
add_executable(vram_plan_test tests/core/vram_plan_test.cpp)
target_link_libraries(vram_plan_test PRIVATE strata_plan)
add_test(NAME vram_plan_test COMMAND vram_plan_test)
endif()
# ---- strata_core (GPU runtime) ---------------------------------------------
# Only built when a GPU backend is on, so the Phase 1 targets keep working without a toolkit.
@@ -475,11 +442,6 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(expert_layout_test PRIVATE strata_engine)
add_test(NAME expert_layout_test COMMAND expert_layout_test ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/native_experts)
set_tests_properties(expert_layout_test PROPERTIES TIMEOUT 60)
# the pool's native-pack rows at the layer's widths (Qwen3.6's 2048 x 512), not the canonical FF / H
add_executable(pool_native_widths_test tests/core/pool_native_widths_test.cpp)
target_link_libraries(pool_native_widths_test PRIVATE strata_engine)
add_test(NAME pool_native_widths_test COMMAND pool_native_widths_test)
set_tests_properties(pool_native_widths_test PROPERTIES TIMEOUT 120)
# #326: a native pack's BF16 (--compat-bf16) PLE key stays in the arena; a quantized key row loads as before
add_executable(native_dense_ple_key_test tests/core/native_dense_ple_key_test.cpp)
target_link_libraries(native_dense_ple_key_test PRIVATE strata_engine)
@@ -494,49 +456,6 @@ 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)
# Qwen3.6 step 4: a real native pack loaded as `strata generate --native --pack` loads it (arena, native
# projections, head, embedding, check_all), given by STRATA_QWEN36_GGUF / STRATA_QWEN36_PACK; skipped without
# them (docs/qwen36-port/step4-pack.md)
add_executable(pack_load_check tests/core/pack_load_check.cpp)
target_link_libraries(pack_load_check PRIVATE strata_engine)
add_test(NAME pack_load_check COMMAND pack_load_check)
set_tests_properties(pack_load_check PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900)
endif()
# Qwen3.6 step 3: the plain block (hc = 1) composed by the engine against the oracle's dumps of the synthetic file
# (docs/qwen36-port/step3-block.md). Needs the synthetic fixture (python3 with numpy) and a CUDA device.
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND NOT _q36_python STREQUAL "")
add_executable(qwen36_block_test tests/cuda/qwen36_block_test.cpp)
target_link_libraries(qwen36_block_test PRIVATE strata_engine strata_artifact)
add_test(NAME qwen36_block_fixtures
COMMAND ${CMAKE_COMMAND} -DPYTHON=${_q36_python} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}
-DSYNTH=${CMAKE_CURRENT_BINARY_DIR}/qwen36_synth -DOUT=${CMAKE_CURRENT_BINARY_DIR}/qwen36_block
-P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/qwen36_block_fixtures.cmake)
set_tests_properties(qwen36_block_fixtures PROPERTIES FIXTURES_SETUP qwen36_block_data
FIXTURES_REQUIRED qwen36_synth_data TIMEOUT 300)
add_test(NAME qwen36_block_test COMMAND qwen36_block_test ${CMAKE_CURRENT_BINARY_DIR}/qwen36_synth
${CMAKE_CURRENT_BINARY_DIR}/qwen36_block/o8)
set_tests_properties(qwen36_block_test PROPERTIES FIXTURES_REQUIRED "qwen36_synth_data;qwen36_block_data"
SKIP_RETURN_CODE 77 TIMEOUT 120)
endif()
# Qwen3.6 step 4 (docs/qwen36-port/step4-runner.md): the verify window on a native pack of the synthetic model at
# the real per-layer geometry (tests/python/qwen36_runner_fixture.py: the GGUF, the pack through tools/iq_pack.py,
# the oracle's dumps), held to the oracle per row and position and to the single-token path bit for bit; then the
# streaming runner (the `strata` binary: chunked prefill, then windows teacher-forced to the oracle) through
# tests/python/qwen36_runner_check.py, with the 4 KB mutation gate. Needs python3 with numpy and a CUDA device.
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND NOT _q36_python STREQUAL "")
add_executable(qwen36_verify_test tests/cuda/qwen36_verify_test.cpp)
target_link_libraries(qwen36_verify_test PRIVATE strata_engine strata_artifact)
add_test(NAME qwen36_runner_fixtures
COMMAND ${_q36_python} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/python/qwen36_runner_fixture.py
--out ${CMAKE_CURRENT_BINARY_DIR}/qwen36_runner)
set_tests_properties(qwen36_runner_fixtures PROPERTIES FIXTURES_SETUP qwen36_runner_data TIMEOUT 1800
ENVIRONMENT "STRATA_GGUF_PY=${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp/gguf-py")
add_test(NAME qwen36_verify_test COMMAND qwen36_verify_test ${CMAKE_CURRENT_BINARY_DIR}/qwen36_runner)
set_tests_properties(qwen36_verify_test PROPERTIES FIXTURES_REQUIRED qwen36_runner_data SKIP_RETURN_CODE 77 TIMEOUT 600)
add_test(NAME qwen36_runner_check
COMMAND ${_q36_python} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/python/qwen36_runner_check.py
--strata $<TARGET_FILE:strata> --fixture ${CMAKE_CURRENT_BINARY_DIR}/qwen36_runner)
set_tests_properties(qwen36_runner_check PROPERTIES FIXTURES_REQUIRED qwen36_runner_data SKIP_RETURN_CODE 77 TIMEOUT 900)
endif()
if(STRATA_BUILD_CONVERSATION_TESTS)
add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp)
@@ -732,50 +651,17 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME iq_multi_parity COMMAND iq_multi_parity)
# the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise, and the engine's
# launches against a host reference at both geometries with the negative controls (Qwen3.6 step 3; GPU,
# the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU,
# synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906)
if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906)
add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu)
target_link_libraries(gdn_rec_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target})
target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target})
add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity)
# the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the
# FP16 tensor cores; GPU, synthetic, no model; --bench adds timings)
add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu)
target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill )
add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity)
# Qwen3.6 step 3: the prompt path at Qwen3.6's geometry against the oracle's dumps (docs/qwen36-port/step3-prefill.md).
# The fixtures (synthetic GGUFs at the real per-layer widths, the oracle's dumps and its rival readings) come from
# tests/python/qwen36_prefill_fixture.py with the numpy interpreter probed above; gdn3 is three DeltaNet layers,
# full4 adds the attention layer (exit 77 until the attention branch's G = 8 kernels are in the tree)
add_executable(prefill_qwen36_test tests/cuda/prefill_qwen36_test.cpp)
target_link_libraries(prefill_qwen36_test PRIVATE strata_prefill ${_strata_gpu_runtime_target})
if(NOT _iq_python STREQUAL "")
add_test(NAME prefill_qwen36_fixtures
COMMAND ${_iq_python} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/python/qwen36_prefill_fixture.py
--out ${CMAKE_CURRENT_BINARY_DIR}/qwen36_prefill)
set_tests_properties(prefill_qwen36_fixtures PROPERTIES FIXTURES_SETUP qwen36_prefill_data SKIP_RETURN_CODE 3
TIMEOUT 1800 ENVIRONMENT "STRATA_GGUF_PY=${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp/gguf-py")
add_test(NAME prefill_qwen36_test COMMAND prefill_qwen36_test ${CMAKE_CURRENT_BINARY_DIR}/qwen36_prefill gdn3)
set_tests_properties(prefill_qwen36_test PROPERTIES FIXTURES_REQUIRED qwen36_prefill_data SKIP_RETURN_CODE 77 TIMEOUT 600)
add_test(NAME prefill_qwen36_attn_test COMMAND prefill_qwen36_test ${CMAKE_CURRENT_BINARY_DIR}/qwen36_prefill full4)
set_tests_properties(prefill_qwen36_attn_test PROPERTIES FIXTURES_REQUIRED qwen36_prefill_data SKIP_RETURN_CODE 77 TIMEOUT 600)
endif()
# Qwen3.6 step 4: the drafter (the -MTP file's nextn block through core/mtp.cpp, its experts on the native kernels)
# against the oracle's --mtp dumps, position by position, with the prompt-side pass (docs/qwen36-port/step4-drafter.md).
# The fixture (tests/python/qwen36_mtp_fixture.py) is the prompt-path trunk plus the nextn block, and the draft
# pack tools/mtp_qwen36_pack.py cuts from it; `qwen36_mtp_test --real ...` is the real-file arm (by hand).
add_executable(qwen36_mtp_test tests/cuda/qwen36_mtp_test.cpp)
target_link_libraries(qwen36_mtp_test PRIVATE strata_prefill strata_engine strata_artifact ${_strata_gpu_runtime_target})
if(NOT _iq_python STREQUAL "")
add_test(NAME qwen36_mtp_fixtures
COMMAND ${_iq_python} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/python/qwen36_mtp_fixture.py
--out ${CMAKE_CURRENT_BINARY_DIR}/qwen36_mtp)
set_tests_properties(qwen36_mtp_fixtures PROPERTIES FIXTURES_SETUP qwen36_mtp_data SKIP_RETURN_CODE 3
TIMEOUT 1800 ENVIRONMENT "STRATA_GGUF_PY=${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp/gguf-py")
add_test(NAME qwen36_mtp_test COMMAND qwen36_mtp_test ${CMAKE_CURRENT_BINARY_DIR}/qwen36_mtp)
set_tests_properties(qwen36_mtp_test PROPERTIES FIXTURES_REQUIRED qwen36_mtp_data SKIP_RETURN_CODE 77 TIMEOUT 900)
endif()
endif()
# native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic,
# no model; --bench adds v1/new timings of a window's 48 calls in a graph)
@@ -800,20 +686,6 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(gdn_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(gdn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME gdn_parity COMMAND gdn_parity --selftest)
# Qwen3.6 step 3: the decode GDN kernels (all four implementations), the router at 256/8 and the shared expert at
# 512 held to ref/qwen36.py's seams on the fixture cmake/qwen36_oracle_dumps.cmake writes (python3 with numpy and
# the vendored gguf-py; both tests skip without them)
add_executable(qwen36_seam_parity src/kernels/qwen36_seam_parity.cpp)
target_include_directories(qwen36_seam_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(qwen36_seam_parity PRIVATE strata_kernels strata_artifact ${_strata_gpu_runtime_target})
if(NOT _q36_python STREQUAL "")
add_test(NAME qwen36_oracle_dumps
COMMAND ${CMAKE_COMMAND} -DPYTHON=${_q36_python} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}
-DOUT=${CMAKE_CURRENT_BINARY_DIR}/qwen36_oracle -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/qwen36_oracle_dumps.cmake)
set_tests_properties(qwen36_oracle_dumps PROPERTIES FIXTURES_SETUP qwen36_oracle_data)
add_test(NAME qwen36_seam_parity COMMAND qwen36_seam_parity ${CMAKE_CURRENT_BINARY_DIR}/qwen36_oracle)
set_tests_properties(qwen36_seam_parity PROPERTIES FIXTURES_REQUIRED qwen36_oracle_data SKIP_RETURN_CODE 77)
endif()
add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp)
target_include_directories(s2_gemv_q8_parity PRIVATE ${_strata_gpu_include_directories})
@@ -891,31 +763,6 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(qsa_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME qsa_parity COMMAND qsa_parity --selftest)
# Qwen3.6 step 3 (docs/qwen36-port/step3-attn.md): dense attention through the split-K decode kernel and the
# prompt kernel - G templated (2, 8, 12), a null ids as the identity, the bounded scratch, the sparse width refused
# for the dense model - against a host reference in every KV format, and the oracle's attention seams on
# the synthetic fixtures at head_dim 256 (cmake/qwen36_attn_fixtures.cmake; skips without python3 + numpy)
add_executable(qsa_dense_parity src/kernels/qsa_dense_parity.cpp)
target_include_directories(qsa_dense_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(qsa_dense_parity PRIVATE strata_kernels strata_artifact ${_strata_gpu_runtime_target})
if(NOT _q36_python STREQUAL "")
add_test(NAME qwen36_attn_fixtures
COMMAND ${CMAKE_COMMAND} -DPYTHON=${_q36_python} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}
-DOUT=${CMAKE_CURRENT_BINARY_DIR}/qwen36_attn -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/qwen36_attn_fixtures.cmake)
set_tests_properties(qwen36_attn_fixtures PROPERTIES FIXTURES_SETUP qwen36_attn_data)
add_test(NAME qsa_dense_parity COMMAND qsa_dense_parity --fixtures ${CMAKE_CURRENT_BINARY_DIR}/qwen36_attn)
set_tests_properties(qsa_dense_parity PROPERTIES FIXTURES_REQUIRED qwen36_attn_data SKIP_RETURN_CODE 77)
else()
add_test(NAME qsa_dense_parity COMMAND qsa_dense_parity)
set_tests_properties(qsa_dense_parity PROPERTIES SKIP_RETURN_CODE 77)
endif()
# the decode attention's cost per call at a few depths (the before / after numbers of step3-attn.md); explicit
# ids only, so it builds against the kernel before step 3 as well
add_executable(qsa_attn_bench src/kernels/qsa_attn_bench.cpp)
target_include_directories(qsa_attn_bench PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(qsa_attn_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target})
# a benchmark, not a test: it asserts nothing, so it is a target and not a CTest entry
# the QSA top-k the engine dispatches against the original kernel: identical ids on both sides of the register
# kernel's reach, with tied and with equal scores (synthetic, no model)
add_executable(qsa_topk_parity src/kernels/qsa_topk_parity.cpp)
@@ -1147,23 +994,6 @@ if(STRATA_NATIVE_EXPERTS)
if(NOT EXISTS ${STRATA_GGML_DIR}/ggml/CMakeLists.txt)
message(FATAL_ERROR "ggml was not found in ${STRATA_GGML_DIR}: run `git submodule update --init` first")
endif()
# The chat-parser patch (patches/llama.cpp-qwen3-coder-any-argument-order.patch) is applied here at configure
# time, not only by `make build`: a tree built with cmake directly (the VMs, the agents' worktrees, a copied
# submodule without .git) otherwise runs upstream's required-first rule and drops a Qwen3.6 tool call whose
# required parameter is not written first (REGINA-104).
set(_strata_patch ${CMAKE_CURRENT_SOURCE_DIR}/patches/llama.cpp-qwen3-coder-any-argument-order.patch)
if(STRATA_GGML_DIR STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp AND EXISTS ${_strata_patch})
execute_process(COMMAND patch -p1 -N -R --dry-run -s -i ${_strata_patch} WORKING_DIRECTORY ${STRATA_GGML_DIR}
RESULT_VARIABLE _strata_patched OUTPUT_QUIET ERROR_QUIET)
if(NOT _strata_patched EQUAL 0)
execute_process(COMMAND patch -p1 -N -s -i ${_strata_patch} WORKING_DIRECTORY ${STRATA_GGML_DIR}
RESULT_VARIABLE _strata_patch_rc OUTPUT_VARIABLE _strata_patch_out ERROR_VARIABLE _strata_patch_out)
if(NOT _strata_patch_rc EQUAL 0)
message(FATAL_ERROR "could not apply ${_strata_patch} to ${STRATA_GGML_DIR}:\n${_strata_patch_out}")
endif()
message(STATUS "applied patches/llama.cpp-qwen3-coder-any-argument-order.patch to third_party/llama.cpp")
endif()
endif()
add_subdirectory(${STRATA_GGML_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL)
# part of strata_kernels_cpu (the pool calls these and they call its CPU probe: one library, so GNU ld's
# one-pass static linking has no cycle to resolve)
@@ -1219,10 +1049,10 @@ if(STRATA_NATIVE_EXPERTS)
src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu)
# q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and
# STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch
# follows eddoursul/Strata 7706c1b), plus q6_k (Qwen3.6-35B-A3B UD-Q4_K_XL's layers 34, 38, 39)
# follows eddoursul/Strata 7706c1b)
set(_strata_mmq_cuda_types ${_strata_mmq_types})
if(STRATA_MMQ_KQUANTS)
list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1 q6_k)
list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1)
endif()
foreach(_t IN LISTS _strata_mmq_cuda_types)
target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
@@ -1321,25 +1151,17 @@ if(STRATA_NATIVE_EXPERTS)
# kernel for it before; q5_0/q5_0 (both roles Q5_0) is left out of this list since stacking the same
# lower-precision format on both roles pushes the GPU path over this test's 3% threshold (quantization
# noise, not a kernel bug -- see the PR).
foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0 q6_K/q8_0)
foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0)
string(REPLACE "/" "_" _name "${_pair}")
add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair})
set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120)
endforeach()
# Qwen3.6-35B-A3B's expert pairs at its 2048 x 512 (docs/qwen36-port/step3-experts.md): UD-IQ3_XXS's
# IQ2_S/IQ3_XXS (37 layers) and IQ2_S/IQ4_XS (34, 38, 39); UD-Q4_K_XL's Q4_K/Q5_K (37), Q4_K/Q6_K (34, 38)
# and Q5_K/Q6_K (39). The 256-value down types need n_ff % 256 == 0, which 512 has and 640 has not.
foreach(_pair iq2_s/iq3_xxs iq2_s/iq4_xs q4_K/q5_K q4_K/q6_K q5_K/q6_K)
string(REPLACE "/" "_" _name "${_pair}")
add_test(NAME native_expert_parity_qwen36_${_name} COMMAND native_expert_parity --geom 2048x512 --synthetic ${_pair})
set_tests_properties(native_expert_parity_qwen36_${_name} PROPERTIES TIMEOUT 120)
endforeach()
add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min)
# #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit
add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd)
# a 256-value down type at Flash-Next's n_ff 640 is refused by native_expert_supported, not run
add_test(NAME native_expert_parity_refuses_q6_K_down_at_640 COMMAND native_expert_parity --synthetic q4_K/q6_K)
set_tests_properties(native_expert_parity_refuses_q6_K_down_at_640 PROPERTIES WILL_FAIL TRUE)
# a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run
add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0)
set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE)
endif()
endif()
# #296's real-weight checks (OrcaRouter Q4_K_S files; docs/ORCA_Q4_K_S.md) - test programs, not part of a release
+11 -28
View File
@@ -1,18 +1,13 @@
# UnbiasedStrata build. Needs CMake 3.24+, a C++20 compiler and the CUDA toolkit. Nothing is downloaded.
BUILD_DIR ?= build
# One binary for every single NVIDIA GPU from Pascal up: GTX 10 (61), Volta (70), RTX 20 / GTX 16 (75), RTX 30 (86),
# RTX 40 (89), RTX 50 (120). Pascal and Volta are the experimental build (STRATA_EXPERIMENTAL_SM60; needs a CUDA 12.x
# toolkit, 13 dropped them): any arch below 75 in the list switches it on. sm_120 needs CUDA 12.8+. An arch the
# installed nvcc cannot compile is dropped from the list with a note (CUDA 12.4 has no 120; CUDA 13 has no 61 / 70),
# so the default builds on any toolkit; `make build CUDA_ARCHS=61` keeps a single-card build short
# (docs/qwen36-port/pascal-build.md).
CUDA_ARCHS ?= 61;70;75;86;89;120
# `make build PASCAL=1` is the short form of `CUDA_ARCHS=61`: sm_61 (GTX 10-series, Tesla P40; sm_60/P100 works too,
# override with CUDA_ARCHS=60). It needs a CUDA 12.x toolkit: CUDA 13 dropped sm_60/sm_70, so the check below fails
# early with the reason instead of inside nvcc.
# Pascal/Volta are a community, experimental build: `make build PASCAL=1` compiles sm_61 (GTX 10-series,
# Tesla P40; sm_60/P100 works too, override with CUDA_ARCHS=60) and turns on the engine's
# STRATA_EXPERIMENTAL_SM60 path (see README.md and src/core/device.cu). It needs a CUDA 12.x toolkit:
# CUDA 13 dropped sm_60/sm_70, so the check below fails early with the reason instead of inside nvcc.
PASCAL ?=
ifeq ($(PASCAL),1)
CUDA_ARCHS := 61
CUDA_ARCHS ?= 61
PASCAL_CMAKE_FLAGS := -DSTRATA_EXPERIMENTAL_SM60=ON
NVCC ?= $(shell command -v nvcc 2>/dev/null)
NVCC_MAJOR := $(shell $(NVCC) --version 2>/dev/null | sed -n 's/.*release \([0-9]*\).*/\1/p' | head -n1)
ifneq ($(NVCC_MAJOR),)
@@ -20,17 +15,10 @@ ifeq ($(shell [ $(NVCC_MAJOR) -ge 13 ] && echo yes),yes)
$(error PASCAL=1 needs a CUDA 12.x toolkit; nvcc $(NVCC_MAJOR) dropped sm_60/sm_70)
endif
endif
else
# RTX 30 (86), RTX 40 (89) and RTX 50 (120) in one binary. sm_120 needs CUDA 12.8+, and upstream recommends 13.0+.
CUDA_ARCHS ?= 86;89;120
endif
NVCC_ARCHS := $(shell nvcc --list-gpu-arch 2>/dev/null | sed 's/compute_//' | tr '\n' ' ')
ifneq ($(NVCC_ARCHS),)
CUDA_ARCHS_DROPPED := $(strip $(foreach a,$(subst ;, ,$(CUDA_ARCHS)),$(if $(filter $(firstword $(subst -, ,$(a))),$(NVCC_ARCHS)),,$(a))))
ifneq ($(CUDA_ARCHS_DROPPED),)
$(info make: nvcc cannot compile CUDA arch(s) $(CUDA_ARCHS_DROPPED); building without them)
CUDA_ARCHS := $(subst $(eval) ,;,$(strip $(foreach a,$(subst ;, ,$(CUDA_ARCHS)),$(if $(filter $(firstword $(subst -, ,$(a))),$(NVCC_ARCHS)),$(a),))))
endif
endif
SM60 := $(shell echo "$(CUDA_ARCHS)" | tr ';' '\n' | sed 's/-.*//' | grep -E '^[0-9]+$$' | awk '$$1 < 75 { print "ON"; exit }')
SM60_FLAG := $(if $(SM60),-DSTRATA_EXPERIMENTAL_SM60=ON,)
# capped: inside a container nproc reports the host's CPUs, not the container's quota
JOBS ?= $(shell n=$$(nproc 2>/dev/null || echo 4); [ $$n -gt 16 ] && n=16; echo $$n)
@@ -42,7 +30,8 @@ build:
@git -C third_party/llama.cpp apply --check --reverse ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch 2>/dev/null || \
git -C third_party/llama.cpp apply ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch
cmake -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON \
-DSTRATA_PORTABLE=ON -DSTRATA_MMQ_KQUANTS=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" $(SM60_FLAG) $(CMAKE_EXTRA)
-DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" \
$(PASCAL_CMAKE_FLAGS)
cmake --build $(BUILD_DIR) -j $(JOBS) --target unbiased-strata
@echo "built: $(BUILD_DIR)/unbiased-strata"
@@ -74,9 +63,3 @@ test-chat-parser:
$(BUILD_DIR)/ggml/src/libggml.a $(BUILD_DIR)/ggml/src/libggml-cpu.a $(BUILD_DIR)/ggml/src/libggml-base.a \
$(BUILD_DIR)/llama.cpp/common/libllama-common-base.a -lpthread -ldl -lm
$(BUILD_DIR)/frontend-tests/chat-parser-test "$(MODEL)"
# Against a running server: a request may ask for more tokens than the context has left (REGINA-112).
.PHONY: test-serve
test-serve:
@test -n "$(PORT)" || { echo 'set PORT to a running server ([HOST:]PORT)'; exit 2; }
python3 tests/python/serve_max_tokens_check.py $(PORT)
+13 -148
View File
@@ -1,10 +1,8 @@
# UnbiasedStrata
[Strata](https://github.com/Niko1221/Strata)'s inference engine and llama.cpp's tokenizer, chat-template and
HTTP code, built into one binary that serves Qwen3.8-Flash-Next (one 24 GB+ card, 128 GB RAM) and
Qwen3.6-35B-A3B (any single NVIDIA card from 6 to 32 GB, Pascal or newer) over an OpenAI-style API. No
network is needed to build or run it: rsync the source, run `make build`, start the binary. No Python, no
installer.
HTTP code, built into one binary that serves Qwen3.8-Flash-Next over an OpenAI-style API. No network is
needed to build or run it: rsync the source, run `make build`, start the binary. No Python, no installer.
## Requirements
@@ -12,18 +10,11 @@ installer.
| --- | --- | --- |
| Network access | no | no |
| CMake 3.24+, C++20 compiler (tested: g++ 13.3) | yes | no |
| CUDA | toolkit 12.x (tested: 12.4 and 12.8; 12.8+ for RTX 50; CUDA 13 dropped Pascal and Volta) | `libcudart.so.12`, `libcublas.so.12`, `libcublasLt.so.12` and the NVIDIA driver |
| CUDA | toolkit 12.8+ (tested: 12.8; 13.0+ advised for RTX 50) | `libcudart.so.12`, `libcublas.so.12`, `libcublasLt.so.12` and the NVIDIA driver |
Hardware: Linux, x86-64 with AVX2, one NVIDIA card.
| Model | Card | RAM |
| --- | --- | --- |
| Qwen3.8-Flash-Next | 24 GB or more (RTX 30, 40 or 50) | 128 GB |
| Qwen3.6-35B-A3B | 6 to 32 GB, Pascal (GTX 10 series, sm_61) or newer, one card | enough to hold the experts the card does not: 32 GB for Q4_K_XL on an 11 GB card, 16 GB for IQ3_XXS (the table under Sizing) |
The model can be on a local disk or on a network volume; what the card does not hold is read into RAM at
start, and what RAM does not hold is read from the file on a miss, so a slow store costs start-up time and,
on the small cards, decode speed.
Hardware, one configuration only: Linux, x86-64 with AVX2, one NVIDIA card with 24 GB or more (RTX 30, 40
or 50), 128 GB RAM. The model can be on a local disk or on a network volume; everything is read into RAM
and VRAM at start, so a slow store costs start-up time only.
## Build
@@ -33,12 +24,7 @@ ssh host 'cd UnbiasedStrata && make build' # produces build/unbiased-strata
```
The tree is 6 MB plus the pinned llama.cpp submodule in `third_party/` (about 170 MB checked out). The
build fetches nothing. `make build JOBS=N` sets the job count; `CUDA_ARCHS` defaults to
`61;70;75;86;89;120`, one binary for every card from Pascal up, minus any architecture the installed
`nvcc` cannot compile (12.4 has no 120, 13 has no 61 or 70; the build says what it dropped). `make build
CUDA_ARCHS=61` builds for one card in about 3 minutes. An architecture below 75 in the list turns on
`STRATA_EXPERIMENTAL_SM60`, the Pascal/Volta build (FP32 and dp4a paths; no tensor cores). The
chat-parser patch in `patches/` is applied to the submodule at configure time.
build fetches nothing. `make build JOBS=N` sets the job count; `CUDA_ARCHS` defaults to `86;89;120`.
Pascal is an experimental, community build: `make build PASCAL=1` compiles sm_61 (GTX 10-series, Tesla P40;
`CUDA_ARCHS=60` for P100) and turns on the engine's `STRATA_EXPERIMENTAL_SM60` path. It needs a CUDA 12.x
@@ -49,21 +35,16 @@ cache.
## Run
```
# Qwen3.8-Flash-Next
./unbiased-strata --model /models/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf \
--pack /models/pack-iq3-xxs --mtp /models/mtp
# Qwen3.6-35B-A3B at the full 262,144-token context (the engine sizes itself to the card; see Sizing)
./unbiased-strata --model /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf \
--pack /models/qwen36-q4 --mtp /models/qwen36-mtp-draft --ctx 262144 -- --kv q4_0
```
| | |
| --- | --- |
| Endpoints | `POST /v1/chat/completions` (streaming or not), `GET /v1/models`, `GET /health`, on `127.0.0.1:8080` |
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024), `--fit-max-tokens` / `--no-fit-max-tokens` (default: on); sampling defaults (a request's own fields win): `--temperature F` (0, greedy), `--top-k N` (1..64), `--top-p F`, `--min-p F`, `--repeat-last-n N`, `--repeat-penalty F`, `--presence-penalty F`, `--frequency-penalty F`, `--dry-multiplier F`, `--dry-base F`, `--dry-allowed-length N`, `--dry-penalty-last-n N`, `--dry-breakers LIST`, `--seed N`; engine flags after `--`: `--kv fp16\|q4_0\|int8`, `--vram-cap MiB` and `--ram-cap GiB` (plan as a smaller card or host), `--expert-cache N`, `--prompt-cache N` (checkpoints kept between requests) |
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024), `--fit-max-tokens` / `--no-fit-max-tokens` (default: on); engine flags after `--` |
| Context | a request whose `max_tokens` would run past `--ctx` has it shortened to the room left; with `--no-fit-max-tokens` it is refused (400) instead |
| Sampling | greedy unless the effective `temperature` > 0; `temperature`, `top_p`, `top_k` (1..64), `min_p`, `seed`, `presence_penalty`, `frequency_penalty`, `repeat_penalty` and `repeat_last_n` per request, else the launch defaults; a penalty with a zero window uses 64 (`repeat_last_n` / the alias `penalty_last_n`) |
| DRY | llama.cpp's `dry` anti-repetition sampler, on when `dry_multiplier` and `dry_penalty_last_n` are both set (per request, else `--dry-multiplier` / `--dry-penalty-last-n`): a token that would extend a repeat longer than `dry_allowed_length` loses `dry_multiplier * dry_base^(repeat - allowed_length)` over the last `dry_penalty_last_n` tokens. `dry_sequence_breakers` / `--dry-breakers` (literal strings, `\|`-separated; default newline, `:`, `"`, `*`) restart the repeat count. Applies in greedy and sampled mode; the front end tokenizes the breakers (the engine has no tokenizer) |
| Sampling | greedy unless `temperature` > 0 |
| Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off |
| Tools | OpenAI format (`tools`, `tool_calls`) |
| Images | with `--mmproj`, OpenAI `image_url` parts holding a base64 `data:image/...` URL (PNG, JPEG, BMP or GIF), several per message |
@@ -82,9 +63,7 @@ message is parsed, so a partial tool-call JSON never changes arguments already s
the child handling and the protocol without a model; `make test-chat-parser MODEL=<shard 1>` checks the chat
template and tool-call parsing against the real GGUF.
## The supported models
### Qwen3.8-Flash-Next
## The one supported model
Qwen3.8-Flash-Next (125B parameters, mixture of experts), the full model at IQ3_XXS quantization, from
[ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF),
@@ -103,66 +82,6 @@ Everything below must be on disk before start. Nothing is fetched.
About 78 GB in total. The commands that make the pack and draft head, and the SHA-256 of every file they
produce, are in [UPSTREAM.md](UPSTREAM.md).
### Qwen3.6-35B-A3B
Qwen3.6-35B-A3B (35B parameters, 3B active: 40 layers, 256 experts of which 8 route per token, 30 Gated
DeltaNet layers and 10 full-attention layers, 262,144-token context), unsloth's UD quantizations from
[unsloth/Qwen3.6-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF) and
[unsloth/Qwen3.6-35B-A3B-MTP-GGUF](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-MTP-GGUF). Two
quantizations, with the pack and draft pack made by this repository's own tools (`tools/iq_pack.py`,
`tools/make_profile.py`, `tools/mtp_qwen36_pack.py`; commands and every file's SHA-256 in
[UPSTREAM.md](UPSTREAM.md)):
| What | Size | SHA-256 |
| --- | --- | --- |
| `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf`, **the default** (K-quants: the fast AVX2 path for the experts the CPU computes) | 22.36 GB | `707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450` |
| `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` from the **-MTP** repository (the same trunk plus the draft block `blk.40`; serves as the model file too) | 22.85 GB | `55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1` |
| `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf`, for 6 and 8 GB cards | 13.21 GB | `9c964e657212fea1f24905dd7b0a89b82fd807d19fab0b41da14251b07b88fbe` |
| Pack `qwen36-q4/` or `qwen36-iq3/` (`index.txt`, `dense.bin`, `native_experts.txt`, `conversions.json`, `expert-profile.bin`, `tokenizer/`) | 65 MB | per file in UPSTREAM.md |
| Draft pack `qwen36-mtp-draft/` (`experts.bin`, `dense.bin`, `dense.txt`, `native_experts.txt`, `mtp.json`, `draft_vocab.bin`), cut from the -MTP file's draft block; serves both quantizations | 0.5 GB | per file in UPSTREAM.md |
No other Qwen3.6 file is accepted: the IQ4_XS-MTP file's draft block (Q3_K experts) and the 27B dense model
are refused by name. Images work with `--mmproj` and the model's own encoder (`mmproj-F16.gguf` from the -MTP repository,
899 MB); the encoder runs on the CPU, so the first use of a full-screen image costs 24 s on an i9-9900K and
about 70 s on a Ryzen 7 1700, and repeats are served from a cache.
#### Sizing
At start the engine prints its plan for the card it finds: the fixed set for the requested context (the
dense weights, the drafter, the KV cache, the session, a reserve), then every remaining megabyte as expert
slots, filled by the route-trace profile's rank. If the fixed set does not fit, the KV cache is streamed
to RAM above a resident window, then the context is lowered toward 131,072, then the engine refuses with
the numbers and suggests the IQ3_XXS file. It never silently picks a shorter context. The experts that do
not fit in VRAM are read from pinned RAM when the host has it, else from the file on a miss; `/health`
reports the VRAM hits, RAM reads and file reads per request. `--vram-cap` and `--ram-cap` make a big card
plan like a small one.
| VRAM | Q4_K_XL at 262,144, q4_0 KV: fixed set, experts resident | IQ3_XXS: fixed set, experts resident |
| --- | --- | --- |
| 24 GB (RTX 4090) | 4,823 MiB; 9,980 of 10,240 (97%) | 4,331 MiB; all 10,240, 8.8 GB spare |
| 11 GB (GTX 1080 Ti) | 4,461 MiB; 3,575 (35%) | 4,019 MiB; 6,748 (66%) |
| 8 GB | 1,949 (19%) | 3,873 (38%) |
| 6 GB | 598 (6%) | 1,486 (15%) |
The 24 GB row is measured; the others are the planner's figures from the same files under `--vram-cap`
(docs/qwen36-port/step2-notes.md section 5, step4-pack.md section 5).
**RAM is a requirement, not a tier.** The engine assumes the card and the host RAM together hold the expert set;
every expert the card does not hold is pinned in RAM. What the host must hold is the expert bytes minus the card's
share, plus the engine's own 3 to 4 GB and the OS:
| VRAM | Q4_K_XL experts off the card | RAM to have | IQ3_XXS experts off the card | RAM to have |
| --- | --- | --- | --- | --- |
| 24 GB | none | 8 GB | none | 8 GB |
| 16 GB | 8 GB | 16 GB | none | 8 GB |
| 11 GB | 13 GB | 32 GB (24 is tight) | 4 GB | 12 GB |
| 8 GB | 15 GB | 32 GB | 7 GB | 16 GB |
| 6 GB | 17 GB | 32 GB | 9 GB | 16 GB |
Below those figures the engine still starts, maps the rest from the file and says so in its plan, but that is a
fallback, not a supported configuration: measured once on the GTX 1080 Ti at Q4_K_XL under a 12 GiB memory bound,
decode fell from 52 tokens/s to 12 to 15, the NVMe's rate, with about 12 experts per token read from the file.
## Status
Checked on one machine: RTX 3090, 32 vCPUs of an EPYC 7763, 125 GB RAM, CUDA 12.8, in a container.
@@ -176,47 +95,6 @@ Checked on one machine: RTX 3090, 32 vCPUs of an EPYC 7763, 125 GB RAM, CUDA 12.
| Start from a network volume | 12 min for 76 GB (S3-backed RunPod volume, 120 to 330 MB/s). The volume refused reads twice with "cannot allocate memory"; the loader retried and went on |
| Not tested | RTX 50 cards; a cold start from local disk |
Qwen3.6-35B-A3B, checked on the RTX 4090 (VM, 16 vCPU i9-9900K, 62 GB RAM, CUDA 12.4):
| | |
| --- | --- |
| Correctness | the engine's logits held to a numpy reference and to llama.cpp at every position of the real files (greedy top-1 64/64 on three prompts at IQ3_XXS, 61-64/64 at Q4_K_XL, mean KL 1e-3 to 7e-3); the expert-miss path (what every card below 24 GB runs on) held with the same prompts under `--vram-cap` |
| Serving | chat, streaming of reasoning and answer per token, tool calls streamed and not, multi-turn prompt checkpoints at 262,144 context, at 24 GB, under an 11 GB cap (Q4_K_XL) and a 6 GB cap (IQ3_XXS); a coding agent (pi) wrote and ran a program through it |
| Pascal | built and unit-tested on a GTX 1080 Ti (sm_61: every kernel parity test, the pack, the drafter, the verify window); the expert-miss path held to llama.cpp's logits there too |
Speed against llama.cpp on the same card (RTX 4090, `--vram-cap` for the smaller budgets, 262,144 context,
no RAM cap, drafter on; llama.cpp with `--n-cpu-moe N` chosen to fit the same budget, no speculation). Decode
is a 1,200-token answer to a 2.4K prompt; prefill is a 32K prompt. Tokens/s, engine / llama.cpp:
| Budget | Q4_K_XL decode | Q4_K_XL prefill | IQ3_XXS decode | IQ3_XXS prefill |
| --- | --- | --- | --- | --- |
| 24 GB | 251 / 159 (1.6x) | 4,319 / 8,604 (0.50x) | 318 / 167 (1.9x) | 4,426 / 8,245 (0.54x) |
| 16 GB | 180 / 41 (4.4x) | 4,232 / 1,798 (2.4x) | 319 / 44 (7.3x) | 4,401 / 2,637 (1.7x) |
| 12 GB | 122 / 38 (3.3x) | 3,877 / 1,475 (2.6x) | 256 / 40 (6.4x) | 4,381 / 2,223 (2.0x) |
| 11 GB | 104 / 37 (2.8x) | 3,723 / 1,420 (2.6x) | 234 / 39 (6.1x) | 4,375 / 2,137 (2.1x) |
| 8 GB | 64 / 33 (2.0x) | 3,003 / 1,212 (2.5x) | 135 / 34 (4.0x) | 4,320 / 1,854 (2.3x) |
| 6 GB | 45 / 30 (1.5x) | 517 / 1,108 (0.47x) | 81 / 32 (2.5x) | 1,121 / 1,713 (0.65x) |
The llama.cpp 24 GB Q4_K_XL row is at 131,072 context; it does not load at 262,144 with every layer on the card.
Prompt processing is the weak side: with every expert resident llama.cpp is twice as fast, and at 6 GB the engine
spends the prompt copying experts to the card. Full tables, profiler windows and plots are in the regina
repository's `analysis/qwen36-35b-single-gpu-ladder/engine-4090/`.
On the GTX 1080 Ti (VM, 14 vCPU of a Ryzen 7 1700, 52 GB RAM), against llama.cpp on the same card and host
(`--n-cpu-moe N` at the lowest N that fits each budget, 8 threads, no speculation, the model file in RAM).
262,144 context on both sides. Tokens/s, engine / llama.cpp:
| Budget | Q4_K_XL decode | Q4_K_XL prefill 3.1K | Q4_K_XL prefill 32K | IQ3_XXS decode | IQ3_XXS prefill 3.1K | IQ3_XXS prefill 32K |
| --- | --- | --- | --- | --- | --- | --- |
| 11 GB (the card) | 66 / 28 (2.4x) | 941 / 570 (1.7x) | 462 / 545 (0.85x) | 81 / 33 (2.5x) | 910 / 904 (1.0x) | 453 / 714 (0.63x) |
| 8 GB (`--vram-cap 8192`) | 54 / 25 (2.1x) | 911 / 488 (1.9x) | 442 / 487 (0.91x) | 69 / 28 (2.5x) | 900 / 747 (1.2x) | 453 / 637 (0.71x) |
| 6 GB (`--vram-cap 6144`) | 42 / 24 (1.8x) | 361 / 452 (0.80x) | 265 / 460 (0.58x) | 55 / 24 (2.3x) | 748 / 614 (1.2x) | 437 / 562 (0.78x) |
Decode is 1.8 to 2.5 times llama.cpp; the GPU computes 85% of the decode window against llama.cpp's 39 to 45%.
A long prompt is slower than llama.cpp at every budget on this card. The draft head is worth a third of the decode
speed (49 tokens/s without drafts at Q4_K_XL on the full card). Tables and plots: regina
`analysis/qwen36-35b-single-gpu-ladder/engine-1080ti/` and `llama-1080ti-52g/`.
Speed, one run of each, same machine and model files, greedy sampling, reasoning off. Generation is the mean
of 8 different prompts of 400 tokens; prompt speed is the mean of 2 different prompts of about 20,000 tokens.
@@ -236,32 +114,19 @@ builds differ in compile flags and in how the n-gram table is held in RAM, and e
token. Upstream's tokenizer keeps it as plain text.
- Replies are not reproducible token for token between runs or between this fork and upstream, even with
greedy sampling, so "same output" cannot be checked by comparing text.
For Qwen3.6-35B-A3B the cause is traced: an expert the card does not hold is computed by a different
kernel on the CPU, and the cache keeps changing which experts those are for the first few requests; replies
diverge only where two tokens are within about 0.3 logits, and every state holds to llama.cpp's logits.
`--adapt-every 0 --suffix-draft 0` makes a request repeat token for token. `--pcie-frac 1.0` does too
only while a layer misses fewer than 16 experts per window; past that the rest are computed on the CPU.
- Qwen3.6-35B-A3B: between user turns the prompt cache reuses the previous prompt but not the previous reply,
because the model's template re-renders an earlier reply without its reasoning. Tool loops reuse nearly
everything (1,867 of 1,948 tokens in a pi session); `chat_template_kwargs.preserve_thinking` with
`reasoning_content` sent back reuses the reply too, at the cost of keeping old reasoning in context.
A tool call arrives as one delta, not streamed. Images are checked on one screenshot only, and not
against llama.cpp; the RTX 50 and Volta builds have not
run on a card. Prompt processing is slower than llama.cpp with every expert on the card, at 6 GB, and for long
prompts on a GTX 1080 Ti.
## Compared with upstream Strata (6f32ec0)
| | Upstream | This fork |
| --- | --- | --- |
| Engine source (`src/`, `include/`) | 272 files | 58 files changed for the Qwen3.6 port (the model geometry read from the GGUF, the plain-residual block, dense attention, the SiLU-gated DeltaNet, the expert kernels for the UD quantizations, the VRAM planner, the drafter pack) plus retrying reads from slow stores; docs/qwen36-port/ has the per-step notes |
| Build | clones llama.cpp during CMake | pinned submodule, fetches nothing; one patch, applied at configure time: tool-call arguments in any order (see UPSTREAM.md) |
| Engine source (`src/`, `include/`) | 272 files | two files changed, one added (retrying reads from slow stores); cutting it down is the next work |
| Build | clones llama.cpp during CMake | pinned submodule, fetches nothing; one patch, applied by `make build`: tool-call arguments in any order (see UPSTREAM.md) |
| Setup | Python installer downloads the model and builds the pack and draft head | none; files must already exist |
| Server | Python | C++, in the same binary (`frontend/`), with the image encoder from llama.cpp's `mtmd` |
| Python | 33,745 lines | 0 |
| C, C++ and CUDA | 208,254 lines (with tests and the Intel port) | 84,086 lines |
| Tracked files | 851, 27 MB | 292, 6 MB |
| Configurations | several models, NVIDIA, AMD and Intel, Linux and Windows, multi-GPU | two models, one NVIDIA card (Pascal to RTX 50), Linux |
| Configurations | several models, NVIDIA, AMD and Intel, Linux and Windows, multi-GPU | one |
## Credits and licence
+1 -48
View File
@@ -20,8 +20,7 @@ The first commit of this repository is the upstream snapshot as published. One f
- **Added:** `frontend/`, the C++ front end (tokenizer, chat template, output parser and HTTP API, using
llama.cpp's code from the submodule), and a build target that links it with the engine into one binary.
- **ggml / llama.cpp common (`third_party/llama.cpp`):** one change, kept as
`patches/llama.cpp-qwen3-coder-any-argument-order.patch`, applied to the submodule's working tree at CMake
configure time (and by `make build`); Qwen3.6's template routes to the same parser:
`patches/llama.cpp-qwen3-coder-any-argument-order.patch` and applied in the submodule's working tree:
the Qwen3-Coder tool-call grammar accepts a call's arguments in any order. Upstream requires the
required arguments first; Qwen3.8 Flash-Next often writes the optional ones first (`limit`, `offset`,
`path`), and because the grammar's tool-call group is optional and has no end anchor, such a call was
@@ -74,49 +73,3 @@ c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a mtp/dense.bin
b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91 mtp/draft_vocab.bin
09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f mtp/experts.bin
```
## Prepared files for Qwen3.6-35B-A3B
Made with this repository's own tools (Python 3 with `numpy`; `STRATA_GGUF_PY` at `third_party/llama.cpp/gguf-py`),
from unsloth's files: `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` and `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` of
[unsloth/Qwen3.6-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF), and the `-MTP` repository's
`Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (41 blocks; the draft block is `blk.40`) for the draft pack.
```
export STRATA_GGUF_PY=$PWD/third_party/llama.cpp/gguf-py
# the pack, one per model file (the tokenizer, the dense weights' index, the expert table, the route profile)
python3 -I tools/iq_pack.py --gguf Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --out qwen36-q4
python3 -I tools/iq_pack.py --gguf Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --out qwen36-iq3
cp data/qwen36-expert-profile.bin qwen36-q4/expert-profile.bin # tools/make_profile.py from the route trace
cp data/qwen36-expert-profile.bin qwen36-iq3/expert-profile.bin
# the draft pack, from the -MTP file's draft block; serves either trunk
python3 -I tools/mtp_qwen36_pack.py --gguf Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf --out qwen36-mtp-draft
```
`--draft-vocab none` leaves `draft_vocab.bin` out (the drafter then scores the whole vocabulary: a few percent
higher acceptance, 345 MiB more VRAM for the head). Building twice gives the same bytes. SHA-256:
```
9c964e657212fea1f24905dd7b0a89b82fd807d19fab0b41da14251b07b88fbe Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf
707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450 Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf
55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1 Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf (the -MTP repository's file)
7c20e11993ff853fe5698843d610b2a87927b04f9a4607551f4e023a39bc71ba qwen36-q4/conversions.json
53467f9b49bbc57d570eb8802125144dd4b4d7fd6a658d685ef72005d75a5f4f qwen36-q4/dense.bin
eb2ed6c8d86ebe0c16bb7a09af6c24fc4059627cc95e35def07c41568a30283c qwen36-q4/expert-profile.bin
1a4725f13e24691a3d6fd10dba4bb6cb217c4831ff8d5529865fc01f39413c79 qwen36-q4/index.txt
257d84e2d36a2e6572cd0dd8382283defe28bc07c2c97ece22ab6c1bd2f5bff4 qwen36-q4/native_experts.txt
39bf397e3fb8591ab84cb9142dbd43f665c3bff456e9772c47dc04db5ca28195 qwen36-iq3/conversions.json
53467f9b49bbc57d570eb8802125144dd4b4d7fd6a658d685ef72005d75a5f4f qwen36-iq3/dense.bin
eb2ed6c8d86ebe0c16bb7a09af6c24fc4059627cc95e35def07c41568a30283c qwen36-iq3/expert-profile.bin
685d475659736b415a5801413f116a4371970d3cb24b16e53625b98019895c73 qwen36-iq3/index.txt
820053214b08d3eab1378705fb7c345a724ed0fe16544df07b2f519423bb10e8 qwen36-iq3/native_experts.txt
4a93092f5716d289367b97ce107d8b08b2236a8e1954bc7f746881875c73d03a qwen36-mtp-draft/dense.bin
dd5990d0ef0926252cad59090fa1d00f138db2e3f316eb96691db83940cde339 qwen36-mtp-draft/dense.txt
b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91 qwen36-mtp-draft/draft_vocab.bin
9126741d7e98f0e470cd04bf7ce3c91a89c08c116af02aa2d8d666c4195fdb15 qwen36-mtp-draft/experts.bin
1e5ad8c088196bc95b49534ce68db9c278635c8a68f7b605ef1776589dea29d7 qwen36-mtp-draft/mtp.json
048604044d93d7dd4e4e1140deba8ccf681b5c7c11e330e9434a570af42bcfa2 qwen36-mtp-draft/native_experts.txt
```
(`dense.bin` is byte-identical between the two packs: the dense weights unsloth keeps unquantized are the same in
both files. The tokenizer directory's files are listed in `qwen36-*/index.txt`.)
-39
View File
@@ -1,39 +0,0 @@
# cmake/qwen36_attn_fixtures.cmake - the synthetic qwen35moe GGUFs at the engine's head_dim (256) and the oracle's
# dumps of their attention layer, for qsa_dense_parity (Qwen3.6 step 3, docs/qwen36-port/step3-attn.md).
#
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DOUT=<dir> -P cmake/qwen36_attn_fixtures.cmake
#
# Three fixtures, one per query-heads-per-KV-head the kernels are built for: g8 (16 / 2, Qwen3.6's ratio), g12
# (24 / 2, Flash-Next's), g2 (4 / 2, the oracle's own GQA case). Each: <OUT>/<name>.gguf and <OUT>/<name>-dump/
# with every seam of ref/qwen36.py on 40 tokens. Writes <OUT>/SKIP (and exits 0) when numpy or gguf-py is
# missing, so the test that needs the files skips (77) instead of passing on nothing.
file(MAKE_DIRECTORY "${OUT}")
set(_synth "${SOURCE_DIR}/tools/qwen36_synth_gguf.py")
set(_oracle "${SOURCE_DIR}/ref/qwen36.py")
set(_text "dense attention over sixteen heads, G=8!") # 40 ASCII tokens (the fixture's vocabulary is the byte set)
foreach(_case "g8;16,2;3" "g12;24,2;5" "g2;4,2;11")
list(GET _case 0 _name)
list(GET _case 1 _heads)
list(GET _case 2 _seed)
execute_process(COMMAND ${PYTHON} -I ${_synth} "${OUT}/${_name}.gguf" --heads ${_heads} --head-dim 256 --no-nextn
--seed ${_seed}
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
if(NOT _rc EQUAL 0)
message("${_out}${_err}")
if(_err MATCHES "ModuleNotFoundError" OR _out MATCHES "gguf-py" OR _err MATCHES "gguf-py")
message("qwen36_attn_fixtures: numpy or gguf-py is missing - skipping")
file(WRITE "${OUT}/SKIP" "${_out}${_err}")
return()
endif()
message(FATAL_ERROR "qwen36_attn_fixtures: ${_synth} ${_name} failed (${_rc})")
endif()
file(REMOVE_RECURSE "${OUT}/${_name}-dump")
execute_process(COMMAND ${PYTHON} -I ${_oracle} "${OUT}/${_name}.gguf" --text "${_text}" --dump "${OUT}/${_name}-dump"
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
if(NOT _rc EQUAL 0)
message("${_out}${_err}")
message(FATAL_ERROR "qwen36_attn_fixtures: ${_oracle} on ${_name} failed (${_rc})")
endif()
endforeach()
file(REMOVE "${OUT}/SKIP")
message("qwen36_attn_fixtures: 3 fixtures and their dumps in ${OUT}")
-28
View File
@@ -1,28 +0,0 @@
# cmake/qwen36_block_fixtures.cmake - the oracle's dumps of the synthetic qwen35moe file on a verify window's worth of
# tokens, for tests/cuda/qwen36_block_test.cpp (the plain block held to the dumps seam by seam).
#
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DSYNTH=<dir with toy.gguf> -DOUT=<dir> -P cmake/qwen36_block_fixtures.cmake
#
# Writes <OUT>/o8/<seam>.f32 and manifest.txt (ref/qwen36.py --dump) for 8 tokens ("hello wo": the fixture's vocabulary is
# the ASCII bytes). Exit 3 when numpy or the vendored gguf-py is missing (the SKIP marker, as qwen36_synth_fixtures.cmake).
file(MAKE_DIRECTORY "${OUT}")
if(EXISTS "${SYNTH}/SKIP" OR NOT EXISTS "${SYNTH}/toy.gguf")
file(WRITE "${OUT}/SKIP" "no synthetic fixture in ${SYNTH}")
message("qwen36_block_fixtures: no toy.gguf in ${SYNTH} - skipping")
return()
endif()
file(REMOVE_RECURSE "${OUT}/o8")
execute_process(COMMAND ${PYTHON} -I "${SOURCE_DIR}/ref/qwen36.py" "${SYNTH}/toy.gguf"
--tokens 104,101,108,108,111,32,119,111 --dump "${OUT}/o8"
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
if(NOT _rc EQUAL 0)
message("${_out}${_err}")
if(_err MATCHES "ModuleNotFoundError")
message("qwen36_block_fixtures: numpy or gguf-py is missing - skipping")
file(WRITE "${OUT}/SKIP" "${_err}")
return()
endif()
message(FATAL_ERROR "qwen36_block_fixtures: ref/qwen36.py failed (${_rc})")
endif()
file(REMOVE "${OUT}/SKIP")
message("qwen36_block_fixtures: dumps in ${OUT}/o8")
-35
View File
@@ -1,35 +0,0 @@
# cmake/qwen36_oracle_dumps.cmake - the Qwen3.6 kernel fixture and the oracle's seam dumps for the GPU parity tests.
#
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DOUT=<dir> -P cmake/qwen36_oracle_dumps.cmake
#
# Writes OUT/k.gguf with tools/qwen36_synth_gguf.py at the geometry the engine's CUDA GDN kernels are pinned to
# (state 128, 2 k-heads / 4 v-heads: VPK 2 like the real 16 / 32), the real router shape (256 experts, top-8), the
# shared expert at its real width (512) in Q8_0, and the weights the engine reads as BF16 already BF16-representable;
# then runs ref/qwen36.py on the 11-token "hello world" sequence twice: OUT/o_f32 (F32 activations) and OUT/o_q8
# (--act-quant q8: activations rounded to Q8 before every quantized matmul, as the engine's native MMVQ path does).
# Every tensor llama.cpp names with cb() lands in those directories as <name>.f32 (docs/qwen36-port/oracle-crosscheck.md).
#
# Exit 3 (and OUT/SKIP written) when numpy or the vendored gguf-py is missing, so the tests that need the files skip.
file(MAKE_DIRECTORY "${OUT}")
set(_synth "${SOURCE_DIR}/tools/qwen36_synth_gguf.py")
set(_oracle "${SOURCE_DIR}/ref/qwen36.py")
set(_tokens "104,101,108,108,111,32,119,111,114,108,100")
set(_step1 ${PYTHON} -I ${_synth} "${OUT}/k.gguf" --gdn 2,4,128 --experts 256,8 --shexp-ff 512 --quant-shexp q8_0 --bf16-exact --no-nextn)
set(_step2 ${PYTHON} -I ${_oracle} "${OUT}/k.gguf" --tokens ${_tokens} --dump "${OUT}/o_f32")
set(_step3 ${PYTHON} -I ${_oracle} "${OUT}/k.gguf" --tokens ${_tokens} --dump "${OUT}/o_q8" --act-quant q8)
foreach(_name _step1 _step2 _step3)
set(_cmd ${${_name}})
execute_process(COMMAND ${_cmd} RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
if(NOT _rc EQUAL 0)
message("${_out}${_err}")
if(_err MATCHES "ModuleNotFoundError" OR _err MATCHES "gguf-py was not found")
message("qwen36_oracle_dumps: numpy or gguf-py is missing - skipping")
file(WRITE "${OUT}/SKIP" "${_err}")
return()
endif()
message(FATAL_ERROR "qwen36_oracle_dumps: `${_cmd}` failed (${_rc})")
endif()
endforeach()
file(REMOVE "${OUT}/SKIP")
file(WRITE "${OUT}/tokens.txt" "${_tokens}\n")
message("qwen36_oracle_dumps: k.gguf, o_f32/, o_q8/ in ${OUT}")
-27
View File
@@ -1,27 +0,0 @@
# cmake/qwen36_synth_fixtures.cmake - writes the synthetic qwen35moe GGUFs the Qwen3.6 geometry tests read.
#
# cmake -DPYTHON=<python3 with numpy> -DSOURCE_DIR=<repo> -DOUT=<dir> -P cmake/qwen36_synth_fixtures.cmake
#
# Exit 3 when numpy or the vendored gguf-py is missing (a trimmed third_party): the tests that need the files skip.
cmake_policy(SET CMP0007 NEW) # keep the empty flag of "toy.gguf;" (cmake < 4 drops it and list(GET 1) fails)
file(MAKE_DIRECTORY "${OUT}")
set(_tool "${SOURCE_DIR}/tools/qwen36_synth_gguf.py")
foreach(_case "toy.gguf;" "toy-nonextn.gguf;--no-nextn" "toy-fused-gate-up.gguf;--fused-gate-up"
"toy-fused-qkv.gguf;--fused-qkv")
list(GET _case 0 _name)
list(GET _case 1 _flag)
execute_process(COMMAND ${PYTHON} -I ${_tool} "${OUT}/${_name}" ${_flag}
RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err)
if(NOT _rc EQUAL 0)
message("${_out}${_err}")
if(_err MATCHES "ModuleNotFoundError")
message("qwen36_synth_fixtures: numpy or gguf-py is missing - skipping")
# cmake -P cannot set the exit code directly: a FATAL_ERROR exits 1, so write the marker the test reads
file(WRITE "${OUT}/SKIP" "${_err}")
return()
endif()
message(FATAL_ERROR "qwen36_synth_fixtures: ${_tool} ${_flag} failed (${_rc})")
endif()
endforeach()
file(REMOVE "${OUT}/SKIP")
message("qwen36_synth_fixtures: 4 files in ${OUT}")
Binary file not shown.
-475
View File
@@ -1,475 +0,0 @@
# Plan: UnbiasedStrata on Qwen3.6-35B-A3B, any single NVIDIA card from Pascal up, 256K context
Written 2026-10-11, revised the same day three times: after reading
[Project Maya](https://github.com/mw00/project-maya); after the target widened from one card to a range;
after the llama.cpp-backend fallback was removed. Status: proposed, nothing started.
Engine base: this repository's Strata snapshot (`6f32ec0`, engine 0.1.39). Maya is a method reference only.
llama.cpp appears in two roles only: the external speed baseline (bare `llama-server`, never inside the
binary) and the numerical oracle for parity. There is no fallback path.
## 0. Target and what "adapt" means
**Target:** one NVIDIA GPU, compute capability 6.1 or newer (GTX 10 series through RTX 50), **6 GB to 32 GB**
of VRAM, Linux, x86-64 with AVX2. The engine sizes itself at start: fixed weights first, then the KV cache
for the requested context, then every remaining byte of VRAM becomes expert-cache slots. The same binary
and the same model files on every card; only speed differs. Q4 is the default quant. Context 262,144 where
it fits, never below 131,072 without saying so. **Multi-GPU is out of scope**; the front end already
refuses `--gpus`, and that stays.
The Strata engine in `src/` runs one architecture, Qwen3.8-Flash-Next (`qwen4_exp_text`). Qwen3.6-35B-A3B
(`qwen3_5_moe_text`) is the same family one generation earlier, with the extras removed. From the two
models' `config.json`:
| | Qwen3.8-Flash-Next (what the engine runs) | Qwen3.6-35B-A3B (the target) |
| --- | --- | --- |
| Hidden / layers | 2560 / 48 | 2048 / 40 |
| Layer pattern | 3 linear attention then 1 full attention (`full_attention_interval` 4) | the same |
| Linear attention (GDN) | 16 k-heads, 48 v-heads, 128-dim, conv 4 | 16 k-heads, **32** v-heads, 128-dim, conv 4 |
| Full attention | 24 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **plus a sparse indexer (QSA)** | 16 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **dense** |
| MoE | 512 experts, top-10, intermediate 640, shared 640 | 256 experts, top-8, intermediate 512, shared 512 |
| Residual | hyper-connections (`hc` 4 streams) | plain residual |
| PLE / n-gram table | yes (28.8 GB shard 2) | none |
| MTP | 1 draft layer | 1 draft layer |
| Vocabulary | 248,320 | 248,320, the same tokenizer |
| Context | 262K | 262K native |
Everything Qwen3.6 has, the engine has a kernel for; what it lacks, the engine treats as optional (PLE) or
needs a bypass for (hyper-connections, the QSA indexer). Maya's port study (`docs/GLM5-FLASH.md` in that
repo) crossed a larger *kernel* gap for GLM-5.3-Flash in about a week: study 2026-09-29, verified
streaming runner 2026-10-01, v1.0.0 on 2026-10-07. The Qwen3.6 kernel gap is smaller (no MLA, no sparse
indexer to write, no manifold hyper-connections, a SiLU-for-sigmoid change in the GDN gate). The
*plumbing* gap is not small: `docs/qwen36-port/geometry-inventory.md` (154 rows, 2026-10-11) shows the
hc = 4 gated residual and the QSA indexer assumed structurally in every block, the output head, the
verify window, the MTP drafter and prefill; prefill refusing any geometry but 2560/4/320/top-10; native
packs decoding only through the verify window; and `ModelGeometry` reading only the expert counts and
rope keys from the file. Expect Maya-scale work, with the risk in plumbing rather than kernels.
**The deliverable:** this tree's engine running Qwen3.6-35B-A3B natively, by Maya's method, behind the
existing front end (`frontend/`: OpenAI API, tokenizer, chat template, tool-call parser, vision), which is
model-agnostic and stays. The payoff is what llama.cpp's `--n-cpu-moe` cannot do: hot experts cached in
VRAM by usage across all layers, the CPU computing the misses concurrently with the GPU, instead of whole
layers' experts on the CPU serially. On a 6 GB card that is the difference between a cache holding the
hottest 7% of experts and a layer cut holding none.
Hypotheses:
- **H1.** Under llama.cpp `--n-cpu-moe N` the GPU is idle most of each decode step, and the idle share
grows with N, so it is worst on the smallest cards. (The baseline sweep measures it.)
- **H2.** The idle is CPU expert matmul, not PCIe transfer.
- **H3.** 256K context fits at Q4 on every card of 11 GB or more; 128K fits on 8 GB; 6 GB at Q4 holds
the 256K fixed set only when prefill borrows cache slots, else it takes 131K or the IQ3 file, and the
engine must say which it chose.
- **H4.** Qwen3.6's routing is skewed enough that a VRAM expert cache serves well above its slot fraction
of routes at every budget from 6 GB up. The replay measures the whole curve before any CUDA.
- **H5.** The ported engine's decode scales as `1 / max(cpu, gpu)` rather than `1 / (cpu + gpu)`, and beats
the llama.cpp baseline at every VRAM budget, by the most at the small end.
- **H6.** With 12 GiB of RAM beside the 1080 Ti, Q4 reaches the disk tier and the profile-ranked VRAM
and RAM tiers keep disk reads under one expert per token on a warm conversation; IQ3 never reaches the
disk. The replay with three tiers predicts this; the engine's tier counters confirm it.
H4 and H5 are not a go/no-go for building the engine; the port is the deliverable regardless. They decide
how the README describes the result and where the expert-cache tuning effort goes.
**Measured on 2026-10-11 (Phase 0; details in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`):**
| | Q4_K_XL at 11 GB | IQ3_XXS at 11 GB |
| --- | --- | --- |
| llama.cpp, 256K, fit edge (`--n-cpu-moe` 32 / 18), smoke test, cold cache, 400 tokens | 8.8 tok/s decode, 129 prefill, GPU busy 15% | 24.6 tok/s decode, 434 prefill, GPU busy 41% |
| llama.cpp, the sweep (warm, 1,200 tokens, `baseline-1080ti.md`) | **the number to beat: N = 30, the lowest N that fits (10,415 MiB): 13.4 tok/s decode on the regina request, 16.3 on the short one.** At N = 32: 13.5 / 12.2, 152 prefill; nvprof at N = 32: busy 13.8%, memcpy 0.6%, gaps 86%; warm nvprof at N = 30: busy 15.0%, memcpy 0.6%, 3.1 MiB of activations per token over PCIe; 14 to 21 MiB per token from disk | 33.5 tok/s decode, 907 prefill; GPU busy 56% (nvidia-smi); warm nvprof at N = 20: busy 24.8% under a 2.1x profiler slowdown, memcpy 0.8%; no disk reads |
| Sweep slope | 0.67 to 0.93 points of GPU busy and 0.5 to 0.7 tok/s per layer moved to the CPU (the N = 32 point was the first run and carried steal) | one point and 0.58 tok/s per layer |
| Route trace, top 40% of experts per layer | 76% of routes (215K routed tokens) | |
| Replay at the censused sizes, LFU with 3 spares per layer, prefill borrowing cache slots | 78 slots per layer: 83.2% hit, 36.6 RAM and 17.0 disk reads per token | 149 slots: 95.4% hit, 14.6 RAM and 0 disk reads |
| Replay, no borrowing (prompt buffer held in VRAM) | 52 slots: 72.2% hit, 35.8 disk reads | 103 slots: 89.4% hit, 0 disk reads |
| Predicted decode, overlap / serial (gpu 17 ms, CPU lane 0.15 ms per expert, disk 1.3 ms; parameters, not measurements), borrowing | 36.2 / 22.4 tok/s | 58.8 / 52.1 tok/s |
Readings: H1 holds (the GPU idles 86% of each Q4 step by the kernel timeline, 44% at IQ3). H2 holds (memcpy is 0.6% of the window; the idle is CPU matmul and, at Q4, page-ins). H4 holds (83% hit from 35% of the
experts). With 12 GiB of RAM the Q4 arm is disk-limited (17 disk reads per token, about 22 ms, more than
the whole GPU step), so on this rung IQ3 is the quant that reaches the GPU ceiling and Q4 needs either
16 GiB of RAM or 12 GB of VRAM. Prefill borrowing cache slots is worth 11 points of hit rate at Q4. Prefill hit rates are linear in slots (a prompt touches nearly every
expert per layer per ubatch), so prompts stream experts over PCIe, as Strata already does. The overlap
column saturates at `1000 / gpu_ms`; the GPU step itself is the next thing to measure properly (nvprof,
in the sweep).
## 1. The card ladder
Real cards in the homelab cover the range, with Pascal at three sizes:
| Budget | Card | Where | Arch | Role |
| --- | --- | --- | --- | --- |
| 6 GB | GTX 1060 | g7 (192.168.50.185), laptop | sm_61 | the floor; regina's `g7/README.md` has llama.cpp numbers here already |
| 8 GB | GTX 1070 Ti | host .4 (`llama-qwen36-35b-mtp.service`, live) | sm_61 | second Pascal point |
| 11 GB | GTX 1080 Ti | .57 at PCI `2a:00`, in **VM 211 `gpu-qwen36`** at 192.168.50.43 (cloned from 210 on 2026-10-11: 8 vCPU, 12 GiB, 100 GB on `local-lvm`, Debian 13, driver 550, CUDA 12.4, gcc-13) | sm_61 | the primary measurement card, and the development card until a pod is rented |
| 32 GB, rented | A6000 or similar on RunPod | on demand; this fork was already checked on a RunPod 3090 container (README) | sm_86 | only for the 32 GB rung and if the 4090 becomes busy again; the user has approved spending on this |
| 24 GB | RTX 4090 | VM 221 (192.168.50.151) on pve2: 16 vCPU, 62 GB RAM, CUDA 12.4, driver 550; root disk nearly full (build trees under `/models/work`, 174 GB free); system gcc is 14, so builds need gcc-13 as the host compiler | sm_89 | **idle since 2026-10-11 17:20, the user's call: the fast-compile development card for Phase 2 steps 3 to 5 and the 24 GB rung.** Both llama-server units there are inactive; leave them so. No RunPod needed while it stays free |
| 12, 16, 32 GB | RTX A6000 (48 GB) **capped** | VM 220 (192.168.50.8) on .57 | sm_86 | **in use by another agent**; the emulated rungs wait for it |
The cap is Maya's `STRATA_GLM_VRAM_GB` idea: the engine limits its own total VRAM so the expert pool gets
what a card of that size would leave it. It is built in Phase 2 step 2; the 1080 Ti emulates the 6 and 8 GB
rungs with it (the real 1060 and 1070 Ti then check launch failures, FP16 paths and PCIe), and the A6000
emulates 12, 16 and 32 GB whenever it is free.
Consequence of the 1080 Ti being the only local card: **the Pascal build comes first, not last.** Every
parity harness and the streaming runner are brought up under `STRATA_EXPERIMENTAL_SM60=ON` on sm_61 from
the start, so Pascal surprises surface in the first week. The rented sm_86 pod runs the same harnesses in
parallel for fast iteration; a kernel passes when it passes on both.
Constraints across the ladder:
| | |
| --- | --- |
| CUDA | one toolkit that compiles sm_61 and sm_120 both: **CUDA 12.8** (12.x is the last with Pascal; 13 dropped it). Upstream saw RTX 50 crashes with 12.8-built engines (issues #220, #224), so RTX 50 is "built, not measured" until a card exists here. Fat binary `CUDA_ARCHS=61;70;75;86;89;120` |
| Pascal specifics | dp4a exists on sm_61 (not sm_60, which gets the shim); no tensor cores; no `__nanosleep`; FP16 math at 1/64 rate on GP102/GP104/GP106, so every kernel's *arithmetic* on these cards must be FP32 or dp4a int8 (fp16 *storage* with conversion, as in the KV pools and prefill's stores, is full rate and stays); the prompt MoE's dp4a MMQ path must be enabled on sm_61. Strata refuses sm < 75 unless `STRATA_EXPERIMENTAL_SM60=ON`; that flag becomes the default build (Phase 2, step 6). Nobody has run this engine on Pascal; Maya requires Volta or newer |
| Build verification | `cuobjdump --list-elf \| grep sm_` after every build; two past incidents here were wrong-arch binaries |
| Profilers | current Nsight Systems: Turing and newer only. Nsight Compute: no Pascal since 2019.5. On Pascal use the `nsys` bundled with CUDA 12.x (2023.x) or `nvprof`; on Turing and newer current `nsys`. Same analysis script either way |
| .57 host | Ryzen 7 1700 (Zen 1, AVX2, no AVX-512), 62 GiB usable DDR4-2133. Checked 2026-10-11: VM 220 shrunk to 36 GiB by another agent, host 18 GiB available before VM 211, about 6 GiB after. The 1080 Ti's link is **Gen3 x8** (`LnkSta: 8GT/s, Width x8`), so the June Gen1 problem is gone. VM 220 shares the memory bandwidth and the 8 physical cores (VM 220 has 12 vCPU, VM 211 has 8: oversubscribed when both are busy), so each run's metadata records VM 220's load and measurement windows prefer its idle hours |
| Stale pointer | `docs/NEW-GPU-VM.md` says "both GTX 1080 Ti"; slot 29:00 now holds the A6000 |
## 2. Models, the memory hierarchy, and the budget table the engine must reproduce at start
**Decision 2026-10-13 (step 5, the user):** the hierarchy is two tiers, VRAM plus host RAM, assumed to hold the
expert set; spilling to the NVMe is out of scope. Measured on the 1080 Ti at Q4_K_XL: 52 tok/s with the set
pinned in the VM's 35 GB, 12 to 15 tok/s under a 12 GiB bound (disk-bound, the replay's prediction; llama.cpp
13.4). The README states the RAM a card needs per quantization; the 12 GiB rows below are kept as the measured
cost of breaking the assumption, not as a supported rung. H6 and the disk-read instruments are therefore
informational.
**The hierarchy on the primary rung is three tiers, by the user's decision:** 11 GB of VRAM in the 1080 Ti,
about 12 GiB of VM RAM (roughly 9 to 10 GB usable for a pinned expert tier after the OS, the process and
the KV), then the VM's NVMe disk for the rest. Strata already has the pieces: the VRAM expert cache, the
pinned RAM tier, and the low-RAM modes (`--mmap-experts` serving misses from the model file through the
page cache; `--resident-experts` copying exactly the non-VRAM experts into RAM when they fit). At Q4 they
do not all fit in 12 GiB, so the mapped mode and the disk are in play; at IQ3_XXS the whole expert set fits
VRAM plus RAM. Every per-budget number below is therefore a pair: where the experts live, and how many
reads per token reach the disk.
| Arm | File | Size | Where it already is |
| --- | --- | --- | --- |
| **Q4, default** | `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (unsloth, repo commit `a483e9e`) | ~21 GB | not on hand; download once on the Mac, SHA-256 against the repo, copy over LAN |
| Q4 + MTP | `Qwen3.6-35B-A3B-UD-Q4_K_M-MTP.gguf` | 22.66 GB | `.4:/mnt/models/qwen3.6/MTP/`, Mac `~/models/qwen3.6/MTP/` |
| Q3 | `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | 13.21 GB | `.4`, `.151:/models`, g7 `/home/rk/models` |
K-quants for the default because most experts run on the CPU on most of the ladder, and K-quant dot
products are the fast AVX2 path. The engine needs the MTP block: Strata's draft protocol is built around
the model's own MTP layer. Settled on 2026-10-11: the `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` from unsloth's MTP
repository (rev 5bc3e238) already carries the draft block as `blk.40` (753 tensors), so it is the default
file, and its `blk.40` serves as the draft pack for the IQ3 arm too (the plain IQ3 file has no draft block).
Fixed VRAM before any expert slot. Measured and censused on 2026-10-11; the authoritative table is
`docs/QWEN36-35B-A3B.md` section 4.1, summarized:
| Item | Q4_K_XL | IQ3_XXS |
| --- | --- | --- |
| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB |
| Draft block (dense 40 MiB + its experts + ring KV + logits) | ~520 MiB | ~520 MiB (the Q4 file's) |
| KV, q4_0, 10 attention layers, 262K | 1,440 MiB | 1,440 MiB |
| Session, CUDA context, reserve | ~0.7 to 1.2 GB | same |
| Prompt buffers | 0 when prefill borrows cache slots (a profile exists); 1,904 MiB at chunk 2048 otherwise | 0 / 1,878 MiB |
| **Decode-time fixed set at 262K** | **~4.8 GB borrowing, ~6.7 without** | **~4.3 / ~6.2** |
| Trunk experts, total / per expert (mean, max) | 18,726 MiB / 1.83 MiB, 2.20 max | 10,594 MiB / 1.04 MiB, 1.17 max |
What each budget leaves for experts at Q4, 262K (the llama.cpp layer cut on the right is the baseline's
equivalent, for the comparison only):
| Budget | Q4 expert slots in VRAM, prefill borrowing (of 10,240) | IQ3 slots | `--n-cpu-moe` equivalent |
| --- | --- | --- | --- |
| 6 GB | ~525 (5%); without borrowing the fixed set does not fit at 262K, so 131K or the IQ3 file | ~1,350 (13%) | 40 (all) |
| 8 GB | ~1,570 (15%) | ~3,200 (31%) | ~37 |
| 11 GB (the 1080 Ti, 11,264 MiB), 12 GiB RAM, NVMe | ~3,550 (35%) in VRAM; ~4,950 (48%) pinned in RAM; ~1,740 (17%) on disk | ~6,700 (66%) in VRAM, the rest in RAM, no disk tier | ~32 (llama.cpp's CPU experts at Q4 exceed 12 GiB, so its baseline on this rung is page-cache bound too) |
| 12 GB | ~3,650 (36%) | ~6,880 (67%) | ~31 |
| 16 GB | ~5,740 (56%) | all | ~26 |
| 24 GB | all, ~1 GB spare | all | 0 |
| 32 GB | all; the spare VRAM goes to f16 KV or a bigger prompt chunk | all | 0 |
The sizing rule the engine implements (Phase 2, step 2): take the fixed total for the requested context;
if it does not fit, lower the context toward 131,072, then refuse with the exact numbers and the IQ3 file's
name. **KV streaming is not a lever for this model**: Strata streams by resolving the *selected* cells, and
dense attention selects every cell (study, 3.3 item 6), so the KV stays in VRAM. Never silently pick a
shorter context. Then the RAM tier: free RAM minus a headroom for the OS and the KV
stream, filled with the next experts by profile rank; whatever remains stays mapped from the GGUF on disk
and is read on a miss. The start-up log states all three counts.
CPU-side ceiling for the misses: ~12 MiB of expert weight per CPU-computed layer-token at Q4. On the .57
host (DDR4-2133, ~30 GB/s) that is ~60 to 70 tok/s before compute; Zen 1's 8 cores will be the lower
bound. Prior Pascal data: GTX 1060 6 GB, IQ3_XXS, N = 32: 16 tok/s at 8K depth, 11 at 32K, 355 tok/s
prefill, all llama.cpp.
## 3. Phase 0: environment, baseline, and the replay
Human steps (Proxmox state is the user's):
1. (Decided: VM 220 stays up; host RAM already freed for a 12 GiB VM.)
2. (Done 2026-10-11.) VM 211 `gpu-qwen36`, a full clone of VM 210: **8 vCPU, 12 GiB RAM, balloon 0,
100 GB on `local-lvm` (NVMe)**, `--hostpci0 0000:2a:00,pcie=1`. No `rombar=0`: that was needed only
for the boot-VGA card at 29:00 (homelab ticket 002); the 1080 Ti at 2a:00 never needed it. VM 220
keeps running. The disk is the third tier, so `fio` its read throughput and 4K random latency once,
into `phase0-notes.md`.
3. Inside the VM: pin the kernel/driver pair, install `build-essential cmake nvtop linux-perf`, CUDA 12.8
(the template has 12.4; 12.8 needs a 570-series driver, still a Pascal-capable branch), confirm
`nvidia-smi`, check `LnkSta`, set `perf_event_paranoid` to 1.
4. Copy the GGUFs over LAN; `sha256sum` each.
Agent steps (fresh sonnet agent; brief = this section plus the hosts):
5. Build bare `llama-server` at the submodule's pinned commit `3cf0325`, `-DGGML_CUDA=ON`, arches
`61;86;89`, static; verify with `cuobjdump`. Also the latest release (v0.6.0) for its MTP arm. One
build per rung, each verified for its own arch. This binary is the baseline and the oracle, nothing
else.
6. Profiler check on the 1080 Ti: CUDA 12.x `nsys status -e`, a 10-second `nsys profile -t cuda` of
`llama-bench`, `nvprof --print-gpu-trace` as fallback. Record which works.
7. Smoke test at 256K on the 1080 Ti with `llama-server`: `-ngl 99 --n-cpu-moe 32 -fa on -c 262144
-ctk q4_0 -ctv q4_0 -b 2048 -ub 2048 --parallel 1 --cache-ram 0 -lv 4 -t 8`. Save the `-lv 4` buffer
lines; they replace the estimates in Section 2.
**The baseline sweep (sonnet to drive, haiku to monitor).** Regina's harness (`scripts/sweep_ncpumoe.py`,
`plot_ncpumoe_sweep.py`): the N sweep with VRAM (`nvidia-smi` and `-lv 4`), host RAM (`RssFile`), prefill
and decode from `timings`, one real launch per point. One env spec per card; the A6000 budgets via
`CUDA_VISIBLE_DEVICES` plus a side process holding the surplus VRAM. Regina's hygiene: 30 s settle, drop
caches, warmup discarded, `--cache-ram 0`, `--parallel 1`. Workload per point: the Opus system prompt
(~27K tokens) + "implement Minesweeper", `n_predict 800`, plus one 3K-prefill / 1200-decode request.
Reasoning off, `temp 0`, `seed 42`.
Instruments, logged per run (the same three serve the engine later):
- **Level 0, always:** `nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used,power.draw
--format=csv -lms 100`. `utilization.gpu` is the GPU-busy share at 100 ms resolution. nvtop in a tmux
pane is for the human, not the record.
- **Level 1, per point:** a decode-phase kernel timeline (`nsys` or `nvprof`). A script computes busy
fraction, gap histogram, memcpy vs kernel share (the H2 test), per-token period, profiler overhead.
- **Level 2:** `perf stat` on the server PID, so gaps match CPU time in ggml matmul threads.
- **Timeline videos, prefill and decode (added 2026-10-13, the user's standing requirement).** For the
engine and for llama.cpp, on the 1080 Ti and the 4090, a real-time video of the request's timeline in the
style of `~/projects/ub-strata/strata.mp4`: lanes for CPU cores used (100 ms per-core `/proc/stat`
samples), GPU kernels, PCIe H2D / D2H bytes and GPU copy / idle, a playhead, the engine-reported tok/s
on completion, and the busy fraction stated both with and without the engine's host-wait spin kernel.
Two windows per point: the **prefill** of a long prompt (the regina request's 3.1K prompt, and a 32K
prompt where the budget allows) and the **decode** of the short request. Stacked engine-over-llama.cpp
comparisons at the fit edges. The traces come from the same nsys / nvprof captures as Level 1, so the
profiled request must cover the prefill as well as the decode. Pipeline: `scripts/decode_video_json.py`,
`scripts/decode_video_render.swift`, `scripts/render_decode_videos.sh` in regina (adapted from
`~/Code/strata-workspace/strata-investigation`); output under
`analysis/qwen36-35b-single-gpu-ladder/video/` with a README carrying the method's honesty statements.
| # | Where | Arm | N values | ctx | Question |
| --- | --- | --- | --- | --- | --- |
| B1 | 1080 Ti | Q4 | fit edge, +2, +4, +8, 40 | 262144 | H1, H3 on the primary card; with 12 GiB of RAM the CPU experts page from disk, so `RssFile` and disk reads are recorded per point |
| B1b | 1060, 1070 Ti, 4090, A6000 at 12/16/32 | Q4 | the fit edge for that budget, and 40 | 262144, or 131072 where 262K does not fit | the baseline row of the ladder table |
| B2 | 1080 Ti | Q4 | fixed N | 262144 | depth 8K, 32K, 128K |
| B3 | 1080 Ti, 1060 | Q3 | fit edge, +4, +8, 40 | 262144 | K-quant vs i-quant CPU cost; the 6 GB default |
| B4 | 1080 Ti | Q4 + MTP | fixed N | 262144 | multi-token verify on CPU experts (llama.cpp's MTP) |
B1, B1b and B3 are the baseline. B2 and B4 run when a card is idle. File-based drivers under `tmux`,
`DRIVER_DONE` markers. B1 takes 2 to 4 hours at 256K context.
**E0, the route trace and cache replay (sonnet agent; any GPU host, even the Mac).** From Maya; it
answers H4 for the whole ladder before any CUDA and it produces the expert profile the engine loads:
8. Record routes: a small patch to llama.cpp's `examples/eval-callback` writing one line per token and MoE
layer with the 8 selected expert ids (`ffn_moe_topk`). Corpus: regina's coding tasks, the Opus system
prompt, a few long chats; ~200K routed tokens.
9. Replay: adapt Maya's `tools/glm_tier_replay.py` (MIT; models LFU residents + spares + the CPU-lane
pick) to 40 layers × 256 experts **and three tiers** (VRAM slots, RAM slots, disk), and sweep the VRAM
slot count from 0 to 10,240 landing on each budget from Section 2, at Q4 and IQ3, with the RAM tier
fixed at what 12 GiB leaves. Policies: LFU, LRU, Belady ceiling.
10. Output: `phase0-replay.md` with VRAM hits, RAM hits and disk reads per token **vs slots**, the seven
budgets marked, and the predicted engine decode ceiling per budget against the baseline, using the
measured disk latency from step 2 for the disk term. The trace also seeds `expert-profile.bin`.
Exit criteria: the baseline ladder row with the 1080 Ti's full N sweep; a working profiler on Pascal; the
hit-rate curve with the budgets marked; Section 2's estimates replaced by measured buffer sizes.
## 4. Phase 1: images and the baseline write-up
Under `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`:
1. `gpu-busy-vs-N.png`: Level-1 busy fraction and Level-0 utilization vs N on the 1080 Ti, both arms. H1.
2. `timeline-N<k>.png`: a 200 ms strip of one decode step, kernels vs memcpys vs gaps. H2.
3. `ladder-baseline.png`: decode and prefill vs VRAM budget (6, 8, 11, 12, 16, 24, 32), llama.cpp at the
fit edge. The engine's points go on the same axes in Phase 2 step 5. The headline image.
4. `vram-vs-N.png`: VRAM vs N with the budget lines and the 262K/131K KV points.
5. `dmon-strip-N<k>.png`: the raw 100 ms trace over prefill then decode.
6. `replay-hitrate-vs-slots.png`: hit rate vs slots per policy, budgets marked. H4.
Analysis reads the PNGs and CSVs. The write-up answers with numbers: busy fraction and its slope in N;
memcpy vs gap; the default quant per budget; the baseline ladder row; the simulated hit rate per budget
and the predicted engine gain, largest-to-smallest card. A fresh agent reviews it, given the data but not
the conclusion. This write-up is what the engine must beat; it does not decide whether the engine is built.
## 5. Phase 2: the engine port, Maya's recipe on a smaller gap
The design document for this phase is `docs/QWEN36-35B-A3B.md` (2026-10-11): the model exactly from the
real GGUF's metadata, the component-by-component gap analysis with file:line citations, the memory plan
with the censused fixed set, the ladder, the envelope, the execution plan with effort weights (step 2
15%, step 3 45%, step 4 20%, step 5 10%, step 6 5%, step 7 5%) and the risks. Where it and this plan
differed, the plan was corrected to the study on 2026-10-11 (its section 8 lists the eight points).
Where: step 2 on VM 211 (the 1080 Ti, the Pascal build from the first step, Section 1). From step 3 on,
kernel work and parity iterate on the 4090 in VM 221 (sm_89, idle since 2026-10-11) and every kernel
also passes on the 1080 Ti before its step closes; the 4090 is also the 24 GB rung for step 5. Each step has a parity harness in Strata's negative-test discipline (every wrong reading must
differ materially before the right one is judged), as Maya's section 6 did. Steps 1 to 4 need no GPU time
beyond seconds of parity runs, so they proceed while the Phase 0 sweeps hold the cards.
1. **Oracle and fixture (sonnet, no GPU).** Found on 2026-10-11 (`docs/qwen36-port/upstream-tooling.md`):
upstream never published its Python oracles (`ref/` holds only `load.py`; `gdn.py`, `moe.py`,
`qsa.py`, `docs/semantics.md` are cited but absent), most parity tests carry a host C++ reference
inside the test file, two embed generated `.inc` vectors, and the ggml-oracle tests link a llama.cpp
build through `STRATA_ORACLE_SOURCE_DIR`. So: `tools/` and `tests/` restored from the import commit `12a7825`
(done, commit c00942d: development tooling only, the binary still needs no Python), then write `ref/qwen36.py` new on `ref/load.py`, following the submodule's
`qwen35moe.cpp` graph with dumps named by its `cb()` calls; `tools/qwen36_synth_gguf.py` from
`test_iq_pack.py`'s `write_gguf()`; invariant tests (top-8 renormalization, GDN state shapes, the
output gate). Cross-check with the submodule's `llama-eval-callback` on the same synthetic GGUF.
One model difference already known: Flash-Next's GDN output norm gates with sigmoid(z), `qwen35moe`
with SiLU(z); `gdn.cu` and `gdn_parity` encode the sigmoid reading, so that is the first negative
test. `make_profile.py` hardcodes 48 layers and 512 experts; the MTP tools hardcode Flash-Next tensor
names; `iq_pack.py`'s `FORM` table has no `qwen35moe` entry. Dependencies: numpy, regex, gguf-py; no
torch, no GPU.
**Done 2026-10-11 on branch `qwen36-oracle`** (commits 9630539, f1ef81d, 0c850c3, 2094992, unmerged):
the oracle matches llama.cpp's own graph on 2,155 comparisons across 14 cases (max abs error 1.1e-4,
identical top-k everywhere, the nextn block included); seven rival readings each fail; 21 invariant
tests (24 after review). Independent review: no blockers; the GQA fixture (4 query heads over 2 KV
heads) added after review and matching on every seam; `ref/load.py`'s dequant bit-identical to ggml's
for Q6_K, IQ2_S, IQ3_XXS and IQ4_XS. **Tolerance policy** (`docs/qwen36-port/oracle-crosscheck.md`):
the oracle has a Q8 activation mode (`--act-quant q8`) and a per-layer protocol (`--force-topk`,
`--force-inputs`) that starts each layer from llama.cpp's inputs; against that, the per-seam relative
spread on the real file is 5e-8 (norm), 7e-7 (qkv), 8e-5 (gdn_out), 1.1e-4 (attn_out), 2.3e-3
(moe_out), 4e-7 (logits). Those are the kernel parity tolerances. Without forcing, errors compound
5 to 30 times and about half the top-k slots flip, so exact top-k agreement stays an F32-fixture-only
test. Branch commits after review: e452c51, 0e5344d, 44b0619. Real-file facts the engine
needs: the plain GGUF has no nextn block (only the `-MTP` files do, as block 40); nothing is fused;
the router, `ssm_alpha`, `ssm_beta` are F32; down experts are IQ3_XXS in 37 layers and IQ4_XS in
layers 34, 38, 39; the untied 2048 × 248,320 head is Q6_K.
2. **Geometry, metadata, sizing (default model).** Per the inventory: `ModelGeometry` is a set of
Flash-Next defaults; only `qwen4exp.expert_count`, `expert_used_count` and the rope keys are read, and
`check_architecture` rejects anything but `qwen4exp`. So: read every field of `ModelGeometry` from
the `qwen35moe.*` keys (hidden, layers, head counts, `ssm.*`, `n_ff`, interval); add `hc = 1` as "no
gated residual" with a plain-residual path and the `attn_norm` / `post_attention_norm` /
`output_norm` tensors the engine never references today; fix the one leak in the native expert path
(`expert_layout.cpp:284` passes compile-time 2560/640 to `native_fmt`); make `--ple-gguf` optional at
the command line (the kernels already allow no PLE); refuse llama.cpp's fused `ffn_gate_up_exps` and
`attn_qkv` forms by name (no shipped Qwen3.6 file uses them; the oracle's fused cases document the
layouts if one appears); the draft geometry follows the target; the draft vocab size comes from the
pack. The per-layer prefetch hints already exist (`FileExpertSource::warm`, `MADV_WILLNEED` on
predicted ids): verify they fire on the Qwen3.6 pack's offsets rather than porting Maya's. **The VRAM planner:** free VRAM minus the fixed set for the requested
context; KV streaming engaged when the fixed set does not fit (`--kv-resident`); the context lowered
toward 131,072 only after that; a refusal with numbers below it; the remainder becomes expert slots;
then the RAM tier from free RAM minus headroom (`--resident-experts` machinery), the rest mapped
from disk (the existing `--mmap-experts` source with its `MADV_WILLNEED` warm); `--vram-cap` and
`--ram-cap` for emulation. This step is what makes "6 GB to 32 GB" one binary, and it is where the
engine's tier counters (VRAM, RAM, disk reads per token) are exposed in the log and on `/health`.
3. **Kernels and the block (default model).** In order of risk, each with a parity harness:
- the GDN mixer: head pairing `h % h_k` already handles 32 v-heads against 16 k-heads; the gate
changes from sigmoid(z) to SiLU(z) in four kernels (`gdn.cu`, `fused_gdn.cu`,
`native_gdn_preprocess.cu`, the prefill GDN kernels), with the sigmoid reading as the negative test;
- the full-attention layer as *dense* attention: the decode kernel reads KV through an index list and
does not care how the list was built, so a "select every cell" producer replaces the indexer; the
kernels fixed at 12 query heads per KV head (Qwen3.6 has 8) and the short-context kernel fixed at
24 heads become parameters; the prompt path is `qsa_prompt_attn.cu` (on Pascal, the batched decode
kernel), parameterized the same way; `native_flash_attn.cu` is a 256-cell diagnostic adapter, not a
fallback;
- the router at top-8 over 256 (generic already; parity at the selection boundary) and the shared
expert at 512 (its Q8_K rule needs a multiple of 256, which 512 satisfies);
- the block without hyper-connections: `layer.cpp` *and* `verify.cpp`, because native packs decode
only through the verify window, and that window requires the fused hc kernels (fixed at
2560/4/320), top-10 and the native indexer today;
- prefill: `Prefill::init` refuses anything but 2560/4/320/10 and its GDN, split-q, route and MoE
kernels carry literals (48 v-heads, 24 heads, 1280, 640, top-10); parameterize or fork them.
Then the layer composition test: one GDN+MoE and one attention+MoE layer against the oracle's dumps.
The canonical Q2_0 CPU expert kernel bakes Flash-Next's shapes; Qwen3.6 rides the native pack path
(per-layer runtime geometry, ggml dot products, Unsloth's Q4_K/Q5_K types already included), as the
Coder with its 256 experts per layer does.
4. **Pack and runner.** `iq_pack.py` taught `qwen35moe` and its BF16-preserve list; the MTP head: the
engine's drafter reads its own Q8_0 directory with vLLM-style names, canonical Q2_0 experts at
2560/640 and the default geometry, and Qwen3.6's single `nextn.eh_proj` over the concatenated
embedding and hidden state does not match the two separate projections it expects, so the drafter
needs a Qwen3.6 pack format and a small graph change (Maya's `mtp_gguf.py` is the model);
`make_profile.py` (hardcoded 48 × 512 today) from the E0 trace;
the streaming runner held to the oracle at every position of a short sequence; then the real Q4 file
end to end, greedy, compared with llama.cpp's output distribution (not token-for-token; the README's
known-problems entry says why).
5. **Serve and measure on the 1080 Ti at 11 GB, then capped to 8 and 6; the 12, 16, 24 and 32 rungs when a card frees up.** CPU lane and PCIe
share calibrated as Maya's `--calibrate` does, against this engine's own session; the Phase 0
harness and instruments; the engine's points onto `ladder-baseline.png`. The H5 measurement. The
front end's `make test-chat-parser MODEL=<gguf>` against Qwen3.6's template (the homelab services
use a patched `qwen3.6-enhanced.jinja`); the Qwen3-Coder any-argument-order patch checked for
misfires on this model's tool-call grammar.
6. **The other Pascal cards and the fat binary.** The sm_61 build has been the working build since step
1; this step makes `STRATA_EXPERIMENTAL_SM60=ON` the default for the fat binary
(`CUDA_ARCHS=61;70;75;86;89;120`, CUDA 12.8) and runs the 1070 Ti and the 1060 against B1b. The
sm_75+ paths (tensor-core prompt attention, thread-block clusters) stay compiled in for the cards that
have them and are checked on the 4090 or A6000 when one is free.
7. **README/UPSTREAM.** The supported model and its checksums, the ladder table with the engine against
the baseline, the sizing rule in words, the Pascal caveats (CUDA 12.x, FP32 paths, no Nsight Compute).
**The base is this repository's `src/` and `include/`: Strata at `6f32ec0`, engine 0.1.39.** Maya's engine
is not merged, cherry-picked or vendored: it forked from Strata around engine 0.1.27 and has rewritten the
expert tiers, the mixers and the server since, so its C++ does not apply to this tree without a port of its
own. Taken from Maya (MIT, by reference to a pinned commit): the method and the Python-side tooling; the
list of places Strata's geometry was hardcoded, each re-found and fixed here; the route-log format,
`glm_tier_replay.py` and `glm_expert_prior.py` adapted as standalone scripts; the VRAM cap and the
CPU-lane calibration as *designs*, implemented against this engine. Left out: the Python installer, the
dashboard, the Anthropic API, all multi-GPU work. One binary, no Python at run time, no network, one GPU.
## 6. Acceptance
Per budget, at the default quant, the engine must meet:
| Criterion | Threshold | Basis |
| --- | --- | --- |
| A1 context | 262,144 on 11 GB and up; 131,072 on 8 GB; on 6 GB whichever the sizing rule picks, stated at start | the stated goal and floor |
| A2 decode | beats the baseline's fit-edge decode on the same rung; absolute floors ≥ 15 tok/s at 8K depth and ≥ 10 at 32K on 11 GB, ≥ 10 / 7 on 6 GB, ≥ 60 / 45 on 24 GB | the 1060 did 16/11 at IQ3 under llama.cpp; the 4090 did 100+ |
| A3 prefill | ≥ 300 tok/s on Pascal, ≥ 2,000 on Ada | the 1060 did 355 |
| A4 stability | 7 consecutive requests, no OOM, ≥ 100 MiB VRAM headroom | g7's "+78 MiB per request" |
| A5 serving | chat, streaming, reasoning, tool calls and images through the front end, pi writing and running a program through it, on the 1060, the 1080 Ti and the 4090 with no flags but the model | the README's existing status bar |
If A2's "beats the baseline" fails on a rung after the cache tuning of step 5, the README reports the
rung's numbers against the baseline as they are. The engine still ships for that rung; the comparison is
the honest part of the result, not a gate.
## 7. Agents: who does what, and how cheaply
Rules:
- `ark` is human-only. If a phase should run under ark, the plan says so and the user starts it.
- One fresh agent per phase boundary, briefed with this file, the phase section, the hosts, the run
directory, and the previous phase's write-up (not its transcript).
- Fork (same context) only to continue an in-progress phase after a wakeup.
- Nothing an agent runs changes Proxmox state. Agents do not touch the live `.4` service except by
starting a second server on another port with the production unit stopped, and restoring it.
- Unattended sweeps: a file-based driver under tmux, polled on a `/loop` or wakeup every 15 to 30
minutes, `DRIVER_DONE` markers.
Tiering:
| Work | Model | Why |
| --- | --- | --- |
| `-lv 4` logs to CSV; `dmon.csv` parsing; nsys/nvprof export to busy-fraction and gap histograms; checksums; marker checks; replay runs at given slot counts; B1b single points on a card with a ready script | **haiku** | mechanical, re-runnable |
| Env specs, drivers, plots; llama.cpp builds per arch; the eval-callback route-dump patch; the replay adaptation; the oracle and synthetic fixture (Phase 2 step 1) | **sonnet** | code with a known shape and an example to copy |
| The Phase 1 write-up; geometry, the VRAM planner, kernels, pack, runner, the Pascal build (Phase 2 steps 2 to 7); diff review before the user ships | **default (Fable)** | judgment and engine code |
| Independent review of the Phase 1 write-up and of each parity harness before it is trusted | fresh **default** agent, given data but not the conclusion | an agent handed a hypothesis tends to confirm it |
Safe parallelism: the 1080 Ti sweep, the B1b points on the other cards, E0 on the Mac, and Phase 2 steps
1 to 4 on the A6000 are independent of each other. If the user wants a multi-agent fan-out for Phase 2,
they say "use a workflow".
## 8. Order of work and checkpoints
1. User: VM 220 decision; the 1080 Ti VM; GGUFs copied to every rung.
2. Agent (sonnet): `llama-server` builds per arch, profiler check, smoke test → `phase0-notes.md`.
**Checkpoint: the first `-lv 4` table on the 1080 Ti; Section 2's estimates replaced.**
3. Agent (sonnet, then haiku): E0 → `phase0-replay.md` and the expert profile. **Checkpoint: the hit-rate
curve with the seven budgets marked.** In parallel, Phase 2 step 1 on the Mac.
4. Agents: B1 on the 1080 Ti; B1b on the 1060, 1070 Ti, 4090 and capped A6000; B3. **Checkpoint: the
baseline ladder row.** In parallel, Phase 2 steps 2 to 4 on the A6000.
5. Agent (default): plots and the baseline write-up; separate reviewer. **Checkpoint: the number to beat
on every rung.**
6. Agent (default): Phase 2 step 5 across the capped budgets. **Checkpoint: the engine's points on the
ladder plot against the baseline, and pi served through the front end on the 4090.**
7. Agent (default): step 6 on the three Pascal cards. **Checkpoint: `unbiased-strata --model <gguf>`
serving pi on the 1060 and the 1080 Ti with no flags but the model; A1 to A5 on every rung.**
8. Step 7, the README. B2 and B4 whenever a card is idle.
Measurements land in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`, infra notes in
`~/homelab/investigations/<date>-vm-1080ti-qwen36.md` with a LOG.md entry, the model-support outcome and
the ladder table in this repo's README, and the port study in `docs/QWEN36-35B-A3B.md`. Tickets: one
`homelab` for the VM, one `regina` for the harness, one `UnbiasedStrata`-prefixed ticket per Phase 2
step, filed when the work starts.
-594
View File
@@ -1,594 +0,0 @@
# Running Qwen3.6-35B-A3B on UnbiasedStrata - the study
What it takes for Qwen3.6-35B-A3B (llama.cpp architecture `qwen35moe`) to run on this tree's Strata
engine, component by component, with the numbers the decision needs. Written 2026-10-11 against engine
0.1.39 (`CMakeLists.txt:11`, the `6f32ec0` snapshot; tree `8634357`). It is the Phase 2 design document
of `docs/PLAN-qwen36-35b-a3b.md` and the counterpart of Project Maya's `docs/GLM5-FLASH.md`, whose shape
it copies. Every `file:line` is this tree; "row N" is `docs/qwen36-port/geometry-inventory.md`; the model
facts come from `docs/qwen36-port/gguf-metadata.md` and `ref/qwen36.py` on branch `qwen36-oracle`; the
measurements from regina's `phase0-notes.md` and `replay/phase0-replay.md`.
Strata is a native implementation of one architecture, Qwen3.8-Flash-Next (`qwen4exp`), with its memory
tiers and its speculation stack built around that shape. Qwen3.6-35B-A3B is the same family one generation
earlier with three things removed (the hyper-connection residual, the sparse-attention indexer, the PLE
table) and one numerical change in the GDN gate. The kernel gap is small. The plumbing gap is not: the
removed pieces are assumed structurally in every block, in the verify window that is the only decode path
for native packs, in the drafter and in prefill, and `ModelGeometry` is never populated from the model file.
---
## 1. The model, exactly
From the shipped GGUFs (`gguf-metadata.md`, dumped with `tools/gguf_reader.py`; sizes and SHA-256s in
`phase0-notes.md`):
| | |
| --- | --- |
| Architecture | `general.architecture = qwen35moe`; `block_count` 40 (41 in the MTP files); `embedding_length` 2048; `context_length` 262,144 |
| Layer pattern | `full_attention_interval` 4: layer `il` is recurrent unless `(il+1) % 4 == 0`, so attention at 3, 7, ..., 39 (10 layers), GDN at the other 30 |
| GDN | `ssm.conv_kernel` 4, `ssm.state_size` 128, `ssm.group_count` 16 (k-heads), `ssm.time_step_rank` 32 (v-heads), `ssm.inner_size` 4096; conv channels 8192 = 2x2048 + 4096. Output gate `rms_norm(o) * ssm_norm * SiLU(z)` (`qwen35moe.cpp:267-276`) |
| Full attention | 16 heads, 2 KV heads, `key_length`/`value_length` 256, `rope.dimension_count` 64 (0.25 of 256), `rope.dimension_sections` [11, 11, 10, 0], `freq_base` 1e7, eps 1e-6; `attn_q` is 2x wide (query then gate per head, interleaved); output `* sigmoid(gate)`. **Dense**: no indexer |
| MoE | 256 experts, top-8, `expert_feed_forward_length` 512, shared expert 512 with a 1-D `ffn_gate_inp_shexp` scalar gate. Softmax over all 256, top-8 weights renormalised to sum 1 (`norm_w = true` hard-coded, `qwen35moe.cpp:506`); no `expert_weights_scale` (never loaded for this architecture) |
| Residual | plain: `attn_norm`, `post_attention_norm`, `output_norm`, all multiplicative RMS weights (no "+1") |
| MTP | `nextn_predict_layers` **absent in the plain file, 1 in the MTP files**; `blk.40` holds one attention + MoE block plus `nextn.eh_proj` [4096, 2048] over `concat(enorm(emb), hnorm(h))`, `nextn.enorm`, `nextn.hnorm`, `nextn.shared_head_norm`; no `embed_tokens`, no `shared_head_head` (the draft head is the main `output.weight`) |
| Vocabulary | 248,320 tokens, `pre = qwen35`, BOS/EOS/PAD 248044/248046/248055; the same tokenizer the engine's `--eos-ids` default already names (row 152) |
| Float tensors | the router `ffn_gate_inp`, `ssm_alpha`, `ssm_beta`, the shexp gate and every norm are **F32** in the plain file; the nextn block's router and shexp gate are BF16 |
| Mixed quantization | per layer and per role: IQ3_XXS file has IQ2_S gate/up everywhere, IQ3_XXS down on 37 layers and IQ4_XS on 3 (34, 38, 39); the nextn block in the MTP files is Q3_K/Q4_K experts with Q8_0 projections |
| Fused forms | none shipped: gate and up are separate `ffn_gate_exps`/`ffn_up_exps`, attention layers carry separate `attn_q`/`attn_k`/`attn_v`; `attn_qkv` exists only in the 30 GDN layers (the conv input) |
The byte census of the three files on hand (gguf-py over the headers, 2026-10-11; `blk.40` separated):
| File | Non-expert on the GPU (`output` + projections + norms) | `token_embd` | Trunk experts (40 x 256) | Per expert mean / max | `blk.40` dense / experts |
| --- | ---: | ---: | ---: | ---: | ---: |
| `UD-Q4_K_XL` (MTP repo, rev 5bc3e238, 21,784 MiB) | **2,038 MiB** (Q8_0 1,939 + F32 100) | 515 MiB Q8_0 | **18,726 MiB** (Q4_K 11,232, Q5_K 6,864, Q6_K 630) | 1.829 / 2.195 MiB (layer 39) | 40 / 464 MiB |
| `UD-IQ3_XXS` (12,589 MiB) | **1,597 MiB** (Q6_K 1,497 + F32 100) | 398 MiB Q6_K | **10,594 MiB** (IQ2_S 6,560, IQ3_XXS 3,626, IQ4_XS 408) | 1.035 / 1.172 MiB | none |
| `UD-IQ4_XS-MTP` (17,355 MiB) | 2,038 MiB | 515 MiB | 14,514 MiB | 1.417 / 1.883 MiB | 40 / 364 MiB |
The two non-expert figures are what llama.cpp's `-lv 4` reported on the 1080 Ti once the GPU-resident
expert layers are subtracted: Q4 `CUDA0 model` 5,917 MiB minus layers 32 to 39 (3,878 MiB) = 2,039; IQ3
7,475 minus layers 18 to 39 (5,878) = 1,597 (`phase0-notes.md`, smoke table). The token embedding stays in
host memory in both llama.cpp and this engine (`generate.cpp:2190`, "token embedding in mapped host
memory"), so it is not in the fixed set. The plan's Section 2 estimated ~3.1 GB for this item; the real
figure is 2.0 GiB.
## 2. What the engine already is
The implemented geometry is a struct of Flash-Next defaults (`include/strata/core/layout.hpp:27-59`):
n_embd 2560, 48 layers, full attention every 4th, GDN 16 k-heads / 48 v-heads / state 128 / conv 4 with
conv channels 10240 and value dim 6144 stored as members (row 2), QSA 24 heads / 2 KV heads / 256 with a
4-head 128-wide indexer, hyper-connections `hc` 4 with a 320-wide bottleneck, 512 experts x top-10 x 640.
`is_qsa_layer` is `layer % 4 == 3` (`layout.hpp:63`). Per layer (`src/core/layer.cpp:1170-1286`,
`1319-1342`):
gr_read(attn) -> GDN | QSA -> gr_write(attn) -> gr_read(ffn) -> moe_route [doorbell] ... moe_finish -> gr_write(ffn)
The unit is a captured per-layer CUDA graph replayed by a host loop (`include/strata/core/session.hpp:1-15`)
that rings a doorbell at the router so a CPU expert pool starts on the misses while the GPU continues.
Experts live in three tiers: a VRAM cache of slots filled by a profile and swapped by decayed usage
(`include/strata/core/expert_cache.hpp`), a RAM tier (pinned arena, or `--resident-experts` /
`--resident-budget-gib` keeping the complement of the VRAM cache in a compact copy,
`generate.cpp:1506-1520`, `expert_source.cpp:1331`), and the model file mapped from disk
(`--mmap-experts`, `expert_source.cpp:618-680`) with a `MADV_WILLNEED` warm hint per role on predicted
ids (`expert_source.cpp:1129-1160`, called at `1264`). Decode for a *native* pack (experts served from the
GGUF in their own ggml types, `include/strata/kernels/cpu/native_expert.hpp`) runs only through the verify
window (`expert_source.cpp:1869-1875`, row 114): windows of up to `kVerifyMaxT = 8` rows
(`verify_kernels.hpp:21`) drafted by the model's own MTP layer, a separate Q8_0 pack in VRAM
(`src/core/mtp.cpp:150-216`, `mtp.hpp:1-20`), plus a prompt-lookup drafter (`generate.cpp:522-524`).
Prompts go through a chunked prefill with the experts streamed over PCIe through a ring that borrows
cache slots (`generate.cpp:2723`, `4404-4425`; `docs/upstream/DETAILS.md`, "How it works"). The front
end (`frontend/`) is model-agnostic: OpenAI API, llama.cpp's chat parser (`frontend/chat_parser_test.cpp`),
vision through `mtmd` (`frontend/vision.hpp:4-87`), and it refuses `--gpus` (`frontend/main.cpp:558`).
## 3. Component-by-component gap analysis
### 3.1 Applies unchanged
| Piece | Why |
| --- | --- |
| Layer pattern | `is_qsa_layer` (`layout.hpp:63`) gives 3, 7, ..., 39 for 40 layers; `n_qsa_layers() = 40/4 = 10` (row 55). Every per-layer loop in `session.cpp` uses `g.n_layers` (row 27). |
| GDN decode kernels | State 128, head pairing `head % h_k` (`native_gdn.cu:51`, `fused_gdn.cu:29`), grids from `h_v`, `h_v % h_k == 0` checked (`native_gdn.cu:99-101`, `fused_gdn.cu:148-153`); 32 % 16 = 0. The conv (`d_conv == 4 && state 128`, `layer.cpp:247-248`) matches. |
| Router | `router_top10` is a generic softmax top-k over runtime `n_expert <= 512`, `k <= 32` (`router_top10.hpp:21`, row 124); `moe_route` takes it whenever the pack is not 512/10 (`layer.cpp:370`). Semantics equal llama.cpp's: softmax over all, stable descending argsort, renormalise with the 2^-14 clamp (`router_top10.hpp:3-5`; `oracle-crosscheck.md`, "Router and experts"). |
| Shared expert | Shape-driven (`layer.cpp:418-451`); its Q8_K activation rule needs `n_ff % 256 == 0` (`shared_expert.cu:237-239`), which 640 failed and 512 satisfies (row 127). |
| Native expert kernels | CPU: `native_fmt` is ggml-cpu trait-driven, whole-block checks only (`native_expert.cpp:40-60`); 2048 and 512 are multiples of 256. `kNativeActBytes` 4096 / `kNativeHBytes` 1024 hold a 2048-wide Q8_K (2,336 B) and a 512-wide one (584 B) (row 111). GPU: `iq_kernels.cu:1076-1140` read `L.n_embd`/`L.n_ff` per layer; Q4_K/Q5_K gate-up and Q5_1/Q8_0 down are already present (row 120); the IQ2_S/IQ3_XXS/IQ4_XS/Q6_K of the shipped files are ggml types ggml-cpu has `vec_dot` for. |
| Expert cache and tiers | Residency `[n_layers x n_expert]`, slots, the profile header checked against `(n_layers, n_expert)` (`expert_cache.cpp:43`); the file source, the complement copy, the warm hint; all parameterised at runtime (rows 118, 109). |
| KV formats and streaming machinery | fp16 / int8 / q4_0 / K8V4 pools at `head_dim 256` (`kv_q4.cu:176`, row 103); paged pools, `--kv-resident`, the resident floor 20,480 cells (`layer.cpp:556`). The *use* of streaming changes (section 4.2). |
| RoPE | `n_rot 64`, `head_dim 256` (`native_rope.cu:121`), interleaved M-RoPE sections 11/11/10/0 with `t = h = w` for text (`mrope.hpp:3-12`); the oracle pins the same pairs `(p, p+32)` (`oracle-crosscheck.md`, "Full attention"). |
| Vocabulary, sampler, head | `n_vocab` is a kernel argument, merge handles <= 262,144 (`sampler.cu:607`); the native head takes `[n_in, n_out]` with `n_in % 256 == 0` (`native_head.cpp:21`); the drafter reads `n_vocab_ = output.weight.ne1` (`mtp.cpp:430`). |
| Speculation protocol | Verify windows, draft policy, prompt lookup; the drafter's *weights* change (3.10). |
| Front end | Tokenizer, template, tool-call parser, vision (row 154). |
| MTP drafter's attention | Already dense over every cell (`mtp.hpp:16-18`, row 76): the one dense-attention path in the tree. |
### 3.2 GDN: head pairing, SiLU gate, four kernels (small)
The geometry changes are runtime except two stored members, `ssm_conv_channels` and `ssm_value_dim`,
which must become 8192 and 4096 (row 2; `session.cpp:41-44` derives the state size from them). The one
numerical change: the output gate is `sigmoid(z)` in the engine and `SiLU(z)` in Qwen3.6 (row 39;
`layer.hpp:16` records the difference). Four kernels carry it:
| Kernel | Line | Path |
| --- | --- | --- |
| `gdn_out_norm` | `src/kernels/cuda/gdn.cu:148` | legacy decode |
| `gdn_step_norm_kernel` | `src/kernels/cuda/fused_gdn.cu:69` (`1/(1+__expf(-zz))`) | the default native decode, inside the fused step |
| out-norm kernel | `src/kernels/cuda/native_gdn_preprocess.cu:110-112` | native unfused |
| `gdn_rec_kernel`, `gdn_out_norm_kernel` | `src/prefill/kernels.cu:324, 612` (`sigm(z)`) | prompt |
The oracle's negative control shows the sigmoid reading moves the layer output by 1.07 relative L1 and the
logits by 0.92 (`oracle-crosscheck.md`, negative controls), so the trap is far above the 5% gate.
`src/kernels/gdn_parity.cpp:104` pins `h_v = 48` and its reference `sigmoid_f` (`:42`); both are re-pinned
at 32 v-heads with SiLU, the sigmoid reading becoming the negative case. The prompt GDN kernels are
specialised on `VPK = HV / HK = 3` value heads per key head (`prefill/kernels.cu:478`) and launched on the
`HV`/`HK`/`C` constants (`kernels.cu:18-19`, rows 89 to 91); they are the prefill item in 3.6.
### 3.3 Dense attention replacing QSA (the largest kernel item, and a memory item)
The decode kernel gathers K/V through `ids` and a page table and does not care how `ids` was built
(`qsa_decode_attn.cu:100-120`, row 102). So dense attention is a "select every cell" producer feeding the
existing kernel. What stands in the way:
1. **The producer.** `qsa_layer` runs the indexer unconditionally: the raw key projection (`layer.cpp:945`),
the append (`:962-964`), the block scores and top-k (`:966-975`), with `indexer.{k,q}_proj.weight` and
`indexer.{k,q}_norm.weight` dereferenced as required tensors (`:891-897`, row 45). The verify window
does the same per row (`verify.cpp:757-761`, `772-870`, row 145). A dense path skips those steps and
writes `ids = 0..n_kv-1` from `st.step`; the selection width `qsa_selection_width(n_kv, s) =
min(n_kv, 2051)` (`qsa.hpp:144-147`) and the capacity `cap = qsa_selection_width(kTopkMaxCells, s)`
(`layer.cpp:876`, `verify.cpp:352`, `prefill.cpp:865`) become `n_kv` and `max_cells`.
2. **The 12-versus-8 literal.** `G = 12` query heads per KV head, refused with `exit(1)` unless
`n_head == 12 * n_head_kv` (`qsa_decode_attn.cu:17, 453, 497`; `qsa_prompt_attn.cu:22, 1447`; row 93, 94).
Qwen3.6 is 8. `G` becomes a template parameter instantiated at 8 and 12.
3. **The 24-head short-context kernel.** `native_flash_attn.cu:196-206` refuses anything but 24/2/256 and
contexts above 256; it is a diagnostic adapter (`layer.hpp:53`, "context <= 256") and is not on the
prompt path. It stays as it is.
4. **State without the indexer.** `qsa_state_bytes` carves `idx_tail`, `idx_dead`, `idx_pooled` with
`pooled_rows = max_cells/4 + 2` (`layer.cpp:559-575`, row 43): at 262,144 cells that is 65,538 x 128 x
4 B = 32 MiB per attention layer, 320 MiB over ten, all dead. The drafter's ring already passes a state
"which has no indexer" with `pooled_rows = 2` (`layer.cpp:527-531`); the dense state takes the same.
5. **The split-K scratch scales with the context.** `qsa_decode_attn_scratch_floats(cap, s) = (cap/64) x
n_head x 258 + 64` (`qsa_decode_attn.cu:489-491`). Today `cap` is 2,051; with `cap = 262,144` and 16
heads it is 64.5 MiB *per query row*: 516 MiB for the 8-row verify window (`verify.cpp:422`) and
`attn_batch` times that in prefill (`prefill.cpp:888`). The dense kernel needs either a larger chunk
per block or an online-softmax merge that does not keep a partial per 64-cell chunk.
6. **KV streaming no longer saves VRAM.** Streaming keeps the authoritative K/V in host memory and resolves
the *selected* blocks into VRAM slots before the read (`layer.hpp:230-236`, `qsa_kv_resolve` at
`layer.cpp:976`). With every cell selected every token, every block must be resident every token: the
mechanism degenerates to copying the whole KV (1,440 MiB at q4_0) over PCIe per token. Section 4.2
and section 8 draw the consequence for the plan's sizing rule.
KV formats, the Hadamard-rotated q4_0 pool, the page table and the RoPE tables carry over unchanged
(`layer.cpp:938-1010`, row 46). The prompt attention has three device paths: cp.async + mma on sm_80+,
mma on Turing, an m8n8k4 kernel on Volta, and for `cc < 70` the host returns false
(`qsa_prompt_attn.cu:1433`) so prefill falls back to the batched decode kernel
(`prefill.cpp:2222-2228`). On Pascal that fallback is the prompt attention; it needs `G = 8` and the
scratch fix above, nothing else.
### 3.4 Router and shared expert (small; one measured-not-asserted parity)
Both are generic already (3.1). Two form questions remain. The router kernel reads a BF16 weight
(`layer.cpp:361-366`, `project_bf16`), `fused_gdn_ab` reads BF16 `ssm_alpha`/`ssm_beta`
(`layer.cpp:285-287`), and `moe_shared` refuses a `ffn_gate_inp_shexp` that is not engine form BF16
(`layer.cpp:427-437`). All four are F32 in the shipped file (`gguf-metadata.md`, "What was unexpected").
The pack rounds them: exactly when the low 16 bits are zero, else only under `--compat-bf16`
(`upstream-tooling.md` section 4, the ORCA precedent). That is a numerical change against llama.cpp, which
multiplies in F32, and it lands on the one place where rounding is not a rounding error: a flipped top-8
selection is a different expert (`layer.hpp:131-139`). The oracle's real-file smoke already shows the
F32-versus-quantized router disagreeing on 6 of 32 (token, slot) choices in layer 0 and 12 to 23 in layers
30 to 39 (`oracle-crosscheck.md`, "Not covered"), so the harness measures a flip rate at the
`logits -> top-8` boundary with the quantized-mode gates Maya calibrated (selection equal at probed layers
on an F32 fixture; a bounded rate on the real file), not bitwise equality. `router_top10_parity.cpp`'s tie
fixtures (all-equal logits, a 12-way tie, the unreachable clamp) carry over at 256/8.
### 3.5 The block without hyper-connections: `layer.cpp` *and* `verify.cpp` (the largest plumbing item)
`hc` sizes the residual `R` (hc, n_embd), `inject`, `gr_rs` and the GR workspace (`layer.cpp:1127-1145`),
and every block reads four `hc_attn_*` and four `hc_ffn_*` tensors with required forms
(`layer.cpp:1231-1255`, row 22). No `hc = 1` meaning exists (row 4): the GR math on one stream is not a
plain residual, and the names Qwen3.6 ships (`attn_norm`, `post_attention_norm`, `output_norm`) are
referenced nowhere in `src/` (rows 22, 23). The plain block is
x = rms_norm(R, attn_norm) -> mixer -> R += out
x = rms_norm(R, post_attention_norm) -> MoE -> R += out head: rms_norm(R, output_norm) -> output.weight
(`qwen35moe.cpp` layer loop; the oracle's `attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `l_out-N`,
`result_norm` seams). The weighted RMS norm kernel exists (`native_qsa_rms_norm_weighted`, used at
`layer.cpp:879` and `mtp.cpp:488`). The places that must grow the plain path:
| Site | What assumes hc |
| --- | --- |
| `layer.cpp:1170-1286` `block_layer_pre`, `1319-1342` `block_layer_post` | the two GR halves, the fused-GR fast path (`fused = g_fused_gr && fused_gr_supported(2560, 4, 320)`, `:1195`; `fused_gr.cu:1164-1166`), `pending_ffn` folding |
| `layer.cpp:1088-1107` `lm_head_mix` | `output_hc_{norm,down,up}` |
| `session.cpp:141-148` | first token = `hc` copies of the embedding (one copy at hc = 1, row 26) |
| `verify.cpp:331-340` | refuses unless `fused_gr_supported && ss.k == 10 && state 128 && d_conv 4` and `layer_verify_compatible` demands the fused GR and the native indexer (`layer.cpp:476-486`, row 141) |
| `verify.cpp:356-434` | `R_`, `xn_` as `T*HC*N`, `inj_`, `lo_ (T*hc_lr)`, `idx_raw_L_`, `qidx_`, `tail_snap_` |
| `verify.cpp:1123-1125` | the head mix |
| `verify_kernels.cu:256-291` | `broadcast_streams` / `add_streams_broadcast` (runtime `hc`, row 140) |
| `mtp.cpp:503-507, 564-568, 613-625`; `prefill.cpp:972-1086` | the drafter's three hc groups (3.10) |
Because native packs decode only in verify windows (row 114) and the window refuses a layer without fused
GR and the indexer (row 141, 142), the plain block has to land in `verify.cpp` for a single token to come
out. The verify window's `ss.k == 10` refusal becomes `k == 8` from the file. `cvec` (the control-vector
apply over `hc*n_embd`, row 140) is runtime-shaped and needs no change.
### 3.6 Prefill (the most literal-heavy subsystem)
`Prefill::init` refuses unless `n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10`
(`prefill.cpp:737`, row 132); the file-wide constants are `N 2560, HC 4, D, LR 320, K 10, NE 512, C 10240,
ZV 6144, HV 48` (`prefill.cpp:90-91`) and `N, HC, D, LR, S, HK 16, HV 48, C 10240` in the kernels
(`prefill/kernels.cu:18-19`). The literals, each with its Qwen3.6 value:
| Site | Literal | Qwen3.6 |
| --- | --- | --- |
| `prefill.cpp:649-650, 883-884` | `Qf` as `T * 12288` (24 x 512), `q`/`attn` as `T * ZV`; `idx_raw`, `q_idx` | 8,192 (16 x 512), 4,096; the two indexer buffers dead |
| `prefill.cpp:681-685, 704-721, 896-907` | MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | `2*n_ff` 1024, `n_ff` 512, `n_embd` 2048 |
| `prefill.cpp:854-856, 1000-1026, 1375-1380` | `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` | removed with hc |
| `prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924` | GDN kernels indexed on `HV`, `HK`, `C`, launched `<<<HV, ...>>>`; `VPK = 3` (`:478`) | 32, 16, 8192; `VPK = 2` |
| `prefill/kernels.cu:616-657` | `route_kernel<REG>`: `REG 8` exists for 256 experts but the rank loop and `ids[t*10 + rank]`, `lane < 10` bake top-10 | `k` as a parameter |
| `prefill/kernels.cu:752-761` | `split_q_kernel`, `gate_attn_kernel` over `T * 24 * 256` and `h * 512` | 16 heads |
| `prefill/moe_fused_iq.cu:59` | `GU_ROWS_K = 2560, D_ROWS_K = 640` (the native-pack fused prompt MoE) | 2048, 512 |
| `prefill.cpp:1724` loop, `1303` `RP = 48` | layers from `g.n_layers` (fine, row 134); `RP` | check |
The GDN kernels are forked per geometry (template on `HV, HK, C`) rather than made runtime, because their
shared-memory staging (`sq[2][TB][S]`, `kernels.cu:482-484`) is sized from them. `src/prefill/gdn_rec_parity.cu`
mirrors the constants (row 91) and is re-pinned with them. The chunked-versus-single-token equivalence (a
prefix through prefill then decoded must agree with token-by-token decode) is the harness that already
exists for this path (`tests/cuda/prefill_*_test.cpp`, restored in `c00942d`).
### 3.7 The native pack path (one leak, otherwise runtime)
The canonical Q2_0 CPU expert kernel bakes `H 2560, FF 640, NE 512, BLOB 1,382,400`
(`include/strata/kernels/cpu/expert.hpp:34-47`, row 107) and `expert_pool_dispatch` refuses any other
width (`expert_source.cpp:1863-1868`); Qwen3.6 does not go through it. It rides the native path, as the
Coder (256 of 512 experts) does. The path is runtime per layer (`NativeFmt` with `n_embd`, `n_ff`, gate/up
and down ggml types, `native_expert.hpp:22-31`) with one leak: `expert_layout_load` builds every layer's
format with the compile-time `H, FF` (`src/kernels/cpu/expert_layout.cpp:284`, `native_fmt(gt, dt, H, FF,
f, err)`) and then checks `f.bytes == blob`, so a 2048/512 pack fails the "blob is X B but its formats make
Y" check (row 108). The fix is the loader taking `n_embd`/`n_ff` from the geometry the caller resolved,
which means the call at `generate.cpp:2008-2010` (today `g0.n_layers, g0.n_expert` from a default struct,
row 10) must run after the metadata read of 3.8, not before it.
`native_experts.txt` already carries a type per layer and per role (gate/up share one, down may differ,
`upstream-tooling.md` section 4; v3 header `(n_expert N)`, `expert_layout.cpp:271`), so the IQ3_XXS file's
37/3 down split and the Q4_K_XL's Q6_K layers need no format change. The engine reads experts as three
separate `ffn_{gate,up,down}_exps` tensors (`expert_source.cpp:2475-2500`, row 116); the shipped files are
separate, and a fused `ffn_gate_up_exps` is refused by name rather than split (section 8, item 5).
### 3.8 Metadata and `ModelGeometry`
`check_architecture` requires `general.architecture == "qwen4exp"` and reads six `qwen4exp.*` keys with
defaults 48/2560/24/2 (`include/strata/artifact/gguf_reader.hpp:576-597`); its callers are the native dense
loader, the native head and embedding, and the GGUF reader (`native_dense.cpp:103`, `native_head.cpp:29`,
`:113`, row 18). Every Qwen3.6 load dies there first. Beyond the guard, only `expert_count`,
`expert_used_count` and the rope keys are read, under `qwen4exp.` and only with `--native`
(`generate.cpp:2089-2096`, rows 8, 9). What `ModelGeometry` must read, all present in the file
(`gguf-metadata.md`, metadata table; row 153):
| Field | Key |
| --- | --- |
| `n_embd`, `n_layers` | `qwen35moe.embedding_length`, `block_count` minus `nextn_predict_layers` (0 when absent) |
| `qsa_interval` | `full_attention_interval` |
| `ssm_state_size`, `ssm_k_heads`, `ssm_v_heads`, `ssm_d_conv`; conv channels and value dim derived | `ssm.state_size`, `ssm.group_count`, `ssm.time_step_rank`, `ssm.conv_kernel`, `ssm.inner_size` |
| `n_head`, `n_head_kv`, `head_dim`, `n_rot`, sections, base, eps | `attention.head_count`, `head_count_kv`, `key_length`, `rope.dimension_count`, `rope.dimension_sections`, `rope.freq_base`, `attention.layer_norm_rms_epsilon` |
| `n_expert`, `k`, `n_ff` (routed and shared) | `expert_count`, `expert_used_count`, `expert_feed_forward_length`, `expert_shared_feed_forward_length` |
| `hc` | 1 (no key; the architecture string decides) |
The oracle's `read_hparams` (`ref/qwen36.py:125-150`) is the reference for defaults and derived values.
Other default-geometry sites: the routing trace's `layer >= 48` bounds (`generate.cpp:771, 795`, row 13),
the embedding load with `g0.n_embd` and the literal 248320 (`generate.cpp:2184-2186`, row 11), the draft
geometry (`generate.cpp:3026`, 3.10), and the standalone planner's `Geometry` and `expert_blob`
(`include/strata/plan/plan.hpp:22-52`, row 19), which is off the serving path.
### 3.9 PLE, optional at the CLI
The kernels already run without it: `block_layer_pre` applies the PLE only at layer 1 when `ple != nullptr
&& ple->ready()` (`layer.hpp:524-545`, row 30), prefill and verify guard on `ple_on` (rows 68, 69). The CLI
does not: `--native` refuses to start without `--ple-gguf` or a shard holding `per_layer_token_embd.weight`
(`generate.cpp:1800-1815`), and without `--native` the flag is "required" with `--no-ple` called a
"diagnostic ablation" (`:1843-1855`, rows 62, 63). The change is to make the absence of the tensor the
normal case when the architecture has no PLE. The fixed `NG_HIST x NG_HC_DIM` history buffer (about 360 KB,
`session.cpp:50-52`, row 29) and the `blk.1.ple_key` special cases (row 65) are dead but harmless.
### 3.10 The MTP drafter
The drafter is its own pack: `<rt_dir>/dense.txt`, `dense.bin` (every dense weight Q8_0), `experts.bin`
written by `tools/mtp_rt.py` (`mtp.cpp:150-216`, row 70). It expects vLLM-style names
(`fc_embedding`, `fc_hidden`, `pre_fc_norm_*`, `self_attn.*`, `mlp.shared_expert.*`, `mlp.gate`,
`mlp.shared_expert_gate`, three `*hyper_connection*` groups; `mtp.cpp:210-212, 488-495, 503-507, 575`),
canonical Q2_0 experts of `n_expert x BLOB` bytes in VRAM through `moe_group_resident` /
`moe_grouped_s2` (`mtp.cpp:191, 579-583`; `s2_expert_grouped.cu:37-46` bakes 2560/640, row 121), and the
default geometry (`generate.cpp:3026`, "the canonical model's MTP head (512 experts)", row 12).
Qwen3.6's draft block (`gguf-metadata.md`, "The nextn block"): `concat(rms_norm(emb) * enorm, rms_norm(h)
* hnorm)` (embedding first) through one `eh_proj [4096, 2048]`, then a plain attention + MoE block
(`attn_norm`, joint q+gate, q/k norm, IMRoPE, causal over its own KV, sigmoid gate, `attn_output`,
residual, `post_attention_norm`, the same top-8 MoE plus gated shared expert, residual), `shared_head_norm`,
the main `output.weight`. Pairing: token k with the trunk's output-normed hidden state of k-1
(`oracle-crosscheck.md`, "Nextn / MTP"; verified at every nextn seam, 50 of 50). What the drafter keeps:
dense attention over its own KV ring (rows 76), the main head and the `draft_vocab.bin` subset (row 77,
the same 248,320 vocabulary, so `data/draft_vocab*.bin` carry over), `token_embd` embeds (row 78). What
changes: the two input projections become one `eh_proj` over the concatenation (`mtp.cpp:488-495`); the
three hc groups become three norms (`:503-507, 564-568, 613-625`; the prefill-side pass at
`prefill.cpp:972-1086` the same); the draft experts are 256 K-quant blobs (Q5_K/Q4_K, 464 MiB in the
Q4_K_XL file; Q3_K/Q4_K, 364 MiB in the IQ4_XS file) served by the native GPU expert kernels
(`iq_kernels.cu`, row 120) instead of the Q2_0 grouped kernel; the geometry follows the target.
A Qwen3.6 draft pack: `dense.txt`/`dense.bin` with llama.cpp's names (`nextn.eh_proj`, `nextn.enorm`,
`nextn.hnorm`, `nextn.shared_head_norm`, `attn_norm`, `post_attention_norm`, `attn_{q,k,v,output}`,
`attn_{q,k}_norm`, `ffn_gate_inp` BF16, `ffn_gate_inp_shexp` BF16, `ffn_*_shexp`), the projections kept
Q8_0 as stored (39 MiB), and a `native_experts.txt`-style line for the one layer's three expert tensors.
Because the drafter is separate from the trunk file, the pack cut from the Q4_K_XL file's `blk.40` serves
the IQ3_XXS trunk too (the plain IQ3 file has no nextn block). Draft acceptance is an empirical question per
model; llama.cpp's own MTP arm (B4) is the external reference.
### 3.11 Tokenizer, chat template, vision
Same vocabulary and the same `qwen35` pre-tokenizer family (`gguf-metadata.md`; `tools/strata_tokenizer.py`
refuses schemes it has not transcribed, `upstream-tooling.md` section 2). The front end uses llama.cpp's
chat parser (`frontend/chat_parser_test.cpp`) and carries the Qwen3-Coder any-argument-order patch
(`chat_parser_test.cpp:48`); the plan's step 5 checks it against Qwen3.6's template with
`make test-chat-parser MODEL=<gguf>` (`Makefile:35-41`). Vision loads an mmproj through `mtmd`
(`frontend/vision.hpp:79-87`); the `Qwen3.6-35B-A3B-MTP-GGUF-mmproj-F16.gguf` is on the VM with its SHA-256
(`phase0-notes.md`). Nothing in the engine changes for either.
## 4. The memory plan
### 4.1 The fixed set, from measurements
| Item | Q4_K_XL, 262,144 | IQ3_XXS, 262,144 | Source |
| --- | ---: | ---: | --- |
| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB | `-lv 4` minus resident expert layers (section 1); census |
| Draft block: 40 MiB dense + 256 experts in VRAM + ring KV + 8 x 248,320 logits | ~520 MiB | ~520 MiB (the Q4 draft pack) | census; `mtp.hpp:19`; `mtp.cpp:430-436` |
| KV, q4_0, 10 layers | 1,440 MiB | 1,440 MiB | `phase0-notes.md` smoke rows (both arms) |
| Session: RoPE table 64 MiB, scratch; **plus 320 MiB of indexer state unless 3.3 item 4 removes it** | ~164 MiB | ~164 MiB | `layer.cpp:559-576` |
| CUDA context | ~230 to 300 MiB | same | nvidia-smi 9,487 (peak 9,565) minus the three buffers, Q4 row |
| Reserve | 300 MiB (`kSmallReserveMib`) to 700 (default) | same | `generate.cpp:424, 3249` |
| Prompt buffers: borrowed from the cache with a profile, else chunk-sized | 0 (borrow) / 1,904 MiB at chunk 2048 | 0 / 1,878 MiB | `generate.cpp:2723`; llama.cpp `-ub 2048` compute buffer |
| **Decode-time fixed set** | **~4,760 MiB** borrowing; ~6,660 without | **~4,320** borrowing; ~6,200 without | sum |
| Trunk experts (file) | 18,726 MiB; 1.829 MiB mean, 2.195 max | 10,594 MiB; 1.035 mean, 1.172 max | census |
| Dense split-K attention scratch at `cap = 262,144` | 64.5 MiB per query row (516 for the verify window) | same | `qsa_decode_attn.cu:489-491` |
The replay and the plan used a 5.8 GB (Q4) / 4.6 GB (IQ3) fixed set that includes the 1.9 GB prompt buffer
and excludes the drafter, and 17.4 GB / 10.5 GB of experts (`phase0-replay.md`, "Budget to slots"). The
census moves the expert total up by 7% at Q4 and the fixed set down by the prompt buffer when prefill
borrows; the two roughly cancel at the 11 GB rung (table 4.4).
### 4.2 The VRAM planner (Phase 2 step 2)
What exists: `--expert-cache auto` reads free VRAM, subtracts the reserve and the prompt estimate, grants
slots at `max_blob` (`generate.cpp:3232-3300`), then for a native pack with a profile re-prices the slots
per layer so the same VRAM holds the profile's hottest experts at their own blob sizes
(`generate.cpp:3307-3327`, "~30% more IQ3_XXS experts than slots of the largest blob"); the prompt path
borrows the last slots (`:4404-4425`); below `min_slots` the reserve shrinks to 300 MiB and then the start
refuses with the numbers (`:3267-3290`, "no VRAM is left for the expert cache"). What the step adds, in the
plan's order with one change:
1. Fixed set first: weights, drafter, KV for the requested context, session. **KV streaming is not a lever
for this model** (3.3 item 6): the resident-window floor of 20,480 cells (`layer.cpp:556`) exists for a
selection of 2,051 cells, and dense attention reads every cell. So the rule's first fallback, "stream
the KV to RAM above a resident window", is replaced by: hold the KV in VRAM, and if the fixed set does
not fit, lower the context toward 131,072, then refuse with the numbers and the IQ3 file's name. Never
silently shorten.
2. Every remaining byte becomes expert slots, sized per layer from the profile as today.
3. The RAM tier: free RAM minus a headroom (`--resident-experts` uses 4 GiB, `generate.cpp:1508`;
`--resident-budget-gib N` sets it, `:1516-1520`), filled with the next experts by profile rank
(`pin_cache_complement`, `expert_source.cpp:1331`); whatever remains stays mapped from the GGUF
(`--mmap-experts`, `:618-680`) with the `MADV_WILLNEED` warm on predicted ids (`:1129-1160`).
4. Emulation: `--vram-cap MiB` clamps every `cudaMemGetInfo` free figure the planner reads (`:3297, 3313`)
to `cap - used` and, so the driver sees the same pressure the real card would, allocates a blocker of
`total - cap` at start; `--ram-cap GiB` bounds `resident_budget` and the pinned arena. The page cache
cannot be capped from inside the process; the 12 GiB VM does that physically, and on a larger host a
cgroup `memory.max` does.
5. The start-up log and `/health` state the three counts (VRAM slots, RAM copies, mapped) and per-token
counters: VRAM hits (`cache_hits`), RAM-copy hits, warm-hint count (`warm_count_`), and disk reads as
the major-fault delta from `/proc/self/stat`, since a page-cache miss is not otherwise observable.
### 4.3 The 6-to-32 GB ladder
Budgets in the replay's decimal convention (6 GB = 5,722 MiB) except the 1080 Ti (11,264 MiB) and a 24 GB
card (24,576 MiB). Slots at the census mean blob; "borrow" is the decode-time fixed set of 4.1, "no borrow"
adds the chunk-2048 prompt buffer.
| Budget | Q4 replay basis (5.8 GB fixed, 1.70 MB/expert) | Q4 derived, no borrow | Q4 derived, borrow | IQ3 replay basis | IQ3 derived, borrow |
| --- | ---: | ---: | ---: | ---: | ---: |
| 6 GB | 80 (1%) | 0 (fixed set does not fit) | ~525 (5%) | 1,360 (13%) | ~1,350 (13%) |
| 8 GB | 1,280 (12%) | ~525 (5%) | ~1,570 (15%) | 3,280 (32%) | ~3,200 (31%) |
| 11 GB (decimal) | 3,040 (30%) | ~2,090 (20%) | ~3,130 (31%) | 6,240 (61%) | ~5,960 (58%) |
| 1080 Ti, 11,264 MiB | | ~2,510 (25%) | ~3,550 (35%) | | ~6,700 (66%) |
| 12 GB | 3,640 (36%) | ~2,610 (26%) | ~3,650 (36%) | 7,200 (70%) | ~6,880 (67%) |
| 16 GB | 6,000 (59%) | ~4,700 (46%) | ~5,740 (56%) | all | all |
| 24 GB (24,576 MiB) | all | ~9,790 (96%) | all, ~1,090 MiB spare | all | all |
| 32 GB | all | all | all | all | all |
The RAM tier at the replay's 9.5 GB usable: Q4 ~4,950 experts at the census blob (the replay's 5,590 was at
1.70 MB), IQ3 ~8,760. The disk tier at Q4 on the 1080 Ti is then 10,240 - 3,550 - 4,950 = ~1,740 experts
(17%) with borrowing and ~2,780 (27%) without; the replay modelled 1,610 (16%). At IQ3 everything fits VRAM
plus RAM at every rung from 6 GB (`phase0-replay.md`, finding 5). The planner's own log at `--vram-cap`
6/8/11/12/16/24/32 is the check of this table, within one slot of the derivation.
## 5. Expected envelope per budget
From `phase0-replay.md` (LFU, profile seed, second half of a 214,940-token trace of the IQ3_XXS model,
decode only; the Q4 arm reuses the IQ3 routes). The parameters are parameters: `gpu_ms` 17 (an upper
estimate from the smoke rows' busy share; 12 is a flag away), `cpu_lane_ms` 0.15 per expert (llama.cpp
IQ3 N=18 implies 0.17), `disk_ms` 1.3 (fio 1 MiB random QD4; parallel faults may halve it), `pcie_ms` 0
(promotions counted, not charged: 47.7 copies per token at Q4 11 GB, about 12 ms at 0.26 ms each, is the
largest omission; charging it takes Q4 11 GB LFU from 42.5 to 27.8 tok/s). "Overlap" is
`1000 / max(gpu, cpu, disk)`, "serial" the sum.
| Budget | Q4 VRAM hit | Q4 disk reads/tok | Q4 tok/s overlap / serial | IQ3 VRAM hit | IQ3 disk/tok | IQ3 tok/s overlap / serial |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| 6 GB | 0.0% | 70.7 | 7.7 / 6.8 | 59.7% | 0 | 51.7 / 27.5 |
| 8 GB | 57.9% | 51.5 | 12.6 / 10.4 | 84.4% | 0 | 58.8 / 40.9 |
| 11 GB | 82.6% | 13.2 | 42.5 / 24.7 | 96.0% | 0 | 58.8 / 52.9 |
| 12 GB | 86.8% | 7.1 | 58.8 / 31.8 | 97.7% | 0 | 58.8 / 55.2 |
| 16 GB | 95.5% | 0 | 58.8 / 52.2 | 100% | 0 | 58.8 / 58.8 |
| 24, 32 GB | 100% | 0 | 58.8 / 58.8 | 100% | 0 | 58.8 / 58.8 |
58.8 is `1000 / gpu_ms` and the overlap column saturates there by construction. The Belady ceiling at Q4
11 GB is 91.0% hit, 6.6 disk reads, 58.8 / 34.6. Against it, the llama.cpp smoke points on the same card:
Q4 N=32 **8.78 tok/s** decode, 128.6 prefill, GPU busy 15%; IQ3 N=18 **24.58** decode, 433.9 prefill, GPU
busy 41% (`phase0-notes.md`). The plan's floors (A2: 15/10 tok/s at 8K/32K on 11 GB, 10/7 on 6 GB, 60/45 on
24 GB; A3: 300 tok/s prefill on Pascal) sit inside these predictions except the Q4 6 GB row, which the
plan already routes to the IQ3 file. With the census tiers (4.3) the Q4 11 GB disk term is 17 to 27% of
experts rather than 16%, so its disk reads per token sit above 13.2; the replay is re-run with the census
blob sizes as part of step 2, not re-derived here. Prefill is not modelled; the engine's chunked MMQ path
amortises expert bytes across the chunk, and on Pascal the prompt MoE's fast path is a risk (section 7).
## 6. Execution plan (Phase 2, steps 2 to 7)
Step 1, the oracle and fixture, is done on `qwen36-oracle`: `ref/qwen36.py` agrees with the pinned
llama.cpp graph on 2,155 comparisons over 116 seam families at 1.1e-4 worst absolute error, the router's
integers identical, and all seven rival readings fail at the seam that makes them (`oracle-crosscheck.md`).
Every harness below holds the engine to those dumps by llama.cpp's `cb()` names. Each step has a parity
harness in the repo's negative-test discipline (`gdn_parity.cpp`: every wrong reading must differ by more
than 5% relative L1 before the right one is judged, `upstream-tooling.md` section 3), runs on the 1080 Ti
under `STRATA_EXPERIMENTAL_SM60=ON` (sm_61) from the first build and on a rented sm_86 card for compile
speed; a kernel passes when it passes on both. Steps 2 to 4 need seconds of GPU per run and proceed while
the Phase 0 sweeps hold the card. Effort weights sum to 100 for steps 2 to 7.
**Step 2, geometry, metadata, sizing (15%).** Files: `gguf_reader.hpp:576-597` (accept `qwen35moe`, read
the 3.8 key set), `layout.hpp:27-59` (`hc = 1`, derived conv channels and value dim, no indexer fields),
`generate.cpp:2008-2010, 2073-2096, 2184-2186, 771, 795` (geometry from the file before the layout load;
the embedding dims from it), `expert_layout.cpp:284` (the leak), `expert_source.cpp:2475-2500` (fused
forms refused by name), `generate.cpp:1800-1815, 1843-1855` (PLE optional), the planner
(`generate.cpp:3232-3327`) with the 4.2 rule, `--vram-cap`, `--ram-cap`, the counters, `tools/make_profile.py`
(`N_LAYER = 48`). Harness: `ModelGeometry` from the synthetic GGUF (`tools/qwen36_synth_gguf.py`) and the
real file equals the oracle's `HParams` field by field; the planner's log at the seven caps reproduces
table 4.3. Negative tests: a `qwen4exp` file refused with its name; a 48 x 512 profile refused
(`expert_cache.cpp:43`); a `--fused-gate-up` fixture refused by tensor name; `--vram-cap` below the fixed
set refuses with the context it would need. No GPU beyond the planner's run.
**Step 3, kernels and the block (45%).** In order of risk:
- *GDN (3.2):* SiLU in the four kernels; `gdn_parity.cpp` at `h_v 32` with sigmoid as the negative, plus the
existing four traps (pairing, decay order, conv direction, l2 epsilon); `gdn_rec_parity.cu` at `VPK 2`.
Seams: `conv_output_silu-0`, `new_state-0`, `final_output-0`.
- *Dense attention (3.3):* the identity-`ids` producer; `G` templated at 8; the indexer skipped in
`qsa_layer` and the verify attention step; the state without indexer buffers; `cap = max_cells`; the
split-K scratch bounded. Harness: `qsa_parity.cpp`'s attention cases with `ids` identity against the
oracle's `kq_soft_max-3`, `kqv-3`, `attn_gated-3`, and a 300-cell case where the old width (2,051) and
the dense width differ. Negative tests: `G = 12` on 16 heads (refused, not mis-indexed), the gate skipped
(1.03 relative L1 at `attn_gated-3`), adjacent-pair RoPE (0.20 at `kqv-3`), both from the oracle's
controls.
- *Router and shared expert (3.4):* `router_top10_parity.cpp` at 256/8 with its tie fixtures; the BF16
rounding of the F32 router measured as a flip rate on the real file's first 8 tokens with the quantized-
mode gates; `shared_expert_parity.cpp` at 512 with the 1-D F32-to-BF16 gate. Seams: `ffn_moe_topk-N`,
`ffn_moe_weights_norm-N`, `ffn_shexp_gated-N`.
- *The block without hyper-connections (3.5):* `layer.cpp` and `verify.cpp` both, `session.cpp:141-148`,
the head. Harness: the layer composition test, Maya's shape: layer 0 (GDN + MoE) and layer 3 (attention +
MoE) of the synthetic model through the engine's kernels, every seam held to the dumps; then the verify
window on an 8-token sequence against the oracle's `l_out-N` per position, with the window's row
arithmetic required to equal the single-token path (the discipline `verify.cpp:773-774` already states).
Negative tests: the GR read with identity weights (not a plain norm), the post-attention norm skipped,
`k = 10` on an 8-expert file.
- *Prefill (3.6):* the constants and the eight literal sites; the GDN kernels forked at 32/16/8192; the
route kernel at `k`; the split-q and gate kernels at 16 heads; `moe_fused_iq.cu` at 2048/512. Harness:
the restored `tests/cuda/prefill_*_test.cpp` plus chunked-prefill-then-decode against token-by-token
decode on a 40-token sequence (the oracle's `base_c7` case: chunks of 7). Negative tests: `VPK 3` on 32
heads, top-10 routing on 8.
**Step 4, pack, drafter, runner (20%).** `tools/iq_pack.py`: a `qwen35moe` entry in `FORM`/`ROUTERS`
(`ssm_alpha`, `ssm_beta`, `ffn_gate_inp`, `ffn_gate_inp_shexp` F32 to BF16 under `--compat-bf16` with
`compat-bf16.json`; norms, `ssm_a`, `ssm_dt.bias`, `ssm_conv1d` F32 copied; projections served natively),
`native_experts.txt` v3 per layer; `tools/test_iq_pack.py`'s `write_gguf()` fixtures at the new
architecture. The draft pack of 3.10 from the MTP file's `blk.40` (a new `tools/mtp_qwen36_pack.py`
replacing `mtp_pack.py`/`mtp_rt.py`), `mtp.cpp` and `prefill.cpp:972-1086` on the plain graph, the draft
experts through the native GPU kernels, `generate.cpp:3026` following the target. `make_profile.py` from
the E0 trace (40 x 256). Harness: the drafter's one-row forward against the oracle's `--mtp` dumps
(`mtp_eh_proj`, `mtp_attn_gated`, `mtp_ffn_out`, `result_output`; 50 nextn seams); the streaming runner
held to the oracle at every position of the 11- and 40-token cases, autoregressive and chunked
(`base_ar`, `base_c7`); then the real Q4 file, greedy, against llama.cpp's output distribution (top-1
agreement and KL per teacher-forced position, Maya's quantized-mode gates: no monotone positional drift,
selection equal at probed layers). Negative test: a 4 KB weight corruption must move the logits by more
than 1e-2 (the mutation-sensitivity gate).
**Step 5, serve and measure (10%).** The 1080 Ti at 11 GB, then `--vram-cap` 8 and 6; the other rungs when
a card frees up. `tools/calibrate.py` for `--pcie-frac`, `--spec-min-p`, `--pool-workers`; regina's harness
and the three instruments (`nvidia-smi` 100 ms, `nvprof` on Pascal, `perf stat`); the engine's points on
`ladder-baseline.png`; H5. `make test-chat-parser MODEL=<gguf>` against the template; the any-argument-order
patch checked for misfires; images through `--mmproj`. Acceptance A1 to A5 per rung.
**Step 6, the Pascal cards and the fat binary (5%).** `CMakeLists.txt:138-176`: `STRATA_EXPERIMENTAL_SM60`
default ON, `CMAKE_CUDA_ARCHITECTURES=61;70;75;86;89;120`, CUDA 12.8 (the sm_120-with-12.8 warning at
`:166-169` stays; RTX 50 is built, not measured). `cuobjdump --list-elf | grep sm_` after every build. The
1070 Ti and the 1060 against B1b; the sm_75+ paths checked on the 4090 or A6000 when one is free.
**Step 7, README (5%).** The supported model and checksums, the ladder against the baseline, the sizing
rule in words, the Pascal caveats.
The critical path runs through step 3's block-and-verify rewrite and its composition harness; the dense
attention kernel is the one new kernel, the rest is parameterisation and removal.
## 7. Risks
1. **Nobody has run this engine on Pascal.** The build refuses `cc < 75` without the experimental flag;
the flag is "community-tested, not in the ready-made engine" for sm_60/sm_70 (`CMakeLists.txt:150-160`),
and Maya requires Volta. The 1080 Ti is sm_61, so `__dp4a` is native and only the `__nanosleep` shim
applies (`dp4a.hpp:27-40`).
2. **FP16 on GP102/GP104/GP106 runs at 1/64 rate.** 21 kernel files touch half types. Conversions
(`__half2float`, the `hf()` stores in `prefill/kernels.cu:614, 761`, the fp16 K/V reads in
`qsa_decode_attn.cu`) are full rate; half *arithmetic* is not. The audit must separate the two in
`native_mmvq.cu`, `iq_kernels.cu`, `s_gemv.cu`, `shared_expert.cu` and the prefill kernels. The prompt
MoE is the exposed case: the MMQ (dp4a) path is gated by `mmq::built()`/`mmq::fits`
(`prefill.cpp:676-684`) and its tests exit 77 below sm_80 (`CMakeLists.txt:1076`); the fallback is the
FP16 GEMM path over dequantized fp16 weights (`prefill.cpp:907`), which is exactly the slow case. The
A3 floor of 300 tok/s prefill on Pascal depends on the dp4a MMQ running on sm_61, where llama.cpp's own
MMQ does run.
3. **Prompt attention on Pascal is the decode kernel.** `qsa_prompt_attn_batch` returns false for
`cc < 70` (`qsa_prompt_attn.cu:1433`) and prefill falls back to `qsa_decode_attn_batch` over the chunk
(`prefill.cpp:2222-2228`): correct, but a 2,048-query chunk through a decode-shaped kernel is a
throughput risk, and its split-K scratch is the 64.5 MiB-per-row item of 3.3.
4. **Memory items the plan did not count:** the draft block (~520 MiB), the dead indexer state (320 MiB
at 256K unless removed), the dense scratch, and the uniform-slot grant before the per-layer re-pricing
(`generate.cpp:3307-3327`), which is 17% of capacity at Q4 (2.195 versus 1.829 MiB) if the profile is
absent and the re-pricing does not run.
5. **KV streaming does not apply** (3.3 item 6): a 6 GB card at 256K holds the KV in VRAM or lowers the
context; there is no third option in this engine without a CPU attention path.
6. **Numerical:** BF16 rounding of the F32 router and GDN gates (3.4); the router's flip rate is measured
on the real file, and the acceptance gates are top-1 and KL, not per-logit tolerances, as Maya's
cross-check found (two flips in 512 explained by 1e-5 selection gaps).
7. **Verify-only decode.** Every token of a native pack goes through `verify.cpp` with `--spec T >= 2`
(`generate.cpp:2178`); the plain IQ3 file has no draft block, so its drafter is the Q4 file's `blk.40`
(3.10). Draft acceptance on Qwen3.6 is unmeasured; the prompt-lookup drafter alone leaves short windows.
8. **The replay's model:** `pcie_ms` 0, one IQ3 trace reused for Q4, a cache that never resets, no
prefill, `gpu_ms` an upper estimate (`phase0-replay.md`, "Limits"); the census blob sizes shift the Q4
disk tier up (4.3). The engine's counters, not the replay, decide H4 and H6.
9. **The host.** VM 211 has 8 vCPU of a Zen 1 shared with VM 220 and AVX2 only; the native expert path then
runs ggml-cpu `vec_dot` for the i-quants and the AVX-2 kernels for the rest (`generate.cpp:2068-2072`).
The 0.15 ms CPU lane is the replay's assumption; `perf stat` measures it.
10. **Upstream tooling gaps:** no published Python oracle for the Flash-Next kernels, so the parity files'
C++ references are the only pins of the existing semantics (`upstream-tooling.md` section 1); the
`bench/micro` llama.cpp-oracle tests cannot be restored.
## 8. Disagreements with the plan
1. **Section 2, the sizing rule's first fallback ("stream the KV to RAM above a resident window").** Not
available for dense attention (3.3 item 6): streaming resolves the selected cells, and every cell is
selected. The rule becomes KV in VRAM, then lower the context, then refuse. H3's "6 GB needs the KV
streamed" is replaced by: 6 GB at Q4 holds the fixed set at 256K only if prefill borrows from the cache
(~525 slots, table 4.3), else it takes 131,072 or the IQ3 file.
2. **Section 2, the fixed set.** Non-expert weights are 2,038 MiB at Q4 and 1,597 at IQ3, not ~3.1 / ~1.9
GB; the prompt buffer is 1.9 GB at chunk 2048, not 0.8; the drafter (~520 MiB) is missing from the
table. The plan says Phase 0 numbers replace the estimates; this study does so and adds the drafter.
3. **Section 2, the expert totals.** Q4 trunk experts are 18,726 MiB (19.6 GB), 1.829 MiB mean and 2.195
max per expert, not 17.4 GB / 1.7 MiB; IQ3 agrees (10,594 MiB). The 11 GB rung's tiers at Q4 shift to
~3,550 VRAM / ~4,950 RAM / ~1,740 disk with borrowing, and the replay's 13.2 disk reads per token is a
lower bound until it is re-run at the census sizes.
4. **Section 5 step 3, "`native_flash_attn.cu` is the fallback for prompts."** It is a diagnostic adapter
for contexts up to 256 with 24 heads hard-coded (`native_flash_attn.cu:196-206`, `layer.hpp:53`). The
prompt path is `qsa_prompt_attn.cu`, and on Pascal it is the batched decode kernel (risk 3). The dense
prompt attention comes from parameterising those two, not from `native_flash_attn.cu`.
5. **Section 5 step 2, "accept llama.cpp's fused `ffn_gate_up_exps` and `attn_qkv` forms or split them at
pack time."** No shipped Qwen3.6 file uses either (`gguf-metadata.md`). The study scopes this to a
named refusal in `check_experts_gguf` and `native_dense.cpp:31-33`; the oracle's fused cases stay as
evidence of the layouts should a file appear.
6. **Section 5 step 2, "per-layer prefetch hints as Maya's section 7 added."** This tree already has them:
`FileExpertSource::warm` issues `MADV_WILLNEED` per role (`PrefetchVirtualMemory` on Windows) for the
predicted ids (`expert_source.cpp:1129-1160`, `1264`). Nothing is ported from Maya; step 2 verifies the
hint fires on the Qwen3.6 pack's offsets and counts it.
7. **Section 2, "which file" (Q4_K_M-MTP, or Q4_K_XL plus a separately packed head).** The Q4_K_XL from the
MTP repository (rev 5bc3e238, SHA in `phase0-notes.md`) already carries `blk.40` (753 tensors). It is
the default file, and its `blk.40` is the draft pack for both arms (3.10).
8. **Section 1, "every kernel path on these cards must be FP32 or dp4a int8."** Agreed for arithmetic;
fp16 *storage* with conversion (the KV pools, the fp16 stores in prefill) is full rate on Pascal and
stays. The prompt MoE's dp4a MMQ must be enabled on sm_61 (risk 2), which the plan does not list.
Nothing else in Sections 0, 2 and 5 is contradicted: the target, the three tiers on the primary rung, the
Q4 default with the IQ3 arm, the Pascal-first build, the step order and the acceptance thresholds stand.
-290
View File
@@ -1,290 +0,0 @@
# Flash-Next geometry and extras baked into the Strata engine (6f32ec0, engine 0.1.39)
Scope: `src/` and `include/`. Target: Qwen3.6-35B-A3B (hidden 2048, 40 layers, GDN 16 k-heads / 32 v-heads,
16 attention heads / 2 KV heads of 256, dense attention, 256 experts top-8 of 512 plus a shared 512, no
hyper-connections, no PLE, MTP 1 layer, vocabulary 248,320). No fixes are proposed here.
Derived Qwen3.6 numbers used below: GDN conv channels 8192 (2*2048 + 4096), GDN value dim 4096, attention
`q_full` width 8192 (16 * 2 * 256), attention output width 4096, GQA group 8 (16 / 2), 40 layers = 30 GDN + 10 attention.
Classes:
- **RT**: already a runtime parameter (`ModelGeometry`, pack metadata, tensor shape). Fine as is.
- **CT**: a compile-time constant that disagrees with Qwen3.6. Must change.
- **CT-ok**: a compile-time constant that is an upper bound or a value Qwen3.6 shares. Needs no change.
- **ST**: a structural assumption. Needs a code path, not a number.
Line numbers are from the current tree. Where a path only runs for the canonical Q2_0 pack (not the `--native` GGUF
pack that Qwen3.6 would use), the note says "canonical only".
## A. The central finding: `ModelGeometry` is a default, and only two fields are ever read from the model file
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 1 | include/strata/core/layout.hpp:28-30 | `n_embd = 2560`, `n_layers = 48`, `qsa_interval = 4` | CT | Struct defaults. Nothing reads `n_embd`/`n_layers` from the file. Interval 4 already matches Qwen3.6. |
| 2 | include/strata/core/layout.hpp:33-38 | `ssm_k_heads 16`, `ssm_v_heads 48`, `ssm_conv_channels 10240`, `ssm_value_dim 6144` | CT | Conv channels and value dim are stored members, not derived from heads. Changing `ssm_v_heads` alone leaves them wrong. Heads 16 and state 128 and d_conv 4 already match. |
| 3 | include/strata/core/layout.hpp:41-45 | `n_head 24`, `idx_q_heads 4`, `idx_key_dim 128` | CT | `n_head` must be 16. `n_head_kv 2` and `head_dim 256` match. Indexer fields are meaningless for Qwen3.6. |
| 4 | include/strata/core/layout.hpp:48-49 | `hc = 4`, `hc_lr = 320` | CT / ST | No "hc = 1" meaning exists. `hc` sizes `R`, `inject`, every GR buffer. See section B. |
| 5 | include/strata/core/layout.hpp:52-53 | `n_expert = 512`, `n_ff = 640` | CT | One `n_ff` serves routed and shared experts. Qwen3.6 has 512 for both, so one field still works. |
| 6 | include/strata/core/layout.hpp:55-58 | `hc_dim() = hc*n_embd`, `n_qsa_layers = n_layers/interval`, `n_gdn_layers` | RT | Derived correctly from the fields. |
| 7 | src/program/generate.cpp:2073-2074 | `ModelGeometry g;` with the comment "canonical defaults", and `K = 10` | CT | `g` and `K` start from Flash-Next defaults. |
| 8 | src/program/generate.cpp:2089-2092 | Only `qwen4exp.expert_count` -> `g.n_expert` and `qwen4exp.expert_used_count` -> `K` are read, and only when `--native` is given | RT (partial) | The only model-file overrides of geometry. `block_count`, `embedding_length`, head counts, `ssm.*`, `expert_feed_forward_length` are never read. |
| 9 | src/program/generate.cpp:2093-2096 | Rope keys read under the `qwen4exp.` prefix | CT | Key prefix must become `qwen35moe.`. Values (base 1e7) happen to match. |
| 10 | src/program/generate.cpp:2008-2010 | `const ModelGeometry g0;` passed to `expert_layout_load(o.pack, g0.n_layers, g0.n_expert)` | CT | Runs before the line-2091 override, so it sees 48 layers and 512 experts. The `native_experts.txt` header can still correct `n_expert` (expert_layout.cpp:271). |
| 11 | src/program/generate.cpp:2184-2186 | `NativeEmbed::load(..., g0.n_embd, 248320, ...)` | CT | Default `n_embd` 2560 would reject a 2048-wide `token_embd.weight`. The 248320 literal equals Qwen3.6's vocabulary. |
| 12 | src/program/generate.cpp:3026 | `static const ModelGeometry draft_geometry{}` handed to `mtp.load` | CT | The comment says the draft layer is "the canonical model's MTP head (512 experts)". Draft geometry does not follow the target. |
| 13 | src/program/generate.cpp:771, 795 | Routing trace rejects `layer >= 48` | CT | Literal 48 in two bounds checks. |
| 14 | src/program/generate.cpp:5769 | `kImagePad = 248056` (comment: `qwen4exp.ple.image_token_id`) | CT-ok | Only feeds the PLE hash for image cells. Dead without PLE. |
| 15 | include/strata/core/session.hpp:48 | `SessionState::k = 10` | CT | Experts per token default. Overwritten from `K` at session init. |
| 16 | include/strata/core/expert_source.hpp:194 | `int k_ = 10` | CT-ok | Default only; set per layer at runtime. |
| 17 | include/strata/artifact/gguf_reader.hpp:576-578 | `Qwen4ExpGuard{block_count 48, hidden 2560, head_count 24, head_count_kv 2}` | CT | Struct defaults for the architecture guard. |
| 18 | include/strata/artifact/gguf_reader.hpp:581-597 | `check_architecture` requires `general.architecture == "qwen4exp"` and reads `qwen4exp.block_count`, `.embedding_length`, `.expert_count`, `.expert_used_count`, `.attention.head_count`, `.attention.head_count_kv` | CT / ST | Callers: native_dense.cpp:103, native_head.cpp:29 and :113, gguf_reader.cpp:57. Every Qwen3.6 load is refused here first. |
| 19 | include/strata/plan/plan.hpp:22-42, 49-52, 83, 133 | Standalone planner `Geometry` (48 layers, 12 QSA, 48 v-heads, 10240 channels, indexer cache term), `Costs::expert_blob = 1382400`, `vram_pool_bytes() = 5,943,000,000`, "slots of 1,382,400 B" | CT | Used only by src/plan/plan_main.cpp and src/core/device_main.cpp. Not on the serving path. Has no streaming-KV or RAM-tier model. |
| 20 | src/core/graph.cpp (whole file) | None | RT | No geometry. Graphs are keyed by `(LayerType, n_tokens)`. |
## B. Layer composition: `layer.hpp`, `layer.cpp`, `session.cpp`
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 21 | src/core/layer.cpp:1170-1286 (`block_layer_pre`), 1319-1342 (`block_layer_post`) | Every layer is `gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> router ... moe_finish -> gr_write(ffn)` | ST | The gated-residual read/write wraps both mixer and FFN on every layer. No plain "rms_norm -> mixer -> residual add" branch exists. |
| 22 | src/core/layer.cpp:1231-1255 | Four GR tensors per half, prefixes `hc_attn_` and `hc_ffn_` (`norm`, `down`, `up`, `inject`), required engine forms (norm F32, other three BF16) | ST | Qwen3.6 has `attn_norm` and `post_attention_norm` (plain RMS norms) instead. Neither name is referenced anywhere in src/. |
| 23 | src/core/layer.cpp:1088-1107 (`lm_head_mix`) | Final mix is `gr_read` with `output_hc_norm/down/up` | ST | Qwen3.6 needs `output_norm.weight` (plain RMS norm). That name is not referenced anywhere in src/. Same in verify.cpp:1123-1125. |
| 24 | src/core/layer.cpp:1127-1145 (`block_buffers_bytes/init`) | `R` is `(hc, n_embd)`; `inject`, `inject2`, `gr_rs`, `gr_workspace_bytes(GrShapes{n_embd, hc, hc_lr})` | RT | Sized from `g.hc`. Works for hc = 1 in size, but the GR math is meaningless there. |
| 25 | src/core/layer.cpp:1146-1158 (`dump_stride_floats`) | C1-oracle dump layout is `2*n_embd + 2*hc + n_head*head_dim + ...` | RT | Debug only. |
| 26 | src/core/session.cpp:141-148 | The first token's residual is `hc` copies of the embedding | RT / ST | Loops `g.hc` times. With hc = 1 it is one copy. |
| 27 | src/core/session.cpp:1, 228, 331, 424 etc. | Comments say "48 layers", but loops use `g.n_layers` | RT | Verified: loops at 55, 77, 194-205, 283, 301, 331, 391, 424, 662, 788, 856, 921 all use `g.n_layers`. |
| 28 | src/core/session.cpp:41-44 | `gdn_state_floats = S*v_heads*S + conv_channels*(d_conv-1)` | RT | From `ModelGeometry`. Correct once row 2 is fixed. |
| 29 | src/core/session.cpp:50-52, 71, 124-126, 159-162 | `ple_hist_bytes() = NG_HIST * NG_HC_DIM * 4` (9 x 10240 floats) is always carved and zeroed | CT-ok | Fixed ~360 KB per session, allocated even with no PLE. Harmless but dead. |
| 30 | include/strata/core/layer.hpp:524-587 and src/core/layer.cpp:1192-1229 | PLE runs only at `layer == 1`, and only when `ple != nullptr && ple->ready()` | RT | PLE is optional in the block. See rows 62 to 66 for what forces it on. |
| 31 | src/core/layer.cpp:355 | `moe_route` requires `1 <= k <= 64`; `moe_finish`/`moe_combine_parts` the same (456, 472) | RT | K = 8 is fine. |
| 32 | src/core/layer.cpp:370 | Native fused router only when `n_expert == 512 && k == 10`, else generic `router_top10` | RT | Guarded at runtime. 256/8 takes the generic kernel (row 87). |
| 33 | src/core/layer.cpp:396 | `moe_route_window` batched path excluded when native router active at 512/10 | RT | Same guard. |
| 34 | src/core/layer.cpp:335-354 | `moe_buffers_*` sized from `n_expert`, `k`, `n_ff` | RT | |
| 35 | src/core/layer.cpp:418-451 (`moe_shared`) | Shared expert has a sigmoid scalar gate `ffn_gate_inp_shexp` that must be engine form BF16 (`Bf16InF32`); the three projections need S-forms | ST | Qwen3.6 has the same scalar gate. Its GGUF dtype (F32 or BF16) has to match what the loader produces; see the tensor tables below. |
| 36 | src/core/layer.cpp:223-333 (`gdn_layer`) | Sizes from `g.ssm_*`; recurrence head pairing is `head % h_k` | RT | Matches ggml `repeat` tiling. Needs `h_v % h_k == 0` (32 % 16 = 0). |
| 37 | src/core/layer.cpp:247-248 | Fused conv path requires `d_conv == 4 && state_size == 128`; fused step requires `state_size == 128` (306) | CT-ok | Qwen3.6 matches. |
| 38 | src/core/layer.cpp:276 | `scale_inplace(b.h, qk, 1/sqrt(S))` on the legacy (non-native) path | RT | |
| 39 | src/core/layer.cpp:288-318 and kernels (rows 76-79) | GDN output gate is `rms_norm(o) * ssm_norm * sigmoid(z)` | **ST / CT** | **Qwen3.6 uses SiLU(z), not sigmoid(z).** llama.cpp qwen35moe.cpp:273 `ggml_silu(gate)`, qwen4exp.cpp:481 says "the one numerical difference from Qwen3.5's GDN". The layer.hpp:16 comment records it. This is the only numerical (not geometric) GDN difference. |
| 40 | src/core/layer.cpp:505 (`qsa_shapes`) | Starts from `qsa_real_shapes()` then overrides `n_head`, `n_head_kv`, `head_dim`, `idx_*` from `ModelGeometry` | RT / CT | `n_rot = 64`, `idx_block = 4`, `idx_top_k = 2048`, `page_size = 4` stay compile-time (rows 41 to 44). `n_rot 64` matches Qwen3.6 (0.25 * 256). |
| 41 | include/strata/kernels/qsa.hpp:98-113 (`qsa_real_shapes`) | `n_head 24`, `idx_n_head 4`, `idx_dim 128`, `idx_block 4`, `idx_top_k 2048`, `page_size 4` | CT | Used by layer.cpp:505, mtp.cpp:71, verify.cpp:~100, prefill.cpp:862 etc. |
| 42 | include/strata/kernels/qsa.hpp:144-147, 282 | `qsa_selection_width = min(n_kv, idx_top_k + idx_block - 1)`; `kTopkMaxCells = 32768` | ST | Attention reads only the selected cells, via `ids`. With the indexer absent there is no selection, so every cell must attend. |
| 43 | src/core/layer.cpp:559-575, 761-790 | `qsa_state_bytes` / `qsa_buffers_bytes` include `idx_pooled`, `idx_tail`, `idx_dead`, `pooled_rows = max_cells/idx_block + 2`, indexer scratch, `cell_scores` | ST | The KV state always carries indexer state (about `max_cells/4 * 128 * 4` B per layer). The drafter already passes `ring_cells > 0` for a state "which has no indexer" (layer.cpp:527-531, `pooled_rows = 2`). |
| 44 | src/core/layer.cpp:876-1019 (`qsa_layer`) | Always runs: `indexer.k_proj` BF16 projection (962), indexer key append (945-948), `indexer.q_proj` + norm + rope (962-964), block scores + top-k (966-975), KV resolve, gather/attend over the selected `ids` | ST | The indexer is not optional in this function. It requires `indexer.{k,q}_proj.weight` BF16 and `indexer.{k,q}_norm.weight` (line 891 and the `Req` list). A dense path would skip steps 3, 5-indexer, 7, 8-score/select and attend over `0..n_kv`. |
| 45 | src/core/layer.cpp:891-897 | `w_idxk = v.get("indexer.k_proj.weight")` and `w_idxq` are dereferenced, with a BF16 form check | ST | Null here is an error, not a skip. |
| 46 | src/core/layer.cpp:938-1010 | KV in 4 formats (fp16 / int8 / q4_0 / k8v4), hybrid rotations (`fwht256`), paged pools | RT | `head_dim 256` only (kv_q4.cu:176). Same for Qwen3.6. |
| 47 | src/core/layer.cpp:556 | `qsa_kv_resident_min() = 20480` cells | CT-ok | Streaming floor. Independent of geometry. |
## C. Loader, layout, metadata
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 48 | src/core/layout.cpp:50-80 | `check_one` requires per layer: `hc_attn_{down,up,inject}`, `hc_ffn_{down,up,inject}` with `hc_dim x hc_lr` shapes | ST | `blk.N.hc_*` do not exist in a Qwen3.6 GGUF. |
| 49 | src/core/layout.cpp:60-63 | `ffn_gate_inp [n_embd, n_expert]`, `ffn_{gate,up}_shexp [n_embd, n_ff]`, `ffn_down_shexp [n_ff, n_embd]` | RT | Use `ModelGeometry`. |
| 50 | src/core/layout.cpp:65-70 | GDN: `attn_qkv [n_embd, conv_channels]`, `attn_gate [n_embd, value_dim]`, `ssm_out [value_dim, n_embd]`, `ssm_conv1d [d_conv, channels]`, `ssm_alpha/beta [n_embd, v_heads]` | RT | Same orientation as llama.cpp qwen35moe. |
| 51 | src/core/layout.cpp:72-79 | Attention: `attn_q [n_embd, 2*n_head*head_dim]`, `attn_k/v [n_embd, n_kv*head_dim]`, `attn_output`, and `indexer.q_proj`, `indexer.k_proj` | RT / ST | Attention shapes RT. The two indexer tensors are ST (required). |
| 52 | src/core/layout.cpp:97-106 | 1-D set: `hc_attn_norm`, `hc_ffn_norm` (`hc_dim`, F32), `ffn_gate_inp_shexp` (BF16), `ssm_a`, `ssm_dt.bias`, `ssm_norm`, `attn_q_norm`, `attn_k_norm`, `indexer.q_norm`, `indexer.k_norm` | ST | Same split as rows 48 and 51. |
| 53 | src/core/layout.cpp:162-169 | `check_all` counts `g.n_qsa_layers()` / `g.n_gdn_layers()` | RT | |
| 54 | src/core/layout.cpp:141, 149; layout.hpp:91 | `check_layer` / `check_all` have no call site in src/ | n/a | Grep finds none. The shape assertions are not enforced at load in this tree. Parity tools outside src/ may call them. |
| 55 | include/strata/core/layout.hpp:63 | `is_qsa_layer = layer % interval == interval - 1` | RT | Layers 3, 7, ..., 39 for Qwen3.6. |
| 56 | src/core/weights.cpp:91, 123, 146-191 | Loads whatever `<pack>/index.txt` lists (19 fields per row), into an arena | RT | Name-driven and shape-driven. The model-specific part is the pack builder (`tools/pack_index.py`, `tools/iq_pack.py`, not in this tree). |
| 57 | src/core/native_dense.cpp:31-33 | Native dense GGUF suffixes: `.attn_qkv`, `.attn_gate`, `.ssm_out`, `.attn_q`, `.attn_k`, `.attn_v`, `.attn_output`, `.ffn_{gate,up,down}_shexp` (all `.weight`) | RT | The names match llama.cpp. A fused attention-layer `attn_qkv` (a llama.cpp option) would not match the engine's separate q/k/v. |
| 58 | src/core/native_dense.cpp:102-104, 169-172 | Needs `general.architecture` passing `check_architecture`; each native tensor must already be in the canonical table with a matching 2-D shape | ST | See row 18. Also requires a pack index entry per tensor. |
| 59 | src/core/native_head.cpp:29, 32-39 | `output.weight` must be `[n_in, n_out]`; `n_in % 256 == 0` | RT | 2048 % 256 = 0. `n_out` comes from the pack. |
| 60 | src/core/native_head.cpp:108-128 | `token_embd.weight` must be `[n_embd, n_vocab]` | RT | Caller passes the literals from row 11. |
| 61 | src/core/layer.cpp:1033-1087 (`embed_row`) | `w->ne0 != g.n_embd` is an error | RT | Follows `g.n_embd`. |
## D. PLE and the n-gram table
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 62 | src/program/generate.cpp:1800-1815 | `--native` requires `--ple-gguf` (or a shard holding `per_layer_token_embd.weight`); `--native` plus `--no-ple` is refused | ST | Qwen3.6 has no such tensor, so every native launch is refused. |
| 63 | src/program/generate.cpp:1843-1855 | Without `--native`, `--ple-gguf` is "required"; `--no-ple` is called a "diagnostic ablation" | ST | PLE is mandatory at the CLI, optional in the kernels. |
| 64 | src/program/generate.cpp:2395-2500 | When a PLE table is opened, the pack must contain `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` or the launch fails ("a DIFFERENT MODEL") | ST | Skipped when `--no-ple`. |
| 65 | src/core/native_dense.cpp:29-30, 65-73, 156; generate.cpp:2207-2209, 1956 | Special-casing of `blk.1.ple_key.weight` | ST | Dead without PLE. |
| 66 | include/strata/kernels/ngram.hpp:31-49 | `NG_N_EMBD 2560`, `PLE_HEAD_DIM 160`, `NGRAM_SIZE 3`, `HEADS_PER_NGRAM 8`, `PLE_N_HEADS 16`, `NG_HC 4`, `NG_HC_DIM 10240`, `NG_HIST 9`, `PLE_TABLE_ROWS 320001536`, `PLE_EOS_TOKEN_ID 248044` | CT-ok | All PLE-only. Dead if PLE is skipped. `NG_HIST` x `NG_HC_DIM` still sizes a session buffer (row 29). |
| 67 | src/kernels/cuda/ple.cu:238; native_ple_postops.cu:35, 98; include/strata/kernels/native_ple_postops.hpp:6 | `static_assert(NG_N_EMBD == 2560 ...)`; `N = 2560, H = 4, HISTORY = 9` | CT-ok | Compiles regardless; never launched without PLE. |
| 68 | src/prefill/prefill.cpp:543-549, 806-814, 924-925, 1401, 1590-1599, 1683-1714, 1920 | Prefill allocates `ple_emb`, `ple_norm`, pinned PLE staging; runs the PLE at layer 1 when `ss.ple.ready()` | RT | Guarded by `ple_on`. Buffers are still allocated (about `T * 2560 * 4`, `NG_HC_DIM * 4`). |
| 69 | src/core/verify.cpp:370, 408, 559, 636-675, 1311, 1405 | Verify window stages and runs the PLE at layer 1 when `ss.ple.ready() && ple_stage()` | RT | Guarded. |
## E. MTP drafter (`mtp.cpp`, `mtp.hpp`)
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 70 | src/core/mtp.cpp:150-216 | Loads `<rt_dir>/dense.txt`, `dense.bin`, `experts.bin` produced by `tools/mtp_rt.py` (not in this tree), all dense weights as Q8_0 | ST | The drafter does not read the GGUF. |
| 71 | src/core/mtp.cpp:210-212 | Required tensors: `fc_embedding.weight`, `fc_hidden.weight`, `self_attn.{q,k,v,o}_proj.weight`, `mlp.shared_expert.{gate,up,down}_proj.weight` | ST | vLLM-style names. Qwen3.6's MTP has one `nextn.eh_proj [2*n_embd, n_embd]` over `[enorm(emb), hnorm(h)]`, not two separate projections. |
| 72 | src/core/mtp.cpp:488-495 | `pre_fc_norm_embedding` -> `fc_embedding`; `pre_fc_norm_hidden` over `hc*n_embd` -> `fc_hidden` per stream -> `R = h + e` broadcast over `hc` streams | ST | Qwen3.6: `eh_proj(concat(enorm(emb), hnorm(h)))`, one stream. |
| 73 | src/core/mtp.cpp:503-507, 564-568, 613-625 | Three hyper-connection groups: `attn_hyper_connection.*`, `mlp_hyper_connection.*`, `hyper_connection_mixer.*` | ST | Same gated-residual structure as rows 21-23. |
| 74 | src/core/mtp.cpp:191, 200, 306-308, 579 | Drafter experts are `n_expert * cpu::BLOB` bytes in VRAM, canonical Q2_0 at 2560/640, run through `moe_group_resident` | CT | `BLOB = 1,382,400`. Qwen3.6 Q2_0 blob would be `3 * 2048 * 512 * 18/64` = 884,736 B. Message text says "the 512 experts do not fit". |
| 75 | src/core/mtp.cpp:575, 598 | Draft router `mlp.gate.weight` BF16 `[n_embd, n_expert]`; `mlp.shared_expert_gate.weight` BF16 | RT | Shape-driven. |
| 76 | src/core/mtp.cpp:71-78, 218-249 | Draft KV is dense attention (no indexer state read), shapes from `ModelGeometry` | RT | The header says it is "identical to the model's sparse selection below 2,051 cells". The only existing dense-attention path. |
| 77 | src/core/mtp.cpp:428-454 | Head is the main `output.weight`; `n_vocab_ = wo->ne1`; optional `draft_vocab.bin` subset | RT | Vocabulary size is a runtime value. Subset files (`data/draft_vocab_*.bin`) are token ids into the same 248,320 vocabulary. |
| 78 | src/core/mtp.cpp:477, 488 | Draft embeds from `token_embd.weight` | RT | |
| 79 | src/core/mtp.cpp:251-268 | Buffers from `g.hc`, `g.hc_lr`, `g.n_head` | RT | |
| 80 | src/prefill/prefill.cpp:972-1086 | MTP prefill reads `attn_hyper_connection.hc_norm.weight`, uses `LR`, `HC`, `fc_hidden` per stream | ST / CT | Same vLLM-style structure as row 72. |
## F. GDN kernels
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 81 | src/kernels/cuda/native_gdn.cu:37, 100-102, 117 | `S = 128`; grid `h_v` x `S/4`; requires `h_v % h_k == 0`, `h_v <= 65535` | RT | Heads from `GdnShapes`. State layout `(S, h_v, S)`. |
| 82 | src/kernels/cuda/native_gdn.cu:51 | `q_head = head % h_k` | RT | Modulo pairing. |
| 83 | src/kernels/cuda/fused_gdn.cu:12-14, 22-24, 127-129, 148-153 | `S = 128`, `RG = 4`; grid `h_v`; `qk_heads` blocks for conv+L2; `h_v % h_k == 0` | RT | |
| 84 | src/kernels/cuda/gdn.cu:46-59, 156 | `MAX_H = 8` heads per block, `S <= 128` | RT | Legacy path; only a performance shape. |
| 85 | src/kernels/cuda/gdn.cu:148 | `y = o * rms * ssm_norm * sigmoid_f(z)` | **CT** | **SiLU for Qwen3.6.** See row 39. |
| 86 | src/kernels/cuda/fused_gdn.cu:69 | `... * (1/(1+exp(-zz)))` in `gdn_step_norm_kernel` | **CT** | **SiLU for Qwen3.6.** The default decode path for native packs. |
| 87 | src/kernels/cuda/native_gdn_preprocess.cu:110-112 | `weighted * sigmoid(z)` in the out-norm kernel | **CT** | **SiLU for Qwen3.6.** The same file's `conv_silu` (53-67) and `beta_sigmoid` (86-88) are correct for both models. |
| 88 | src/prefill/kernels.cu:324, 612 | `sigm(z)` in `gdn_rec_kernel` and `gdn_out_norm_kernel` | **CT** | **SiLU for Qwen3.6.** Prompt path. |
| 89 | src/prefill/kernels.cu:18-19 | `N = 2560, HC = 4, D = N*HC, LR = 320`; `S = 128, HK = 16, HV = 48, C = 10240` | CT | Constants for every prompt-path GDN, GR and gate kernel. |
| 90 | src/prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924 | GDN prompt kernels index with `HV`, `HK`, `C`; launched `<<<HV, ...>>>`, `<<<HV*NCB>>>`, `<<<HK*NCB>>>` | CT | Includes `VPK = HV/HK = 3` value heads per key head (478): 2 for Qwen3.6. `gdn_rec_kh_kernel` is specialised on it. |
| 91 | src/prefill/gdn_rec_parity.cu | Parity harness for the above | CT | Mirrors the same constants. |
| 92 | include/strata/kernels/gdn.hpp:11, 64; layer.hpp:10, 21, 23, 546 | Comments cite 10240 / 48 / 2560 | n/a | Comments only. |
## G. Attention kernels (the QSA path)
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 93 | src/kernels/cuda/qsa_decode_attn.cu:16-17, 110, 272, 453, 497 | `HD = 256`, `G = 12` (query heads per KV head); refuses with `exit(1)` unless `n_head == 12 * n_head_kv` | CT | The main decode kernel. Qwen3.6 has G = 8. |
| 94 | src/kernels/cuda/qsa_prompt_attn.cu:21-22, 115-116, 1442-1447 | `HD = 256`, `G = 12`; refuses unless `n_head == 12 * n_head_kv` | CT | The prompt attention kernels (tensor-core). |
| 95 | src/kernels/cuda/native_flash_attn.cu:55, 196-197, 206 | `kv = head / 12`; refuses unless `n_head == 24 && n_head_kv == 2 && head_dim == 256`; grid 24; context 1..256 | CT | Short-context adapter only. |
| 96 | src/kernels/cuda/qsa.cu:96 | Generic `qsa_attend`/`kv_append`/`kv_gather`; requires `n_head % n_head_kv == 0` | RT | Reference-quality path. |
| 97 | src/kernels/cuda/native_rope.cu:121 | `head_dim in {128, 256}`, `n_rot == 64` | CT-ok | Matches Qwen3.6 (partial rotary 0.25 of 256). |
| 98 | include/strata/kernels/mrope.hpp:3-12 | Interleaved M-RoPE sections 11/11/10/0; text has `t = h = w` | CT-ok | Qwen3.6 uses the same sections. |
| 99 | src/kernels/cuda/native_qsa_score.cu:31, 194 | Indexer: `D = 128, HEADS = 4, R = 4`, `idx_top_k == 2048` | ST | Indexer-only. Not reachable without the indexer. |
| 100 | src/kernels/cuda/native_qsa_indexer.cu:35, 231, 259 | `D = 128, R = 4, ROT = 64` | ST | Indexer-only. |
| 101 | src/kernels/cuda/qsa_select.cu:17-19, 161-165, 467-475, 1081, 1115, 1220 | `IDX_DIM 128`, `IDX_HEADS 4`, `R 4`; requires `cap >= qsa_selection_width(kTopkMaxCells, s)` | ST | Indexer-only. With the indexer absent nothing here runs, and nothing else produces the `ids` that `qsa_decode_attn` consumes. |
| 102 | src/kernels/cuda/qsa_decode_attn.cu | The kernel gathers K/V through `ids` and `pools.page_table`, so it is selection-agnostic | RT | An identity `ids` would attend over every cell. No other dense decode kernel exists. |
| 103 | src/kernels/cuda/kv_q4.cu:176, kv_q8.cu | `head_dim == 256` | CT-ok | Matches Qwen3.6. |
| 104 | src/kernels/cuda/kv_stream.cu:23 | `RT = 1024` resolve block | CT-ok | Streaming resolve granularity. Reads `ids`. |
| 105 | src/prefill/kernels.cu:752-761, 1016, 1020 | `split_q_kernel`, `gate_attn_kernel`: `T * 24 * 256`, `24 * 512` | CT | Prompt-path q/gate split and gate. 16 heads for Qwen3.6. |
| 106 | src/prefill/prefill.cpp:649-650, 883-884 | `T * 12288` (= 24 * 512) for `Qf`; `T * 512` for `Kc/Vc` (2*256, unchanged); `T * ZV` for `q` and attn; `T * 128`, `T * 512` for `idx_raw`, `q_idx` | CT | `12288` and `ZV = 6144` must change. `512` for K/V stays. The two indexer buffers are dead without the indexer. |
## H. Experts, router, shared expert
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 107 | include/strata/kernels/cpu/expert.hpp:34-36, 40-47 | `H = 2560`, `FF = 640`, `NE = 512`, `BLOB = 1,382,400`, `ROW_GU`, `SC_GU` | CT | Canonical Q2_0 blob geometry. Canonical only. Used by the rows below. |
| 108 | src/kernels/cpu/expert_layout.cpp:284 | `native_fmt(gt, dt, H, FF, f, err)` | **CT** | **The one compile-time leak in the native-pack path.** The layout loader builds each layer's `NativeFmt` with 2560/640 and then checks `f.bytes == blob`. A 2048/512 pack fails the "blob is X B but its formats make Y" check. |
| 109 | src/kernels/cpu/expert_layout.cpp:233-244, 271 | `native_experts.txt` header "(n_expert N)" overrides `n_expert`; absent file means canonical pack, total = `n_layers*n_expert*BLOB` | RT | |
| 110 | include/strata/kernels/cpu/expert_layout.hpp:20, 32, 35-37 | `n_expert = NE` default, `max_blob = BLOB` default | CT-ok | Overwritten for native packs. |
| 111 | include/strata/kernels/cpu/native_expert.hpp:17-19; src/kernels/cpu/native_expert.cpp:64 | `kNativeActBytes = 4096`, `kNativeHBytes = 1024` upper bounds, checked at layout time | CT-ok | 2048-wide Q8_K is 2336 B; 512-wide Q8_K is 584 B. Both fit. |
| 112 | src/kernels/cpu/native_expert.cpp:40-60 | `native_fmt(gu_type, d_type, n_embd, n_ff)` is runtime; requires whole ggml blocks | RT | 2048 and 512 are multiples of 256 and 32. K-quants and Q8_K activations work for n_ff = 512 (unlike 640). |
| 113 | src/core/expert_source.cpp:1863-1868 (`expert_pool_dispatch`) | Refuses `n_embd != H` ("compiled for a 2560-wide activation") | CT | Canonical single-token path only. |
| 114 | src/core/expert_source.cpp:1869-1875 | `expert_pool_dispatch` refuses a native pack outright ("single-token expert path does not take a native pack") | **ST** | **Native-pack experts run only in verify windows.** generate.cpp:~2180 also requires `--spec T >= 2` and `--prefill`. Every decoded token therefore goes through verify.cpp. |
| 115 | src/core/expert_source.cpp:367-376, 2328; include/strata/core/expert_source.hpp:241 | Canonical size checks with `BLOB`; `ExpertDispatch::n_expert = cpu::NE`; hit path uses `cpu::H` | CT | Canonical only. `n_expert` is overwritten at generate.cpp:3683. |
| 116 | src/core/expert_source.cpp:2475-2500 (`check_experts_gguf`) | Native experts are read from `blk.N.ffn_{gate,up,down}_exps.weight` as three separate tensors, each `[cols, rows, n_expert]` | ST | llama.cpp may fuse gate and up into `ffn_gate_up_exps` (`create_tensor_gate_up_exps`, llama-model.cpp:3253). The engine accepts only the separate form. |
| 117 | src/core/expert_source.cpp:1979-1980 | `MAXT * 10 <= kMaxWindowEntries (128)` | CT-ok | 8 * 10 = 80; with k = 8 it is 64. |
| 118 | src/core/expert_cache.cpp, include/strata/core/expert_cache.hpp | Slots, residency `[n_layers * n_expert]`, profile file `(n_layers, n_expert)` header, `n_layers/n_expert <= 65535` | RT | All sizes passed in. The profile header is checked against `(n_layers, n_expert)` (cache.cpp:43). |
| 119 | src/kernels/cuda/iq_kernels.cu:1076-1140, 2543 | Native GPU expert kernels read `L.n_embd` and `L.n_ff` per layer; the fast sub-warp paths apply only when `n_ff == 640` (else 8-row fallback) | RT | Runtime guard. |
| 120 | src/kernels/cuda/iq_kernels.cu:309-350, 512-518 | Unsloth UD-Q4_K_XL expert types already supported: Q4_K / Q5_K gate-up, Q5_1 / Q8_0 down | RT | Native GPU expert dequant kernels exist for the Qwen3.6 UD quant family. |
| 121 | src/kernels/cuda/s2_expert_grouped.cu:37-46, 139-195, 301-346 | `H = 2560`, `FF = 640`, `ROW_GU`, `SC_GU`, blob offsets | CT | Canonical Q2_0 VRAM-hit kernels. Used for the MTP drafter's experts (row 74), not for native packs. |
| 122 | src/core/remote_experts.cpp:16-18, 246; src/core/peer_experts.cpp:25-26, 115, 130; src/core/remote_expert_opt.cu:13-14 | `H`, `FF` from `cpu::`, `CAP = MAXT * 10`, `k != 10` refused | CT | Multi-GPU expert tiers. Out of scope for a single card. |
| 123 | src/program/generate.cpp:3721 | `moe_hit_grouped_scratch_bytes(K, g.n_embd, cpu::FF)` | CT-ok | Over-allocates by 640 vs 512. |
| 124 | src/kernels/cuda/router_top10.cu:65-215; include/strata/kernels/router_top10.hpp:21 | Generic top-k softmax router: `n_expert <= 512`, `k <= 32`, runtime `n_expert` and `k` | RT | Handles 256 / 8. |
| 125 | src/kernels/cuda/native_router.cu:49, 54, 73, 97, 111-122 | Fused pinned router: `512` logits, `10` outputs, `REG 16`, hard-coded in the kernel and the validity checks | CT | Used only when `n_expert == 512 && k == 10` (row 32). Otherwise bypassed. |
| 126 | src/kernels/cuda/native_moe.cu:62-63, 79-80 | `native_moe_combine` requires `1 <= k <= 15` | RT | |
| 127 | src/kernels/cuda/shared_expert.cu:191, 237-239, 325-328 | `n_tok 1..8`; Q8_K activation needs `n_ff % 256 == 0` | RT | 640 failed this; 512 passes. Header comments in s_gemv.hpp:122-124 and layer.cpp:419-437 ("Q8_K is structurally impossible") describe Flash-Next only. |
| 128 | src/prefill/kernels.cu:616-657, 928-936 | Prompt `route_kernel<REG>`: `REG 16` for 512, `REG 8` for 256; rank loop `< 10`, writes `ids[t*10 + rank]`, `lane < 10` | CT | A 256 variant exists, but top-10 is baked into the kernel. |
| 129 | src/prefill/kernels.cu:660-692, 947, 951; moe_fused.cu:46-53, 199-203, 343; moe_mmq.cu:60-75, 249 | Canonical Q2_0 blob dequant and fused kernels: `1280 * 640`, `2560 * 160`, `n * 640`, `10 * AB` | CT | Canonical only. |
| 130 | src/prefill/moe_fused_iq.cu:59 | `GU_ROWS_K = 2560, D_ROWS_K = 640` | CT | Native-pack fused prompt MoE. Used as K of gate/up and of down. |
| 131 | src/prefill/prefill.cpp:90-91 | `N = 2560, HC = 4, D = N*HC, LR = 320, K = 10, NE = 512; C = 10240, ZV = 6144, HV = 48` | CT | File-wide constants. |
| 132 | src/prefill/prefill.cpp:737 | `Prefill::init` refuses unless `g.n_embd == N && g.hc == HC && g.hc_lr == LR && ss.k == K` | CT / ST | Hard refusal; every chunked-prefill launch fails on Qwen3.6. |
| 133 | src/prefill/prefill.cpp:681-685, 704-721, 896-907, 1294-1322, 1391 | Prompt MoE buffers: `T*K*1280`, `T*K*640`, `q8_bytes(.., 640)`, `1280 * 2560`, `2560 * 640`, `RP = 48` (1303) | CT | `1280 = 2*n_ff`, `640 = n_ff`, `2560 = n_embd`. |
| 134 | src/prefill/prefill.cpp:1724 and loops | Iterates `g.n_layers` and `is_qsa_layer` | RT | |
| 135 | src/prefill/prefill.cpp:854-856, 1000-1026, 1375-1380 | `grs`, `gated`, `inj`, `xq`, `ident` sized from `HC`, `D`, `LR` | CT | Hyper-connection buffers in prefill. |
| 136 | include/strata/prefill/kernels.hpp:15-16, 40, 52, 54, 58, 79 | Declarations documented as `2560 / 4 / 320`, `48 v heads`, `512, top-10`, `[1280, 2560]`, `640`, `[T, 24, 512]` | CT | Comments describing the constants above. |
## I. Hyper-connection (gated residual) kernels
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 137 | src/kernels/cuda/fused_gr.cu:20-28, 253-254, 320-321, 1164-1166 | `N = 2560, HC = 4, LR = 320, D = 10240`; `DOWN_BLOCKS = LR/8`, `UP_BLOCKS = N/32`, `UPM_BLOCKS = N/16`; `fused_gr_supported()` returns `n_embd == N && hc == HC && hc_lr == LR` | CT | Default decode and verify GR kernels. |
| 138 | src/core/layer.cpp:1195, 1319-1342, verify.cpp:336 | `fused = g_fused_gr && ... fused_gr_supported(...)`; verify refuses without it | CT / ST | Row 142. |
| 139 | src/kernels/cuda/gr.cu, native_gr_norm.cu, native_gr_postops.cu | Generic `GrShapes{n_embd, hc, hc_lr}` unfused path | RT | The generic GR is runtime-shaped, but its semantics (down/up/inject mixing) are the hyper-connection. |
| 140 | src/kernels/cuda/cvec.cu:11-17; verify_kernels.cu:256-291 (`broadcast_streams`, `add_streams_broadcast`) | Control-vector apply on `hc*n_embd`; stream broadcast | RT | `MAXK = 16` supports `n_embd <= 4096`. |
## J. Verify window (`verify.cpp`) and the speculation protocol
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 141 | src/core/verify.cpp:331-334 and layer.cpp:476-486 (`layer_verify_compatible`) | The verify window needs native BF16 projections, fused GR, fused native GDN, split-K decode attention, block top-k selection, **native QSA indexer** | ST | Verify is the only decode path for native packs (row 114). It cannot be built on a layer that has no fused GR and no indexer. |
| 142 | src/core/verify.cpp:336-340 | Refuses unless `fused_gr_supported && ss.k == 10 && ssm_state_size == 128 && ssm_d_conv == 4` ("geometry differs from the artifact's") | CT / ST | |
| 143 | src/core/verify.cpp:356-434 | Buffers `R_ (T*HC*N)`, `inj_`, `lo_ (T*hc_lr)`, `xn_ (T*HC*N)`, `idx_raw_L_`, `qidx_`, `tail_snap_` | RT / ST | Sized from `g.hc`, `g.hc_lr`, `idx_*`. |
| 144 | src/core/verify.cpp:550-559 | `IQ = idx_q_heads`, `ID = idx_key_dim`, `NE = n_expert`, `TS = (idx_block-1)*ID` | RT | |
| 145 | src/core/verify.cpp:757-761, 772-870, 1271-1311 | Attention step: `need(v, "indexer.k_proj.weight")`, `indexer.q_proj`, `indexer.q_norm`, `indexer.k_norm`; indexer append, block scores, top-k per window row; commit restores the indexer tail | ST | Same as row 44, for the multi-token path. |
| 146 | src/core/verify.cpp:916 | Batched native router only when `NE == 512 && K == 10` | RT | Guarded. |
| 147 | src/core/verify.cpp:1123-1125 | Head mix needs `output_hc_{norm,down,up}.weight` | ST | Row 23. |
| 148 | src/core/verify.cpp:347-349 | `n_vocab_ = output.weight.ne1` | RT | |
| 149 | include/strata/kernels/verify_kernels.hpp:21 | `kVerifyMaxT = 8` | CT-ok | Draft window cap. |
| 150 | src/kernels/cuda/verify_kernels.cu:366, 397-401, 506 | Grid `48 * 8`; `kVerifyMaxT * 10 <= kResidentPlanMax` | CT-ok | The 48 is a block count, not a layer count. |
## K. Vocabulary, sampler, metadata keys
| # | file:line | Assumption | Class | Note |
|---|---|---|---|---|
| 151 | src/kernels/cuda/sampler.cu:102-700 | `n_vocab` is a kernel argument everywhere; the split top-k merge handles `n_vocab <= 262,144` (607) | RT | 248,320 fits. |
| 152 | src/program/generate.cpp:479-481 | Default EOS ids `{248044, 248046}` | CT-ok | Same tokenizer; override with `--eos-ids`. |
| 153 | include/strata/artifact/gguf_reader.hpp:581-597 | All keys read use the `qwen4exp.` prefix | CT | Row 18. The Qwen3.6 GGUF uses `qwen35moe.*`. Also needed and not read anywhere: `qwen35moe.ssm.{conv_kernel,inner_size,state_size,time_step_rank,group_count}`, `.expert_feed_forward_length`, `.expert_shared_feed_forward_length`, `.full_attention_interval`, `.rope.dimension_sections`, `.nextn_predict_layers`. |
| 154 | frontend/ | Tokenizer, template, tool-call parser, vision | n/a | Model-agnostic per the plan. Not part of this inventory. |
## Tensor names the loader expects (engine side) against llama.cpp qwen35moe
Engine names come from layout.cpp:50-106, layer.cpp, native_dense.cpp:31-33 and expert_source.cpp:2491.
llama.cpp names come from `third_party/llama.cpp/src/models/qwen35moe.cpp:43-138` and `src/llama-arch.cpp:435-587`
(pinned commit 3cf0325).
**One GDN layer, `blk.N.`**
| Engine expects | Shape / form | llama.cpp qwen35moe | Match |
|---|---|---|---|
| `hc_attn_norm.weight`, `hc_attn_down.weight`, `hc_attn_up.weight`, `hc_attn_inject.weight` | `[hc_dim]` F32; BF16 | none | **Engine-only (hyper-connection)** |
| `hc_ffn_norm.weight`, `hc_ffn_down.weight`, `hc_ffn_up.weight`, `hc_ffn_inject.weight` | same | none | **Engine-only** |
| (none) | | `attn_norm.weight` `[n_embd]` | **llama.cpp-only** |
| (none) | | `post_attention_norm.weight` `[n_embd]` (pre-FFN norm; there is no `ffn_norm`) | **llama.cpp-only** |
| `attn_qkv.weight` | `[n_embd, conv_channels]` | `attn_qkv.weight` `[n_embd, 2*key_dim + value_dim]` | yes |
| `attn_gate.weight` | `[n_embd, value_dim]` | `attn_gate.weight` | yes |
| `ssm_conv1d.weight` | `[d_conv, conv_channels]` F32 | `ssm_conv1d.weight` | yes |
| `ssm_alpha.weight`, `ssm_beta.weight` | `[n_embd, v_heads]` BF16 | same names, `{n_embd, n_v_heads}` | yes, dtype to confirm |
| `ssm_a` | `[v_heads]` F32 | `ssm_a` (no `.weight`) | yes |
| `ssm_dt.bias` | `[v_heads]` F32 | `ssm_dt.bias` | yes |
| `ssm_norm.weight` | `[128]` F32 | `ssm_norm.weight` `{head_v_dim}` | yes |
| `ssm_out.weight` | `[value_dim, n_embd]` | `ssm_out.weight` | yes |
| `ffn_gate_inp.weight` | `[n_embd, n_expert]` BF16 | same | yes, dtype to confirm |
| `ffn_gate_exps.weight`, `ffn_up_exps.weight`, `ffn_down_exps.weight` | `[n_embd, n_ff, n_expert]` x2, `[n_ff, n_embd, n_expert]` | same, or fused `ffn_gate_up_exps.weight` `[n_embd, 2*n_ff, n_expert]` | yes if unfused |
| `ffn_gate_shexp.weight`, `ffn_up_shexp.weight`, `ffn_down_shexp.weight` | `[n_embd, n_ff]`, `[n_ff, n_embd]` | same | yes |
| `ffn_gate_inp_shexp.weight` | `[n_embd]` engine form BF16 | `ffn_gate_inp_shexp.weight` `{n_embd}` | yes, dtype to confirm |
**One attention layer, `blk.N.` (layers 3, 7, ..., 39)**
| Engine expects | Shape / form | llama.cpp qwen35moe | Match |
|---|---|---|---|
| the six `hc_*` tensors and two `hc_*_norm` as above | | none | **Engine-only** |
| (none) | | `attn_norm.weight`, `post_attention_norm.weight` | **llama.cpp-only** |
| `attn_q.weight` | `[n_embd, 2*n_head*head_dim]` (q then gate per head, interleaved) | `attn_q.weight` `{n_embd, head_dim*n_head*2}` | yes |
| `attn_k.weight`, `attn_v.weight` | `[n_embd, n_kv*head_dim]` | same | yes, unless the GGUF fuses them into `attn_qkv.weight` (`create_tensor_qkv`) |
| `attn_output.weight` | `[n_head*head_dim, n_embd]` | `attn_output.weight` | yes |
| `attn_q_norm.weight`, `attn_k_norm.weight` | `[head_dim]` F32 | same | yes |
| `indexer.q_proj.weight`, `indexer.k_proj.weight`, `indexer.q_norm.weight`, `indexer.k_norm.weight` | BF16 / F32 | none | **Engine-only (QSA indexer)** |
| the same five MoE tensors, three shexp tensors, `ffn_gate_inp_shexp` as a GDN layer | | same | as above |
**Global tensors**
| Engine expects | llama.cpp qwen35moe |
|---|---|
| `token_embd.weight` `[n_embd, n_vocab]` | same |
| `output.weight` `[n_embd, n_vocab]` (native head; mtp.cpp:428 and verify.cpp:347 read `ne1`) | `output.weight` (optional; falls back to `token_embd.weight`) |
| `output_hc_norm.weight`, `output_hc_down.weight`, `output_hc_up.weight` | `output_norm.weight` `{n_embd}` |
| `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` and `per_layer_token_embd.weight` | none |
| MTP: `<rt_dir>/dense.txt` names `fc_embedding`, `fc_hidden`, `pre_fc_norm_embedding`, `pre_fc_norm_hidden`, `self_attn.*`, `mlp.*`, three `*hyper_connection*` groups | `blk.40.nextn.eh_proj.weight` `{2*n_embd, n_embd}`, `blk.40.nextn.enorm.weight`, `blk.40.nextn.hnorm.weight`, optional `blk.40.nextn.{embed_tokens,shared_head_head,shared_head_norm}.weight`, plus a full attention + MoE block under `blk.40.` (attn_norm, post_attention_norm, attn_q/k/v/output, attn_q_norm, attn_k_norm, ffn_gate_inp, ffn_*_exps, ffn_*_shexp, ffn_gate_inp_shexp) |
## Summary of which subsystems are runtime-parameterized
1. **Already parameterized:** the GDN decode kernels (state 128, head counts and head pairing by `h % h_k`, grids from `h_v`), the generic router, the shared expert (and 512 now satisfies its Q8_K rule), the native CPU and GPU expert kernels (`NativeFmt` and `L.n_embd`/`L.n_ff` per layer, UD-Q4_K_XL types already present), the expert cache, the weight loader, the sampler, `output.weight` and vocabulary size, and the drafter's dense-attention KV.
2. **The geometry struct is never populated from the model.** Only `expert_count` and `expert_used_count` (and rope keys) are read, under a `qwen4exp.` prefix, and only with `--native`. `n_embd`, `n_layers`, head counts, `ssm.*` and `n_ff` stay at Flash-Next defaults. `check_architecture` refuses any other architecture string.
3. **The gated residual is structural.** Every block, the output head, the verify window, the drafter and prefill assume `hc` streams with down/up/inject mixing. The fused kernels are hard-coded to 2560/4/320, and `hc = 1` has no plain-norm meaning. The plain `attn_norm`, `post_attention_norm` and `output_norm` tensors are never referenced.
4. **Dense attention is structural.** `qsa_layer`, `verify.cpp`, the KV state size and the selection width all assume the indexer. The decode and prompt attention kernels are compile-time for group 12 (Qwen3.6 is 8) and the short-context kernel is compile-time for 24 heads. The attention kernel reads through `ids`, so it is selection-agnostic, but no producer of dense `ids` exists.
5. **GDN output gate differs numerically:** Qwen3.6 applies SiLU(z) where the engine applies sigmoid(z) in four kernels (gdn.cu, fused_gdn.cu, native_gdn_preprocess.cu, prefill/kernels.cu). This is a semantic change, not a size change.
6. **Native-pack decode is verify-window only.** The single-token expert dispatch refuses native packs, and the verify window demands fused GR, K = 10, and the native indexer. Any hc = 1 or dense-attention work has to land in verify.cpp as well as layer.cpp.
7. **Prefill is the most compile-time-heavy subsystem.** `Prefill::init` refuses non-2560/4/320/10, and GDN, gate, split-q, route and MoE buffers all use literal constants (HV 48, 24 heads, 1280, 640, top-10).
8. **One leak inside otherwise-runtime expert code:** `expert_layout.cpp:284` passes compile-time `H, FF` to `native_fmt`, so a 2048/512 pack fails the blob-size check.
9. **PLE is optional in kernels but mandatory in the CLI.** `--native` refuses to start without `--ple-gguf`, and a table implies `blk.1.ple_*` tensors. Qwen3.6 has neither. A small session buffer (about 360 KB) is allocated regardless.
10. **MTP drafter is separate from the GGUF** (Q8_0 `rt_dir` from `tools/mtp_rt.py`, canonical Q2_0 experts at 2560/640, three hyper-connection groups, two fc projections). It gets the canonical default geometry, not the target's. The `tools/` packers are not in this tree, so the pack and MTP tensor names are defined by scripts that were not inspected.
-102
View File
@@ -1,102 +0,0 @@
# Qwen3.6-35B-A3B GGUF: metadata and tensors as shipped
Dumped 2026-10-11 with `tools/gguf_reader.py` (no gguf-py) from two files:
- **Plain**: `/Users/robertkarl/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` (Unsloth `UD-IQ3_XXS`, 733 tensors, `general.file_type` 23, 13.2 GB). The file the port is built against.
- **MTP**: `/Users/robertkarl/models/qwen3.6/MTP/Qwen3.6-35B-A3B-UD-IQ4_XS-MTP.gguf` (753 tensors, 41 blocks). Same architecture plus the nextn block. Shown only where it differs.
GGUF dims below are **ne order** (fastest first). The numpy / `ref/load.py` shape is the reverse, `(out, in[, experts])`.
"llama.cpp reads it" cites the pinned submodule (`third_party/llama.cpp`, commit 3cf0325).
## Metadata
| key | value | llama.cpp reads it |
| --- | --- | --- |
| `general.architecture` | `qwen35moe` | `llama-arch.cpp:42` |
| `qwen35moe.block_count` | 40 (MTP file: 41) | `llama-model.cpp:1259`; trunk layers = block_count - nextn |
| `qwen35moe.nextn_predict_layers` | **absent** in the plain file; 1 in the MTP file | `llama-model.cpp:1261`, optional, default 0 |
| `qwen35moe.context_length` | 262144 | `llama-model.cpp:1254` |
| `qwen35moe.embedding_length` | 2048 | `:1255` |
| `qwen35moe.attention.head_count` / `head_count_kv` | 16 / 2 | `:1328`, `:1336` |
| `qwen35moe.attention.key_length` / `value_length` | 256 / 256 | `:1372`, `:1375` |
| `qwen35moe.attention.layer_norm_rms_epsilon` | 1e-6 (stored as f32 9.99999997e-07) | `qwen35moe.cpp:7`, required |
| `qwen35moe.rope.dimension_count` | 64 (= 0.25 * 256) | `:1380` |
| `qwen35moe.rope.dimension_sections` | `[11, 11, 10, 0]` (sum 32 = 64 / 2) | `qwen35moe.cpp:9`, required, 4 entries |
| `qwen35moe.rope.freq_base` | 1e7 | `:1347` |
| `qwen35moe.expert_count` / `expert_used_count` | 256 / 8 | `:1263`, `:1265` |
| `qwen35moe.expert_feed_forward_length` | 512 | `qwen35moe.cpp:5` |
| `qwen35moe.expert_shared_feed_forward_length` | 512 | `qwen35moe.cpp:6` |
| `qwen35moe.ssm.conv_kernel` | 4 | `qwen35moe.cpp:12` |
| `qwen35moe.ssm.state_size` | 128 (head dim of k and v) | `:14` |
| `qwen35moe.ssm.group_count` | 16 (k heads) | `:16` |
| `qwen35moe.ssm.time_step_rank` | 32 (v heads) | `:15` |
| `qwen35moe.ssm.inner_size` | 4096 (= 32 * 128, the value dim) | `:13` |
| `qwen35moe.full_attention_interval` | 4 | `:22`; layer `il` is recurrent when `(il+1) % 4 != 0` |
| `tokenizer.ggml.model` / `pre` | `gpt2` / `qwen35` | vocab, 248320 tokens, 247587 merges |
| `tokenizer.ggml.{bos,eos,padding}_token_id` | 248044 / 248046 / 248055 | `add_bos_token` false |
| `tokenizer.chat_template` | 8424 characters | frontend, not llama.cpp's graph |
| `general.*`, `quantize.imatrix.*` | name, license, Unsloth provenance, imatrix file | not used by the graph |
Keys that are **not** in the file and **not** read by the `qwen35moe` loader: `expert_weights_norm`, `expert_weights_scale`,
`attention.recurrent_layers` (read if present, `qwen35moe.cpp:20`), `feed_forward_length`, `expert_group_count`, rope scaling.
`HParams` defaults then apply: `expert_weights_scale` stays 0.0 (`llama-hparams.h:124`, the key is never loaded for this architecture),
so no scaling; `norm_w` is hard-coded `true` at the call site (`qwen35moe.cpp:506`), so the top-8 weights always renormalize to sum 1.
A GGUF cannot change either; a stray `qwen35moe.expert_weights_scale` key is ignored (checked with `--expert-weights-scale` on the fixture).
## Tensors (plain file, 733)
| name | ne | dtype in the IQ3_XXS file | count |
| --- | --- | --- | --- |
| `token_embd.weight` | 2048, 248320 | Q6_K | 1 |
| `output.weight` | 2048, 248320 | Q6_K (not tied) | 1 |
| `output_norm.weight` | 2048 | F32 | 1 |
| `blk.N.attn_norm.weight` | 2048 | F32 | 40 |
| `blk.N.post_attention_norm.weight` | 2048 | F32 | 40 |
| `blk.N.ffn_gate_inp.weight` (router) | 2048, 256 | F32 | 40 |
| `blk.N.ffn_gate_exps.weight` | 2048, 512, 256 | IQ2_S | 40 |
| `blk.N.ffn_up_exps.weight` | 2048, 512, 256 | IQ2_S | 40 |
| `blk.N.ffn_down_exps.weight` | 512, 2048, 256 | IQ3_XXS (37), IQ4_XS (3: layers 34, 38, 39) | 40 |
| `blk.N.ffn_gate_inp_shexp.weight` | **2048** (1-D) | F32 | 40 |
| `blk.N.ffn_{gate,up}_shexp.weight` | 2048, 512 | Q6_K | 80 |
| `blk.N.ffn_down_shexp.weight` | 512, 2048 | Q6_K | 40 |
| GDN layers (30: 0-2, 4-6, ..., 36-38): | | | |
| `blk.N.attn_qkv.weight` | 2048, 8192 (= 2*2048 + 4096) | Q6_K | 30 |
| `blk.N.attn_gate.weight` (z) | 2048, 4096 | Q6_K | 30 |
| `blk.N.ssm_conv1d.weight` | 4, 8192 | F32 | 30 |
| `blk.N.ssm_alpha.weight`, `ssm_beta.weight` | 2048, 32 | F32 | 60 |
| `blk.N.ssm_a` (no `.weight` suffix) | 32 | F32 | 30 |
| `blk.N.ssm_dt.bias` | 32 | F32 | 30 |
| `blk.N.ssm_norm.weight` | 128 | F32 | 30 |
| `blk.N.ssm_out.weight` | 4096, 2048 | Q6_K | 30 |
| Attention layers (10: 3, 7, ..., 39): | | | |
| `blk.N.attn_q.weight` (query and gate, interleaved per head) | 2048, 8192 (= 16 * 2 * 256) | Q6_K | 10 |
| `blk.N.attn_k.weight`, `attn_v.weight` | 2048, 512 (= 2 * 256) | Q6_K | 20 |
| `blk.N.attn_output.weight` | 4096, 2048 | Q6_K | 10 |
| `blk.N.attn_q_norm.weight`, `attn_k_norm.weight` | 256 | F32 | 20 |
Values worth knowing (layer 0 and 3): `ssm_a` is **negative**, -72.3 to -0.019 (it is `-exp(A_log)`, so `gate = softplus(alpha + dt_bias) * ssm_a` is already a log decay);
`ssm_dt.bias` -5.3 to 15.6; every RMS-norm weight is stored multiplicatively (`attn_norm` mean 1.03, `output_norm` mean 2.63), so no "+1" is applied anywhere;
`ssm_conv1d` is within +-0.41; `ffn_gate_inp_shexp` is a 2048-vector with mean 0.
## The nextn block (MTP file only)
`blk.40` is the draft block, 20 tensors: the same ones an attention layer plus MoE carries (`attn_norm`, `post_attention_norm`, `attn_q/k/v/output`,
`attn_q_norm/k_norm`, `ffn_gate_inp`, `ffn_{gate,up,down}_exps`, `ffn_gate_inp_shexp`, `ffn_{gate,up,down}_shexp`) plus
`nextn.eh_proj.weight` (4096, 2048: one projection over `[enorm(token embedding), hnorm(hidden)]` concatenated, embedding first),
`nextn.enorm.weight`, `nextn.hnorm.weight`, `nextn.shared_head_norm.weight` (each 2048, F32).
There is **no** `nextn.embed_tokens` and **no** `nextn.shared_head_head`: the block embeds with `token_embd.weight` and the draft head is the main `output.weight`
(`qwen35moe.cpp:583`, `:733`); the head norm is `shared_head_norm` when present, else `output_norm`.
In that file the nextn router `blk.40.ffn_gate_inp.weight` and `ffn_gate_inp_shexp.weight` are **BF16** while the trunk's are F32; the
experts are Q3_K gate/up and Q4_K down (trunk: IQ3_S / IQ4_XS).
## What was unexpected
- **The plain GGUF has no nextn block at all.** `nextn_predict_layers` is absent and `block_count` is 40. The MTP head exists only in the separate `-MTP.gguf` builds, which carry 41 blocks.
- **Gate and up are not fused** (`ffn_gate_exps` + `ffn_up_exps`), and attention layers are **not** fused (`attn_q`, `attn_k`, `attn_v`). `attn_qkv` exists, but only in the 30 GDN layers where it feeds the conv, next to a separate `attn_gate` (z). llama.cpp accepts the fused forms (`llama-model.cpp:3253-3300`, `ffn_gate_up_exps` with gate rows first, `attn_qkv` with Q|K|V rows), and the fixture and oracle support both, but no shipped file uses them.
- **`expert_weights_norm` and `expert_weights_scale` are not in the file and cannot matter**: the architecture hard-codes renormalization and never loads a scale (see above).
- **The router and the GDN `ssm_alpha` / `ssm_beta` are F32**, not BF16. `ref/load.py`'s `FORM` table in `iq_pack.py` must not assume the Flash-Next BF16 forms for them.
- **`attn_q` is 2x wide**: per head 256 query values then 256 gate values, interleaved, which is how `attn_output_gate` is stored. There is no separate gate tensor.
- **`ssm_a` carries no `.weight` suffix** and `ssm_dt` is named `ssm_dt.bias`.
- **`ffn_gate_inp_shexp` is 1-D** (a vector, producing one scalar per token), not a 2048x1 matrix.
- **Per-layer quantization is mixed** (down experts: IQ3_XXS in 37 layers and IQ4_XS in 3; the MTP block uses a different family altogether), so any pack format must carry a type per layer and per role, as `native_experts.txt` already does.
- `ref/load.py` did not know IQ2_S, IQ3_XXS, IQ3_S (gate/up/down of this file); it is extended in the same commit that adds the oracle.
-313
View File
@@ -1,313 +0,0 @@
# Qwen3.6 oracle cross-check against the pinned llama.cpp graph
Run 2026-10-11 on this branch (`qwen36-oracle`), CPU only, F32 synthetic fixtures, against `third_party/llama.cpp` at 3cf0325.
`ref/qwen36.py` (the numpy oracle) and the submodule's own graph agree on **every named tensor of every case**: 2,155 comparisons over 116 seam
families, worst absolute error **1.1e-4** (on a tensor whose values reach 3.8), the router's integer outputs identical. The printed stats of
`llama-eval-callback` agree on all 209 named nodes it prints. A reading that is wrong in any of the 8 places a port could plausibly get wrong
fails the comparison at the layer that makes it. Dequantization of the real file's types is bit-identical to ggml's (below).
## Reproduce
One command builds the submodule's `libllama` and `llama-eval-callback` (CPU, outside the repo), builds the dumper, writes the fixtures, runs
every case and exits 1 on any failed seam. About 4 seconds once built; the first build takes a few minutes.
```
export STRATA_GGUF_PY=$PWD/third_party/llama.cpp/gguf-py # optional: tools/_paths.py finds it there anyway
tools/qwen36_crosscheck.sh /path/to/scratch [REAL-MTP.gguf] # 2nd argument: a real qwen35moe file, for the --like-real case
python3 -I tools/test_qwen36_oracle.py # 21 invariant tests, no llama.cpp build needed
```
The same steps by hand, for one case (`$B` is the build directory, `$W` a scratch directory):
```
cmake -S third_party/llama.cpp -B $B -DCMAKE_BUILD_TYPE=Release -DGGML_METAL=OFF -DGGML_BLAS=OFF \
-DLLAMA_CURL=OFF -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_SERVER=OFF
cmake --build $B --target llama-eval-callback -j8
c++ -std=c++17 -O1 tools/qwen36_dump_llama.cpp -o $B/qwen36-dump -Ithird_party/llama.cpp/include \
-Ithird_party/llama.cpp/ggml/include -L$B/bin -lllama -lggml -lggml-base -Wl,-rpath,$B/bin
python3 tools/qwen36_synth_gguf.py $W/base.gguf # add --like-real REAL.gguf / --fused-gate-up / --fused-qkv / --no-nextn
T=104,101,108,108,111,32,119,111,114,108,100 # "hello world": the fixture's vocabulary is the 128 ASCII bytes
python3 ref/qwen36.py $W/base.gguf --tokens $T --dump $W/o --mtp # oracle dumps (+ $W/o_mtp)
$B/qwen36-dump $W/base.gguf $W/d $T 0 mtp # llama.cpp's graph, every named tensor in full (+ $W/d_mtp)
python3 tools/qwen36_compare_dumps.py $W/o $W/d # per-seam max |difference|; exit 1 on a failure
$B/bin/llama-eval-callback -m $W/base.gguf -p "hello world" -ctk f32 -ctv f32 -fa off -c 64 -t 1 -ngl 0 > $W/eval.txt 2>&1
python3 tools/qwen36_check_eval_callback.py $W/o $W/eval.txt --require-tail
```
`-ctk f32 -ctv f32 -fa off` matter: the default F16 KV cache would put half-precision rounding into attention, and `qwen36-dump` sets the same.
Both tools use one thread, so the only differences left are float32 summation order.
## Cases (all in `tools/qwen36_crosscheck.sh`)
| case | fixture | tokens | what it adds |
| --- | --- | --- | --- |
| `base_11` | default, seed 0 | 11 ("hello world") | the baseline; also the nextn block |
| `base_40` | default | 40 | longer GDN history, attention over 40 keys |
| `base_ar` | default | 40, one token per decode call | llama.cpp's autoregressive GDN path: state and KV carried through 40 calls; only the last call is dumped |
| `base_c7` | default | 40, chunks of 7 | state carried across 5 calls of 7, then 5 |
| `seed7` | seed 7 | 11 | different weights, so a coincidence in seed 0 cannot hide a bug; nextn |
| `fused_gu` | `--fused-gate-up --seed 3` | 11 | `ffn_gate_up_exps` (gate rows then up rows) for trunk and nextn; nextn |
| `fused_qkv` | `--fused-qkv --no-nextn --seed 4` | 11 | `attn_qkv` in the attention layer (Q, K, V rows in that order) |
| `gqa4_2` | `--heads 4,2 --seed 11` | 40 | **non-degenerate GQA**: 4 query heads over 2 KV heads, so `kv = h // (n_head/n_head_kv)` is tested (every other fixture has one KV head, where any mapping passes); nextn |
| `stray_scl` | `--expert-weights-scale 2.5 --seed 5` | 11 | the key is in the file; llama.cpp ignores it, so must the oracle; nextn |
| `like_real` | `--like-real <MTP build>` | 40 | rope base 1e7, real eps, interval, head ratios, and the exact tensor-name set of the real file (32 of 32 patterns); nextn |
Geometry of the default fixture: hidden 64; layers 0-2 Gated DeltaNet, layer 3 full attention; GDN 4 k-heads / 8 v-heads of 16; conv kernel 4;
attention 2 heads / 1 KV head of 32 with 8 rotated dims (25 %) and IMRoPE sections [2,1,1,0]; 8 experts, top 2, ff 32, shared ff 32; vocabulary 128;
one nextn block at index 4.
## Results
All 10 trunk cases: `0 failed` of 211 seams (215 with fused gate/up, 212 with fused qkv). The 6 nextn cases: `0 failed` of 50 (51 fused). Per seam family
(max over all layers and the first nine cases, 2,155 comparisons; the `gqa4_2` case adds 261 more, all within tolerance; "max abs value" is the largest magnitude of the llama.cpp tensor):
#### Trunk (`qwen35moe` graph, 9 cases)
| seam (all layers) | comparisons | max abs error | max abs value |
| --- | --- | --- | --- |
| `model.input_embed` | 9 | 0.0e+00 | 3.763 |
| `norm` | 126 | 1.1e-04 | 3.937 |
| `attn_norm` | 36 | 1.7e-05 | 5.397 |
| `conv_states` | 27 | 8.6e-06 | 3.773 |
| `conv_states_reshaped` | 27 | 8.6e-06 | 3.773 |
| `linear_attn_qkv_mixed` | 27 | 8.5e-06 | 4.543 |
| `qkv_mixed_transposed` | 27 | 8.5e-06 | 4.543 |
| `z` | 27 | 7.6e-06 | 4.58 |
| `beta` | 27 | 5.9e-06 | 6.075 |
| `beta_sigmoid` | 27 | 1.5e-06 | 0.9977 |
| `alpha` | 27 | 9.2e-06 | 3.173 |
| `a_softplus` | 27 | 2.4e-06 | 3.359 |
| `gate` | 27 | 8.5e-06 | 38.85 |
| `conv_input` | 27 | 8.6e-06 | 4.543 |
| `conv_state_last` | 27 | 4.8e-06 | 3.944 |
| `conv_output_raw` | 27 | 1.0e-05 | 9.484 |
| `conv_output_silu` | 27 | 1.1e-05 | 9.483 |
| `q_conv` | 27 | 1.1e-05 | 9.483 |
| `k_conv` | 27 | 9.4e-06 | 7.217 |
| `q_conv_predelta` | 27 | 2.3e-06 | 0.9935 |
| `k_conv_predelta` | 27 | 2.9e-06 | 0.9874 |
| `v_conv_predelta` | 27 | 1.1e-05 | 6.957 |
| `state_predelta` | 27 | 4.6e-06 | 2.4 |
| `new_state` | 27 | 3.9e-06 | 3.382 |
| `attn_output` | 36 | 4.1e-06 | 1.878 |
| `final_output` | 27 | 5.3e-05 | 8.531 |
| `linear_attn_out` | 27 | 1.8e-05 | 3.891 |
| `attn_residual` | 36 | 2.0e-05 | 9.001 |
| `attn_post_norm` | 36 | 1.5e-05 | 5.079 |
| `ffn_moe_logits` | 36 | 2.3e-05 | 12.4 |
| `ffn_moe_probs` | 36 | 6.8e-06 | 0.9995 |
| `ffn_moe_argsort` | 36 | identical | 0 |
| `ffn_moe_topk` | 36 | identical | 0 |
| `ffn_moe_weights` | 36 | 6.8e-06 | 0.9995 |
| `ffn_moe_weights_sum` | 36 | 2.3e-06 | 0.9999 |
| `ffn_moe_weights_sum_clamped` | 36 | 2.3e-06 | 0.9999 |
| `ffn_moe_weights_norm` | 36 | 8.3e-06 | 0.9997 |
| `ffn_moe_gate` | 36 | 1.4e-05 | 4.662 |
| `ffn_moe_up` | 36 | 1.2e-05 | 4.383 |
| `ffn_moe_swiglu` | 36 | 2.4e-05 | 10.1 |
| `ffn_moe_down` | 36 | 1.3e-05 | 5.36 |
| `ffn_moe_weighted` | 36 | 1.2e-05 | 3.552 |
| `ffn_moe_out` | 36 | 1.4e-05 | 3.635 |
| `ffn_up` | 36 | 1.5e-05 | 4.215 |
| `ffn_gate` | 36 | 1.1e-05 | 4.541 |
| `ffn_swiglu` | 36 | 2.9e-05 | 5.875 |
| `ffn_shexp` | 36 | 1.6e-05 | 3.419 |
| `shared_expert_gate` | 36 | 9.8e-06 | 5.545 |
| `shared_expert_gate_sigmoid` | 36 | 2.2e-06 | 0.9961 |
| `ffn_shexp_gated` | 36 | 6.8e-06 | 3.12 |
| `ffn_out` | 36 | 1.2e-05 | 4.451 |
| `l_out` | 36 | 2.3e-05 | 8.791 |
| `Qcur_full` | 9 | 1.4e-05 | 4.189 |
| `Kcur` | 18 | 1.1e-05 | 3.824 |
| `Vcur` | 18 | 1.4e-05 | 4.189 |
| `Qcur_reshaped` | 9 | 1.2e-05 | 3.753 |
| `Qcur_normed` | 9 | 2.2e-05 | 5.186 |
| `Kcur_normed` | 9 | 8.7e-06 | 3.824 |
| `Qcur` | 9 | 2.2e-05 | 5.186 |
| `kq` | 9 | 8.8e-05 | 22.06 |
| `kq_soft_max` | 9 | 3.0e-06 | 1 |
| `kqv` | 9 | 1.1e-05 | 3.075 |
| `attn_pregate` | 9 | 1.1e-05 | 3.075 |
| `gate_reshaped` | 9 | 1.4e-05 | 4.189 |
| `gate_sigmoid` | 9 | 3.3e-06 | 0.9768 |
| `attn_gated` | 9 | 8.2e-06 | 2.669 |
| `h_nextn` | 9 | 1.7e-05 | 3.835 |
| `result_norm` | 9 | 3.6e-06 | 3.259 |
| `result_output` | 9 | 7.3e-06 | 7.799 |
| `ffn_moe_gate_up` | 4 | 6.3e-06 | 3.595 |
| `wqkv` | 1 | 6.7e-06 | 3.492 |
#### Nextn block (`graph_mtp`, 5 cases that carry a nextn block)
| seam (all layers) | comparisons | max abs error | max abs value |
| --- | --- | --- | --- |
| `mtp_tok_embd` | 5 | 0.0e+00 | 3.372 |
| `norm` | 35 | 1.7e-05 | 3.956 |
| `mtp_enorm` | 5 | 4.8e-07 | 3.57 |
| `mtp_hnorm` | 5 | 1.5e-05 | 4.633 |
| `mtp_concat` | 5 | 1.5e-05 | 4.633 |
| `mtp_eh_proj` | 5 | 8.2e-06 | 3.742 |
| `mtp_attn_norm` | 5 | 8.7e-06 | 4.298 |
| `mtp_Qcur_full` | 5 | 8.8e-06 | 4.519 |
| `mtp_Qcur_normed` | 5 | 1.1e-05 | 4.886 |
| `mtp_gate` | 5 | 7.5e-06 | 4.387 |
| `mtp_Kcur_normed` | 5 | 6.6e-06 | 3.528 |
| `mtp_Vcur` | 5 | 8.6e-06 | 4 |
| `kq` | 5 | 6.1e-05 | 23.47 |
| `kq_soft_max` | 5 | 2.1e-06 | 1 |
| `kqv` | 5 | 4.2e-06 | 3.701 |
| `mtp_attn_pregate` | 5 | 4.2e-06 | 3.701 |
| `mtp_attn_out` | 5 | 3.8e-06 | 1.818 |
| `mtp_attn_residual` | 5 | 9.3e-06 | 4.383 |
| `mtp_attn_post_norm` | 5 | 7.5e-06 | 4.184 |
| `ffn_moe_logits` | 5 | 1.6e-05 | 11.01 |
| `ffn_moe_probs` | 5 | 2.7e-06 | 0.9975 |
| `ffn_moe_argsort` | 5 | identical | 0 |
| `ffn_moe_topk` | 5 | identical | 0 |
| `ffn_moe_weights` | 5 | 2.7e-06 | 0.9975 |
| `ffn_moe_weights_sum` | 5 | 1.5e-06 | 0.9993 |
| `ffn_moe_weights_sum_clamped` | 5 | 1.5e-06 | 0.9993 |
| `ffn_moe_weights_norm` | 5 | 2.8e-06 | 0.9982 |
| `ffn_moe_gate` | 5 | 7.7e-06 | 4.102 |
| `ffn_moe_up` | 5 | 7.6e-06 | 3.967 |
| `ffn_moe_swiglu` | 5 | 1.3e-05 | 6.547 |
| `ffn_moe_down` | 5 | 1.2e-05 | 4.218 |
| `ffn_moe_weighted` | 5 | 5.1e-06 | 2.526 |
| `mtp_ffn_moe_out` | 5 | 5.9e-06 | 2.647 |
| `ffn_up` | 5 | 8.7e-06 | 3.683 |
| `ffn_gate` | 5 | 7.2e-06 | 4.162 |
| `ffn_swiglu` | 5 | 1.5e-05 | 5.923 |
| `mtp_ffn_shexp` | 5 | 8.3e-06 | 2.811 |
| `mtp_shared_expert_gate_sigmoid` | 5 | 2.1e-06 | 0.9887 |
| `mtp_ffn_shexp_gated` | 5 | 4.7e-06 | 2.501 |
| `mtp_ffn_out` | 5 | 6.8e-06 | 3.119 |
| `mtp_post_ffn` | 5 | 1.6e-05 | 4.947 |
| `h_nextn` | 5 | 1.4e-05 | 3.562 |
| `mtp_shared_head_norm` | 5 | 1.4e-05 | 3.562 |
| `result_output` | 5 | 2.1e-05 | 7.916 |
| `ffn_moe_gate_up` | 1 | 3.7e-06 | 3.81 |
The largest absolute error is 1.1e-4 on `norm-2#2`, the RMS norm of a GDN layer's recurrence output. Those values are small, so the norm amplifies the
float32 summation-order difference of the recurrence by about 1 / rms; relative to the tensor's largest value it is 2.8e-5. The router's
`ffn_moe_argsort` and `ffn_moe_topk` are bit-identical in every case.
### `llama-eval-callback` printed stats
`tools/qwen36_check_eval_callback.py` reconstructs which indices the tool prints (first and last 3 of every dimension, `%12.4f`) and its float32 `sum`:
209 named nodes through `result_output`, 0 failed; worst printed value 6.2e-5 apart (that is the 4-decimal rounding, not a difference), worst `sum`
3.9e-7 of the tensor's L1 mass. `kq` and `kq_soft_max` are skipped there because llama.cpp pads their KV axis to its cache size (256); the full-tensor
comparison crops the padding and requires it to be exactly zero for `kq_soft_max`.
### Negative controls: the comparison fails when the oracle reads the graph wrongly
Each row runs the oracle with one `Model.opts` entry flipped to its rival (`ref/qwen36.py --opt KEY=VALUE`) against the same llama.cpp dump of `base_11`.
All 8 fail, at the layer and seam that makes the mistake; `tools/test_qwen36_oracle.py` requires every one to move its seam by more than 5 % relative L1.
| rival reading | first failing seam | seams failing / 211 | change at that seam (relative L1) | change in logits |
| --- | --- | --- | --- | --- |
| GDN output gate `sigmoid(z)` (the Flash-Next engine) instead of `SiLU(z)` | `final_output-0` | 179 | 1.07 | 0.92 |
| v-head h paired with k-head `h // 2` instead of `h % 4` | `new_state-0` | 182 | 1.03 | 0.84 |
| decay applied after the rank-1 update instead of before | `new_state-0` | 182 | 0.16 | 0.30 |
| conv window applied in the opposite direction | `conv_output_raw-0` | 189 | 1.23 | 1.05 |
| attention output gate skipped | `attn_gated-3` | 32 | 1.03 | 0.12 |
| top-k weights not renormalized | `ffn_moe_weighted-0` | 152 | 0.14 | 0.12 |
| query head h reads KV head `h % n_kv` instead of `h // (n_head/n_kv)` (on `gqa4_2`; invisible with one KV head) | `kq-3` | 36 | 0.74 (at `kqv-3`) | 0.13 |
| RoPE on adjacent pairs (2p, 2p+1) instead of (p, p + n_rot/2) | `Qcur-3` | 37 | 0.20 (at `kqv-3`) | 0.04 |
## Formulas pinned (file:line in `third_party/llama.cpp`)
**Gated DeltaNet** (`qwen35moe.cpp:359-492`; `qwen35moe.cpp:20-26` decides which layers are recurrent). CPU always takes the fused op
(`llama-context.cpp:232-233`), whose scalar loop is the reference; the chunked and autoregressive graphs in `delta-net-base.cpp:16-371` compute the same thing.
| step | formula | source |
| --- | --- | --- |
| beta | `sigmoid(ssm_beta x)` | `qwen35moe.cpp:382-387` |
| log decay | `g = softplus(ssm_alpha x + ssm_dt.bias) * ssm_a`, `ssm_a < 0` in the file; softplus is `x > 20 ? x : log1p(exp(x))` | `qwen35moe.cpp:389-398`, `ggml-cpu/unary-ops.cpp:80-82` |
| conv | per channel, `y[t] = sum_i w[c][i] * in[c][t+i]` over `[state (K-1) \| qkv]`, then `silu`; new state = last K-1 inputs | `qwen35moe.cpp:402-421`, `delta-net-base.cpp:449-525`, `ggml-cpu/ops.cpp:9703-9754` |
| split | channels `[0,2048)` q, `[2048,4096)` k (16 heads of 128), `[4096,8192)` v (32 heads of 128); head h is a contiguous 128-run | `qwen35moe.cpp:424-444` |
| q, k norm | `x / sqrt(sum(x^2) + eps)`, eps 1e-6, per head: `rms_norm(x, eps/n) * 1/sqrt(n)` | `models.h:14-18`, `qwen35moe.cpp:451-454` |
| head pairing | v-head h uses k-head `h % 16` (tiling, not blocks) | `qwen35moe.cpp:462-466`, `ggml-cpu/ops.cpp:10971-10972` |
| state | `S[j][i]`, j = v index, i = k index, per v-head, `ne [S_k, S_v, H_v]`, zero at sequence start | `ggml-cpu/ops.cpp:10999`, `qwen35moe.cpp:411-413` |
| step | `S *= exp(g)`; `d = (v - S k) * beta`; `S += d (x) k`; `o = (S q) / sqrt(S_v)` | `ggml-cpu/ops.cpp:11012, 11016-11020, 11023-11025, 11028-11032` |
| output | `rms_norm(o) * ssm_norm * SiLU(z)`, per head; then `ssm_out` | `qwen35moe.cpp:267-276, 475-486` |
**Full attention** (`qwen35moe.cpp:278-357`): `attn_q` is `[n_head, 2, head_dim]` per token, so query is the first `head_dim` of each head's `2*head_dim` slice and the gate the second
(`:299-317`); RMS norm on q and k per head (`:305-311`); IMRoPE on the first 64 of 256 dims, pairs `(p, p+32)` (`ggml-cpu/ops.cpp:6205-6213`), theta per sector
from `t,h,w,e` positions = `pos,pos,pos,0` for text (`llama-graph.cpp:131-141`, `ops.cpp:6026-6036`); scale `1/sqrt(256)` (`:340`); causal softmax; GQA groups are
contiguous (`kv head = h / (n_head / n_head_kv)`); output `* sigmoid(gate)` then `attn_output` (`:347-354`).
**Router and experts** (`qwen35moe.cpp:494-548`, `llama-graph.cpp:1993-2355`): logits `ffn_gate_inp x`; `softmax` over all 256 (`:2043`); `argsort_top_k` of the probabilities, descending (`:2109`);
weights are the unbiased probabilities of the chosen experts (`:2123`); **renormalized to sum 1** with the sum clamped at 6.1035e-5 (`:2134-2148`), because `qwen35moe.cpp:506`
passes `norm_w = true`; `expert_weights_scale` is `0.0` (`llama-hparams.h:124`, never loaded for this architecture), so no scale (`:2149`). Experts: `silu(gate x) * (up x)` (`:2246`),
`down`, times weight, summed in top-k order (`:2339-2345`). Shared expert: same SwiGLU with `ffn_{gate,up,down}_shexp`, times `sigmoid(ffn_gate_inp_shexp . x)` (a scalar per token), added to the routed sum
(`qwen35moe.cpp:516-545`).
**Nextn / MTP** (`qwen35moe.cpp:550-741`, a real graph in this commit, run by llama.cpp's `LLAMA_CONTEXT_TYPE_MTP` context): `concat(rms_norm(embed(token)) * enorm, rms_norm(h) * hnorm)` (embedding first),
`eh_proj`, then an attention block (`attn_norm`, joint q+gate, q/k norm, IMRoPE, causal over the MTP block's own KV, sigmoid gate, `attn_output`, residual), `post_attention_norm`, the same MoE
plus gated shared expert, residual, `shared_head_norm` (else `output_norm`), and the main `output.weight` (there is no `nextn.shared_head_head` in shipped files). The pairing the speculative code builds
(`common/speculative.cpp`, "shift the tgt embeddings to the right by one position"): token k with the trunk hidden state of position k-1, at position k; the cross-check does the same (`tokens[1:]`, `h[:-1]`, positions 1..).
The trunk's `h_nextn` is the output-normed hidden state of every input token (`qwen35moe.cpp:230-233`).
## Quirks of the comparison that a later reader will trip over
- **Repeated names.** `cb()` renames the tensor, so `Kcur-3` and `Vcur-3` each exist twice (projection, then the reshaped or rope'd tensor), and every `build_norm` sets `norm-<layer>` on its unweighted result,
so a layer has up to four. The dumps number repeats `#2`, `#3` in **execution order**, which is the graph's dependency order, not build order: in the nextn block `ggml_concat(e_norm, h_norm)` pulls
`e_norm` first, so `norm-4` is the embedding norm. The oracle emits in that order. A later `cb` on the same tensor overwrites an earlier name (`v_conv` is only ever visible as `v_conv_predelta`, `post_moe` as `l_out`).
- **Views read before their copy.** `conv_state_update-N` is a view of the cache that llama.cpp evaluates before the copy that writes it; it shows the old state. The new state is `conv_state_last-N`; the comparison ignores the former.
- **`kq` is padded** to the KV cache size (256 here); `result_norm` and `result_output` hold the last token only because `llama_batch_get_one` requests logits for the last position; `h_nextn` holds all tokens.
- **`llama-eval-callback` loses the end of its own output.** Its asynchronous logger drops its queue at exit, so the tail (sometimes through `result_output`) is cut off in a fraction of runs. The checker discards an unterminated block and
`--require-tail` fails unless the printout reaches `result_output`; `qwen36_crosscheck.sh` retries up to 8 times. `tools/qwen36_dump_llama.cpp` writes files and is not affected.
- **Tokenizer.** The fixture's vocabulary is the 128 ASCII byte tokens (GPT-2 byte-level BPE with a single dead merge), so `-p "text"` yields token id = ASCII code and `llama-eval-callback` can be driven by text.
- **Stray metadata.** A `qwen35moe.expert_weights_scale` key changes nothing (case `stray_scl`); `expert_weights_norm` is not read either. `llama.cpp` warns about "unused tensor blk.4.*" when the nextn block is present and `--mtp` is not requested; harmless.
## ref/load.py dequantization against ggml (real file)
`tools/qwen36_check_dequant.py MODEL.gguf $B/qwen36-dequant` (the helper, `tools/qwen36_dequant_ggml.cpp`, calls ggml's own `to_float` on the raw bytes) on
`Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf`: **max |difference| 0.0 (bit-identical)** for `token_embd.weight` rows (Q6_K), `output.weight` and a dense Q6_K block, whole experts of
`blk.0.ffn_gate_exps` (IQ2_S), `blk.0.ffn_down_exps` (IQ3_XXS) and `blk.34.ffn_down_exps` (IQ4_XS), two experts each. Independently, `model.input_embed` from the real llama.cpp graph
(a `get_rows` of the Q6_K table, exact dequantization) equals the oracle's rows with max error 0.0 over the 4 smoke-test tokens. So every real-file difference below comes from activation
quantization and summation order, not from the weights.
## Tolerance policy for parity tests on the real file
The oracle is F32 weights x F32 activations. llama.cpp and the CUDA paths round activations to Q8 (`Q8_K` blocks of 256 for K-quant and IQ weights, `Q8_0` blocks of 32 for Q4_0/Q8_0/IQ4_NL)
before each quantized matmul; F32 weights (router, `ssm_alpha`/`ssm_beta`, conv) are not affected. On the real file that moves seams by percents and flips near-tied expert picks
(12 tokens: 1,895 of 3,840 top-k slots differ position-wise once errors have compounded). Therefore:
1. **Teacher-force expert selection** in any real-file parity test: `ref/qwen36.py --force-topk DIR` takes the choices from a dump's `ffn_moe_topk-<layer>.f32`
(the CUDA test feeds the oracle's own, or the engine's). Exact top-k agreement is checked only on the F32 fixtures (`tools/qwen36_crosscheck.sh`, where it is bit-identical in every case).
2. **Compare per layer, not accumulated**: `--force-inputs DIR` starts every layer from the reference's `l_out-(il-1)`, so each seam's error is that layer's own. Accumulated error over 40
layers is 5-30x larger (table below, first block) and is not a usable tolerance.
3. **Use these per-seam-class relative tolerances** (`||oracle - reference|| / ||reference||`, 12 tokens, 40 layers, topk and inputs forced). Column "F32 oracle" is the plain oracle; "Q8 oracle" is `--act-quant q8`:
| seam class | F32 oracle median / max over layers | Q8 oracle median / max |
| --- | --- | --- |
| `attn_norm` (input is the forced residual) | 5e-8 / 7e-8 | 5e-8 / 7e-8 |
| `linear_attn_qkv_mixed` (GDN in-projection) | 1.4e-2 / 1.8e-2 | 6.9e-7 / 7.5e-7 |
| `linear_attn_out` (GDN output) | 3.8e-2 / 6.6e-2 | 7.8e-5 / 3.7e-4 |
| `attn_output` (full attention, 10 layers) | 4.2e-2 / 6.3e-2 | 1.1e-4 / 6.7e-4 |
| `ffn_moe_out` | 2.9e-2 / 5.3e-2 | 2.3e-3 / 5.3e-3 |
| `ffn_out` (routed + shared) | 3.0e-2 / 4.7e-2 | 2.1e-3 / 4.5e-3 |
| `l_out` (layer output) | 6.9e-3 / 2.7e-2 | 1.8e-4 / 1.4e-3 |
| `result_output` (logits, last token) | 1.9e-2 | 4.0e-7 |
Against an F32-activation engine path, use the F32 column with a 2x margin (for example `qkv_mixed` 4e-2, `gdn_out`/`attn_out` 1.3e-1, `moe_out` 1.1e-1, `l_out` 5e-2, logits 4e-2). Against a path that
rounds activations to Q8 the way ggml does, use the Q8 column with a 4x margin.
4. **Q8 mode is cheap and closes the gap**: `quantize_act` (about 25 lines) reproduces ggml's `quantize_row_q8_K_ref` / `quantize_row_q8_0_ref` and leaves 1e-6 to 1e-3 instead of 1e-2 to 1e-1; at layer 0
the GDN in-projection goes from 7.6e-3 to 6e-7. What remains in `ffn_moe_out` (2e-3) is the IQ2_S / IQ3_XXS integer dot product against float summation. For the last three rows of that
table the Q8 oracle is a better reference than the F32 one whenever the engine under test quantizes activations.
5. The accumulated spread, for reference (`tools/qwen36_spread.py`, no forcing at all, medians over layers; F32 / Q8): `attn_norm` 1.3e-1 / 1.1e-1, `gdn_out` 1.9e-1 / 1.6e-1, `moe_out` 3.4e-1 / 2.8e-1,
`l_out` 5.6e-2 / 4.5e-2, logits 9.8e-2 / 5.9e-2; with only the top-k forced: `l_out` 2.1e-2 / 1.3e-2, logits 3.1e-2 / 3.2e-2. Greedy next-token and the top-5 ids still agree. Q8 mode does not close this one: chaotic
amplification through 40 layers, plus the attention layers (layer 3 alone takes `l_out-2` from 7e-3 to `attn_output-3` 2e-2), dominate, which is why the per-layer protocol above is the one to use.
## Not covered
- **Quantized numerics.** Everything above is F32 weights. On the real file (below) llama.cpp quantizes activations to Q8 for the matmuls, so seams agree to about 1e-2 relative, and near-tied router scores flip.
- Real-file smoke, 4 token ids (`9707,11,1879,0`) through `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf`, oracle against `qwen36-dump` (8 threads): the seams computed from F32 weights
(`beta`, `alpha`, `a_softplus`, `gate`) agree to 2e-5 abs and every projection with a quantized weight to about 1e-2 relative (layer 0 `linear_attn_qkv_mixed` 0.20 of 29.8); the last-token logits
correlate 0.993, argmax (271) and the top 5 ids are identical, and the router picks different experts in 6 of 32 (token, slot) choices in layer 0, 5 in layer 3 and 12-23 in layers 30-39. That is a plausibility check that the
oracle reads the real tensors in the real conventions (dequantization of IQ2_S / IQ3_XXS / IQ4_XS / Q6_K, 1-D `ffn_gate_inp_shexp`, negative `ssm_a`), not a parity claim.
- YaRN / rope scaling (the file has none), sliding windows (none), multimodal position ids (text-only: `t = h = w = pos`, `e = 0`), batches of more than one sequence, GPU kernels, F16 KV.
- Ties in the router: `argsort` here is stable descending; ggml's tie order is unspecified. Random fixtures have no ties; the engine's router kernel needs its own tie test (see `router_top10_parity.cpp`).
-198
View File
@@ -1,198 +0,0 @@
# The Pascal (sm_61) build of the engine on the GTX 1080 Ti
Phase 2 step 2, the one item that needed the GPU (2026-10-11, branch `qwen36-step2`, VM 211: GTX 1080 Ti sm_61,
8 vCPU of a Ryzen 7 1700, 12 GiB, CUDA 12.4, Debian's gcc 14.2 as the default compiler and gcc-13 / g++-13 as the
host compiler for nvcc). The configure line is the one in `step2-notes.md` section 4.
## 1. Where the tree uses what Pascal lacks (read before the build)
Pascal GP102 is compute capability 6.1: `__dp4a` is native; no tensor cores (`mma.sync`, `ldmatrix`, tf32), no
`cp.async` (sm_80), no `__nanosleep` (sm_70), no thread-block clusters (sm_90), no `__match_any_sync` (sm_70),
no `__reduce_*_sync` (sm_80), fp16 arithmetic at 1/64 rate. The tree was searched for every one of those before
the build (`grep -rl` over `src/` and `include/`, `.cu` / `.cuh` / `.hpp` / `.cpp`):
| Feature | Files | Guard already in the file |
| --- | --- | --- |
| `mma.sync` f16 (m16n8k16 sm_80, m16n8k8 sm_75), `cp.async` | `src/kernels/cuda/qsa_prompt_attn.cu` | `STRATA_PA_SM80` (`__CUDA_ARCH__ >= 800`); `mma16816` is `__trap()` below sm_75 and `qsa_prompt_attn_batch` refuses `cc < 70` at run time, prefill takes `qsa_decode_attn_batch` instead. The Volta m8n8k4 kernel is under `STRATA_EXPERIMENTAL_SM60 && 700 <= arch < 750`, so it is not compiled for sm_61 |
| `mma.sync` tf32, `ldmatrix` | `src/kernels/cuda/native_qsa_score.cu` | `__CUDA_ARCH__ >= 800` around `load_a` / `load_b` / `mma`; `score_kernel` has an FP32-FMA path under `__CUDA_ARCH__ < 800` |
| `cvt.rna.tf32`, `mma.sync` tf32, `cp.async` | `src/kernels/cuda/qsa_select.cu` | `STRATA_SEL_SM80`; `qsa_block_scores_tc` refuses the device, the warp kernel runs |
| thread-block clusters (`cudaLaunchKernelEx`, cluster barriers) | `src/kernels/cuda/qsa_select.cu`, `src/kernels/cuda/sampler.cu` | `STRATA_SEL_CLUSTER` / `STRATA_AM_CLUSTER` (`__CUDA_ARCH__ >= 900`): a trap that `qsa_block_topk_cluster` / `sample_greedy_cluster` never launch below sm_90 |
| `__match_any_sync` | `src/kernels/cuda/qsa_select.cu` | inside the sm_80 region above (checked at the build) |
| `cp.async` | `src/kernels/cuda/fused_gr.cu` | `__CUDA_ARCH__ >= 800 && !__HIPCC__` |
| `cp.async` in the GDN recurrence | `src/prefill/kernels.cu`, `src/prefill/gdn_rec_parity.cu` | `STRATA_GDN_CP_ASYNC` (`__CUDA_ARCH__ < 800`: plain copies, and `gdn_keyhead_ok` never launches the key-head kernel there) |
| `mma.sync` / `ldmatrix` / `cp.async` in the fused prompt MoE | `src/prefill/moe_fused.cu`, `src/prefill/moe_fused_iq.cu` | `__CUDA_ARCH__ >= 800` at the two sites of each; their tests exit 77 below sm_80 |
| `__nanosleep` | `include/strata/kernels/dp4a.hpp` (`strata_spin_pause`), `src/prefill/gdn_rec_parity.cu` (`nap`) | `__CUDA_ARCH__ < 700`: the loop spins |
| `__dp4a` | `include/strata/kernels/dp4a.hpp` | `STRATA_DP4A`: the byte-loop fallback only below 6.1; sm_61 uses the instruction |
| half arithmetic (`__hfma2` and kin) | none found outside `qsa_prompt_attn.cu`'s mma path | conversions only elsewhere (the 1/64-rate risk of the design doc's section 7 item 2 is a throughput item, not a build item) |
| bf16 intrinsics (`__nv_bfloat16`, `__float2bfloat16`), fp16 atomics, `__reduce_*_sync` | none | |
| `STRATA_EXPERIMENTAL_SM60` itself | `src/core/device.cu` (the cc check), `src/kernels/cuda/qsa_decode_attn.cu` (the sm_60 decode kernel), `src/kernels/cuda/qsa_prompt_attn.cu` (the Volta kernel), `src/prefill/gemm.cu` (the FP32 GEMM default) | the flag the configure line passes |
So upstream's experimental build already guards every sm_75+ site this tree has; the question the build answers is
whether any site was missed for sm_61 specifically (the guards were written for sm_60 and sm_70, and nobody has run
the build at 61).
## 2. The build
Nothing needed a guard. The tree as it stood at `8b7525e` configured and built for sm_61 unchanged:
| Phase | Command | Result | Time (8 Zen 1 vCPU) |
| --- | --- | --- | --- |
| configure | the `cmake -S . -B build ...` line of `step2-notes.md` section 4 | `Strata: CUDA enabled, arch 61`; `NVIDIA 12.4.131 with host compiler GNU 13.3.0` | 4 s |
| `unbiased-strata` | `cmake --build build -j 8 --target unbiased-strata` | 38,221,376 B; `cuobjdump --list-elf` shows `sm_61` only | 173 s |
| every other target | `cmake --build build -j 8 -- -k` | 93 targets built, 0 errors (`logs/all.log`) | 43 s on top of the engine's libraries |
No compile error for sm_61 at all, so the table of section 1 stands: every `mma.sync` / `ldmatrix` / tf32 /
`cp.async` / cluster / `__nanosleep` / `__match_any_sync` site is behind a `__CUDA_ARCH__` guard with a fallback or
a trap that its host code never launches below the architecture. The 102 warnings of the engine build are the same
on every target: 46 `-Wdeprecated-enum-enum-conversion` from ggml's `ggml_scale_mode | ggml_scale_flag`, nvcc's
`#611-D` partially overridden `ExpertSource::prefetch` (twice each for `FileExpertSource` and `ArenaExpertSource`),
`#177-D` the unused `MAGIC` of `strata::prefill::fused`, a handful of unused variables (`w`, `width`, `n_bid`) and
unused functions in the vendored jinja. None is architecture-specific.
The VM has no `gguf` module for its system Python, but `tools/qwen36_synth_gguf.py` and `tools/iq_pack.py` run
there with the vendored `third_party/llama.cpp/gguf-py` on `PYTHONPATH` (numpy 2.2.4 is installed).
## 3. The parity tests and ctest on the 1080 Ti
`ctest --output-on-failure --timeout 900` in `build/`: 75 tests, 52 s. First run: 7 failed, 2 skipped. Two of the
failures were the branch's own tests that had never been run (both CUDA-gated in CMake, so the Mac had no binary),
fixed on the branch; the final run (`logs/ctest-final.log`) is **69 passed, 4 failed, 2 skipped**.
| Test | 1080 Ti | First line of the failure | Pascal-specific? |
| --- | --- | --- | --- |
| `qwen36_synth_fixtures` then `model_geometry_test` | failed, then Not Run; **pass after the fix** | `CMake Error at cmake/qwen36_synth_fixtures.cmake:11 (list): list index: 1 out of range (-1, 0)` | no: cmake 3.31 drops the empty element of `"toy.gguf;"` with CMP0007 unset (cmake 4 on the Mac does not). Fix: `cmake_policy(SET CMP0007 NEW)` in the script (commit `cd2a73c`). `model_geometry_test --real` also passes on the VM against both real files |
| `expert_layout_test` | 3 checks failed; **all pass after the fix** | `qwen36-q4_k_xl.txt: per-layer formats and blobs (... total 19636158464 B) FAIL` and twice `at Flash-Next's 2560 x 640 refused by its numbers: native experts: expert geometry is not whole blocks FAIL` | no: the test's Q4 total constant was 524,288 B above the pack's own header (19,635,634,176 B), and n_ff 640 is not whole 256-value blocks for Q4_K / IQ2_S rows, so `native_fmt` refuses before the blob message the test looked for (commit `5798a46`) |
| `kv_hybrid_parity` | **FAIL** at `[5/5]` (steps 1 to 4 pass, max error 7.8e-08 / 4.4e-03 vs true fp32) | `[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)` | **yes**: `qsa_prompt_attn_batch` returns false for `cc < 70` (`qsa_prompt_attn.cu:1433`), by design (the prompt path takes the decode kernel on Pascal, design doc section 7 item 3). The test counts a refusal as PASS on HIP and FAIL on CUDA; it needs the same "refused below sm_70: the old kernel runs" branch. Step 3 item, with the dense attention work |
| `platform_memory_test` | FAIL | `lock_resident: ok=0 locked=0 MiB (mlock failed (raise ulimit -l))` | no: the VM's `ulimit -l` hard limit is 8,192 KiB; every `file_cache_keeps` case before it passes |
| `ple_parity` | FAIL | `ple_parity: required PLE table is missing or incompatible: ../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf (cannot open ...)` | no: the test hardcodes a Flash-Next shard path relative to the build directory; the VM has no Flash-Next file |
| `expert_multi_test` | FAIL | `strata: this CPU cannot run the expert kernel: missing AVX512F AVX512BW AVX512VL AVX512-VNNI AVX512-VBMI.` | no: the canonical Q2_0 CPU expert kernel needs AVX-512; the Ryzen 7 1700 has AVX2 only (`STRATA_PORTABLE=ON`). Qwen3.6 rides the native pack path, which does not use this kernel |
| `prefill_fused_moe_test`, `prefill_fused_iq_test` | Skipped (exit 77) | | expected: the fused prompt MoE needs sm_80 (`CMakeLists.txt`, SKIP_RETURN_CODE 77) |
**`expert_multi_test` and AVX-512, on both VMs.** VM 211's Ryzen 7 1700 (Zen 1) and VM 221's i9-9900K (Coffee Lake)
both lack AVX-512, so `expert_multi_test` refuses on both with `this CPU cannot run the expert kernel`. The kernel it
tests is the canonical Q2_0 pack's CPU expert kernel (`src/kernels/cpu/expert.cpp`, `s2_expert_vnni_q`: AVX-512 VNNI
and VBMI, with a scalar fallback for tests only), which bakes Flash-Next's 2560 x 640. The engine calls
`cpu_require_expert_support()` only when the pack is NOT native (`generate.cpp`, "the canonical Q2_0 pack's CPU
kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well"); for a native pack it logs instead that the
expert kernels run on AVX-2 (or ggml-cpu `vec_dot` without AVX2 / with `STRATA_NO_IQ256`). What that means for
step 5's RAM tier: the RAM tier (`FileExpertSource`'s pinned "cache complement", filled by profile rank) is read in
two ways, both from the same bytes. The CPU lane computes experts from it: `ExpertPool`'s native modes 5 and 6
(`src/kernels/cpu/pool.cpp`, `native_gu_rows` / `native_down_rows`, the AVX-2 i-quant kernels or ggml-cpu's
`vec_dot`) take the blob pointer the source hands them, which is the complement's copy when the expert is held there
and the mapped GGUF otherwise. And the VRAM staging path copies from it: `FileExpertSource::copy_blob` memcpys the
complement's blob into the stage buffer bound for a VRAM slot (`prefetch` skips experts the complement holds; the
`RAM-copy reads` counter of STATS). So the RAM tier is both a compute tier (the CPU lane, on AVX-2 for Qwen3.6
on these hosts) and the source of VRAM refills; neither path touches the AVX-512 kernel, and the engine's own
start-up refusal on these CPUs applies to the canonical pack only.
Everything else passed, including every kernel parity on the card: `iq_parity`, `iq_multi_parity`, `mmvq_multi_parity`,
`s2_gemv_*`, `s_gemv_*`, `dequant_s2_parity`, `gdn_parity`, `gdn_rec_parity`, `gr_parity`, `qsa_parity`,
`qsa_topk_parity`, `qsa_topk_active_parity`, `decode_cluster_parity`, `sampler_parity` (all three), `rope_parity`,
`quantize_act_parity`, `route_window_parity`, `router_top10_parity`, `router_dot_parity` (and `_avx`),
`elementwise_parity`, `bf16_gemv_parity`, `gemm_bf16_parity`, `kv_q4_parity`, `kv_q8_parity`, `kv_stream_parity`,
`cvec_parity`, `native_grouped_parity`, `shared_expert_parity`, `s2_expert_grouped_parity`, the nine
`native_expert_parity_*` cases (including `refuses_q6_K`), `cuda_device_selftest`, `ple_reader_selftest`, the
expert cache / source / profile tests, `vram_plan_test`, `gguf_*`. So on the 1080 Ti the numerics of every kernel
that has a parity test agree with their references; the one Pascal-specific result is a refusal, not a wrong number.
## 4. The pack and the gate
The pack is the layout half (`tools/iq_pack.py --layout-only`): one `native_experts.txt`, made on the Mac in 0.35 s
and copied to `/home/rk/packs/qwen36-iq3/` (2,669 B). The Q4_K_XL layout was made on the VM itself
(`PYTHONPATH=third_party/llama.cpp/gguf-py`, 0.6 s, 2,727 B, `/home/rk/packs/qwen36-q4/`), byte-identical in its
layer lines to `tests/data/native_experts/qwen36-q4_k_xl.txt`.
**The first run did not reach the gate.** With the tree at `8b7525e` both files printed the geometry block and then
exit 1 in 0.13 s from the expert format whitelist that `generate.cpp` ran right after the layout load:
strata generate: layer 0's experts are IQ2_S/IQ3_XXS (ggml types 22/18), which this engine has no GPU kernels for
(`Q4_K/Q5_K (ggml types 12/13)` for the Q4 file). `native_expert_supported()`'s *down* types (`STRATA_D_FMTS` in
`src/kernels/cuda/iq_kernels.cu`) are IQ4_NL, IQ4_XS, Q5_0, Q5_1, Q8_0 and type 42; Q4_K / Q5_K / IQ2_S / IQ3_XXS
are gate/up types only and Q6_K is in neither (`native_expert_parity_refuses_q6_K` pins that). The IQ3_XXS file's
down projections are IQ3_XXS on 37 layers (IQ4_XS on 34/38/39, which the kernels have); the Q4_K_XL's are Q5_K on
37 and Q6_K on 34/38/39. The study's section 3.7 checked the layout against these types, not the kernels. The down
kernels are step 3's `qwen36-step3-experts` branch; commit `30e3add` moved the gate ahead of the whitelist, so a
Qwen3.6 file now prints the plan and the missing pairs. The whitelist still runs, unchanged, for every other file.
**The gate as it stands** (`30e3add` and after, `logs/gate-IQ3_XXS-cap0.log`): exit 2 after 0.36 s, the IQ3_XXS
file with its layout pack, the notes' command:
strata generate: model geometry (/home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf, from the file's metadata):
arch qwen35moe
n_embd 2048
n_layers 40
nextn_layers 0
qsa_interval 4
n_qsa_layers 10
n_gdn_layers 30
ssm_state_size 128
ssm_k_heads 16
ssm_v_heads 32
ssm_d_conv 4
ssm_conv_channels 8192
ssm_value_dim 4096
n_head 16
n_head_kv 2
head_dim 256
n_rot 64
rope_sections 11,11,10,0
rope_base 10000000.000000
rms_eps 0.000001
idx_q_heads 0
idx_key_dim 0
hc 1
hc_lr 0
n_expert 256
n_expert_used 8
n_ff 512
n_ff_shexp 512
has_ple no
has_indexer no
strata generate: VRAM plan for /home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf on this card (kv q4_0, prefill borrows cache slots):
VRAM budget 11001 MiB
fixed set at 262144 tokens: 4019 MiB = weights 1596 + drafter 520 + KV 1440 + session 162 + CUDA context 0 + reserve 300 (prefill borrows cache slots)
expert slots in VRAM: 6748 of 10240 (65%) at 6981 MiB, 1084825 B mean blob
expert copies in RAM: 3492 (3612 MiB of 9409 MiB available minus 4096 headroom)
experts mapped from the model file: 0
strata generate: step 3 also needs GPU expert kernels for gate-up/down IQ2_S/IQ3_XXS (37 layers: 0, 1, 2, 3, 4, 5, 6, 7, ... (37 layers))
strata generate: this is a Qwen3.6-35B-A3B file (qwen35moe, 40 layers, 2048 wide, 256 experts x top-8): Phase 2 step 2 (geometry, metadata, the VRAM plan above) is done, but the engine cannot run it yet. Not done: step 3 (kernels and the block: the GDN gate SiLU(z) instead of sigmoid(z), dense attention at 16 heads with no indexer, the block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native pack and the MTP drafter from blk.40, the expert profile at 40 x 256). See docs/PLAN-qwen36-35b-a3b.md section 5 and docs/qwen36-port/step2-notes.md
The Q4_K_XL file (`logs/gate-Q4_K_XL-cap0.log`, exit 2): the same geometry block with `nextn_layers 1`, then
strata generate: VRAM plan for /home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf on this card (kv q4_0, prefill borrows cache slots):
VRAM budget 11001 MiB
fixed set at 262144 tokens: 4461 MiB = weights 2038 + drafter 520 + KV 1440 + session 162 + CUDA context 0 + reserve 300 (prefill borrows cache slots)
expert slots in VRAM: 3575 of 10240 (34%) at 6539 MiB, 1917542 B mean blob
expert copies in RAM: 2929 (5356 MiB of 9453 MiB available minus 4096 headroom)
experts mapped from the model file: 3736 (read from disk on a miss)
strata generate: step 3 also needs GPU expert kernels for gate-up/down Q4_K/Q5_K (37 layers: 0, 1, 2, 3, 4, 5, 6, 7, ... (37 layers))
strata generate: step 3 also needs GPU expert kernels for gate-up/down Q4_K/Q6_K (2 layers: 34, 38)
strata generate: step 3 also needs GPU expert kernels for gate-up/down Q5_K/Q6_K (1 layers: 39)
strata generate: this is a Qwen3.6-35B-A3B file (qwen35moe, ...): [the same gate message]
(CUDA reports the card as 11,165 MiB total with 11,001 free at start, 164 MiB in use by the display and the
driver; `nvidia-smi`'s 11,264 is the marketing figure.)
**`--vram-cap` on the 1080 Ti** (`logs/gate-*-cap*.log`, after commit `2b4fcf1`): the cap line and the plan at
the study's caps that fit on an 11 GB card. "Free to this engine" is cap minus the 164 MiB in use before the
start, within the driver's 1 MiB rounding of the blocker, at every cap; the start would refuse if it were more than
64 MiB off.
| `--vram-cap` (MiB) | held back | free to this engine | expected (cap - 164) |
| ---: | ---: | ---: | ---: |
| 5722 (6 GB) | 5443 | 5557 | 5557 |
| 7629 (8 GB) | 3536 | 7463 | 7464 |
| 8192 | 2973 | 8027 | 8027 |
| 10490 (11 GB decimal) | 675 | 10325 | 10325 |
| 12288 | "is not below this card's 11165 MiB: no cap" | 11001 | |
The plan's tiers at each cap are in `step2-notes.md` section 5, next to the study's table 4.3.
## 5. The Makefile's Pascal switch
`make build CUDA_ARCHS=61 BUILD_DIR=build-make` on the VM, with no compiler override at all (`logs/make-plain.log`):
the llama.cpp patch applied (`git apply` works outside a repository, so the rsynced tree without `.git` is fine and
the patch now sits in the VM copy of the submodule), CMake chose Debian's g++ 14.2 for the host code and nvcc 12.4
took g++-13 as its host compiler by itself (`NVIDIA 12.4.131 with host compiler GNU 13.3.0`), `Strata: CUDA enabled,
arch 61` with `STRATA_EXPERIMENTAL_SM60=ON` from the Makefile's switch, 0 errors, `built: build-make/unbiased-strata`
(38,627,048 B) in 181 s from configure to link; `cuobjdump --list-elf build-make/unbiased-strata` shows `sm_61` only.
-166
View File
@@ -1,166 +0,0 @@
# Qwen3.6 port, Phase 2 step 2: geometry, metadata, the VRAM planner
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step2`, branched from `qwen36-oracle`).
The design is `docs/QWEN36-35B-A3B.md` sections 3.7 to 3.9 and 4.2; the plan is `docs/PLAN-qwen36-35b-a3b.md`
section 5 step 2. Every item below says what was decided, where it lives, and how it is checked.
## 1. What the engine does with a Qwen3.6 file at the end of this step
Started with `--native Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --pack <dir with native_experts.txt>` the engine:
1. reads every field of `ModelGeometry` from the file's `qwen35moe.*` keys and logs them;
2. refuses the two fused tensor layouts by name if the file had them (no shipped file does);
3. starts without `--ple-gguf` (the architecture has no PLE), with no PLE kernels selected;
4. checks the pack's `native_experts.txt` against the model's 2048 x 512 (every layer's ggml formats must make
the pack's blob size);
5. makes the VRAM plan of section 4.2 from this card's free VRAM (clamped by `--vram-cap`) and the file's own
census, prints the three tiers (VRAM slots, RAM copies, mapped experts), and
6. **stops at the step 2 gate**, exit 2, with this message (from `strata::core::qwen35moe_not_yet`):
> this is a Qwen3.6-35B-A3B file (qwen35moe, 40 layers, 2048 wide, 256 experts x top-8): Phase 2 step 2
> (geometry, metadata, the VRAM plan above) is done, but the engine cannot run it yet. Not done: step 3 (kernels
> and the block: the GDN gate SiLU(z) instead of sigmoid(z), dense attention at 16 heads with no indexer, the
> block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native pack and
> the MTP drafter from blk.40, the expert profile at 40 x 256).
Why a gate and not a run: `layer.cpp` and `verify.cpp` still wrap every layer in the hyper-connection read/write
and require the `hc_*` and `indexer.*` tensors (`layout.cpp`'s `check_one`), the GDN kernels gate with sigmoid,
prefill refuses any geometry but 2560/4/320/top-10. Each of those is step 3. Failing before the first weight
moves, with the plan printed, is Maya's Phase 0 shape.
The real file's log on the Mac (`model_geometry_test --real`), both the IQ3_XXS and the Q4_K_XL file:
arch qwen35moe, n_embd 2048, n_layers 40 (nextn 0 / 1), qsa_interval 4 (10 attention, 30 GDN),
ssm state 128 / 16 k-heads / 32 v-heads / conv 4, conv channels 8192, value dim 4096,
n_head 16, n_head_kv 2, head_dim 256, n_rot 64, sections 11,11,10,0, base 1e7, eps 1e-6,
hc 1, n_expert 256, k 8, n_ff 512, shexp 512, no PLE, no indexer
## 2. Decisions
| Decision | Where | Why |
| --- | --- | --- |
| `ModelGeometry` carries `arch` (an enum), `nextn_layers`, `n_rot`, `rope_sections`, `rope_base`, `rms_eps`, `n_ff_shexp`, `n_expert_used`, `n_vocab`, `has_ple`; `derive()` computes conv channels and value dim | `include/strata/core/layout.hpp` | the stored conv channels / value dim were the row-2 trap: changing `ssm_v_heads` alone left them at Flash-Next's. An enum, not a string, so the struct stays trivially copyable for the `.cu` files that take it by value |
| The reader is header-only and CUDA-free | `include/strata/core/model_geometry.hpp` | the unit test links only the GGUF reader; the engine reads the geometry before any weight moves |
| `hc = 1`, `has_ple = false`, no indexer come from the architecture string, not a key | same | the file has no key for any of them; llama.cpp decides the same way |
| For `qwen4exp` the GDN, ff and interval keys are optional (defaults stay); for `qwen35moe` they are required | same | no Flash-Next file was on hand to confirm which of its keys are present; a required key that a shipped Flash-Next file lacks would have broken the working model. The six keys the guard always demanded stay required for both |
| `check_architecture` accepts `qwen35moe` with presence-only checks of llama.cpp's required key set | `include/strata/artifact/gguf_reader.hpp` | the file is the authority on its sizes; the guard's job is "is this a file llama.cpp's own loader would accept" |
| Fused forms refused by tensor name (`ffn_gate_up_exps`, `attn_qkv` in an attention layer) at the engine and in `iq_pack.py` | `model_geometry.hpp` (`check_model_tensor_forms`), `tools/iq_pack.py` (`expert_layout`) | `attn_qkv` is legitimate in a GDN layer (the conv input), so the check is per layer type |
| `expert_layout_load` takes `n_embd`, `n_ff` | `include/strata/kernels/cpu/expert_layout.hpp`, `src/kernels/cpu/expert_layout.cpp` | the one leak (row 108). A pack with no `native_experts.txt` (canonical Q2_0, which bakes 2560 x 640) is now refused for any other geometry with a message naming the packer |
| The geometry is read before the layout load in `generate.cpp`; `K` and the embedding dims come from it; the rope keys are read under the file's own prefix | `src/program/generate.cpp` (the block before `expert_layout_load`) | rows 7 to 11 |
| The draft (nextn) block is left out of the trunk's `native_experts.txt` | `tools/iq_pack.py` | the Q4_K_XL file carries `blk.40`; a layout with 41 layers would make the engine route layer 40 of a 40-layer model. The drafter's pack (step 4) takes it |
| `--ple-gguf` is not required when the architecture has no PLE; an explicit one is refused; the PLE kernels are not selected; the session carves no PLE history | `generate.cpp` (the `--native` block), `src/core/session.cpp` | 3.9: the kernels already ran without it, only the CLI insisted. The 360 KB `NG_HIST x NG_HC_DIM` buffer is skipped through `has_ple` |
| The planner is a pure function at the mean blob | `include/strata/plan/vram_plan.hpp` | testable without a GPU; the engine's per-layer sizing prices the same bytes at each profile entry's own blob and lands within a few slots |
| The context is lowered in steps of 4,096 toward 131,072, never below; below the floor the start refuses with every number and the IQ3 file's name | same | the plan's rule; KV streaming is not a lever for dense attention |
| The reserve in the Qwen3.6 plan is 300 MiB (`kSmallReserveMib`) unless `--vram-reserve-mib` was given | `generate.cpp` (the gate) | table 4.3 was derived at the small reserve; the Flash-Next auto sizing starts at 700 and shrinks to 300 only when the cache would be too small |
| The prompt buffers in the plan are the engine's own estimate (`160 + chunk * 680 / 1024` MiB: 1,520 at chunk 2048), not llama.cpp's 1,904 | same | it is this engine's prompt path that allocates them; the study's figure was the baseline's compute buffer. With a profile prefill borrows cache slots and the term is 0 |
| `--vram-cap MIB`: every `cudaMemGetInfo` in `generate.cpp` goes through `vram_info`, which clamps the free figure to `cap - used`; a blocker of `total - cap` is allocated before the weight arena | `generate.cpp` (`vram_info`, the cap block) | 4.2 item 4. `used` counts every process, so the cap is the card's size, not this engine's share |
| `--ram-cap GIB`: `host_available_memory` is clamped (so `pin_cache_complement` sizes the RAM tier as that machine would), the resident budget is clamped, the pinned arena's limit too | `src/core/expert_source.cpp` (`set_host_ram_cap`), `generate.cpp` | the page cache cannot be capped from inside the process (the 12 GiB VM does that physically) |
| Tier counters: the serve loop's `STATS` command answers one JSON line; the same line is logged at start; `/health` carries it as `tiers` | `generate.cpp` (`tier_stats`), `frontend/main.cpp` | VRAM slots and how many hold an expert, RAM copies (`complement_count`), mapped experts, tokens served, VRAM hits of lookups, RAM-copy reads, file reads, warm hints, and the major page faults from `/proc/self/stat` since start as the disk-read proxy. During a request `/health` serves the last reading marked `tiers_stale` |
| The Flash-Next path keeps its allocation order and auto sizing; it gains the cap and the counters | `generate.cpp` | its fixed set is allocated progressively with its own refusals; the lowering rule is for the dense-KV model, which is gated here anyway |
## 3. What a Qwen3.6 native pack contains (step 4 builds it; the layout half exists now)
`tools/iq_pack.py --gguf <file> --out <dir> --layout-only` writes `native_experts.txt` alone (v3: one line per
trunk layer with the gate/up and down ggml types, the blob size, and the three tensors' absolute offsets) and
prints the census. The two real files:
| File | Layers x experts | Expert bytes | Mean / largest blob | Per-layer formats |
| --- | --- | ---: | ---: | --- |
| `UD-IQ3_XXS` | 40 x 256 | 10,594 MiB (11,108,614,144 B) | 1.035 / 1.172 MiB | gate/up IQ2_S everywhere; down IQ3_XXS on 37 layers (blob 1,073,152 B), IQ4_XS on 34, 38, 39 (1,228,800 B) |
| `UD-Q4_K_XL` (MTP repo) | 40 x 256 (+ `blk.40`, the drafter's, left out) | 18,726 MiB (19,635,634,176 B) | 1.829 / 2.195 MiB | gate/up Q4_K, down Q5_K on 37 layers (1,900,544 B); Q4_K / Q6_K on 34 and 38 (2,039,808 B); Q5_K / Q6_K on 39 (2,301,952 B) |
These two files are `tests/data/native_experts/qwen36-{iq3_xxs,q4_k_xl}.txt` and `expert_layout_test` loads them
at 2048 x 512 (every layer's `NativeFmt` makes the blob) and sees them refused at 2560 x 640. The full pack
(step 4) adds `index.txt` (the dense projections served natively from the GGUF: Q6_K / Q8_0 `attn_*`, `ssm_out`,
`ffn_*_shexp`, `output`), `dense.bin` with the float tensors in the engine's forms (the norms F32 as stored;
the F32 routers, `ssm_alpha`, `ssm_beta` and the 1-D shexp gate need `--compat-bf16` today, which step 4 decides),
the tokenizer, and `expert-profile.bin` at 40 x 256 from the E0 trace.
## 4. Build and test commands
On the Mac (no CUDA; the artifact reader, the planner and the geometry test build and run):
cmake -S . -B build-mac -G Ninja -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=ON
cmake --build build-mac --target model_geometry_test vram_plan_test gguf_split_test gguf_reader_test
(cd build-mac && ctest -R 'qwen36_synth|model_geometry|vram_plan|gguf' --output-on-failure)
./build-mac/model_geometry_test --real ~/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf
./build-mac/vram_plan_test --at q4 11264
python3 tools/iq_pack.py --gguf ~/models/qwen3.6/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --out /tmp/p --layout-only
python3 tools/test_iq_pack.py
Results on the Mac, 2026-10-11: `model_geometry_test` 32 checks pass on the synthetic files and the real-file
mode passes on both files; `vram_plan_test` 43 checks pass; `test_iq_pack.py` 23 tests pass.
On VM 211 (the 1080 Ti, sm_61; `docs/qwen36-port/pascal-build.md` has the build's outcome):
rsync -a --delete --exclude build-mac --exclude .git --exclude build --exclude build-make --exclude logs \
/Users/robertkarl/Code/UnbiasedStrata-step2/ rk@192.168.50.43:/home/rk/UnbiasedStrata-step2/
# (--delete without the three VM-side excludes removed the VM's build/, build-make/ and logs/ once)
cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON \
-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DCMAKE_CUDA_HOST_COMPILER=g++-13 \
-DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13
cmake --build build -j 8 --target unbiased-strata
cmake --build build -j 8 # every parity target the root CMakeLists declares
(cd build && ctest --output-on-failure)
./build/expert_layout_test tests/data/native_experts
./build/model_geometry_test build/qwen36_synth
./build/unbiased-strata --engine --native /home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --pack /home/rk/packs/qwen36-iq3 \
--tokens 1 --max-context 262144 --kv q4_0 --spec 4 --prefill 2048 --expert-profile /dev/null # the gate
## 5. VM 211 results
Done 2026-10-11 after the sweep and its nvprof re-runs released the card (`docs/qwen36-port/pascal-build.md` has
every log line; the VM keeps the tree at `/home/rk/UnbiasedStrata-step2/` with `build/`, `build-make/` and `logs/`).
| Item | Result |
| --- | --- |
| sm_61 build | no source change needed: configure 4 s, `unbiased-strata` 173 s, every other target 43 s more, 0 errors; `cuobjdump --list-elf` shows `sm_61` only. Every sm_75+ site was already behind `__CUDA_ARCH__` (pascal-build.md section 1) |
| `make build CUDA_ARCHS=61` | end to end with no compiler override, 181 s, `sm_61` only; the Makefile's switch sets `STRATA_EXPERIMENTAL_SM60=ON` |
| ctest on the 1080 Ti | 75 tests: 69 pass, 4 fail, 2 skip (sm_80 fused prompt MoE). Of the failures one is Pascal-specific, `kv_hybrid_parity` [5/5], where `qsa_prompt_attn_batch` refuses `cc < 70` by design and the test counts the refusal as a failure (step 3). The other three are the host: `platform_memory_test` (mlock limit 8 MiB), `ple_parity` (hardcoded Flash-Next path), `expert_multi_test` (AVX-512 on Zen 1). Two of the branch's own tests had never been built (CUDA-gated): `qwen36_synth_fixtures` failed under cmake 3.31 (CMP0007, commit `cd2a73c`) and `expert_layout_test` carried a wrong Q4 total and a refusal-message expectation (commit `5798a46`); both pass now, and `model_geometry_test --real` passes on the VM against both real files |
| the pack | `native_experts.txt` only: 2,669 B in 0.35 s on the Mac for the IQ3_XXS file; 2,727 B in 0.6 s on the VM (vendored gguf-py) for the Q4_K_XL file |
| the gate | **not reached.** Both real files print the geometry block and are then refused by the native expert kernel's format whitelist, before the plan: `layer 0's experts are IQ2_S/IQ3_XXS (ggml types 22/18), which this engine has no GPU kernels for` (exit 1, 0.13 s), and `Q4_K/Q5_K (12/13)` for the Q4 file. The grouped kernels' *down* types are IQ4_NL / IQ4_XS / Q5_0 / Q5_1 / Q8_0 only; the IQ3_XXS file's down is IQ3_XXS (37 layers), the Q4_K_XL's Q5_K and Q6_K. A step 3 kernel item (or a step 4 repack of the down projections) the plan did not list; the gate message itself is exercised by `model_geometry_test --real` |
Correction to section 3's table: the Q4_K_XL expert total is 19,635,634,176 B (the pack header's figure, and the sum
of its blobs); the earlier 19,636,158,464 was 524,288 B high and was also in `expert_layout_test`.
### The planner on the 1080 Ti against the study's table 4.3 (2026-10-11, after `4a998ad`)
The engine's own plan (`--vram-cap`, prefill borrowing, `logs/gate-*-cap*.log` on the VM) at the caps an 11 GB card
can emulate; the study's "derived, borrow" column beside each. The engine's figures run a few percent above the
study's because the study's budgets carry a 300 MiB CUDA-context term that the engine's free figure already lacks,
less the 164 MiB this VM's display and driver hold. The 12, 16, 24 and 32 GB rungs cannot be emulated on this card
(`--vram-cap 12288` is "not below this card's 11165 MiB: no cap"); `vram_plan_test` covers them from the study's
inputs.
| Budget | cap (MiB) | VRAM budget | Q4 slots (study) | Q4 RAM copies / mapped | IQ3 slots (study) | IQ3 RAM copies / mapped |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| 6 GB | 5722 | 5557 | 598 (~525) | 2,894 / 6,748 | 1,486 (~1,350) | 5,172 / 3,582 |
| 8 GB | 7629 | 7463 | 1,641 (~1,570) | 2,855 / 5,744 | 3,328 (~3,200) | 5,115 / 1,797 |
| 8 GiB | 8192 | 8027 | 1,949 | 2,874 / 5,417 | 3,873 | 5,068 / 1,299 |
| 11 GB (decimal) | 10490 | 10325 | 3,206 (~3,130) | 2,959 / 4,075 | 6,094 (~5,960) | 4,146 / 0 |
| 1080 Ti, no cap | | 11001 | 3,575 (~3,550) | 2,929 / 3,736 | 6,748 (~6,700) | 3,492 / 0 |
The RAM tier is sized from this VM's ~9.4 GiB available minus the 4 GiB headroom (the `--resident-experts` rule),
so the Q4 file keeps a disk tier at every cap on this host and the IQ3 file none from 11 GB up, as 4.3 said.
### What the review and the Pascal run changed afterwards (2026-10-11, the same branch)
| Finding | Commit | What changed |
| --- | --- | --- |
| the down-type whitelist, missed by the study's section 3.7 | `30e3add` | 3.7 said "the IQ3_XXS file's 37/3 down split and the Q4_K_XL's Q6_K layers need no format change" of the *layout*; it did not check `STRATA_D_FMTS`, the grouped kernels' down types (IQ4_NL, IQ4_XS, Q5_0, Q5_1, Q8_0), against the files' IQ3_XXS / Q5_K / Q6_K down projections. The gate now runs before that whitelist and names the missing pairs per layer; the kernels are step 3's `qwen36-step3-experts` branch |
| `--vram-cap` subtracted the blocker twice | `2b4fcf1` | `vram_info` takes the blocker's own bytes out of `used`; the cap line prints what a card of the cap would show and refuses if the clamped figure is off by more than 64 MiB |
| the planner's 300 MiB CUDA-context term on top of a free figure already net of it | `4a998ad` | the engine passes 0; the unit test keeps the study's 300 MiB with the cards' sizes as budgets |
| `--ram-cap` set an explicit resident budget on the auto path | `76a437f` | only an explicit budget above the cap is clamped |
| `/health`'s last reading raced | `84794ce` | its own mutex, copies under it |
| the qwen4exp reader's optional keys untested | `afec2f1` | a fixture with the real Flash-Next key set equals the defaults field by field; the fixture writer gained f32 and u32-array values |
| the trace bound literal 48; the refused-profile test | `db4da2f`, `d010040` | `Drive::n_layers` from the geometry; `expert_profile_save_test` sees a 48 x 512 profile refused for 40 x 256 |
| `test_iq_pack.py` had no test of the step's additions | `b2ccff0` | `--layout-only`, the nextn exclusion, the fused refusal: 26 tests |
| `tools/make_profile.py` `N_LAYER, N_EXPERT = 48, 512` | (step 4) | the profile from the E0 trace at 40 x 256 is step 4's, with the trace format |
`model_geometry_test --real` on the Mac's `~/models/dwarfstar/Qwen3.8-Flash-Next-Q2.gguf` (147 GB, the only Flash-Next
file on the Mac or VM 211; the `ple_parity` shard path does not exist anywhere): the qwen4exp reader reads it
(48 trunk layers, `nextn_layers 1`, every other field the struct's default, separate tensor forms), but the
architecture guard refuses it with `qwen4exp.block_count = 49, expected 48`: the guard's qwen4exp branch wants the
literal 48 (unchanged by this step, the reviewer's byte-for-byte check), and this file is an MTP build with a draft
block. Whether that file ever ran under this engine is not this step's question; it is recorded here because the
guard, not the reader, is what refuses it.
-214
View File
@@ -1,214 +0,0 @@
# Qwen3.6 port, Phase 2 step 3: dense attention replacing QSA
Working notes of the `attn` area (branch `qwen36-step3-attn`, from `qwen36-step2` at 8b7525e, 2026-10-11). The
design is `docs/QWEN36-35B-A3B.md` section 3.3 (six items) and section 6 step 3, second bullet. Every item says
what was decided, where it lives, how it is checked, and the numbers from both cards.
## 1. What changed, item by item
| 3.3 item | Decision | Where |
| --- | --- | --- |
| 1, the producer | A **null `ids` is the identity selection**: the decode and prompt kernels read cell `j = j` for `j < step[kStepWidth]`. The engine's dense paths pass `nullptr` and carve no ids buffer (prefill at 2,048 queries x 262,144 cells would carry 2 GiB of ids). The explicit form `qsa_identity_ids(ids, steps, n_q, cap, stream)` exists for a caller that must hand a buffer on (a dump, the streaming resolver) and for the test, which holds the two forms bit for bit equal | `src/kernels/cuda/qsa_decode_attn.cu`, `qsa_prompt_attn.cu`; `qsa_layer` and the verify window's attention step pass null |
| 1, the indexer skipped | `g.has_indexer()` (step 2: false for `qwen35moe`) gates the raw key projection, the append, the indexer query, the block scores and the top-k in `qsa_layer` and in `Verifier`'s attention step; the four `indexer.*` tensors are required only with an indexer | `src/core/layer.cpp` (c4793cd), `src/core/verify.cpp` (bc2fb91), each one commit |
| 2, G = 12 | `G` is a template parameter of every attention kernel, instantiated at **2, 8, 12**; `qsa_attn_group(s, why, n)` picks it from the geometry and returns 0 with a message naming the heads for any other ratio; `qsa_attn_group_check(s, G, why, n)` refuses a G that does not divide the geometry (G = 12 on 16 / 2 is a message, never a mis-indexed run); `qsa_prompt_attn_batch` returns false for an unknown ratio and the decode kernel then refuses by name | `qsa_decode_attn.cu`, `qsa_prompt_attn.cu`, `include/strata/kernels/qsa_decode_attn.hpp` |
| 3, the selection width and the capacity | **One builder**, `strata::core::qsa_shapes(g)` (`include/strata/core/qsa_shapes.hpp`, header-only), used by `layer.cpp`, `verify.cpp`, `mtp.cpp`, `session.cpp` and `prefill.cpp` (the last two as `[shared]` commits): for a geometry without an indexer it zeroes `idx_n_head`, `idx_dim` **and** `idx_top_k`. The dense signal is `qsa_dense(s)` = the three zero together; `qsa_shapes_valid(s, why, n)` (what every kernel's guard checks, non-exiting for the test) refuses a half-set shape - two zeros with the 2,048 budget kept, which the first hand-written builders in verify and mtp made and the kernels' guard then exited on at the first append. `qsa_selection_width(n_kv, s)` returns `n_kv` when dense, so `qsa_step_fill` writes `width = n_kv`; **`qsa_selection_cap(max_cells, s)`** is the capacity every buffer is sized by: `max_cells` when dense, `qsa_selection_width(kTopkMaxCells, s)` = 2,051 otherwise. The indexer entry points refuse a dense shape by name (`validate_indexer`). Not converted: `generate.cpp:7469` (a snapshot-hash shape that sets only `n_head_kv`/`head_dim`/`idx_dim`; not edited on this branch) | `qsa_shapes.hpp`, `qsa.hpp`, `qsa.cu`, `layer.cpp`, `verify.cpp`, `mtp.cpp`, `session.cpp`, `prefill.cpp` |
| 4, the state without the indexer | `kv_plan` gives a dense state `pooled_rows = 2` (the drafter's ring) and `idx_dim` is 0, so the three indexer regions are 0 bytes (section 3). The buffers carve no `cell_scores`, `ids`, `k_scratch`, `v_scratch` for the dense model: at 262,144 cells those are 1 + 1 + 512 + 512 MiB (the gather scratch was `cap x n_head_kv x 256 x 2 B` each) | `layer.cpp`: `kv_plan`, `qsa_state_bytes/init`, `qsa_buffers_bytes/init` |
| 5, the split-K scratch | The grid is capped at **128 blocks per KV head**; a block walks its span of the selection in 64-cell sub-chunks with the running (m, l, acc) rescale. The span is computed **on the device from the token's width**, not from the capacity, so a selection up to 8,192 cells still spreads one block per 64 cells (decode at a short depth keeps its parallelism). **The bound applies to dense shapes only**: a sparse (Flash-Next) shape keeps `ceil(cap / 64)` blocks at any capacity, because the MTP drafter's ring runs this kernel at its `--mtp-window` (32,768 by default: 512 blocks, `mtp.cpp:249`) and keeps its previous grid, scratch (12 MiB at 24 heads) and summation order. On sm_75+ one looped kernel serves every capacity (the 4090 measures it equal to the old one at 2,051 cells). Below sm_75 (`STRATA_EXPERIMENTAL_SM60`, PR #540's kernel) the looped form costs 16-28 registers on sm_61 (80-92 at G 12 against 63-64; a register cap spilled and cost more), so every sparse shape, and a dense capacity under 8,192 cells, runs `attn_chunk_kernel_pre75_single`, PR #540's body as it was: every Flash-Next state (the QSA layers at cap 2,051, the drafter's ring at its window) is the old kernel to the instruction, and the looped `attn_chunk_kernel_pre75` runs only for the dense model's long-context states. `qsa_decode_attn_scratch_floats(cap, s) = min(ceil(cap / 64), 128) x n_head x 258 + 64`: **528,448 floats = 2.02 MiB per query row at 16 heads** for any cap >= 8,192 (was 64.5 MiB at 262,144); 16 MiB for the 8-row verify window, 64 MiB for prefill at `attn_batch` 32 | `qsa_decode_attn.cu` (`kMaxChunks`, `chunks_for`, both chunk kernels, `attn_merge_kernel<G>`) |
| 6, KV streaming | `qsa_kv_streaming_applies(g, why)` (false for a no-indexer geometry, with the sentence that says why: every block resident every token is the whole KV over PCIe per token); `qsa_state_init` refuses a streamed dense state with that message as the backstop. The CLI check belongs in `generate.cpp`, which this branch does not edit (the step-2 branch owns it): the integrator wires `--kv-resident > 0 && !qsa_kv_streaming_applies(g, why)` into the start-up refusal | `include/strata/core/layer.hpp`, `layer.cpp` |
The formats carry over unchanged: the fp16 / INT8 / Q4_0 / K8V4 pools, the Hadamard rotation (`kv_rot`: q and the
output rotated in `qsa_layer` and in verify exactly as before), the page table (shuffled in every test), the
RoPE tables (the test builds them with `build_rope_table` at base 1e7 and holds `rope_neox_apply` to the oracle).
The prompt path on Pascal is the batched decode kernel (`qsa_prompt_attn_batch` returns false below cc 70), so
G = 8 and the scratch bound above are the prefill attention there; on the 4090 the MMA kernels run at G = 8 (and
2, 12). The MMA kernels pad the 16-row tile with zero rows for any G <= 16 exactly as 12 did; one real bug came
out of G = 2: the two `mma` kernels wrote accumulator rows 0..7 unconditionally, which at G < 8 overwrote the next
KV head's output (the 4 / 2 fixture read 0.99 relative L2). The writes are guarded by G now (856daa0).
## 2. The dense state's layout, exactly
`qsa_state_init` carves one 16-byte-aligned cursor (`layer.cpp`); for a no-indexer geometry (`pooled_rows = 2`,
`idx_dim = 0`, `idx_block = 4`, mode 0, no ring) the regions are, in order:
| region | bytes | note |
| --- | --- | --- |
| K/V pools | `kv_pool_bytes(s, pages)` + 64: fp16 `pages x 2 x page_size x 256 x 2 x 2`; INT8 `pages x page_size x 1,056 + 64`; Q4_0 `pages x page_size x 576 + 64`; K8V4 `rows x 256 + rows x 8 + rows x 144 + 64` | `pages = ceil(max_cells / 4)`; 1,024 MiB fp16 / 528 INT8 / 288 Q4_0 / 408 K8V4 at 262,144 cells |
| `page_table` | `pages x 4` | 256 KiB at 262,144 |
| residency map | none | mode 1 is refused for the dense model |
| `idx_tail` | `3 x idx_dim x 4` = **0** | pointer taken, nothing carved |
| `idx_dead` | `idx_dim x 4` = **0** | |
| `idx_pooled` | `pooled_rows x idx_dim x 4` = **2 x 0 x 4 = 0** | `idx_pooled_rows = 2` as the drafter's ring |
| `idx_block_pos` | 16 (one int32, aligned) | kept: `QsaIndexerBuffers` is still a struct of four pointers |
| `cos_tab`, `sin_tab` | `max_cells x 32 x 4` each, in the primary state only; the others borrow | 32 MiB each at 262,144 (`n_rot` 64) |
| `step` | 16 | `kStepCount` int32 |
| `attention_status` | 16 | |
| `pos_dev` | `n_head x 4` -> 64 | |
| trailer | +256 | `qsa_state_bytes` adds 256 after the alignment |
So the indexer's 32 MiB per attention layer at 262,144 cells (`65,538 x 128 x 4`) is gone; a dense state is the
pools, the page table, the rope tables (primary only) and 112 bytes. `qsa_state_zero` memsets the 0-byte regions
(a no-op). The buffers (`qsa_buffers_bytes`, one set per session): `x_q8k`, `x_q8_0`, `x_bf16`, `q_full`, `qcur`,
`kcur`, `vcur`, `idx_raw` (0), `q_idx` (0), **no** `cell_scores` / `ids` / `k_scratch` / `v_scratch`, `attn`,
`attn16`, `attn32`, `attn_q8k`, `attn_scratch` (2.02 MiB at 16 heads, any `max_cells` >= 8,192).
`conversation_state.cpp` / `conversation_snapshot.cpp` (the session save and restore) still address the indexer
regions by `qsa_real_shapes().idx_block`; with `idx_dim = 0` their sizes are 0. Not exercised here (step 4's area).
## 3. How it is checked
`src/kernels/qsa_dense_parity.cpp` (CTest `qsa_dense_parity`, after the fixture test `qwen36_attn_fixtures`, which
runs `cmake/qwen36_attn_fixtures.cmake`: `tools/qwen36_synth_gguf.py --heads 16,2|24,2|4,2 --head-dim 256
--no-nextn` and `ref/qwen36.py --text "dense attention over sixteen heads, G=8!" --dump` on each; 40 tokens; about
1 s). The `--head-dim` option is the one `[shared]` change (7368da2): the toy fixture is head_dim 32 and the
engine's kernels are 256, so an engine-level comparison against the oracle needs a fixture at 256 (`n_rot` 64,
the real IMRoPE sections in proportion, base 1e7).
1. **Host only.** The one builder on a `qwen35moe` geometry gives a dense shape the guard accepts, on Flash-Next's defaults the sparse real shape; the half-set shape (two zeros, budget 2,048) is neither dense nor valid (the negative). The chunk count by shape: dense 2,051 -> 33, 8,192 / 262,144 -> 128; sparse 32,768 -> 512 with the old scratch formula. The group from the geometry (16/2 -> 8, 24/2 -> 12, 4/2 -> 2, 26/2 refused naming 26 and 13);
**G = 12 asked of 16 heads refused by name**; width and cap (sparse 3,000 -> 2,051 / 2,051; dense 3,000 ->
3,000 / `max_cells`); `qsa_step_fill` width; `chunks` (2,051 -> 33, 8,192 and 262,144 -> 128); the scratch
at 2,051 x 24 heads equals the old formula and at 262,144 x 16 heads is 528,448 floats.
2. **The decode kernel against a host reference in double over the dequantized pools**, every KV format (fp16,
INT8, Q4_0, K8V4; the pools filled through the engine's own append kernels behind a shuffled page table,
read back and dequantized exactly as the kernel's loads do), at G = 8 (16 / 2) and G = 12 (24 / 2), widths
300, 3,000 and 20,000 (the last one takes the multi-sub-chunk path: 313 sub-chunks over 128 blocks), three
query rows per case with widths w, w - 1, w - 77 and their own steps; **null ids == explicit identity ids bit
for bit**; the prompt kernel on the same rows where the host takes it (sm_70+). G = 2 fp16 at 3,000.
**Negative:** the sparse width 2,051 handed to the kernel on the 3,000-cell context (what the old
`qsa_selection_width` would have written for Qwen3.6) differs from the dense reference by 0.65-0.69 relative
L1.
3. **The oracle's fixtures.** For g8, g12, g2: `Qcur_reshaped-3` and `Kcur-3` through the engine's
`rms_norm_weighted` and `rope_neox_apply` (table from `build_rope_table`) against `Qcur-3` and `Kcur-3#2`;
the softmax of the engine's q/k (host, double) against `kq_soft_max-3`; the attention over the engine's fp32
q/k/v (host, double) against `kqv-3`; then the **fp16 KV through `kv_append_step` and the batched decode kernel
with null ids, 40 queries at widths 1..40**, against `kqv-3`; `qsa_gate_apply_f32` on `Qcur_full-3` against
`attn_gated-3`. **Negatives, the oracle's controls:** the gate skipped (relative L1 0.995-0.998 at
`attn_gated-3`; the oracle's table says 1.03 on its own fixture), RoPE on adjacent pairs from the oracle's
normed q/k (0.17-0.20 at `kqv-3`; the oracle: 0.20), the GQA map `h % n_kv` (0.69-0.72; the oracle: 0.74).
4. `src/kernels/qsa_attn_bench.cpp` (CTest `qsa_attn_bench`, 2,051 and 8,192 cells at 16 / 2): the kernel's
time per call on random pools, explicit ids only, so it builds against the pre-step-3 kernel as well (the
"before" column below is that build: `8b7525e`'s `qsa.hpp`, `qsa_decode_attn.{hpp,cu}`, `qsa_prompt_attn.cu`
dropped into a copy of this tree).
Tolerances and what was measured (both cards):
| check | tolerance | 4090 (sm_89) | 1080 Ti (sm_61) |
| --- | --- | --- | --- |
| decode kernel vs host reference, dequantized pools, all formats, G 8 / 12 / 2 | 3e-5 rel L2 | 2.0e-7 .. 3.9e-7 | 2.0e-7 .. 3.9e-7 (the `pre75` kernel runs there) |
| prompt kernel vs host reference (fp16 / INT8 / Q4_0 / K8V4), G 8 / 12 / 2 | 2e-3 | 4.1e-7 .. 6.3e-7; K8V4 1.6e-4 | the host keeps the decode kernel (cc < 70): skipped |
| engine norm + RoPE vs `Qcur-3`, `Kcur-3#2` | 2e-6 | 8.1e-8 .. 9.8e-8 | 8.1e-8 .. 9.8e-8 |
| host softmax of the engine's q/k vs `kq_soft_max-3` | 1e-5 | 1.6e-7 .. 1.7e-7 | 1.6e-7 .. 1.7e-7 |
| host attention over the engine's fp32 q/k/v vs `kqv-3` | 1e-5 | 1.5e-7 .. 1.7e-7 | 1.5e-7 .. 1.7e-7 |
| decode kernel over the **fp16** KV vs `kqv-3`; gated vs `attn_gated-3` | 1.5e-3 | 2.2e-4 .. 2.3e-4 | 2.2e-4 .. 2.3e-4 |
The 2.2e-4 is the fp16 KV pool (K and V rounded to 11 bits; the oracle's are F32): the same q/k/v in fp32 give
1.5e-7, so the kernel's own arithmetic is at the 1e-7 level and the format is the whole gap. The policy's
`attn_out` class (`oracle-crosscheck.md`: 1.1e-4 median, 6.7e-4 max for the Q8 oracle, 4x margin) is the right
class for it and 1.5e-3 is inside that margin.
The rest of the attention suite on the branch: `qsa_parity`, `qsa_prompt_attn_parity`, `kv_hybrid_parity`,
`kv_stream_parity`, `qsa_topk_parity`, `qsa_topk_active_parity` (the Flash-Next geometry, G = 12: the
instantiation Flash-Next keeps). `kv_hybrid_parity`'s case [5/5] now skips below sm_70 instead of failing (the
prompt kernel refuses cc < 70 by design and prefill takes the batched decode kernel, which case [4/4] holds to
the same reference).
## 4. The numbers
`qsa_attn_bench`, one query row, identity selection of `cells` cells, median of the reps, microseconds per call
(the chunk kernel plus the merge). "before" is the pre-step-3 kernel (G = 12 only: it refuses 16 heads).
**RTX 4090 (sm_89), VM 221**, `--reps 200` (24 / 2) and `100` (16 / 2):
| cells | 24/2 fp16 before -> after | 24/2 INT8 | 24/2 Q4_0 | 16/2 fp16 | 16/2 INT8 | 16/2 Q4_0 |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 2,051 | 32.8 -> 32.7 | 33.8 -> 34.5 | 34.6 -> 34.8 | 29.3 | 29.4 | 30.3 |
| 8,192 | 57.2 -> 57.0 | 58.2 -> 57.3 | 59.2 -> 59.2 | 48.0 | 47.4 | 49.2 |
| 32,768 | 215.7 -> 148.4 | 205.0 -> 143.2 | 212.6 -> 150.7 | 130.9 | 110.5 | 115.7 |
(A rerun of the final build: fp16 32.8 / 56.3 / 138.0, Q4_0 34.6 / 58.3 / 147.5 at 2,051 / 8,192 / 32,768; the
sm_89 build runs the one looped kernel at every capacity.)
| 131,072 | | | | 540.7 | 539.6 | 467.9 |
| 262,144 | | | | 1,032 | 1,051 | 1,053 |
At 2,051 cells on Flash-Next's path the kernel is the same grid and the same arithmetic (33 blocks of one
sub-chunk; the test holds the scratch formula equal there) and the time is the same within the run-to-run
spread (32.7 vs 32.8 us; INT8 34.5 vs 33.8 is the spread of a 34 us launch, the Q4_0 pair is 34.8 vs 34.6). Above
8,192 the bounded grid is faster (fewer, longer blocks: 148 vs 216 us at 32,768) and the scratch stays at 2.0 /
3.0 MiB instead of 12. At 262,144 cells, 16 heads, one row costs 1.03 ms on the 4090 whatever the format: the
fp16 pool streams at 520 GB/s and the quantized pools are bound by the dequantization in the value loop, not by
bytes (INT8 263 GB/s, Q4_0 143 GB/s over fewer bytes, the same time). Ten attention layers at 256K are therefore
about 10 ms of a token on this card.
**GTX 1080 Ti (sm_61), VM 211** (the `attn_chunk_kernel_pre75` path of `STRATA_EXPERIMENTAL_SM60`), `--reps 100`
(24 / 2) and `50` (16 / 2):
| cells | 24/2 fp16 before -> after | 24/2 INT8 | 24/2 Q4_0 | 16/2 fp16 | 16/2 INT8 | 16/2 Q4_0 |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 2,051 | 41.0-42.0 -> 41.0-41.9 | 38.9 -> 38.9-39.9 | 41.0-42.0 -> 41.0 | 43.0 | 33.8 | 34.8 |
| 8,192 | 141.3-142.3 -> 140.3-141.3 | 141.3 -> 140.3-141.3 | 146.4-147.5 -> 143.4-144.4 | 140.4 | 121.9 | 135.2 |
| 32,768 | 493.6-494.6 -> 494.4-494.6 | 496.6 -> 496.6-497.4 | 505.9-506.9 -> 497.6-497.7 | 378.9 | 330.8 | 373.8 |
| 131,072 | | | | 1,290 | 1,126 | 1,287 |
| 262,144 | | | | 2,354 | 2,117 | 2,605 |
The before / after pairs are interleaved A/B runs (rounds 2 and 3 of three; round 1 is the warm-up). The 24/2
shape is sparse, so after e7c9c8d both sides are the same grid (one block per 64 cells at every capacity, the
same 12.09 MiB scratch at 32,768) and the same single-chunk kernel body: the pairs agree within the 1 us
run-to-run spread at every capacity and format, which is the drafter's case (its ring at 32,768) as much as the
QSA layers' (2,051). The 16/2 columns are the dense model's states (cap >= 131,072 in practice), which take the
looped kernel on Pascal: on Q4_0 it is 10-15% slower than the single-chunk body would be at short depths (the
looped body's extra registers cost the Q4_0 value loop a block per SM; a `__launch_bounds__(THREADS, 4)` cap
spilled and made every format slower, 44.0 / 44.0 / 47.1 us at 2,051 in that build), about 0.15 ms of a token
at 8K depth, which the A2 floor cannot see; at long depths it is ahead of the unbounded grid (465 vs 504 us at
32,768 in the 24/2 trial that measured the looped kernel on a sparse shape).
At 262,144 cells, 16 heads, one row is 2.1 ms INT8 / 2.4 ms fp16 / 2.6 ms Q4_0 on the 1080 Ti: 21-26 ms of a
token for the ten attention layers at the full context (the fp16 pool streams at 228 GB/s of the card's 484;
Q4_0 is bound by the nibble decode in the value loop at 58 GB/s over a quarter of the bytes). At 8K depth the ten
layers are 1.2-1.4 ms. The verify window multiplies the per-row figure by its rows (8), so the window's attention
at 256K is about 17-21 ms on this card; A2's 10 tok/s at 32K depth leaves 100 ms per token, of which the
attention is 3.3-3.8 ms.
## 5. Commands
4090 (`/models/work/qwen36-step3-attn`, `build-step3-attn.sh` = the configure of `step3-common.md` with
`-DCMAKE_CUDA_ARCHITECTURES=89`, 162 s for the full tree):
export STRATA_GGUF_PY=/models/work/qwen36-step3-attn/third_party/llama.cpp/gguf-py
cd build && ctest --output-on-failure -R "qwen36_attn_fixtures|qsa_dense_parity|qsa_parity|qsa_prompt_attn_parity|kv_hybrid_parity|kv_stream_parity|qsa_topk"
./qsa_dense_parity --fixtures qwen36_attn
for kv in fp16 int8 q4_0; do ./qsa_attn_bench --heads 24,2 --kv $kv --cells 2051,8192,32768 --reps 200; done
for kv in fp16 int8 q4_0; do ./qsa_attn_bench --heads 16,2 --kv $kv --cells 2051,8192,32768,131072,262144 --reps 100; done
# the "before" column: the same bench built in a copy of the tree with 8b7525e's four attention files
/models/work/qwen36-step3-attn-base/build/qsa_attn_bench --heads 24,2 --kv fp16 --cells 2051,8192,32768 --reps 200
1080 Ti (`/home/rk/qwen36-step3-attn`, `-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, under
`/home/rk/VM-BUSY`): the same, by `/home/rk/pascal-run-attn.sh` (logs in `/home/rk/logs/qwen36-step3-attn-*.log`).
## 6. Not done, surprises, and where the study was off
- `generate.cpp` is not edited (the step-2 branch owns it): the `--kv-resident` refusal for a dense model is a
predicate (`qsa_kv_streaming_applies`) plus the backstop in `qsa_state_init`; the integrator adds the one call.
- `prefill.cpp` is not edited (the prefill agent's): its three sites take `qsa_selection_cap`, a null `sel_ids`
for the dense model, and `attn_scratch` at the new bound (section 1).
- The Volta (`launch70`, m8n8k4) and Turing prompt kernels are templated on G but no such card was on hand; the
4090 runs `launch_i8` / `launch<>`, Pascal runs none of them. Flash-Next's G = 12 on those paths is unchanged
code apart from the template parameter.
- No test drives `Verifier` (the verify window) on a `qwen35moe` geometry yet; its attention step is checked by inspection and by the builder test above. That is step 4's streaming-runner test (the window against the oracle's `l_out-N` per position).
- `layer_verify_compatible` still demands the native QSA indexer flag for the verify window; it is a global
(on by default) and not a geometry question, so it is left for the block agent's verify rewrite.
- Pascal's looped kernel is 10-15% slower than the single-chunk one on the Q4_0 pool at short depths (section 4);
the single-chunk body is kept for capacities under 8,192 so Flash-Next's path is untouched, and the dense model
pays it only below about 8K of depth, where the attention is a small part of the token.
- The study's 3.3 item 5 sizes the scratch "(cap/64) x n_head x 258 + 64 ... 64.5 MiB per query row": right.
Its proposed fixes were "a larger chunk per block, or an online-softmax merge that does not keep a partial per
64-cell chunk": the kernel does the second inside the block (the running rescale) while keeping the 64-cell
sub-chunk as the unit of work, so the short-context grid and arithmetic are untouched. The bound came out at
2.02 MiB, not the 2 MiB-per-row-at-128-chunks guess rounded either way: 528,448 floats.
- Item 4 says the drafter's ring passes "pooled_rows = 2"; what makes the dense state small is `idx_dim = 0`
(the tail and the dead key are sized by it too), the 2 rows alone would still have carved `3 x 128 x 4 + 128 x 4
+ 2 x 128 x 4` bytes. Both are in place.
- Nothing in the study mentions `qsa.cu`'s geometry guard (`validate`: `idx_dim <= 0 || idx_n_head <= 0` is
"geometry is not set up", and `n_rot > idx_dim` is refused): every KV append would have exited on the dense
shape. The guard now distinguishes a dense shape (all three indexer widths 0) from a half-set-up one.
- The oracle's negative controls reproduce on the head_dim-256 fixtures at the same order (gate 1.0, adjacent
RoPE 0.17-0.20, GQA map 0.69-0.72); the oracle's own table was on its head_dim-32 fixture.
-202
View File
@@ -1,202 +0,0 @@
# Qwen3.6 port, Phase 2 step 3: the block without hyper-connections
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step3-block`, from `qwen36-step2` at 8b7525e).
The design is `docs/QWEN36-35B-A3B.md` section 3.5 and section 6 (step 3, fourth bullet); the plan is
`docs/PLAN-qwen36-35b-a3b.md` section 5 step 3. Every item says what was decided, where it lives, how it is
checked, and the numbers from both cards.
## 1. What changed, in one paragraph
`ModelGeometry::hc == 1` (set by the `qwen35moe` architecture string in step 2) now selects a second block path:
llama.cpp's plain pre-norm residual block, in the single-token functions (`block_layer_pre`, `block_layer_post`,
`lm_head_mix`) and in the verify window (`Verifier::record_window`'s `pre`, `post` and head), through two row-count
helpers that the single-token path calls with one row and the window with its T rows. The hyper-connection kernels
are never entered for this model: the GR read on one stream is not a plain norm (its bottleneck gates the normed
stream with a sigmoid and its norm weight is stored as `1 + w`), which the harness shows as a negative case. The
Flash-Next path (`hc = 4`) is untouched: every `hc == 1` test is a branch in front of the existing code, no GR
call site moved, and the no-geometry `layer_verify_compatible` keeps its Flash-Next meaning.
x = rms_norm(R) * attn_norm -> mixer (GDN | attention) -> R += out
x = rms_norm(R) * post_attention_norm -> MoE (routed top-k, normalised, + shared expert) -> R += out
head: rms_norm(R) * output_norm -> output.weight
## 2. Decisions
| Decision | Where | Why |
| --- | --- | --- |
| Two helpers, `plain_norm_rows(R, w, mixed, n_embd, eps, n_tok, stream)` and `plain_residual_rows(R, block_out, n_embd, n_tok, stream)`, take a ROW COUNT | `include/strata/core/layer.hpp` ("the plain block"), `src/core/layer.cpp` | the single-token path (1 row) and the verify window (T rows) call the same kernels, so the window's row arithmetic equals the single-token path by construction; the harness asserts it bitwise |
| The norm is `native_qsa_rms_norm_weighted` (one block per row, fixed reduction order, `rsqrtf`, `(scale * x) * gamma`); the add is `add_inplace` | `layer.cpp` | the engine's pinned-arithmetic norm kernel, already used on q/k and in the drafter; ggml's `rms_norm` then `mul` in that order |
| No pending write at hc = 1: `R += out` is applied where the reference adds it (stage 2 and `post`), never folded into the next read | `layer.cpp` (`plain_block_pre` / `plain_block_post`), `verify.cpp` | the fold exists to fuse the GR write into the GR read; with no GR there is nothing to fuse, and an in-place add keeps `R` materialised for the control vector, the hand-off and the head |
| The stages and the `half` / `stage_prefix` selection are the GR path's (0 read, 1 mixer, 2 write, 3 read, 4 route) | `plain_block_pre` | `session_replay_stages`, the per-stage timing and the measurement splits apply unchanged; the harness drives stage 0 and half 2 separately |
| The norm weights are read as `const float*` after a form check (F32, `n_embd` elements) | `plain_norm_weight` in `layer.cpp`, `plain_w` in `verify.cpp`, `lm_head_mix` | Qwen3.6's norms are F32 in the file and the pack keeps them F32; a BF16 row read as f32 walks 2x the tensor inside the arena and yields a finite wrong norm (the `layout.cpp` failure) |
| `check_one` skips the `hc_*` rows at hc = 1 and requires `attn_norm` / `post_attention_norm` (F32, `n_embd`) instead; at hc > 1 the two plain names are skipped | `src/core/layout.cpp` | row 22 of the inventory; the indexer rows are the attention branch's |
| `layer_verify_compatible(const ModelGeometry&, std::string&)`: at hc = 1 the fused GR read is not required; without an indexer the block selection and the native indexer are not required | `layer.cpp`, `layer.hpp` | the window's compatibility check named kernels this model has no use for; the no-argument form stays Flash-Next's |
| `verify_geometry_supported(g, k, why)` replaces the window's `ss.k == 10` refusal: `k == g.n_expert_used` (8 from the file), the fused GR shape only at hc > 1, state 128 / conv 4 | `include/strata/core/verify.hpp`, `verify.cpp` | row 142; a free function so the negative case (top-10 on an 8-expert file) is a unit test and the message names both numbers |
| The window's head at hc = 1: `output_norm` over the T rows in one launch when the native head is loaded; the canonical head goes through `lm_head`, which branches the same way | `verify.cpp` (`record_window`, the head block) | the per-row arithmetic is the single-token `lm_head_mix`'s |
| A PLE run with hc = 1 is refused (`block_layer_pre`, `record_window`) | `layer.cpp`, `verify.cpp` | the model has no PLE (`has_ple = false`); a wired one would be a different model |
| `session_zero`'s first token needs no change | `src/core/session.cpp:141-148` | the loop is over `g.hc` (row 26): one copy at hc = 1 |
| `broadcast_streams` / `add_streams_broadcast` need no change | `src/kernels/cuda/verify_kernels.cu:256-291` | runtime `hc` (row 140): the identity copy at hc = 1 |
## 3. The harness: `tests/cuda/qwen36_block_test.cpp`
Maya's layer composition shape on the synthetic fixture (`tools/qwen36_synth_gguf.py`: hidden 64, layers 0-2 GDN,
layer 3 attention, 8 experts top-2, F32 everywhere) against the oracle's dumps of 8 tokens
(`cmake/qwen36_block_fixtures.cmake` runs `ref/qwen36.py --dump`; the fixture test `qwen36_block_fixtures` depends on
step 2's `qwen36_synth_fixtures`). CTest: `qwen36_block_test` (exit 77: no CUDA device or no numpy).
**Through the engine's own functions.** The test writes a pack (index.txt + dense.bin) holding, per layer, the two
norms (F32, index kind 2), the router `ffn_gate_inp` (BF16, kind 4, the engine's contract) and the shared expert's
scalar gate, plus `output_norm`; `WeightTable::load` reads it like any pack. Then, per layer and token, with the
mixer's output and the experts' outputs TEACHER-FORCED from the dumps:
| seam | engine call | tolerance (relative L2) |
| --- | --- | --- |
| `attn_norm-N` | `block_layer_pre(..., stage_prefix = 1)` on `R = l_out-(N-1)` (`model.input_embed` at N = 0) | 1e-6 |
| `attn_residual-N` | `plain_residual_rows` with `block_out = linear_attn_out-N` (GDN) or `attn_output-N` (attention) | 1e-6 |
| `attn_post_norm-N` | `block_layer_pre(..., half = 2)` on `R = attn_residual-N` (shared expert off: its weights are not in the pack) | 1e-6 |
| `ffn_moe_topk-N`, `ffn_moe_weights_norm-N` | the same call's router (`moe_route`: BF16 weight, F32 activations, `router_top10` at 8 / 2) | picks identical; weights 1e-2 reported |
| `ffn_out-N`, `l_out-N` | `block_layer_post` with `parts = ffn_moe_down-N`, `weights = ffn_moe_weights_norm-N`, `shared = ffn_shexp_gated-N` | 1e-6 |
| `result_norm` | `lm_head_mix` on `R = l_out-3[last]` | 1e-6 |
| `result_output` | the engine's `result_norm` through a host F32 projection of `output.weight` | 1e-5 |
**The window.** `plain_norm_rows` and `plain_residual_rows` over the 8 rows against the one-row calls per row
(bitwise, `memcmp`), `native_moe_combine_multi` against `native_moe_combine` per row (bitwise), and the 8-token
sequence carried through the four layers from the embeddings (`R` is never reloaded from the dumps) against
`attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `ffn_out-N`, `l_out-N` at every position, then `h_nextn`
(every row) and `result_norm` (row 7), all at 1e-6.
**Negative cases** (each must differ from the oracle by more than 5 % relative L1): the GR read at hc = 1 with
identity bottleneck weights (`GrShapes{64, 1, 64}`, `w_down = w_up = I`, `w_norm = attn_norm`) against
`attn_norm-0`; the post-attention norm skipped (`attn_residual-0` as the MoE input) and unweighted; top-10 on the
8-expert file refused by `verify_geometry_supported` with both numbers in the message; a layer whose `attn_norm`
is not in the pack refused by name; `layer_verify_compatible` at hc = 1 passing without the fused GR read while
the Flash-Next geometry still demands it.
**The mixers are reported, not asserted.** The fixture's projections are F32 and the engine has no F32 projection
kernel (the mixers take quantized planes or native GGUF types), so `block_layer_pre(..., stage_prefix = 2)` is
attempted and its own error printed (`blk.N.attn_qkv.weight is missing`; the attention layer's RoPE table of 0 rows).
The mixer seams (`conv_output_silu-N`, `new_state-N`, `final_output-N`, `linear_attn_out-N`; `kq_soft_max-3`,
`kqv-3`, `attn_gated-3`, `attn_output-3`) wait on the GDN and attention branches and on step 4's pack, which is
where the engine first runs a Qwen3.6 mixer end to end.
**Why 1e-6 and not the policy's 5e-8.** `oracle-crosscheck.md`'s norm figure is numpy F32 against numpy F32 on a
forced input; the CUDA norm uses `rsqrtf` (2 ulp, 2.4e-7) under `--use_fast_math`, so one CUDA ulp is above that
figure. The measured numbers are below.
## 4. Build and test commands
On VM 221 (the 4090, sm_89; the working copy is synced with the worktree's empty `third_party/llama.cpp` excluded
and the pinned submodule copied from the step-2 tree):
rsync -a --delete --exclude .git --exclude '/build/' --exclude '/build-mac/' --exclude '/logs/' \
--exclude '/third_party/llama.cpp/' ~/Code/UnbiasedStrata-step3-block/ rk@192.168.50.151:/models/work/qwen36-step3-block/
/models/work/build-step3-block.sh configure # the common file's configure line, logged
/models/work/build-step3-block.sh target qwen36_block_test
/models/work/build-step3-block.sh ctest 'qwen36'
/models/work/build-step3-block.sh all # everything else still builds (the gate binary links the engine)
On VM 211 (the 1080 Ti, sm_61) under the `/home/rk/VM-BUSY` lock, the same with `-DSTRATA_EXPERIMENTAL_SM60=ON
-DCMAKE_CUDA_ARCHITECTURES=61` and the working copy in `/home/rk/qwen36-step3-block/`.
## 5. Results
### VM 221, the RTX 4090 (sm_89), 2026-10-11
`./build/qwen36_block_test build/qwen36_synth build/qwen36_block/o8` (the fixtures written by hand, below), all 30
checks pass:
| seam (single-token path through the engine) | measured, worst over 4 layers x 8 tokens | tolerance |
| --- | ---: | ---: |
| `attn_norm-N` (`block_layer_pre` stage 0) | 1.13e-7 | 1e-6 |
| `attn_residual-N` | 0.0 | 1e-6 |
| `attn_post_norm-N` (`block_layer_pre` half 2) | 1.23e-7 | 1e-6 |
| `ffn_moe_topk-N` (the BF16 router) | 0 of 64 slots differ | identical |
| `ffn_moe_weights_norm-N` (the BF16 router) | 9.82e-3 | 1e-2, reported |
| `ffn_out-N` (`block_layer_post`) | 7.02e-8 | 1e-6 |
| `l_out-N` (`block_layer_post`) | 4.82e-8 | 1e-6 |
| `result_norm` (`lm_head_mix`) | 0.0 | 1e-6 |
| `result_output` (host projection of the engine's `result_norm`) | 1.63e-7 | 1e-5 |
| the window (8 rows) | measured | tolerance |
| --- | ---: | ---: |
| `plain_norm_rows`, `plain_residual_rows`, `native_moe_combine_multi` against the one-row calls | bitwise | bitwise |
| `attn_norm-N` / `attn_residual-N` / `attn_post_norm-N` / `ffn_out-N` | 6.98e-8 / 2.61e-8 / 7.78e-8 / 2.52e-8 | 1e-6 |
| `l_out-N` per position, `R` carried from the embeddings (layers 0..3) | 1.99e-8 / 2.22e-8 / 2.65e-8 / 2.81e-8 | 1e-6 |
| `h_nextn` (all rows) / `result_norm` (row 7) | 4.75e-8 / 3.25e-8 | 1e-6 |
| negative case | relative L1 against the oracle | required |
| --- | ---: | ---: |
| the GR read at hc = 1, identity bottleneck, against `attn_norm-0` | 0.423 | > 0.05 |
| the post-attention norm skipped | 0.276 | > 0.05 |
| the post-attention norm without its weight | 0.180 | > 0.05 |
| top-10 on the 8-expert file | refused: "the session routes top-10 but the file routes top-2 of 8 experts" | refused by name |
| the fixture's GDN state 16 | refused: "the T-token GDN kernels are built for state 128 and conv 4" | refused by name |
| `blk.4.attn_norm.weight` absent | refused by name | refused by name |
The mixer seams, reported: layers 0-2 `blk.N.attn_qkv.weight is missing`, layer 3 `qsa_layer: position 0 is
outside the RoPE table (0 rows)` (no attention state is built for a mixer that cannot run on F32 weights).
The 9.8e-3 on the router's renormalised weights is the BF16 contract on an F32 weight (2^-9 per element over a
64-long dot product); the picks are identical on this fixture, whose logits are spread for that purpose. The
real file's flip rate is the router branch's measurement (study 3.4).
**Two things found on the way.** (1) `cmake/qwen36_synth_fixtures.cmake` (step 2's) fails on this cmake 3.28
under policy CMP0007 (`list(GET)` on `"toy.gguf;"` with its empty flag element), so `ctest -R qwen36` cannot
reach `qwen36_block_test` until the step-2 branch fixes it; the fixtures were written by hand
(`python3 -I tools/qwen36_synth_gguf.py build/qwen36_synth/toy.gguf`, then the block fixture script with `-P`)
and the test run directly. (2) `read_model_geometry` leaves `n_vocab` at the Flash-Next default (248,320) on the
synthetic file; the engine takes the vocabulary from `output.weight`'s `ne1` (verify.cpp, mtp.cpp), and so does
the test, but a reader of `ModelGeometry::n_vocab` should know it is not the file's.
### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY`
The same tree (`/home/rk/qwen36-step3-block/`, the submodule copied from the step-2 tree), configured with
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, `cmake --build build -j 8 --target qwen36_block_test`
(the engine library and the kernels compile for sm_61), the fixtures by hand as above, then
`./build/qwen36_block_test build/qwen36_synth build/qwen36_block/o8`: all 30 checks pass with **the same numbers as
the 4090 to the printed digit** (1.13e-7, 1.23e-7, 7.02e-8, 4.82e-8, 1.63e-7, 9.82e-3; the window's 1.99e-8 ..
2.81e-8; the negatives 0.423 / 0.276 / 0.180; the router's 64 picks identical). The kernels the plain block adds
to the path are a block-per-row reduction and an elementwise add: nothing Pascal lacks. The lock was held for
the sync, the build, the run and released (about 12 minutes).
## 6. The hunks, for the integrator (against 8b7525e)
| file | hunks (old -> new line ranges) | what |
| --- | --- | --- |
| `include/strata/core/layer.hpp` | 479,8 -> 479,35 | `layer_verify_compatible(g, why)`, the plain-block section, `plain_norm_rows`, `plain_residual_rows` |
| `src/core/layer.cpp` | 473,17 -> 473,22 | `layer_verify_compatible` with the geometry; the no-argument form calls it with the defaults |
| | 1087,6 -> 1092,20 | `lm_head_mix`: the `hc == 1` branch (`output_norm`) in front of the GR mix |
| | 1167,7 -> 1186,115 | the two helpers, `plain_norm_weight`, `plain_block_pre`, `plain_block_post`; `block_layer_pre` dispatches on `g.hc == 1` as its first statement |
| | 1316,7 -> 1443,9 | `block_layer_post` dispatches on `g.hc == 1` as its first statement |
| `src/core/layout.cpp` ([shared]) | 2,6 -> 2,7; 81,6 -> 82,9; 96,6 -> 100,10; 108,6 -> 116,10 | `<cstring>`; the `hc_*` 2-D rows skipped at hc = 1; the two plain norms in the 1-D table, skipped at hc > 1 |
| `include/strata/core/verify.hpp` | 42,6 -> 42,13 | `verify_geometry_supported` |
| `src/core/verify.cpp` | 125,6 -> 125,30 | `verify_geometry_supported` (after the first anonymous namespace) |
| | 329,13 -> 353,12 | `init`: the two refusals |
| | 557,7 -> 580,23 | `record_window`: the PLE refusal, `eps`, `plain_w` |
| | 622,7 -> 661,14; 631,8 -> 677,8 | `pre`: the `hc_*` lookups only at hc > 1, `pending` only at hc > 1 |
| | 693,9 -> 739,16 | `pre`: the first read (`attn_norm` or the GR read) |
| | 899,7 -> 952,15 | `pre`: the residual add and `post_attention_norm`, or the second GR read |
| | 998,7 -> 1059,7 | `fuse_head_gr` only at hc > 1 |
| | 1091,7 -> 1152,15 | `post`: the plain write, else the last-layer materialisation |
| | 1120,10 -> 1189,24 | the head: `output_hc_*` only at hc > 1; the plain head over the T rows |
| `CMakeLists.txt` | 490,6 -> 490,22 | `qwen36_block_test`, `qwen36_block_fixtures` |
| new | `tests/cuda/qwen36_block_test.cpp`, `cmake/qwen36_block_fixtures.cmake`, this file | |
The attention branch's regions (`qsa_layer` ~945-975 at the base, the window's attention step ~757-870, the state
carve) and the GDN branch's (the decode GDN kernels, their launch sites) are not touched: the plain block calls
`qsa_layer` / `gdn_layer` through their existing entry points, and the window's mixer steps are left as they are
between my two hunks at 739 and 952.
## 7. What waits on the sibling branches and step 4
- The mixer seams (section 3) and `block_layer_pre` stage 1 on this model: the GDN gate (sigmoid today, SiLU on the
GDN branch) and the dense attention (the indexer still runs in `qsa_layer`; the attention branch removes it).
The window's attention step still builds the indexer's selection and `max_blocks_` from `idx_block` and demands
the `indexer.*` tensors; that is the attention branch's hunk in `record_window` and in `layer_verify_compatible`'s
`has_indexer()` conditions are already in place for it.
- The real-file run of the window (the engine's first Qwen3.6 token) needs step 4's pack: the native projections,
the F32 norms kept F32 (`attn_norm`, `post_attention_norm`, `output_norm` as index kind 2), the router and the
shexp gate as BF16, and the `qwen35moe_not_yet` gate in `generate.cpp` lifted.
- `check_one`'s indexer rows (`indexer.q_proj`, `indexer.k_proj`, `indexer.*_norm`) are still required on attention
layers at hc = 1; the attention branch owns them.
-163
View File
@@ -1,163 +0,0 @@
# Qwen3.6 port, Phase 2 step 3, experts: the native GPU expert kernels' format coverage
Working notes (2026-10-11, branch `qwen36-step3-experts`, from `qwen36-step2` at 8b7525e). The gap: the study's
section 3.7 called the native pack path "otherwise runtime", but `native_expert_supported()` refused every layer of
both real files because the DOWN-projection list `STRATA_D_FMTS` (`src/kernels/cuda/iq_kernels.cu`) held only the
types Flash-Next's and the Coder's packs use (IQ4_NL, IQ4_XS, Q2_0, Q5_1, Q5_0, Q8_0). Qwen3.6's files put IQ3_XXS
(37 layers) and IQ4_XS (34, 38, 39) on `ffn_down_exps` in UD-IQ3_XXS, and Q5_K (37) and Q6_K (34, 38, 39) in
UD-Q4_K_XL, whose layer 39 gate/up is Q5_K (`tests/data/native_experts/qwen36-{iq3_xxs,q4_k_xl}.txt`, step2-notes.md
section 3). The engine's refusal at `generate.cpp:2100` named the pair; it still does for anything not below.
## 1. What changed, and why it was small
| Decision | Where | Why |
| --- | --- | --- |
| IQ3_XXS (18) and Q5_K (13) join `STRATA_D_FMTS` | `iq_kernels.cu`, the three `STRATA_*_FMTS` lists | `native_down_kernel<TD>` and `native_down_multi_kernel<TD>` were already generic in `Fmt<TD>` (one row per warp, `row_dot<TD>` lane-strided over the row's dot calls); the list was the only restriction. The 256-value block types need `n_ff % 256 == 0`, which `native_expert_supported` already demanded: Qwen3.6's 512 passes, Flash-Next's 640 is refused as before (`native_grouped_parity.cpp` had noted "IQ4_XS: n_ff % 256") |
| Q6_K (14): `vec_dot_q6_K_q8_1` and `dq_q6_k` transcribed from llama.cpp (`vecdotq.cuh`, `dequantize.cuh` at the pinned commit), `Fmt<14>` with `VDR_Q6_K = 1` (`ipb = QI6_K / 1 = 32`, `step = 1`), on all three lists, in `is_iq` and `iq_row_bytes` (210 B per block) | `iq_kernels.cu` (the K-quant section after Q5_K, the dequant section after `dq_q5_k`) | 16 int8 sub-scales per block, the value `(ql | qh << 4) - 32` by `__vsubss4`, no min term, `__dp4a` only: native on sm_61, nothing Pascal lacks. The HIP shim already defines `__vsubss4`. Q6_K takes the per-entry kernels (no `Split<14>`), as Q4_K / Q5_K do |
| `native_expert_supported` unchanged | | its block-divisibility rule was right; only the type tables were short |
| Q6_K in the MMQ prompt path under `STRATA_MMQ_KQUANTS` | `src/prefill/moe_mmq.cu`, the CMake instance list (`[shared]` commit 52b5dcd) | llama.cpp ships `mmq-instance-q6_k.cu`; the Q4_K_XL file's three Q6_K layers then take the int8 tiles rather than the fp16 GEMM over dequantized weights. The option defaults OFF: the step-5 build must turn it on for the Q4_K_XL file |
Not changed: `moe_fused_iq.cu` (the sm_80+ fused native prompt experts: gate/up IQ2_XXS..IQ4_XS, down Q2_0 / IQ4_NL
only; the new types need a load stage of their own and its geometry is the prefill agent's), the CPU native path
(`native_fmt` is ggml-generic and takes Q6_K through ggml-cpu's `vec_dot`; `kq256_supported` keeps its Q4_K / Q5_1 /
Q8_0 AVX-2 kernels, Q5_K and Q6_K rows go to ggml's), `generate.cpp`.
## 2. Interface other agents consume
- `bool strata::kernels::native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff)`: true for
every (gate/up, down) pair of both files at 2048 x 512: (22, 18), (22, 23), (12, 13), (12, 14), (13, 14). Gate/up
types: 16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 6, 8; down types: 20, 23, 42, 7, 6, 8, 18, 13, 14, the 256-value
ones only where `n_ff % 256 == 0`.
- `native_expert_grouped(...)`, `native_expert_layout(...)`, `native_expert_scratch_bytes(...)`,
`iq_dequant_f16 / _f32 / _gu_f16`, `iq_embed_rows`, `iq_mmvq`: signatures unchanged; type 14 accepted everywhere
`is_iq` gates.
- `strata::prefill::mmq::supported(14)`: true when the build has `STRATA_MMQ_KQUANTS=ON`, as for 12, 13, 7.
- `native_expert_parity [--geom HxFF] ...`: the geometry flag; `native_grouped_parity --bench-down`.
## 3. How it is checked
`src/kernels/native_expert_parity.cpp` (a CTest per pair): (a) the float reference is ggml's own `to_float` of the
blob (the dequantization `oracle-crosscheck.md` cross-checked bit for bit against `ref/load.py` on the real file)
times a double-precision SwiGLU expert on 3 random tokens; (b) the CPU path (ggml-cpu `vec_dot`, Q8_K activations);
(c) the GPU path (`native_expert_grouped`, q8_1 activations), once per kernel family (decode-once vs per-entry, bitwise);
(d) the GPU dequantizers against `to_float`; (e) the negative control. Tolerances (relative L1): GPU against (a)
2e-2, the Q8-activation bound of `oracle-crosscheck.md` "Tolerance policy" (the Q8 oracle's `ffn_moe_out` max 5.3e-3
with the 4x margin), 3e-2 only for a pair with a Q5_0 role (32-value blocks without a min: q4_K/q5_0 measures 2.7e-2
at 2560 x 640, the pre-existing pair the CMake note describes); CPU against (a) 3e-2 (ggml-cpu rounds the activations
to Q8_K, one scale per 256 values, against the GPU's q8_1 per 32: measured up to 2.2e-2); CPU against GPU 4e-2 (both
roundings, measured up to 2.4e-2). Qwen3.6's five pairs measure 9.7e-3 to 1.3e-2 on the GPU (section 4).
The negative control (e), per the brief and `upstream-tooling.md` section 3: the high byte of one block's fp16 scale
(its sign) flipped in down row 5 must move that row's GPU output by more than the gate and no other row by any bit
(row locality: a flipped byte in row r's block reaches only row r); the same in gate row 3 must move the output by
more than 1e-4 (one of n_ff SwiGLU terms). The gate is 1e-2 for a 256-value block of a 512-wide row (Qwen3.6's down
types) and scales with the block's share of the row for the others (`1e-2 x qk/256 x 512/n_ff`: 1e-3 for a 32-value
block at Flash-Next's 640, where one of 20 blocks moved the row by 8e-3 to 1.4e-2 on the 4090). The Q6_K scale sits
at the block's last two bytes (`ggml_type_size(Q6_K) - 2`), the others at byte 0.
`src/kernels/native_grouped_parity.cpp`: every gate/up format with every down format at 512 x 256 (96 pairs, the
grid-stride launches bitwise equal to v1's over 84 call shapes each), the five Qwen3.6 pairs at 2048 x 512, plus
`--bench-down`. `src/kernels/iq_multi_parity.cpp`: the IQ3_XXS down pair at 1024 x 512 (decode-once vs per-column,
bitwise). `tests/cuda/prefill_mmq_kquant_test.cpp`: Q5_K and Q6_K down products at 2048 x 512 through MMQ against a
double-precision product of ggml's dequantized weights (its screen: rel L2 < 0.04).
Real file: `native_expert_parity --geom 2048x512 <file> 0 34 39` takes expert 7 of `blk.{0,34,39}` straight from the
GGUF (the three tensor slices into one blob) through (a) to (e). Layers 0 and 39 are the brief's; 34 adds the third
pair of each file.
## 4. Results, RTX 4090 (VM 221, sm_89, CUDA 12.4, gcc-13, `-DSTRATA_MMQ_KQUANTS=ON`)
Build: `/models/work/build-step3-experts.sh configure` then `targets` (116 s for the five test targets).
cd /models/work/qwen36-step3-experts/build
ctest -R "native_expert_parity|native_grouped_parity|iq_multi_parity|prefill_mmq_kquant|^iq_parity"
./native_expert_parity --geom 2048x512 /models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf 0 34 39
./native_expert_parity --geom 2048x512 /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf 0 34 39
./native_grouped_parity --bench-down
ctest: 19 of 19 pass (15 `native_expert_parity_*` including the five `qwen36_*` pairs, `q6_K_q8_0` at 2560 x 640 and
the `refuses_q6_K_down_at_640` WILL_FAIL; `native_grouped_parity`, `iq_multi_parity`, `iq_parity`,
`prefill_mmq_kquant_test`).
Synthetic pairs at 2048 x 512 (relative L1 against the float reference; the negative control's down-row move, with
0 other rows touched in every case, and the gate-row move):
| pair | cpu | gpu | cpu-gpu | GPU dequant vs `to_float` | down row flipped | gate row flipped |
| --- | ---: | ---: | ---: | --- | ---: | ---: |
| iq2_s / iq3_xxs | 1.7e-2 | 9.7e-3 | 1.8e-2 | bit-exact | 1.8e-1 | 3.5e-4 |
| iq2_s / iq4_xs | 1.8e-2 | 1.2e-2 | 2.0e-2 | bit-exact | 5.8e-1 | 1.2e-3 |
| q4_K / q5_K | 1.7e-2 | 1.0e-2 | 1.9e-2 | bit-exact | 1.5 | 2.5e-3 |
| q4_K / q6_K | 2.2e-2 | 1.3e-2 | 2.4e-2 | bit-exact | 1.5e-1 | 1.3e-3 |
| q5_K / q6_K | 2.2e-2 | 1.2e-2 | 2.3e-2 | bit-exact | 1.8e-1 | 3.3e-3 |
(The table's first three rows are the real-file layers 0 / 34 / 39 of UD-IQ3_XXS and the q4_K / q5_K row is layer 0 of
UD-Q4_K_XL; the synthetic runs of the same pairs are within 1e-3 of them. The decode-once and per-entry kernels are
bitwise equal on every pair; the CPU path's width invariance holds.)
Real files, both: 0 failures. UD-IQ3_XXS layers 0 (iq2_s/iq3_xxs), 34 and 39 (iq2_s/iq4_xs): gpu 9.7e-3, 1.2e-2,
1.1e-2. UD-Q4_K_XL layers 0 (q4_K/q5_K), 34 and 39 (q4_K/q6_K): gpu 1.0e-2, 1.2e-2, 1.1e-2. Every layer's GPU
dequantization of all three matrices equals ggml's `to_float` bit for bit.
The down kernel alone (`--bench-down`: phase 2, 48 calls in a graph, each layer its own 32 experts streamed from
DRAM; medians of 40 launches), microseconds per expert at 2048 x 512:
| down type | MB / expert | 32 groups x 1 entry | 8 groups x 4 entries |
| --- | ---: | ---: | ---: |
| Q5_1 (the comparator) | 0.786 | 0.92 | 1.73 |
| Q8_0 | 1.114 | 1.23 | 2.55 |
| IQ4_XS | 0.557 | 0.98 | 1.97 |
| IQ3_XXS | 0.401 | 0.96 | 1.88 |
| Q5_K | 0.721 | 0.86 | 1.99 |
| Q6_K | 0.860 | 0.96 | 2.53 |
On this card the 32 x 1 row is bandwidth-bound for every type (25 to 36 MB per 29 to 39 us call, 0.85 to 0.92 TB/s),
so the new types cost what their bytes cost; the 8 x 4 row shows the per-entry kernels' cost (Q6_K, Q5_K: no
`Split<>`, the dot redone per entry) against the decode-once ones (IQ3_XXS, IQ4_XS). The 1080 Ti numbers (section 5)
set the step-5 budget.
## 5. Results, GTX 1080 Ti (VM 211, sm_61, CUDA 12.4, gcc-13)
`/home/rk/qwen36-step3-experts/run-vm211.sh` under the lock (2026-10-11, 20:02 UTC): configure with
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DSTRATA_MMQ_KQUANTS=ON` (5 s), the five test targets
(149 s at `-j 8`), then the same three commands as section 4 with `/home/rk/models/` for the files; logs in its
`logs/`. No guard was needed: the new kernels use `__dp4a`, `__vsubss4`, `__byte_perm` and fp16 conversions only.
- ctest: 20 of 20 pass (the 15 `native_expert_parity_*`, `native_grouped_parity`, `iq_multi_parity`, `iq_parity`
with its fixture, `prefill_mmq_kquant_test` through llama.cpp's dp4a MMQ tiles on cc 61).
- Real files, both 0 failures, the same numbers as the 4090 to the printed digits (the kernels are integer dp4a
chains with one float expression per block; the q8_1 rounding is the same): UD-IQ3_XXS layers 0 / 34 / 39 gpu
9.7e-3 / 1.2e-2 / 1.1e-2, UD-Q4_K_XL layers 0 / 34 / 39 (q4_K/q5_K, q4_K/q6_K, q5_K/q6_K) 1.1e-2 / 1.2e-2 /
1.2e-2; GPU dequantization bit-exact for every matrix; the negative control's down-row move 1.8e-1 to 1.6 with no
other row touched, the gate-row move 3.5e-4 to 3.4e-3.
- `native_grouped_parity`: all 96 pairs at 512 x 256 and the seven model shapes bitwise equal to v1.
The down kernel alone per expert at 2048 x 512 (`--bench-down`, SM 1873 MHz, memory 5508 MHz, 46 C), the step-5
budget:
| down type | MB / expert | 32 groups x 1 entry | 8 groups x 4 entries (per group) |
| --- | ---: | ---: | ---: |
| Q5_1 (the comparator) | 0.786 | 4.43 | 14.3 |
| Q8_0 | 1.114 | 7.58 | 25.3 |
| IQ4_XS | 0.557 | 6.58 | 12.1 |
| IQ3_XXS | 0.401 | 6.78 | 10.8 |
| Q5_K | 0.721 | 4.29 | 12.2 |
| Q6_K | 0.860 | 5.32 | 15.6 |
Against Q5_1 at one entry per expert: Q5_K 0.97x, Q6_K 1.20x, IQ3_XXS 1.53x, IQ4_XS 1.49x. Pascal is not
bandwidth-bound here (Q5_1: 25 MB per 142 us call, 178 GB/s of the card's 484): the i-quant down types pay their
grid lookups and sign unpacking per call, so IQ3_XXS costs 1.5x Q5_1's time for half its bytes, while the K-quants'
plain nibble chains run at Q5_1's speed. At four entries per expert the decode-once kernels (IQ3_XXS, IQ4_XS) amortise
and come out ahead of the per-entry Q5_K / Q6_K. For a window of 4 tokens x top-8 routed to 32 distinct experts the
down projection is 137 to 217 us per layer, 5.5 to 8.7 ms over 40 layers; the gate/up (twice the rows at the wider
n_embd) is the larger half and was not re-timed here (the Flash-Next numbers in `native_grouped_parity --bench` stand).
## 6. Surprises
- `prefill_mmq_kquant_test` had a latent race: its sentinel memset on the legacy default stream was not ordered
before the product on its non-blocking stream; the second product at 2048 x 512 read as entirely unwritten on the
4090 and passed under `CUDA_LAUNCH_BLOCKING=1`. Fixed in the test (`[shared]` commit); not an MMQ fault.
- The negative control's 1e-2 gate, stated for Qwen3.6's 256-value blocks, is above what a single 32-value block's
sign flip moves a 640-wide Flash-Next row (8e-3 to 1.4e-2): hence the block-share scaling.
- The study's 3.7 was right that the path is runtime per layer and that `native_experts.txt` carries the types; it
missed that the GPU kernels' *type lists* did not include the files' down types, which is why "otherwise runtime"
did not hold for either file.
-173
View File
@@ -1,173 +0,0 @@
# Qwen3.6 port, Phase 2 step 3, area `gdn`: the GDN output gate, the router and the shared expert
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step3-gdn`, from `qwen36-step2` at 8b7525e).
The design is `docs/QWEN36-35B-A3B.md` sections 3.2 and 3.4 and step 3's first and third bullets in section 6; the
plan is `docs/PLAN-qwen36-35b-a3b.md` section 5 step 3. Every item says what was decided, where it lives, and how
it is checked, with the numbers from both cards.
## 1. What changed
| Decision | Where | Why |
| --- | --- | --- |
| `kernels::GdnGate { Sigmoid, Silu }` names the GDN output gate; every decode output kernel takes it as a required argument | `include/strata/kernels/gdn.hpp` | the one numerical difference between the two models (study 3.2, inventory row 39): `rms_norm(o) * ssm_norm * act(z)`, sigmoid for Flash-Next and SiLU for Qwen3.6. A required parameter, not a default, so a call site rewritten later cannot silently keep sigmoid |
| `ModelGeometry::gdn_gate()` returns SiLU for `qwen35moe`, sigmoid for `qwen4exp` | `include/strata/core/layout.hpp` (`[shared]`) | from the architecture string, like `hc` and the indexer; no key says it. No global anywhere: one process can serve both models |
| The four kernels: `gdn_out_norm` (legacy, `gdn.cu`), `fused_gdn_step_norm` (the default native decode, `fused_gdn.cu`), `native_gdn_out_norm` (pinned unfused, `native_gdn_preprocess.cu`), `gdn_step_norm_multi` (the verify window, `verify_kernels.cu`) | `src/kernels/cuda/` | SiLU is ggml's `op_silu` form `z / (1 + exp(-z))`; the sigmoid expression is untouched, so Flash-Next's arithmetic is bitwise what it was. `verify_kernels.cu` was not in the brief's list of three, but native packs decode only through the verify window (inventory row 114), so the gate had to reach it; it stays bitwise the fused kernel (checked) |
| The seven call sites pass `g.gdn_gate()`: `layer.cpp` (3), `verify.cpp` (4) | `src/core/layer.cpp`, `src/core/verify.cpp` (`[shared]`, one commit, nothing else touched) | the smallest change the block agent's files needed |
| No decode-path literal assumed 16/48 | (none) | `grep` of `src/kernels/cuda`, `src/core`, `src/program`, `include` for 48 / 6144 / 10240 / VPK finds only `ModelGeometry`'s defaults (step 2 reads them from the file), the PLE post-ops (Flash-Next only) and comments (`session.hpp:34`, `layer.hpp:10-16`, `gdn.hpp:11`). The kernels' only rule is `h_v % h_k == 0`; `fused_gdn_conv_l2` wants `channels % 128 == 0` (8192 is), `native_gdn_*` wants counts up to 65,535 (8192 is), `fused_gdn_ab` wants `n_embd % 8 == 0` (2048 is). The VPK 2 shape is run through every kernel in `gdn_parity` (16/32) and `qwen36_seam_parity` (2/4) |
| The router and the shared expert: parameterisation and tests only | `src/kernels/router_top10_parity.cpp`, `src/kernels/shared_expert_parity.cpp` | generic already (study 3.1): `router_top10` takes `n_expert <= 512, k <= 32` at runtime; the native 512 x 10 router is guarded by `n_expert == 512 && k == 10` in `layer.cpp:370` and `verify.cpp:915`, so 256/8 takes the generic kernel. No literal of 10 or 512 in the decode router path needed changing; `verify.cpp`'s `HIP_GFX906` branch already carries a 256-expert window path |
| The fixture tool grows `--gdn K,V,S`, `--experts E,K`, `--shexp-ff N`, `--quant-shexp q8_0`, `--bf16-exact` | `tools/qwen36_synth_gguf.py` (`[shared]`) | the CUDA GDN kernels are pinned to state 128 and the toy fixture has 16; the default fixture is byte-identical to before |
## 2. The harnesses
### `gdn_parity` (`src/kernels/gdn_parity.cpp`, `ctest -R gdn_parity`)
Both geometries, 16/48 (VPK 3, sigmoid) and 16/32 (VPK 2, SiLU), through all four implementations; the existing
four traps (modulo versus interleaved pairing, decay order, conv direction, l2 epsilon) kept; the fifth trap is the
gate, and it is run THROUGH the kernels: each kernel with the other model's gate must differ from the reference by
more than 5%. The verify kernel is held bitwise to the fused one on the verify, commit and split-commit paths.
Note for a later reader: the first version of this rewrite reported the native and fused kernels 7.5x off at the
32-head geometry and exact at 48. It was the harness: fixtures reset with pageable `cudaMemcpy` on a non-blocking
stream race the DMA. The stream is blocking now, and the comment at its creation says why.
### `qwen36_seam_parity` (`src/kernels/qwen36_seam_parity.cpp`, `cmake/qwen36_oracle_dumps.cmake`)
`ctest -R 'qwen36_oracle_dumps|qwen36_seam_parity'`. The fixture `k.gguf`: hidden 64, GDN 2 k-heads / 4 v-heads of
128 (VPK 2), conv 4, 256 experts top-8 of 32, shared expert 512 in Q8_0, the BF16-read weights BF16-exact; the oracle
run twice on the 11-token "hello world" sequence (F32, and `--act-quant q8`). The engine's kernels then hold, by
llama.cpp's `cb()` names, token by token with the state carried:
| seam | through | tolerance | basis |
| --- | --- | --- | --- |
| `conv_output_silu-0`, `q_conv_predelta-0`, `k_conv_predelta-0` | legacy, native, fused (`fused_gdn_conv_l2`), verify window (`gdn_conv_l2_multi`) | 1e-6 | one 4-tap F32 dot per channel |
| `gate-0`, `beta_sigmoid-0` | fused (`fused_gdn_ab`), verify window (`gdn_ab_multi`) | 1e-6 | a 64-term dot against a BF16-exact weight |
| `final_output-0` (every token) | all four | 8e-5 | oracle-crosscheck.md's `gdn_out` class |
| `new_state-0` (after the 11th token; the verify window after two commits of 8 + 3) | all four | 2e-5 | the recurrence in F32 both sides |
| `ffn_moe_topk-0` | `router_top10` at 256/8 from the oracle's `ffn_moe_logits-0` | identical | exact top-k on the F32 fixture only |
| `ffn_moe_weights_norm-0` | same | 1e-5 | |
| `ffn_shexp_gated-0` | `shared_expert`, native Q8_0 projections, the 1-D BF16 scalar gate | 1e-5 against the Q8 oracle | the engine rounds activations to Q8_1 as ggml does; the F32 oracle is 1.2e-2 away, which is the rounding itself and is printed, not gated |
| `shared_expert_multi` | 8 + 3 tokens | bitwise the per-token call | verify.cpp's contract |
Negative cases through the kernels: the sigmoid gate at `final_output-0` (the oracle's control says 1.07), the
un-normalised router weights at `ffn_moe_weights_norm-0`, the shared gate skipped at `ffn_shexp_gated-0`.
### `router_top10_parity` and `shared_expert_parity`
The router's five fixtures at both 512/10 and 256/8 (random, all-equal, a 12-way tie wider than k, a tie of exactly
k scattered through the range, a dominant expert) and the clamp proved unreachable at both (8/256 is 512x the
2^-14 clamp). The shared expert gains Qwen3.6's shape, 2048 x 512 with Q8_0 projections through `native_mmvq` and
Q8_1 activations and the native BF16 scalar gate, against a host reference written from the block layouts; the
silu-on-up reading and the skipped gate as negatives; `shared_expert_multi` bitwise the per-token call; and the
output moved by rounding the F32 gate weight to BF16 reported (2.5e-4 on a random gate), not asserted.
## 3. The measured-not-asserted parity: the BF16 router (study 3.4)
`tools/qwen36_router_bf16_flips.py REAL.gguf DUMP` on the oracle's `--act-quant q8` dump of the first 8 tokens of
`"Hello, world! How are you?"` (ids 9419, 11, 1814, 0, 2500, 513, 488, 30 by `llama-tokenize` on the IQ3_XXS file),
VM 221, 2026-10-11 (`/models/work/logs/qwen36-step3-gdn-flips.log`):
| contract | top-8 slots differing (of 320) | experts in one set and not the other | tokens affected | rate |
| --- | ---: | ---: | ---: | ---: |
| F32 x F32 (llama.cpp, the oracle) | 0 | 0 | 0 | 0 |
| F32 x BF16(W) (the engine's native MMVF, `bf16_gemv_fp32_mmvf`) | **0** | **0** | **0** | **0** |
| BF16(x) x BF16(W) (the legacy `bf16_gemv`, both rounded) | 34 | 6 | 6 | 0.23% (layers 4, 9, 12, 31, 32, 37; one slot each) |
**Why the native contract flips nothing: the F32 routers are already BF16.** A census of both shipped files
(IQ3_XXS and Q4_K_XL): every element of `ffn_gate_inp`, `ffn_gate_inp_shexp`, `ssm_alpha`, `ssm_beta` and
`ssm_conv1d` has its low 16 bits zero (20,971,520 of 20,971,520 router values per file); the checkpoint is BF16 and
the converter stored these as F32. So `BF16(W) == W`, the engine's BF16 reading is lossless, and the pack's own rule
("round exactly when the low 16 bits are zero", `upstream-tooling.md` section 4) already covers all four tensors
`moe_shared`, `fused_gdn_ab` and the router read as BF16: **`--compat-bf16` is not needed for Qwen3.6**. The only
rounding left is the activation's, in the legacy both-operands contract, which `native_bf16_projections` (step 2's
default for native packs) does not use. `attn_norm` is not BF16-exact (17%) and is read as F32, which is fine.
The study's "the router's flip rate is measured on the real file" (3.4, risk 6) stands, with the answer zero.
## 4. Results
### VM 221, the RTX 4090 (sm_89), 2026-10-11
rsync -rlpgoD --checksum --delete --exclude .git --exclude '/build/' --exclude '/build-mac/' --exclude '/logs/' \
--exclude '/third_party/llama.cpp/' ~/Code/UnbiasedStrata-step3-gdn/ rk@192.168.50.151:/models/work/qwen36-step3-gdn/
/models/work/build-step3-gdn.sh configure && /models/work/build-step3-gdn.sh all # 178 s clean, rc 0
(cd build && ctest --output-on-failure -R 'qwen36_oracle_dumps|qwen36_seam_parity|gdn_parity|router_top10_parity|shared_expert_parity')
(`rsync -a` preserves the Mac's mtimes, and an object built seconds after an edit then looks newer than the edit:
the first full build linked against a stale `verify.cpp.o`. `-rlpgoD --checksum` is `-a` without `-t`.)
5 of 5 pass. The numbers (relative L1 unless stated):
| harness | check | measured | tolerance |
| --- | --- | ---: | ---: |
| `gdn_parity` 16/48 | legacy / native / fused state vs reference | 4.0e-8 / 6.0e-8 / 6.0e-8 | 1e-5 |
| | legacy / native / fused y (sigmoid) | 2.3e-7 / 1.4e-7 / 1.7e-7 | 1e-5 |
| | the wrong gate (SiLU) through each kernel | 87% / 87% / 90% / 91% apart | > 5% |
| `gdn_parity` 16/32 | legacy / native / fused state vs reference | 4.4e-8 / 6.0e-8 / 6.0e-8 | 1e-5 |
| | legacy / native / fused y (SiLU) | 2.8e-7 / 1.4e-7 / 1.7e-7 | 1e-5 |
| | the wrong gate (sigmoid) through each kernel | 110% / 125% / 116% / 110% apart | > 5% |
| | verify kernel bitwise fused (y; commit; split commit) | yes / yes / yes | bitwise |
| | pairing, decay, conv layout, l2 eps traps | 128% / 83% / 128% / 1031% apart | > 5% |
| `qwen36_seam_parity` | `conv_output_silu-0`, worst path | 5.96e-8 | 1e-6 |
| | `q/k_conv_predelta-0` (fused, verify) | 9.4e-8 | 1e-6 |
| | `gate-0` / `beta_sigmoid-0` (fused_gdn_ab, gdn_ab_multi) | 2.3e-7 / 1.1e-7 | 1e-6 |
| | `final_output-0`, worst token, legacy / native / fused / verify | 2.28e-7 / 1.91e-7 / 2.15e-7 / 2.15e-7 | 8e-5 |
| | `new_state-0`, legacy / native / fused / verify (two commits) | 1.31e-7 / 1.49e-7 / 1.59e-7 / 1.59e-7 | 2e-5 |
| | sigmoid gate at `final_output-0` (fused; verify window) | 125.8% / 125.8% apart | > 5% |
| | `ffn_moe_topk-0` | 0 of 88 differ | identical |
| | `ffn_moe_weights_norm-0`; the un-normalised reading | 6.1e-8; 23.5% apart | 1e-5; > 5% |
| | `ffn_shexp_gated-0` vs the Q8 oracle; vs the F32 oracle | 3.5e-7; 1.2e-2 (reported) | 1e-5 |
| | the shared gate skipped; `shared_expert_multi` vs per-token | 51.5% apart; bitwise | > 5%; bitwise |
| `router_top10_parity` 512/10 and 256/8 | ids on 5 fixtures x 64 tokens; weights | exact; worst 1e-6-class | exact; 1e-5 |
| `shared_expert_parity` 2048 x 512 | native Q8_0 + BF16 gate vs reference | 9.6e-8 | 1e-4 |
| | silu-on-up; gate skipped; F32 vs BF16 gate weight | 83% / 272% apart; 2.5e-4 (reported) | > 5% |
### VM 211, the GTX 1080 Ti (sm_61), 2026-10-11
`/home/rk/qwen36-step3-gdn-run.sh` (kept on the VM), under the card lock for 5 minutes: the rsync above to
`/home/rk/qwen36-step3-gdn/`, `set -o noclobber; echo qwen36-step3-gdn > /home/rk/VM-BUSY` after checking
`pgrep -x llama-server` and `pgrep -f "[s]weep_ladder_1080ti.py"` are empty (the bracket keeps `pgrep -f` from
matching its own shell, which it did on every earlier poll), then
cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON \
-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DCMAKE_CUDA_HOST_COMPILER=g++-13 \
-DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13 # 4 s
cmake --build build -j 8 -- -k # 287 s, rc 0, everything
(cd build && ctest --output-on-failure -R 'qwen36_oracle_dumps|qwen36_seam_parity|gdn_parity|router_top10_parity|shared_expert_parity')
rm /home/rk/VM-BUSY # the script's EXIT trap
5 of 5 pass (`/home/rk/logs/qwen36-step3-gdn-1080ti.log`, the four binaries' printouts beside it). Every seam number
of `qwen36_seam_parity` is the same digits as on the 4090 (the kernels are F32 and the summation orders do not
depend on the card): `final_output-0` 2.28e-7 / 1.91e-7 / 2.15e-7 / 2.15e-7, `new_state-0` 1.31e-7 / 1.49e-7 /
1.59e-7 / 1.59e-7, `conv_output_silu-0` 5.96e-8 worst, `gate-0` 2.27e-7, `ffn_moe_topk-0` identical,
`ffn_moe_weights_norm-0` 6.1e-8, `ffn_shexp_gated-0` 3.5e-7 against the Q8 oracle, `shared_expert_multi` bitwise,
the three negatives 125.8% / 23.5% / 51.5%. `gdn_parity`: states 5.3e-8 to 6.0e-8, y 1.4e-7 to 2.8e-7, the verify
kernel bitwise the fused one on all three paths, the wrong gate 87% apart at 16/48 and 110% at 16/32 through every
kernel. `shared_expert_parity` at 2048 x 512: 9.6e-8; `router_top10_parity`: ids exact at both shapes, weights
worst 1.5e-7.
Nothing in the changed kernels is architecture-conditional: the SiLU is an `expf` and a divide in kernels that
already ran on sm_61 in step 2's build, so no new guard was needed; the pass on the card is the proof.
## 5. The interface other agents consume
namespace strata::kernels {
enum class GdnGate : int { Sigmoid = 0, Silu = 1 }; // strata/kernels/gdn.hpp
inline const char* gdn_gate_name(GdnGate g);
void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S,
float eps, GdnGate act, void* stream); // gdn.hpp (legacy)
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, GdnGate act,
float* y, int h_k, int h_v, void* stream); // fused_gdn.hpp
void native_gdn_out_norm(const float* output, const float* z, const float* gamma, float* destination,
int64_t heads, int64_t cols, float epsilon, GdnGate act, void* stream); // native_gdn_preprocess.hpp
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, GdnGate act, float* y, int h_k, int h_v,
int n_tok, const int32_t* n_keep, void* stream, int t_out_begin = 0); // verify_kernels.hpp
}
kernels::GdnGate strata::core::ModelGeometry::gdn_gate() const; // strata/core/layout.hpp
Everything else is unchanged: `GdnShapes{S, h_k, h_v}` at runtime, the state `(S, h_v, S)` with j fastest, the conv
history `[channel][3]`, `router_top10(logits, n_tokens, n_expert, k, ids, weights, stream)` at 256/8, `shared_expert`
and `shared_expert_multi` with `NativeSharedWeights` (type ids per `native_mmvq.hpp`) at `n_ff` 512. The prompt-path
GDN kernels (`src/prefill/kernels.cu:324, 612`) are the prefill agent's and still gate with sigmoid; they will want the
same `GdnGate` argument. `layer.hpp:16`'s comment still says "SIGMOID for qwen4exp; qwen3.5 used SiLU" (the block
agent's file; the code beneath it is right).
-63
View File
@@ -1,63 +0,0 @@
# Qwen3.6 port, Phase 2 step 3: the integration branch `qwen36-step3`
Branched from the step-2 head (0e40d4e) on 2026-10-11. Five areas were developed in parallel from 8b7525e, each on its
own branch with its own notes, and cherry-picked here in this order with no conflicts: block (`step3-block.md`, 5
commits), gdn (`step3-gdn.md`, 8), experts (`step3-experts.md`, 7), attn (`step3-attn.md`, 9), prefill
(`step3-prefill.md`, 12 of 17: its five cherry-picks of attn and gdn commits were dropped here because the originals
are present). One commit of the integrator's own, 7cfb7dc: `generate.cpp` calls `qsa_kv_streaming_applies` right after
the geometry is read (the attention agent could not edit that file).
## Both cards, the whole branch
Configure for both: `-DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=ON
-DSTRATA_MMQ_KQUANTS=ON` with gcc-13 as the host compiler; the 1080 Ti adds `-DSTRATA_EXPERIMENTAL_SM60=ON
-DCMAKE_CUDA_ARCHITECTURES=61`, the 4090 `-DCMAKE_CUDA_ARCHITECTURES=89`. `STRATA_MMQ_KQUANTS` is needed for the
Q4_K_XL file's prompt path (Q6_K down on layers 34, 38, 39) and defaults OFF; step 5 turns it on in the Makefile.
| Card | Build | ctest | Failures |
| --- | --- | --- | --- |
| RTX 4090 (VM 221, sm_89) | 0 errors, 420 s for every target | 89 of 92 pass | ple_parity (no Flash-Next shard on the host), platform_memory_test (mlock limit), expert_multi_test (no AVX-512) |
| GTX 1080 Ti (VM 211, sm_61) | 0 errors, 302 s | 87 of 92 pass, 2 skipped (the sm_80 fused prompt MoE tests) | the same three |
Every step-3 test (qwen36_block_test, qwen36_seam_parity, gdn_parity, router_top10_parity, shared_expert_parity,
qsa_dense_parity, the native_expert_parity pairs, prefill_mmq_kquant_test, gdn_rec_parity, prefill_qwen36_test) passes
on both cards; the per-seam numbers are in each area's notes and are identical on both cards to the printed digits.
## The review (`step3-review`, read-only, on the 41-commit range) and what it changed
1. HIGH, attn x block seam: `shapes_of` in verify.cpp and mtp.cpp left `idx_top_k = 2048` on a no-indexer geometry, a
"half set up" shape that `qsa.cu`'s validate refuses, so the verify window would have exited on the first Qwen3.6
attention layer. Not covered by any test (no test drives `Verifier` on qwen35moe; that is step 4's runner test).
Fix: one exported shape builder for all four sites and one dense predicate.
2. MEDIUM, Flash-Next: the MTP drafter's attention (cap = the 32,768 draft window) took the new bounded split-K kernel,
a different summation order; drafts are verified, so draft quality, not correctness. Fix: sparse-model shapes keep
the previous grid.
3. LOW: the prefill fixture failed instead of skipping without numpy (fixed, c4f599f); native_expert_parity's 3e-2
bound tightened to the policy's 2e-2 with separate CPU rows (77983af); `qsa_attn_bench` registered as a test
(removed from the suite).
All fixed on the attention branch and cherry-picked here (one builder `strata::core::qsa_shapes(g)` in
`include/strata/core/qsa_shapes.hpp` used by layer, verify, mtp, session and prefill, the last by delegation from
prefill's `shapes_of`; `qsa_dense()` and the kernels' guard test the same three-zero predicate; the split-K bound applies
to dense shapes only, so Flash-Next's drafter keeps its 512-block grid and 12.09 MiB scratch, A/B equal within 1 us on
the 1080 Ti). After the fixes: 4090 88 of 91 (the same three host failures); 1080 Ti incremental build 81 s, the 33
attention / prefill / expert / verify tests 33 of 33.
4. NOTE: the GDN head pairing is tiled (`h % 16`), as llama.cpp, the oracle and the engine all have it; the reviewer's
brief had said interleaved, which is the oracle's negative control.
Not checked end to end until step 4's pack and runner exist: the verify window on qwen35moe, the decode mixers through
`block_layer_pre` stage 1 on a real pack, `native_rope_apply` against the Qwen3.6 oracle, dense attention above 20,000
cells against a reference, the drafter on qwen35moe.
## Findings that feed step 4 and 5
- The real files' F32 routers, `ffn_gate_inp_shexp`, `ssm_alpha`, `ssm_beta` and `ssm_conv1d` are BF16-exact
(low 16 bits zero in every element of both files), so the engine's BF16 reading is lossless and `--compat-bf16` is
not needed; the measured top-8 flip rate on the real file is 0 of 320 slots (`step3-gdn.md`).
- The native expert kernels accept every layer of both files; on the 1080 Ti the down projection per expert is
Q5_K 4.3 us, Q6_K 5.3, IQ3_XXS 6.8, IQ4_XS 6.6 against Q5_1's 4.4 (`step3-experts.md`).
- Dense attention per query row at 262,144 cells: 1.0 ms on the 4090, 2.4 ms on the 1080 Ti (fp16 KV); the split-K
scratch is 2.02 MiB per row (`step3-attn.md`).
- `moe_fused_iq.cu` (sm_80+) still lacks the new down types; those layers take MMQ in the prompt path.
- VM hygiene: sync with `rsync -rlpgoD --checksum` (`-a` keeps Mac mtimes and can leave a stale object linked);
`pgrep -f "[s]weep_ladder_1080ti.py"` (the unbracketed pattern matches its own shell).
-217
View File
@@ -1,217 +0,0 @@
# Qwen3.6 port, Phase 2 step 3: the prompt path at Qwen3.6's geometry
Working notes of the prefill item of step 3 (2026-10-11, branch `qwen36-step3-prefill`, branched from `qwen36-step2` at
8b7525e). The design is `docs/QWEN36-35B-A3B.md` section 3.6 (the table of literal sites) and section 6, step 3, the
prefill bullet; the rules are `step3-common.md`. Every item says what was decided, where it lives, how it is checked,
and the numbers from both cards.
## 1. What changed, site by site
`src/prefill/*` is the whole scope. The study's table (3.6) had eight literal sites; what each became:
| Study's site | What it was | What it is now |
| --- | --- | --- |
| `prefill.cpp` constants `N, HC, D, LR, K, NE, C, ZV, HV` | file-wide `constexpr` (2560 / 4 / 10240 / 320 / 10 / 512 / 10240 / 6144 / 48) | a `Geom` struct built from the `ModelGeometry` (`Geom::of`): n_embd, hc, hc*n_embd, hc_lr, k, n_expert, n_ff (and 2 n_ff, the shared width), conv channels, value dim, value heads, key heads, heads, KV heads, head dim, `attn_q`'s width, n_head*256, n_head_kv*256, `indexer`, `silu`. Every count (`gdn_set_bytes`, `qsa_set_bytes`, `moe_bufs`, `moe_set_bytes`, `bytes_needed`) and every launch in `carve` and `run_impl` reads it. The old names stay as local aliases inside each function so the arithmetic reads as before |
| `Prefill::init`'s refusal (`n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10`) | one geometry | per architecture: `qwen4exp` keeps exactly that check; `qwen35moe` needs `hc == 1`; both need `ss.k == n_expert_used`, `k` in 1..32 and at most `n_expert`, a GDN geometry the kernels are built for (`gdn_geometry_supported`: 48/16/10240 or 32/16/8192, state 128, conv 4), head_dim 256, 2 KV heads, n_rot 64, n_embd a multiple of 256, n_ff of 64. Each refusal names what it saw |
| `Qf` as `T * 12288`, `q` / `attn` as `T * ZV`, `idx_raw`, `q_idx` | 24 heads x 512; the indexer's two buffers always | `T * G.qf` (n_head * 512), `T * G.av` (n_head * 256); the indexer's buffers, the selection scores and the ids rows only with an indexer (`G.indexer`). Dense attention carries no ids: a null is the identity selection (below) |
| MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | 2 n_ff and n_ff as 1280 / 640 | `G.ff2`, `G.ff`, `G.ffs`; `mmq_plan()` takes each layer's widths from the native layout (`fmt[l].n_embd`, `fmt[l].n_ff`; the canonical Q2_0 pack's 2560 / 640 otherwise), so the plan is per pack, not per build. The peer paths (`set_peer`, `bind_stage_helper`, the peer products in `run_impl`) use the same members; `PeerPrefill`'s event ring and host bounds are sized once from `NE_MAX = 512` |
| `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` (`:854-856, :1000-1026, :1375-1380`) | the hyper-connection's buffers and the GR read / write around every half | carved only at `hc > 1`. At `hc == 1` the half is `x = rms_norm(R, attn_norm) -> mixer -> R += out; x = rms_norm(R, post_attention_norm) -> MoE -> R += out` through two new kernels, `rms_norm_images` (the FP32 norm with its BF16 and FP16 images, gr_norm_kernel's arithmetic on one stream) and `residual_add`. The GR path is untouched (`gr_*` kernels, the F-2 fusion, `STRATA_GR_UNFUSED`); the embedding broadcast becomes a copy. `draft_kv` (the MTP drafter's K/V through this path) is Flash-Next's graph and returns false for `qwen35moe` (step 4 brings the nextn block) |
| GDN kernels on `HV`, `HK`, `C`, launched `<<<HV, ...>>>`; `VPK = 3` | file constants | templates on `<HV, HK, C>` (`gdn_gates_kernel<HV>`, the three conv kernels and the l2 norm on `<C>`, `gdn_rec_kernel<HV, HK, C, SILU>`, `gdn_rec_cols_kernel`, `gdn_rec_cols_pipe_kernel`, `gdn_rec_kh_kernel<HV, HK, C>` with `VPK = HV / HK` and a `static_assert(HV % HK == 0 && VPK <= RG)`, `gdn_out_norm_kernel<HV, SILU>`, `gdn_keyhead_ok<HV, HK, C>`), dispatched by `gdn_dispatch` from a `GdnGeom {hv, hk, c, silu}` at exactly the two geometries; any other stops the process (the kernels' convention) after `init` has refused it by name. The output gate is `gdn_gate<SILU>(z)`: `z * sigmoid(z)` for Qwen3.6, `sigmoid(z)` for Flash-Next, chosen from `g.arch` (`Geom::silu`) |
| `route_kernel<REG>` with `rank < 10`, `ids[t*10 + rank]`, `lane < 10` | top-10 baked | `k` a kernel parameter (the warp kernel at 512 and 256 experts, `router_top10` for any other count); `moe_combine` takes the width and `k`; the SwiGLU kernels take n_ff; `swiglu_pair` runs over `n * n_ff` |
| `split_q_kernel`, `gate_attn_kernel` over `T * 24 * 256` and `h * 512` | 24 heads | `n_head` a parameter (head_dim 256, `attn_q` as `[n_head, 2, 256]` per token in both models) |
| `moe_fused_iq.cu:59` `GU_ROWS_K 2560 / D_ROWS_K 640`; the `1280 / 2560` weight-row counts; `dm[row * 2560]`; `out + row * (10 * AB)` | constants | `NativeGeom` carries `n_embd` and `n_ff`; the kernel's stage count, weight-row blocks per tile, activation row stride, H block count and output stride come from them (loop bounds, not unrolled constants); `experts_native` refuses a width that does not tile the work item (n_embd a multiple of 256, 2 n_ff and n_embd multiples of the item's 64 WW rows). `moe_fused.cu` is NOT touched: it is the Strata Q2_0 blob's kernel and the blob format itself is the Flash-Next shape (gate/up codes `[1280][640 B]`, down `[2560][160 B]`); the canonical pack is refused for any other geometry since step 2, so no Qwen3.6 chunk reaches it (`fused_l` needs `!lay.native`). The study's "likewise" for that file does not apply |
| the layer loop at `:1724`, `RP = 48` at `:1303` | "check" | the loop runs `g.n_layers` (it always did); `RP = 48` is the peer-streaming ring's slot count (`STRATA_PF_PEER_RING`), not a head count: unchanged |
Also changed: `kv_append_kernel` keeps `t * 512 + kvh * 256 + d` and the grid `(T, 2, 8)`: 2 KV heads x 256 in both
models (init refuses anything else); `rope()` keeps its 64 rotated dims and the pairs `(p, p + 32)` (n_rot 64, the
IMRoPE sections and the 1e7 base are the same in both models; `rope_scaling()` is the process config). The
`on_seam` hook on `Prefill` (null by default, nothing else changes) is how the harness reads the layer loop by
llama.cpp's seam names and teacher-forces every layer's input. `STRATA_PREFILL_ALLOC_TRACE=1` names the allocation
that did not fit (it found the harness's own bug below).
### The attention step
The study (3.3, risk 3) has the prompt attention through `qsa_prompt_attn_batch` on sm_80+ and the batched decode
kernel below cc 70, both at `G = 12` with a split-K scratch that grows with the context. The attention branch
(`qwen36-step3-attn`) templated `G` at 2 / 8 / 12, made a null `ids` the identity selection and bounded the scratch
at 128 blocks per KV head; its three kernel commits are cherry-picked here (section 4). The prefill's dense path
is then: the shapes zero the three indexer widths together (`shapes_of`: that is the kernels' `qsa_dense` signal;
`qsa.cu`'s guard refuses a shape with only some of them zero), the capacity is `qsa_selection_cap` (every cell of
the primary state), no ids are carved or passed, `qsa_attn_group` is asked before any launch and its refusal is
`run`'s error string (a 16-head model asked for G = 12 is a message, not a mis-indexed run), the step records'
width is `n_kv` (`qsa_step_fill` under the dense shape). The indexer tensors are not required of a dense layer.
No kernel of the attention branch was rewritten here.
## 2. The harness
### 2.1 Fixtures (`tests/python/qwen36_prefill_fixture.py`)
The oracle's own fixture is 64 wide with heads of 16 and 32; the prompt kernels are built for the real widths
(the GDN templates at 128-wide heads, the attention kernels at head_dim 256, the fused experts at 256-wide tiles),
so the harness has its own: the synthetic model of `tools/qwen36_synth_gguf.py` (its weights, its 128-token
vocabulary) at the real per-layer geometry, few layers, few experts:
| Case | Layers | Geometry | Forms |
| --- | --- | --- | --- |
| `gdn3` | 3, all Gated DeltaNet (interval 4: no layer satisfies `(il + 1) % 4 == 0`) | n_embd 2048, GDN 16 / 32 heads of 128 (conv 8192), attention 16 / 2 of 256, n_rot 64, sections 11/11/10/0, base 1e7, 16 experts top-8 of 512, shared 512 | projections, experts, shared expert and head Q8_0 (what the engine serves natively); `ffn_gate_inp`, `ssm_alpha`, `ssm_beta`, `ffn_gate_inp_shexp` F32 rounded to BF16-exact values (the engine's forms, exact); norms, conv, dt bias, ssm_a, `token_embd` F32 |
| `full4` | 4: three DeltaNet, layer 3 full attention | the same | the same |
The router runs at half the toy's gain (`ffn_gate_inp * 0.5`): at the toy's spread the top-8 of 16 carry 99 % of
the softmax mass and the renormalisation rival moves `ffn_out` by 1.3 %, invisible to a 5 % gate; at this gain it
moves it by 5.7 %. For each case the script runs `ref/qwen36.py` on 40 tokens (the ASCII codes of
`"the quick brown fox jumps over the lazy "`) three ways: the faithful reading (`o`), `--act-quant q8` (`o_q8`), and
the rival readings `neg_gate` (`gdn_gate=sigmoid`), `neg_pair` (`head_pairing=interleaved`), `neg_norm`
(`router_norm=False`) and, on `full4`, `neg_attngate` (`attn_gate=False`). The oracle dequantizes Q8_0 with
gguf-py, bit-identical to ggml (oracle-crosscheck.md), so every difference the harness sees is the engine's
arithmetic. `gdn3` is a file `read_model_geometry` refuses by design (block_count must be a multiple of the
interval): the harness takes `full4`'s geometry with `gdn3`'s layer count, which is what the oracle ran it as.
4m55s on VM 221 for both cases (the oracle in numpy); 269 and 351 MB.
### 2.2 The test (`tests/cuda/prefill_qwen36_test.cpp`; CTest `prefill_qwen36_fixtures`, `prefill_qwen36_test`, `prefill_qwen36_attn_test`)
The fixture's tensors go into a `WeightTable` row by row (`WeightTable::set`, the one `[shared]` change: Q8_0 as
`native_data`, the BF16 set as `Bf16InF32`, the rest F32), the experts into an in-memory `ExpertSource` of
`[gate | up | down]` blobs (unpinned: the prompt path's stager copies them) under a `native_experts.txt` the test
writes, the session from `session_init` at 64 cells, the embedding rows through `embd_rows`. Then:
1. `Prefill::init` refusals: top-10 on the top-8 file ("top-10 routing over 16 experts (the file says top-8 ...)"),
and 32 value heads / 8 key heads (VPK 4; "no GDN kernels for 32 value heads / 8 key heads / 6144 conv channels
(built for 48/16/10240 and 32/16/8192 ...)"). Both must be refused with those words.
2. One chunk of 40 and chunks of 7 (the oracle's `base_c7` case), every layer's input teacher-forced at the `l_in`
seam to the oracle's `l_out` of the layer before (oracle-crosscheck.md, "Tolerance policy", item 2: per layer,
not accumulated), each seam held to the faithful dumps as the relative L1 of the sums over the chunks:
`attn_norm`, `linear_attn_out` / `attn_output`, `attn_post_norm`, `ffn_out`, `l_out`, and `ffn_moe_topk`.
3. The router's top-k: a rank swap is allowed only where the oracle's own softmax puts the two experts within
2e-3 of each other (the prompt path's router multiplies BF16-rounded activations, as the study notes under
`STRATA_PREFILL_BF16X2`; the decode path's is FP32), any other disagreement fails.
4. The negative controls: the engine, forced from the faithful dumps, against the rival readings' dumps at the seam
that makes each, more than 5 % apart.
5. For the record: the same seams against the Q8 oracle, and the accumulated error without forcing.
The gates (`gate_for`): `attn_norm` 1e-4 (FP32 norm), `attn_post_norm` 2e-3 (the mixer's error passes through
the norm of R + out), `linear_attn_out` / `attn_output` 1e-2 (FP16 GEMMs over FP16-dequantized Q8_0 weights, BF16
alpha / beta), `ffn_out` 2e-2 (the int8 MMQ products: q8_1 activations and H), `l_out` 1e-2. They are the measured
numbers below with a 4x to 10x margin; the negatives sit at 0.06 to 0.92.
### 2.3 The GDN kernels alone (`src/prefill/gdn_rec_parity.cu`)
Kept its bit-for-bit check of the two recurrence variants, now at both geometries; added a double-precision host
transcription of the recurrence (decay before the rank-1 update, v-head h with k-head h % HK, the gated RMS-normed
output) that the engine's own `gdn_recurrence` and `gdn_conv` launches are held to (through their `GdnGeom`), the
rival readings computed by the same reference (the other model's gate, the interleaved pairing h // VPK) required
to sit more than 5 % away, and the geometry refusals. Links `strata_prefill`.
### 2.4 The fused native experts (`tests/cuda/prefill_fused_iq_test.cpp`)
The reference part runs at both geometries (the widths are variables set per pass); the timing part keeps the pack
it was measured on. Exit 77 below sm_80 (the 1080 Ti: the prompt MoE takes MMQ or the FP16 path there, below).
## 3. Numbers
### 3.1 VM 221, RTX 4090 (sm_89), 2026-10-11
Build: `/models/work/build-step3-prefill.sh configure && ... all` (the common file's configure line at sm_89).
`./build/gdn_rec_parity`: 0 failures. Both geometries, T = 1 .. 4099: the two recurrence variants the same bits
(output, state, FP16 output). Engine vs reference (T = 1, 7, 33, 257): y16 1.76e-4 to 1.79e-4, state 4e-8 to
1.0e-7 relative L1 at both 48/16/10240 (sigmoid) and 32/16/8192 (SiLU). Rivals: the other gate 0.86 to 1.10 from
the right reading (the engine 0.87 to 1.10 from the rival), the interleaved pairing 1.24 to 1.33. `gdn_conv`: h
5.2e-8 to 5.4e-8, the history exact. Refused: 32/16/10240, 32/8/8192, 48/16/8192.
`./build/prefill_fused_iq_test --no-timing`: passed; every pair (IQ2_S / IQ2_XXS / IQ2_XS / IQ3_XXS / IQ3_S /
IQ4_XS gate/up over Q2_0 / IQ4_NL down) within 1.45e-2 to 1.49e-2 rel RMS of the FP32 reference at 2560 / 640
top-10 and 1.46e-2 to 1.49e-2 at 2048 / 512 top-8. `prefill_fused_moe_test`, `gemm_bf16_parity`: pass (the
Flash-Next geometry unchanged).
`./build/prefill_qwen36_test /models/work/qwen36-step3-prefill-fx gdn3` and `full4`: pass, both chunkings.
Relative L1 against the F32 oracle with forced layer inputs (one chunk of 40; chunks of 7 within 5 % of these):
| seam | layer 0 | layer 1 | layer 2 | layer 3 (attention) | gate |
| --- | ---: | ---: | ---: | ---: | ---: |
| `attn_norm` | 2.4e-8 | 2.2e-8 | 3.1e-8 | 2.7e-8 | 1e-4 |
| `linear_attn_out` / `attn_output` | 8.7e-4 | 8.5e-4 | 8.3e-4 | 5.9e-4 | 1e-2 |
| `attn_post_norm` | 4.4e-4 | 3.6e-4 | 3.0e-4 | 8.2e-5 | 2e-3 |
| `ffn_out` | 1.0e-2 | 8.2e-3 | 9.2e-3 | 7.9e-3 | 2e-2 |
| `l_out` | 3.7e-3 | 2.6e-3 | 2.5e-3 | 2.1e-3 | 1e-2 |
The router: 7 rank swaps of 960 (40 x 8 x 3) slots on `gdn3` (one more in layer 3 on `full4`), every one a pair
within 2e-5 to 1.3e-3 of each other in the oracle's softmax (an adjacent-rank swap); none elsewhere. Negatives:
`neg_gate` 0.922, `neg_pair` 0.690, `neg_norm` 0.057 at the seams that make them, `neg_attngate` 0.541 at
`attn_output-3`. Accumulated without forcing, `l_out` 3.7e-3 (layer 0) to 8.7e-3 (layer 3). Against the Q8
oracle the GDN seams are worse (1.4e-2: the GDN projections run FP16 GEMMs, not Q8 products, so the Q8 oracle is
the wrong reference for them) and `ffn_out` is not better (1.2e-2 to 2.4e-2): the MMQ products' q8_1 rounding of
the activations and of H is not ggml's Q8_K rounding of the K-quant path the Q8 oracle models. The F32 column is
the one the gates use.
Where the 1e-2 of `ffn_out` comes from: Q8_0 weights x q8_1 activations (a scale per 32) on int8 tensor cores,
SwiGLU in FP32, H to q8_1 again, the down product the same. The fused test measures the same path at 1.45e-2 rel
RMS against an FP32 reference over random weights; the oracle's own real-file numbers for `ffn_moe_out` are
2.9e-2 (F32) / 2.3e-3 (Q8).
### 3.2 VM 211, GTX 1080 Ti (sm_61), 2026-10-11
Under the card's lock (taken 13:08 after the experts agent released it; held 182 s): `/home/rk/run211-prefill.sh`,
the tree at `/home/rk/qwen36-step3-prefill/` (configure as the common file says at sm_61 with
`STRATA_EXPERIMENTAL_SM60=ON`, the five test targets built in 168 s), the fixtures and dumps copied from VM 221 to
`/home/rk/qwen36-step3-prefill-fx/`; the log is `/home/rk/logs/qwen36-step3-prefill-211.log`.
- `gdn_rec_parity`: 0 failures; the same bits for both variants at both geometries; engine vs reference y16
1.76e-4 to 1.79e-4, state 4e-8 to 1.0e-7; the rivals 0.86 to 1.33 away; `gdn_conv` 5.2e-8 to 5.4e-8; the three
geometry refusals. The numbers equal the 4090's to the printed digits.
- `gemm_bf16_parity`: 0 failures (Pascal's fp32 widening path).
- `prefill_fused_iq_test`, `prefill_fused_moe_test`: exit 77 ("the fused kernels need sm_80 or newer"), as expected.
- `prefill_qwen36_test gdn3` and `full4`: pass, both chunkings. Against the F32 oracle with forced inputs:
`attn_norm` 2.2e-8 to 3.1e-8, `linear_attn_out` 8.3e-4 to 8.6e-4, `attn_output-3` 5.9e-4, `attn_post_norm`
8.2e-5 to 4.4e-4, `ffn_out` 7.9e-3 to 1.05e-2, `l_out` 2.1e-3 to 3.7e-3; the router 5 (gdn3) / 7 (full4)
near-tie swaps, none elsewhere; negatives 0.922 / 0.690 / 0.057 / 0.541; accumulated `l_out` 3.7e-3 to 9.1e-3.
The same as the 4090 to two digits: the prompt MoE took the same path on both cards.
- Which prompt-MoE path runs on Pascal: MMQ. `STRATA_PREFILL_TIMING=1` shows the MMQ phases (gather, dequant =
the gather marks, gemm gate/up 1 ms); and `STRATA_PREFILL_MMQ=0` (the FP16 GEMM over dequantized weights) gives
different numbers (accumulated `l_out` 1.4e-3 / 3.0e-3 / 4.1e-3 instead of 3.7e-3 / 6.0e-3 / 8.2e-3; against the
Q8 oracle `ffn_out-0` 2.25e-2 instead of 2.36e-2), so the default run was not that path. Q8_0 x q8_1 through
llama.cpp's MMQ on sm_61 is dp4a, the study's risk 2 wants it enabled there, and it is. The FP16 path is the
closer one to the F32 oracle (no int8 rounding of the activations), which is what the Q8 column says too.
- 40 tokens through 3 GDN layers (and 4 with attention): a 60 to 100 ms GPU timeline per run, 36 to 40 ms of it
host staging of the unpinned expert blobs; no throughput claim from a 40-token harness (step 5 measures).
## 4. Git
Commits on `qwen36-step3-prefill` past 8b7525e, in order: the kernels (templated GDN, runtime widths), the fused
native experts' widths, the prefill geometry and plain block, `gdn_rec_parity` at both geometries, `[shared]
WeightTable::set`, the fused test's second geometry, the three cherry-picks from `qwen36-step3-attn` (4a24760 and
65a4f2b whole, 856daa0's three kernel files without its parity-test hunk, which belongs to that branch), the dense
attention wiring with the harness and its fixtures, the harness's chunk accounting.
What the integrator should know:
- `src/kernels/cuda/qsa_decode_attn.cu`, `qsa_prompt_attn.cu`, `qsa.cu` and the two headers are the attention
branch's versions at 856daa0; the decode GDN kernels and `gdn_parity.cpp` are the GDN branch's at 7954497;
rebasing onto the integration branch makes those cherry-picks empty.
- The GDN branch's 7954497 (`kernels::GdnGate`, the decode kernels' gate argument) and 4f9aeb9 (`[shared]`
`ModelGeometry::gdn_gate()`) are cherry-picked here too: `GdnGeom::gate` is that enum, required with no default,
and `Geom::of` takes it from `g.gdn_gate()`, so the prompt and decode paths agree by construction (drop the two
at integration). The block branch's `layout.cpp` change (`[shared]` 69d52c9) is not needed by the prompt path:
`Prefill::run` reads the two norms through `need()` and refuses a non-F32 one by name.
- `WeightTable::set` is the only change outside `src/prefill`, `tests/cuda/prefill_*`, `tests/python`,
`docs/qwen36-port` and the CMake lines that register the tests.
## 5. Not done, and surprises
- **The dense ids and scratch on the serve path** are the attention branch's bound (128 blocks per KV head, no ids
buffer); `qsa_set_bytes` counts no ids rows for a dense model and the scratch at the bounded size. A 256K
context on the serve path is step 5's measurement, not this harness's (64 cells).
- **The prompt MoE on Pascal**: `moe_fused*.cu` need sm_80 (their tests exit 77 below it); the unfused path is MMQ
where `mmq::fits` on sm_61 (dp4a) and the FP16 GEMM path otherwise, both at the new geometry (`mmq_plan` from the
layout's widths, `dq_gu` / `dq_d` from `Geom`). Which one the 1080 Ti takes for Q8_0 is recorded in 3.2.
- **The harness's own bug**: `ss.qsa_states[ss.qsa_primary()]` for a model with no attention layer at all (`gdn3`)
reads past a zero-length array; the prefill now guards every read of the primary state with `ss.qsa_alloc`
(`primary_cells`). Found by `STRATA_PREFILL_ALLOC_TRACE` as three multi-exabyte `cudaMalloc`s.
- **Teacher forcing across a non-blocking stream**: a pageable `cudaMemcpy` into R returns before its DMA has
landed, and the next kernel on the prompt stream read half-old rows (2.5e-3 at `attn_norm-1`); the harness waits
for the device after the copy. Not an engine issue (the engine never copies host rows into R mid-layer).
- **The study's table** is right about every site; two of its "check" items were not geometry (`RP = 48`, the
peer ring; the layer loop already ran `g.n_layers`), and `moe_fused.cu` cannot take the new geometry because its
blob format is the geometry (section 1).
- **The study's harness line** ("chunked-prefill-then-decode against token-by-token decode") is met with the oracle
standing in for the decode: the decode mixers are the other agents' and the oracle is the reference both are held
to; the prefill is compared at every position of the chunked and the single-chunk run.
-266
View File
@@ -1,266 +0,0 @@
# Qwen3.6 port, Phase 2 step 4, area `drafter`: the MTP draft block from `blk.40`
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-drafter`, from the step-4 integration
branch `qwen36-step4` at 1db8252). The design is `docs/QWEN36-35B-A3B.md` 3.10 and section 6 (step 4); what the
block computes is `docs/qwen36-port/oracle-crosscheck.md` ("Nextn / MTP", 50 seams verified against llama.cpp) and
`gguf-metadata.md` ("The nextn block"); the trunk pack this one sits beside is `step4-pack.md`. Section 2 is the
pack's layout, section 5 the numbers from both cards, section 7 the interface the runner consumes.
## 1. The numbers first
**The real file, RTX 4090 (VM 221).** The draft pack cut from `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf`'s
`blk.40`, loaded by the engine (506 MiB of VRAM: experts 464, dense 39, the K/V aside), fed the trunk's final residual
of a 33-token prompt (llama.cpp's own `l_out-39` from `tools/qwen36_dump_llama.cpp` on that file), one row per
position, token k with the hidden of k-1:
| | |
| --- | --- |
| top-1 agreement with llama.cpp's MTP arm (its `graph_mtp` on the same pairs, `qwen36-dump ... mtp`) | **32 of 32** (the whole head); 31 of 32 with the shipped `data/draft_vocab.bin` subset (position 2's " fox", id 37550, is not in the subset) |
| top-1 equal to the prompt's next token (teacher-forced acceptance over 31 positions) | **engine 24 of 31 (77.4 %)**, llama.cpp's MTP 24 of 31 (77.4 %): the same 24 |
| seams vs llama.cpp's MTP graph (relative L2 per row, worst over 32 positions / relative L1 over all) | `mtp_eh_proj` 1.2e-3 / 5.6e-4, `mtp_attn_out` 1.2e-2 / 7.7e-3, `mtp_ffn_out` 2.5e-2 / 1.8e-2, `mtp_shared_head_norm` 2.2e-2 / 1.5e-2 |
llama.cpp's figures are its CPU graph with Q8_K / Q8_0 activation rounding; the engine's are q8_1 activations on
the GPU. Those are the real-file numbers of the policy's Q8 class (`oracle-crosscheck.md`: `ffn_out` 4.5e-3 max per
forced layer; here the block's products compound) and the drafts agree at every position. This is the B4 arm of
the plan taken as a per-position reference rather than a generation: the 64-token greedy acceptance under the
runner's verify window is the runner's measurement, after the gate is lifted.
**The synthetic fixture, both cards, all 37 checks** (section 5): every seam at every one of 75 positions within
the gates against the Q8 oracle (the first product `mtp_eh_proj` at 2.3e-4), the router's top-8 identical at
75 of 75 positions, the argmax identical at 74 and a near tie at the 75th, the three negatives 0.14 to 1.41 away.
## 2. The pack, exactly
`python3 -I tools/mtp_qwen36_pack.py --gguf <-MTP file>.gguf --out <dir> [--draft-vocab data/draft_vocab.bin | none]`
(4 s on the Mac, 17 s on VM 221; reads 505 MB). Flash-Next's `tools/mtp_pack.py` / `mtp_rt.py` are untouched; the
file names are theirs, so `--mtp DIR` is the one CLI and `MtpDrafter::load` picks the path by the trunk's
architecture. Six files:
| File | Contents |
| --- | --- |
| `dense.txt` | 17 lines `name kind rows cols offset bytes`; the name without `blk.40.`; `kind` = `f32` (the 7 norms), `bf16` (`ffn_gate_inp` 256 x 2048, the 1-D `ffn_gate_inp_shexp`), or the projection's ggml type in lowercase (`q8_0` for all 8 in both shipped files); rows = ne1, cols = ne0 |
| `dense.bin` | the tensors' bytes as stored, 256-aligned: **42,317,824 B** (Q4_K_XL-MTP: 7 x F32 norms 34 KiB, 2 x BF16 1.0 MiB, 8 x Q8_0 41.3 MiB) |
| `experts.bin` | 256 blobs of `[gate rows \| up rows \| down rows]`, raw GGUF blocks, in id order: **486,539,264 B** (blob 1,900,544 = Q4_K 589,824 + 589,824 + Q5_K 720,896; `native_expert_layout(12, 13, 2048, 512)`) |
| `native_experts.txt` | the v3 header and one line `0 12 13 0 1900544 0 589824 1179648` (the role offsets inside a blob; the header says so and names the source) |
| `mtp.json` | `format`, `arch`, `source`, `source_bytes`, `trunk_layers` / `draft_block` 40, `n_embd` 2048, `n_head` 16, `n_head_kv` 2, `head_dim` 256, `n_rot` 64, `n_expert` 256, `n_expert_used` 8, `n_ff` 512, `n_ff_shexp` 512, the expert types and blob bytes, the dense types by name, `draft_vocab` |
| `draft_vocab.bin` | copied from `--draft-vocab` (default `data/draft_vocab.bin`, 106,299 ids; `none` leaves it out: the whole head) |
Refused by name: a file without exactly one nextn block (the plain IQ3_XXS: "nextn_predict_layers is 0"), fused
`ffn_gate_up_exps` / `attn_qkv`, a projection type outside `iq_pack.py`'s `NATIVE_PROJECTION_TYPES`, an F32 router
that is not BF16-exact, and an expert pair the native kernels lack: **the IQ4_XS-MTP file's `blk.40` is Q3_K
gate/up with Q4_K down, neither of which is in `iq_kernels.cu`'s lists (gate/up 16, 17, 18, 21, 22, 23, 29, 42,
12, 13, 14, 6, 8; down 20, 23, 42, 7, 6, 8, 18, 13, 14)**, so only the Q4_K_XL-MTP file's draft block is served
today, and it serves the IQ3_XXS trunk too (the study's 3.10: the drafter is separate from the trunk file; the
float tensors are the same in every quant and the head and embedding come from the trunk's file).
The engine's view (`MtpDrafter::load`): `check_qwen36_pack` holds `mtp.json`'s nine geometry fields against the
trunk's `ModelGeometry` and refuses a mismatch by name ("was cut for n_expert 256 but the trunk has 512"), requires
the 17 names in the forms above (norms F32 of n_embd or head_dim elements, routers BF16, projections a type
`native_mmvq_supported` takes, `eh_proj` n_embd x 2 n_embd); `load_qwen36_experts` requires one layer line, the
header's `n_expert` equal to the trunk's, `native_expert_supported(gu, d, n_embd, n_ff)` and the blob and role
offsets equal to `native_expert_layout`'s, then uploads `experts.bin` whole.
## 3. The drafter on the plain graph
`src/core/mtp.cpp`, `record_forward_qwen36` (dispatched from `record_forward` when `g.arch == Qwen35Moe`; the
Flash-Next body is byte-for-byte what it was), T rows for the K/V-only pass, one row for the full layer, the same
step / position records, graphs, staging, window, K/V formats, coupled sampling and draft chain as Flash-Next:
emb = token_embd[tok] (the native embedding table)
e = rms_norm(emb) * nextn.enorm
hn = rms_norm(R_in) * output_norm (the trunk's output norm: the caller hands the FINAL RESIDUAL, as
h = rms_norm(hn) * nextn.hnorm for Flash-Next; llama.cpp's h_nextn is the normed state)
R = eh_proj . concat(e, h) (embedding first; q8_1 x the pack's type through native_mmvq)
x = rms_norm(R) * attn_norm
K = rope(k_norm(attn_k . x)), V = attn_v . x -> the drafter's own K/V at the row's cell [the K/V-only pass stops here]
q = rope(q_norm(attn_q . x)[:, :256]), gate = attn_q . x[:, 256:] per head
a = dense attention over the cache (qsa_decode_attn_batch, the window's ids) * sigmoid(gate)
R += attn_output . a
x = rms_norm(R) * post_attention_norm
ids, w = top-8 of softmax(ffn_gate_inp . x), renormalised (bf16_gemv_fp32_mmvf, router_top10 at 256 / 8)
R += sum_j w_j expert_ids[j](x) + sigmoid(ffn_gate_inp_shexp . x) * shexp(x)
(moe_group_resident over experts_ at blob stride -> native_expert_grouped on q8_1 x; shared_expert native)
y = rms_norm(R) * nextn.shared_head_norm
logits = head . y (the draft subset or the whole head), argmax / the coupled sampler, map_ids
What changed against Flash-Next's drafter, item by item of the study's 3.10: the two input projections
(`fc_embedding`, `fc_hidden`) are the one `eh_proj` over the concatenation; the three hyper-connection groups are
the three norms (`attn_norm`, `post_attention_norm`, `shared_head_norm`) with `add_inplace` residuals; the draft
experts are 256 native blobs through `native_expert_grouped` (the kernels of step 3, `step3-experts.md`) instead of
the Q2_0 grouped kernel; the geometry is the trunk's. What is the same: the dense attention over the drafter's own
ring at `qsa_shapes(g)` (dense: null indexer, cap = max_cells or the `--mtp-window`), the main head over
`draft_vocab.bin`'s subset, `token_embd` embeds, the pairing (cell i: the residual of position i with the token at
i+1, RoPE at i).
**The RoPE position.** llama.cpp's MTP rotates the pair (token k, hidden k-1) at position k; the engine's drafter
(both models) rotates at the cell, k-1. RoPE enters the scores only through position differences, so the two
conventions give the same attention; the harness runs the engine's convention against the oracle's dumps and the
seams agree to float rounding (`mtp_attn_pregate` 1.6e-3, the fp16 pool inside). Nothing in `prefill` / `draft` /
`draft_kv` needed a Qwen branch for it.
**Buffers**: `cat_` (T x 2 n_embd) for the concatenation, `xq_` sized for the wider of `n_head x head_dim` and
2 n_embd, `hit_scratch_` the larger of the grouped kernel's and `native_expert_scratch_bytes(T x k, n_ff)`; the
rest of the carve is Flash-Next's at hc = 1. The K/V: without `--kv-resident` (KV streaming does not apply to the
dense model, `step3-attn.md` item 6) `kv_plan` gives no ring, so the drafter's cache is `max_cells` whole: 2 KiB
per cell fp16 (512 MiB at 262,144 cells), 576 B q4_0 (144 MiB); `--mtp-window` still bounds what a row attends to.
**The harness's entry point**: `MtpDrafter::debug_row(R_row, token, cell, pos, DebugOpts, seam, &top1, err)` runs
the full layer for one row on the drafter's stream outside any graph and hands every seam to `seam` by llama.cpp's
`cb()` name after a stream sync (the list is in `mtp.hpp`); `DebugOpts{hidden_first, skip_hnorm}` are the rival
readings, set by nothing else.
**The prompt-side pass** (`src/prefill/prefill.cpp`, `Prefill::draft_kv`): the `qwen35moe` branch computes the
nextn block's K/V for the prompt's cells through the prompt path's GEMMs in the drafter's order (embedding, the
three norms, the concat, `eh_proj`, `attn_norm`, `attn_k` / `attn_v`, `k_norm`, RoPE at the cell, the append in the
state's format), MMQ q8_1 x the pack's type where `mmq::supported` and `fits` say so (Q8_0: yes), else the FP16
GEMM over dequantized weights; batches of 64 rows and up as for Flash-Next (`B < 64` declines and the drafter's own
`prefill` runs). The harness checks it end to end: the positions after 64 `draft_kv` cells agree with the oracle
to the same figures as the drafter's own pass and draft the same tokens.
## 4. The harness: `tests/cuda/qwen36_mtp_test.cpp`
The fixture (`tests/python/qwen36_mtp_fixture.py`; CTest `qwen36_mtp_fixtures`, 3 min on VM 221, 11 s on the Mac
at 11 tokens) is the prompt-path harness's `full4` trunk (n_embd 2048, three DeltaNet layers, layer 3 attention
16 / 2 x 256, 16 experts top-8 of 512, shared 512) plus the nextn block `blk.4` from `tools/qwen36_synth_gguf.py`,
with every projection, `nextn.eh_proj`, the experts, the head and the embedding Q8_0 (the native paths' types) and
the routers BF16-exact; 76 tokens, so 75 nextn positions and a 64-row `draft_kv` batch. The oracle runs twice
(`--mtp`: faithful, and `--act-quant q8`) and `tools/mtp_qwen36_pack.py` cuts the pack from the fixture itself.
`qwen36_mtp_test <dir>` (CTest `qwen36_mtp_test`, exit 77 without a device or the fixture):
1. Per position k = 1..75, `debug_row(l_out-3[k-1], tokens[k], cell k-1, pos k-1)`: 21 seams against the Q8
oracle's row k-1 (relative L2 per row, the worst over positions; the F32 oracle's figure beside it from a
second pass over its own trunk rows), `ffn_moe_topk` identical as a set, the draft equal to the oracle's argmax
(a flip counts as a near tie when the oracle's gap is within 3x the row's largest logit error, and is printed).
2. The negatives, each more than 5 % relative L1 from the oracle: the concat with the hidden state first
(`mtp_eh_proj`, `result_output`), hnorm skipped (`mtp_hnorm`, `mtp_eh_proj`), the pairing with position k
instead of k-1 (`mtp_hnorm`, `result_output`).
3. `draft_first` (the captured round graph: the catch-up and the full layer at cell 0): draft 0 equals the
uncaptured forward's draft at cell 0.
4. `Prefill::draft_kv` for cells 0..63 (a `Prefill` on the fixture's trunk), then positions 65..75 through the
forward again: the five seams within the same gates and the drafts equal to the drafter's own pass's.
`qwen36_mtp_test --real --gguf F --pack D --dump D1 --mtp-dump D2 --tokens ...` is the real-file arm of section 1:
`D1` / `D2` from `qwen36-dump F D1 <tokens> 0 mtp` (CPU llama.cpp at the pinned commit, built under
`/models/work/llama-cpu` on VM 221 with gcc-13; 52 s for 33 tokens at 4 threads, 871 MB of dumps).
The gates, relative L2 per row against the Q8 oracle, and why: `mtp_tok_embd` 1e-6 (exact dequantization),
the norms of forced inputs 1e-5, `mtp_eh_proj` / `mtp_attn_norm` 1e-3 (one q8_1 x Q8_0 product: 2.3e-4 measured),
then **every product after the first sees an input 2.3e-4 away from the oracle's, and the oracle's own q8 rounding
of that input flips about 1 % of the int8 codes by a step (2e-4 x rms/amax x 127), which is 2e-3 of the output**:
the Q/K/V projections 5e-3 (2.0-2.2e-3 measured), `mtp_attn_pregate` 5e-3 (1.6e-3), `mtp_attn_out` 1e-2 (5.4e-3),
the residual / post norm / router logits 5e-3 (1.1-1.2e-3), the renormalised weights 1e-2 (1.7e-3), the shared
expert and `mtp_ffn_out` 3e-2 (1.1-1.2e-2: the moe_out class), `mtp_post_ffn` / `mtp_shared_head_norm` 1.5e-2
(5.3e-3: the l_out class), `result_output` 3e-2 (1.0e-2). The exact checks are the router's picks and the argmax.
## 5. Results
### VM 221, the RTX 4090 (sm_89), 2026-10-11
Build: `/models/work/build-step4-drafter.sh` (the common configure at sm_89 with `-DSTRATA_MMQ_KQUANTS=ON`;
`qwen36_mtp_test` and `strata`, 2 min 34 s). `./build/qwen36_mtp_test /models/work/qwen36-drafter-fx`
(`/models/work/logs/qwen36-drafter-synth.log`), 37 of 37:
| seam (75 positions) | vs Q8 oracle | gate | vs F32 oracle (reported) |
| --- | ---: | ---: | ---: |
| `mtp_tok_embd` | 0.0 | 1e-6 | 0.0 |
| `mtp_enorm` / `mtp_hnorm` / `mtp_concat` | 1.3e-7 / 1.3e-7 / 1.2e-7 | 1e-5 | 1.3e-7 / 1.3e-7 / 1.3e-7 |
| `mtp_eh_proj` / `mtp_attn_norm` | 2.30e-4 / 2.31e-4 | 1e-3 | 6.2e-3 / 6.2e-3 |
| `mtp_Vcur` / `mtp_Kcur_normed` / `mtp_Qcur_full` / `mtp_Qcur_normed` | 2.02e-3 / 2.08e-3 / 2.15e-3 / 2.22e-3 | 5e-3 | 9.0e-3 / 9.3e-3 / 8.6e-3 / 8.8e-3 |
| `mtp_attn_pregate` / `mtp_attn_out` | 1.64e-3 / 5.41e-3 | 5e-3 / 1e-2 | 1.3e-2 / 1.5e-2 |
| `mtp_attn_residual` / `mtp_attn_post_norm` / `ffn_moe_logits` | 1.09e-3 / 1.09e-3 / 1.19e-3 | 5e-3 | 7.4e-3 / 7.4e-3 / 1.2e-2 |
| `ffn_moe_topk` | identical at 75 of 75 | identical | |
| `ffn_moe_weights_norm` | 1.65e-3 | 1e-2 | 1.3e-2 |
| `mtp_ffn_shexp_gated` / `mtp_ffn_out` | 1.18e-2 / 1.08e-2 | 3e-2 | 2.6e-2 / 1.9e-2 |
| `mtp_post_ffn` / `mtp_shared_head_norm` | 5.32e-3 / 5.33e-3 | 1.5e-2 | 1.1e-2 / 1.1e-2 |
| `result_output` | 1.09e-2 | 3e-2 | 1.4e-2 |
| the draft = the oracle's argmax | 74 of 75; position 45 a near tie (oracle gap 1.2e-2, largest logit error 4.6e-2) | | 3 of 75 differ from the F32 argmax |
| negative case | relative L1 from the oracle | required |
| --- | ---: | ---: |
| concat(hnorm, enorm), the hidden state first, at `mtp_eh_proj` / `result_output` | 1.41 / 1.38 | > 0.05 |
| hnorm skipped, at `mtp_hnorm` / `mtp_eh_proj` | 0.165 / 0.143 | > 0.05 |
| paired with position k instead of k-1, at `mtp_hnorm` / `result_output` | 1.38 / 1.01 | > 0.05 |
`draft_first` at cell 0: drafts 65, 35, 16; the forward's draft at position 1: 65 (equal). `Prefill::draft_kv`
took the 64 cells (batched, MMQ); positions 65..75 after it: `mtp_attn_pregate` 1.42e-3, `mtp_attn_out` 4.83e-3,
`mtp_ffn_out` 1.11e-2, `mtp_shared_head_norm` 5.22e-3, `result_output` 1.14e-2, the drafts equal to the drafter's
own pass's at 11 of 11. `ctest -R qwen36_mtp` (the fixture through CMake and the test): 2 of 2 (the fixture 132.5 s, the test 0.6 s).
The real file: section 1 (`/models/work/logs/qwen36-drafter-real-qwen36-mtp-draft{,-full}.log`;
`/models/work/packs/qwen36-mtp-draft{,-full}`, the dumps in `/models/work/qwen36-drafter-real/`).
### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY`
The same tree (`/home/rk/qwen36-step4-drafter/`, the submodule copied from the step-4 pack tree), configured with
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`, `qwen36_mtp_test` and `strata` built in 3 min 52 s;
the fixture written there (`/home/rk/qwen36-drafter-fx`, 4 min 43 s) and the two packs cut from
`/home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (the MTP repo's file, 22 s); the real-file dumps copied from VM 221
(`l_out-39`, the MTP `result_output` and four seams). The lock was held from 21:28 to 21:34 UTC (the build and the
fixture ran under it; the runs take seconds). Logs in `/home/rk/logs/qwen36-drafter-*.log`.
`./build/qwen36_mtp_test /home/rk/qwen36-drafter-fx`: **37 of 37**, the same numbers as the 4090 to the printed
digits at every seam but four (`mtp_attn_out` 5.42e-3, `ffn_moe_logits` 1.23e-3, `ffn_moe_weights_norm` 1.61e-3,
`mtp_ffn_shexp_gated` 1.14e-2, `mtp_post_ffn` / `mtp_shared_head_norm` 5.75e-3 / 5.70e-3: the per-entry expert
kernels Pascal takes, `step3-experts.md`), the router's picks identical at 75 of 75, the argmax identical but the
same near tie at position 45, the negatives 1.41 / 1.38, 0.165 / 0.143, 1.38 / 1.01, `draft_first` 65 35 16 = 65,
`draft_kv` batched with the positions after it at 1.45e-3 / 4.75e-3 / 1.09e-2 / 5.34e-3 / 1.04e-2 and the drafts
equal. The kernels the drafter adds to Pascal's path are the step-3 native expert kernels (dp4a), the MMVQ, the
rms norm, the dense attention's `pre75` kernel: nothing new was guarded.
The real file, both packs: **top-1 agreement with llama.cpp's MTP arm 32 of 32 (the whole head), 31 of 32 (the
subset: position 2 again); teacher-forced acceptance 24 of 31 = 77.4 % (23 with the subset), llama.cpp 24 of 31**;
`mtp_eh_proj` 1.18e-3 / 5.6e-4, `mtp_attn_out` 1.22e-2 / 7.7e-3 as the 4090, but `mtp_ffn_out` 1.54e-1 / 2.6e-2 and
`mtp_shared_head_norm` 1.42e-1 / 1.9e-2 (worst row / relative L1): **one position, 10, is 1.4e-1 from llama.cpp's
head-normed state on the 1080 Ti and 1.6e-2 on the 4090**, every other position 1.0e-2 to 2.3e-2 on both. The
only mechanism that moves one row by 14 % while its neighbours stay at 1 % is a routed-expert flip at a near tie
(the real file's router sees percent-level differences, `oracle-crosscheck.md` "Tolerance policy"), from the
cards' different dot-product orders in the attention and expert kernels; the draft at that position (411) is the
same on both cards and equals llama.cpp's. Not confirmed by dumping both cards' `ffn_moe_topk` for that row (the
lock was released); the runner's end-to-end parity on Pascal is where a flip rate per position is measured.
## 6. Not done, surprises, where the study was off
- **The 64-token greedy acceptance** (the brief's alternative to the llama.cpp arm) needs the trunk generating,
which is the runner's (the step-2 gate, the verify window on qwen35moe); the per-position reference against
llama.cpp's MTP arm is the stronger check and was cheap (the dumper exists since step 1). `draft()` and
`draft_first()` run on the real pack (the captured graphs are the same code as Flash-Next's); only `draft_first`
is held to the forward here.
- **The VRAM plan's drafter line** (`generate.cpp`, `in.drafter_bytes = draft + 16 MiB` "its ring KV and 8 x n_vocab
logits") undercounts: the weights are 506 MiB as planned, but the K/V is the whole context (no ring without
`--kv-resident`: 512 MiB fp16 / 144 MiB q4_0 at 262,144 cells; `--mtp-window` does not shrink it), the draft head
subset is `n_dvocab x row_bytes` (106,299 x 2,176 B = 221 MiB on the Q8_0 head of the Q4_K_XL file, 171 MiB on the
IQ3_XXS file's Q6_K head), the logits 7.6 MiB, the identity ids T x max_cells x 4 (8 MiB at 256K). The runner's
area (the plan is the gate block's); the numbers are here for it.
- **The IQ4_XS-MTP file's draft block cannot be served** (Q3_K gate/up, Q4_K down: section 2). The study's 3.10
counted it ("Q3_K/Q4_K, 364 MiB in the IQ4_XS file"); the step-3 expert kernels never gained those two roles.
The Q4_K_XL-MTP pack serves every trunk, so nothing is lost today; adding Q3_K gate/up and Q4_K down to
`iq_kernels.cu`'s lists is a step-5 item if that file is wanted.
- **The data/draft_vocab.bin subset drops " fox"** (id 37550) and so one of 32 positions on the English prompt;
the subset is Flash-Next's English-and-code selection over the same vocabulary and carries over as the study
said, with that coverage.
- **The study's 3.10 said "IMRoPE"** for the draft block's attention: the sections reduce to plain NEOX rope for
text (section 1 of the study), and the engine's `native_rope_apply` / `rope_neox_apply` at n_rot 64 are what the
oracle's dumps match.
- The oracle's `mtp_ffn_moe_out` (the routed sum without the shared expert) is not a seam the engine materialises
(`native_moe_combine` adds the shared expert in the same launch); `mtp_ffn_out` covers it.
- `tests/python/qwen36_mtp_fixture.py` imports the prompt-path fixture module for its geometry and the BF16 rounding;
a change there changes this fixture's trunk too (intended: one trunk shape for both harnesses).
## 7. The interface the runner consumes
- `MtpDrafter` is unchanged for the runner: `load(rt_dir, g, ss, max_t, err, window)` with `g` the trunk's geometry
(`generate.cpp`: `draft_geometry = g.arch == Qwen35Moe ? g : ModelGeometry{}`, the one `[shared]` hunk, lines
3267-3271), `bind(wt, &native_head, window_R, err)` (needs `output_norm.weight` F32 in `wt`, `output.weight`'s row
for n_vocab, `token_embd.weight`'s row and the native embedding set, as the trunk pack provides), `prefill(R_rows,
next_tokens, n, cell0)`, `draft(T, tokens, p, a, drafts, ...)`, `draft_first(...)`, `kv_state()`, `vram_bytes()`,
`bind_bytes(row_bytes, n_vocab)`. `R_rows` / `window_R` are the trunk's FINAL RESIDUAL rows (hc = 1: n_embd each,
`Verifier::final_R_all()`), not the normed state: the drafter applies `output_norm` itself.
- `Prefill::draft_kv(mtp, R_rows, next_tokens, n, cell0, err)`: the same call; true for the Qwen3.6 drafter when
the native embedding is set and the batch is at least 64 rows, false (err empty) otherwise.
- New: `MtpDrafter::qwen36()`, `tensor_native(name, &type)`, `expert_gu_type()` / `expert_d_type()` /
`expert_blob_bytes()`, `debug_row(...)` with `DebugOpts` and `SeamFn` (the harness's).
- `tools/mtp_qwen36_pack.py`: `--gguf`, `--out`, `--draft-vocab`; the layout of section 2. The CLI's `--mtp DIR`
takes the directory; `--draft-vocab en` style selection is whatever the pack holds as `draft_vocab.bin`.
- The commits on `qwen36-step4-drafter` past 1db8252: ad70f3d the pack tool, 6ae03ea the drafter, f0e5362 the
prompt-side pass, e21be6c `[shared] generate` (the one hunk, `src/program/generate.cpp:3267-3271`), 41c568d the
harness and the fixture, then this file.
-58
View File
@@ -1,58 +0,0 @@
# Qwen3.6 port, Phase 2 step 4: the integration branch `qwen36-step4`
Branch `qwen36-step4` (worktree `~/Code/UnbiasedStrata-step4`), from the step-3 head 355ce3c. Unmerged, unpushed.
## What is on it, in order
| range | from | what |
| --- | --- | --- |
| 3ad2847..1db8252 (7) | `qwen36-step4-pack` | `iq_pack` FORM_QWEN35MOE, the regex-free tokenizer, `make_profile --n-layer`, the 40x256 expert profile, `pack_load_check`; notes step4-pack.md |
| 02ff47e | integrator | step-3 notes |
| ad70f3d..84b4756 (6) | `qwen36-step4-drafter` | `tools/mtp_qwen36_pack.py`, the qwen35moe drafter in `mtp.cpp`, prefill draft K/V, `[shared] generate.cpp` draft geometry, `qwen36_mtp_test`; notes step4-drafter.md |
| 6d0d817..6042a32 (6, cherry-picked clean) | `qwen36-step4-runner` | the step-2 gate lifted, `[shared] verify.cpp` indexer tail, `qwen36_verify_test` + `qwen36_runner_check.py`, the llama.cpp teacher and the logits comparison, notes, the VRAM plan's drafter term |
| 85d5d12 | `main` f07b81e | the front end's SSE keepalive and client-gone cancel (another session's patch, cherry-picked on request) |
| e73adc6 | integrator | CMake applies the chat-parser patch at configure time (REGINA-104); `make build` turns `STRATA_MMQ_KQUANTS` on |
The expected `generate.cpp` conflict between the drafter's draft-geometry hunk (:3307) and the runner's gate region
(:2184, :2557) did not occur; the three hunks sit apart.
## Builds and tests
- **VM 221, the RTX 4090**: the integrated tree at e73adc6 configures and builds with 0 errors (the common line,
`-DSTRATA_MMQ_KQUANTS=ON`, sm_89; logs `/models/work/logs/qwen36-step4-*.log`, script `/models/work/build-step4.sh`).
The full ctest of the integrated tree is **not** a result: 63 of 97 tests fail in under a second on
`malloc x: out of memory`, because another session's Flash-Next service (`unbiased-strata.service`, active since
2026-10-12 22:08 UTC) holds 23.9 of 24.5 GB. The 34 that pass are the CPU tests (`vram_plan_test`, the pack and
planner tests, the tokenizer). Owed: the full run once the card has VRAM.
- **VM 211, the GTX 1080 Ti**: the runner's own tree ran steps 2-4 at 21:38 UTC 2026-10-11 (step4-runner.md section
4): verify test and runner check pass; the real-file llama.cpp comparison did not run (fixtures not synced). The
integrated tree has not been built there: since 2026-10-12 22:04 UTC the card runs a Flash-Next coder service and
the user has asked that it not be interrupted.
- **The chat parser**: `make test-chat-parser MODEL=/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf BUILD_DIR=build` passes
on VM 221 after the fix (all four argument orders).
- **The Mac** (arm64, CUDA off): the upstream CPU expert kernel is compiled with `-mavx512*` flags unconditionally
(CMakeLists.txt:1086), which clang rejects on arm64, so the CUDA-off Mac build has never linked past
`strata_kernels_cpu`. Not the port's regression; the Mac configure step was used only to verify the patch logic.
## Numbers that carry forward
- Speculation with the real drafter on the 4090 (step4-runner.md, round 8): IQ3_XXS 0.77 accepted / 3.20 tokens per
round with the full head, 0.72 / 3.05 with the subset head; Q4_K_XL (plain trunk, MTP-file draft) 0.53 / 2.54.
- The VRAM plan's drafter share is now the whole context's K/V plus the head subset plus the ids (f2e70c8);
`vram_plan_test` passes with the new cases.
- Correctness held on both cards: 1080 Ti argmax 40/40 vs the Q8 oracle, 4090 teacher-forced IQ3 64/64 x3 prompts.
## Owed to step 5
1. ~~Full ctest of the integrated tree on a card with free VRAM.~~ Done 2026-10-13 once the 4090's service was
stopped: 95 of 98 at 22d72e6 (the three host-environment failures), including the serve fixes and
`pool_native_widths_test` of step5-serve.md.
2. The 1080 Ti real-file comparison (sync `/models/work/qwen36-step4-teacher` to VM 211) and the Q4 fit at 11 GB.
3. The ladder: serve and measure on 11 GB, then `--vram-cap` 8 and 6 GB; the three instruments; engine points on
`ladder-baseline.png`; acceptance A1-A5.
4. The step-6 fat binary, compile-checked on VM 221's CPU (`build-fat`, `/models/work/logs/qwen36-step4-fat-*.log`):
`CUDA_ARCHS=61;70;75;86;89` with `STRATA_EXPERIMENTAL_SM60=ON` and `STRATA_MMQ_KQUANTS=ON` configures and builds
`unbiased-strata` in 6 min 17 s at `-j 14`, 0 errors; `cuobjdump --list-elf` shows 62 ELF images per architecture
for all five; 235 MiB. **sm_120 cannot come from this host**: CUDA 12.4's nvcc rejects `compute_120`
("Unsupported gpu architecture"); Blackwell needs a 12.8+ toolkit, so the step-6 release build either uses a newer
toolkit or ships 120 as PTX from 89. Nothing in this binary has run on a card yet.
-209
View File
@@ -1,209 +0,0 @@
# Qwen3.6 port, Phase 2 step 4, area `pack`: the native pack
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-pack`, from the step-3 integration
branch `qwen36-step3` at c6fa016). The design is `docs/QWEN36-35B-A3B.md` 3.7, 3.8, 3.11 and section 6 (step 4);
what the engine reads is `docs/qwen36-port/step3-block.md`, `step3-gdn.md`, `step3-attn.md`, `step3-prefill.md`;
the census that decided the forms is `step3-gdn.md` section 3. This file is the contract the drafter and runner
agents consume: section 2 is the pack's layout, exactly; section 5 is how the engine loads it and what was verified
on both cards.
## 1. What changed
| Where | What | Why |
| --- | --- | --- |
| `tools/iq_pack.py` | `FORM_QWEN35MOE` beside Flash-Next's `FORM` (`FORMS[arch]`, `form_of(name, arch)`); `NATIVE_PROJECTIONS_QWEN35MOE` / `NATIVE_PROJECTION_TYPES` / `NATIVE_EMBED_TYPES` with `native_type_problem`; the draft block (`blk.<trunk>` and up) left out of `index.txt` and `dense.bin` (`n_trunk`); the inexact-BF16 refusal carries the count; `--expert-profile` (default `data/qwen36-expert-profile.bin` for qwen35moe) copied in as `expert-profile.bin` after a header check | the study's step 4 line; "a second entry, not a rewrite": a toy Flash-Next model with every FORM tensor kind packs byte-identically with the step-3 and the step-4 packer (all six files, checked) |
| `tools/test_iq_pack.py` | `write_gguf(..., architecture=)`; `Qwen36PackTests`: the forms and `index.txt`'s contents, the count in the refusal and `--compat-bf16`'s rounding, the native types refused by name (projection, head, embedding each with its list), the nextn block left out, the profile checked and copied, the Flash-Next table untouched | the brief's fixtures |
| `tools/make_profile.py`, `test_make_profile.py` | `--n-layer` (the base's header decides when given), `--text-trace` for llama.cpp eval-callback route traces (`<layer> <e0> ... <e7>` lines, `#` headers, `.gz`), `profile_header` | `N_LAYER = 48` was the study's row; the E0 trace is text |
| `data/qwen36-expert-profile.bin` | the 40 x 256 ranking from the E0 trace (section 3) | shipped in every Qwen3.6 pack |
| `tools/strata_tokenizer.py` | `regex` imported if present; `extract` needs no pattern, `encode` refuses by name without it | neither VM's system python has `regex`, and the packer runs the export as a subprocess |
| `src/core/layout.cpp` (`[shared]`) | `check_one` skips the four `indexer.*` rows when `!g.has_indexer()` | they were still required of every attention layer at hc = 1 (step3-block.md section 7 said so): every Qwen3.6 pack would have been refused "missing blk.3.indexer.q_proj.weight" |
| `src/program/generate.cpp` | `native_dense.load(..., 0, g.n_layers)` | a -MTP file's `blk.40` carries the projection names; it is not in the trunk's pack and `NativeDense::load` refuses a name absent from the table. A no-op for Flash-Next |
| `tests/core/pack_load_check.cpp`, `CMakeLists.txt` | the pack loaded as `generate` loads it after the gate (section 5) | the gate fires before any of those loads |
Not needed, and why: `--compat-bf16` for the real files (section 2: 140 of 140 conversions exact, max error 0);
any change to `weights.cpp` (index kinds 4 and 2 were already the raw-BF16 and F32 paths), `native_dense.cpp`
(every projection type of both files is in `native_mmvq_supported`), `native_head.cpp` or the embedding (Q6_K /
Q8_0 are in both lists), `expert_layout.cpp` (v3 at 2048 x 512 since step 2).
## 2. The pack, exactly
Built by `python3 -I tools/iq_pack.py --gguf <file>.gguf --out <dir>` from a single-shard qwen35moe GGUF
(both shipped files are single shards; a split would name its shards in `native_experts.txt` as for Flash-Next).
Six entries:
| File | Contents |
| --- | --- |
| `index.txt` | "strata pack index v3", `# align 64 pool <arena bytes> tensors 613`, then one row per non-expert trunk tensor: `name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias group_elems codebook has_offset codes_bytes scales_bytes offset_bytes scales_fp16 act_kind` (19 fields; `file` 0 = dense.bin). Kinds: **4** = raw BF16 in dense.bin (the loader's `Bf16InF32` form, copied), **2** = F32 copied, **0** with `code_bits 8 group_elems 32` and every byte count 0 = served natively from the GGUF (shape only; the loader refuses to read such a row, `NativeDense` / the head / the embedding attach it). `dst_off` is the running 64-aligned arena offset; a native row carries the current offset with 0 bytes. |
| `dense.bin` | the kind-4 and kind-2 tensors at their `src_off`, each padded to 64 B: **54,610,432 B** for both files (byte-identical between IQ3_XXS, the plain Q4_K_XL and the MTP Q4_K_XL: md5 `096a0d6e140c3ac412b2f9542eb3c335`; the float tensors are the same in every quant, as they were for Flash-Next) |
| `native_experts.txt` | v3, one line per trunk layer `layer gu_type d_type offset blob_bytes gate_off up_off down_off` (absolute byte offsets of the three expert tensors in the GGUF), header `(n_expert 256, total <bytes>; absolute offsets in <file>)`; 40 lines, the nextn block excluded. The IQ3_XXS table equals `tests/data/native_experts/qwen36-iq3_xxs.txt` byte for byte; the MTP Q4_K_XL table equals `qwen36-q4_k_xl.txt` up to the file name in the header. |
| `conversions.json` | schema 1: the 140 F32 -> BF16 records (`exact: true`, `max_abs_err 0.0`, the source bytes' SHA-256), `compat_bf16: false` |
| `expert-profile.bin` | `STRP`, version 1, 40 x 256, 10,240 ranked `(layer, expert)` u16 pairs then the 40 x 256 slot table: 81,944 B (section 3) |
| `tokenizer/` | `vocab.json` (248,320), `merges.txt` (247,587), `token_type.json`, `tokenizer.json` (`pre: qwen35`, the shipped pattern, `add_bos_token false`, eos 248046 / pad 248055 / bos 248044), `chat_template.jinja` (8,057 B, the file's own) |
The 613 rows, per tensor (the suffix after `blk.N.`; shapes as GGUF `ne0 x ne1`, ne0 contiguous):
| Tensor | Layers | Index kind, form in the arena | Shape | Engine site that reads it (form it demands) |
| --- | --- | --- | --- | --- |
| `attn_norm.weight`, `post_attention_norm.weight` | all 40 | 2, F32 (8,192 B) | 2048 | `plain_block_pre` / verify `plain_w` / prefill `rms_norm_images`: `const float*`, `WeightKind::F32`, `n_embd` elements |
| `ffn_gate_inp.weight` | all 40 | 4, BF16 (1,048,576 B) | 2048 x 256 | `moe_route` (`bf16_gemv_fp32_mmvf`), prefill `bf16_proj`: `Bf16InF32` |
| `ffn_gate_inp_shexp.weight` | all 40 | 4, BF16 (4,096 B) | 2048 (1-D) | `moe_shared`, verify, prefill: `Bf16InF32`, `n_embd` elements (the one 1-D BF16 tensor) |
| `ffn_gate_shexp`, `ffn_up_shexp`, `ffn_down_shexp` | all 40 | 0, native (Q6_K in IQ3_XXS, Q8_0 in Q4_K_XL) | 2048 x 512, 2048 x 512, 512 x 2048 | `moe_shared` through `NativeSharedWeights` (`native_data`, `native_type`) |
| `attn_qkv.weight`, `attn_gate.weight`, `ssm_out.weight` | 30 GDN | 0, native (Q6_K / Q8_0) | 2048 x 8192, 2048 x 4096, 4096 x 2048 | `gdn_layer` (`native_mmvq` through `w.native_data`), verify, prefill |
| `ssm_alpha.weight`, `ssm_beta.weight` | 30 GDN | 4, BF16 (131,072 B each) | 2048 x 32 | `gdn_layer` (`fused_gdn_ab`), prefill `bf16_proj`: `Bf16InF32` |
| `ssm_conv1d.weight` | 30 GDN | 2, F32 (131,072 B) | 4 x 8192 | `gdn_layer`: `const float*` (`ssm_d_conv x ssm_conv_channels`) |
| `ssm_a`, `ssm_dt.bias` | 30 GDN | 2, F32 (128 B each) | 32 | `gdn_layer`: `const float*` (`ssm_v_heads`) |
| `ssm_norm.weight` | 30 GDN | 2, F32 (512 B) | 128 | `gdn_layer` / `gdn_out_norm`: `const float*` (`ssm_state_size`) |
| `attn_q.weight`, `attn_k.weight`, `attn_v.weight`, `attn_output.weight` | 10 attention | 0, native (Q6_K / Q8_0) | 2048 x 8192, 2048 x 512, 2048 x 512, 4096 x 2048 | `qsa_layer` (`gemv_quantized` takes the native path), verify, prefill |
| `attn_q_norm.weight`, `attn_k_norm.weight` | 10 attention | 2, F32 (1,024 B) | 256 | `qsa_layer` `normalize_rotate`: `const float*` (`head_dim`) |
| `output_norm.weight` | once | 2, F32 (8,192 B) | 2048 | `lm_head_mix` / verify's head: `WeightKind::F32`, `n_embd` |
| `output.weight` | once | 0, native (Q6_K / Q8_0) | 2048 x 248320 | `NativeHead::load` from the GGUF (`native_mmvq`); the index row gives `n_vocab = ne1` |
| `token_embd.weight` | once | 0, native (Q6_K / Q8_0) | 2048 x 248320 | `NativeEmbed::load` from the GGUF into mapped host memory (`iq_embed_rows`) |
Counts: 252 native rows (30 x 3 + 10 x 4 + 40 x 3 + 2), 140 BF16 rows, 221 F32 rows; 613 in all. The arena
(`dense.bin` as loaded, every tensor at its `dst_off`) is 54,610,432 B.
**The types the native paths accept** (`native_type_problem`): projections and the head, `native_mmvq_supported`:
Q4_0, Q5_0, Q5_1, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL, IQ4_XS, Q2_0, IQ2_XXS, IQ2_XS, IQ3_XXS, IQ3_S, IQ2_S,
IQ1_M; the embedding, `embed_type_supported` (the `is_iq` set plus BF16): the same minus Q4_0, plus BF16. Any
other type on one of those names (F32, F16, Q4_1, Q2_K, IQ1_S, ...) is refused before anything is written, naming
the tensor, the type, the path and the list. The head also needs `n_embd % 256 == 0` (2048: yes).
**The BF16 rule.** The 140 F32 tensors read as BF16 (40 routers, 40 shexp gates, 30 `ssm_alpha`, 30 `ssm_beta`)
have their low 16 bits zero in every element of both files, as `step3-gdn.md` found: written as BF16 exactly,
`conversions.json` records 140 exact / 0 rounded / max error 0, no `compat-bf16.json`. A file where that fails is
refused with "`<name>` is F32 with N of M values that are not BF16 (low 16 bits set), but the engine reads it as
BF16; --compat-bf16 would round them to nearest-even (a lossy pack, recorded in compat-bf16.json)". `ssm_conv1d`
is BF16-exact too but the engine reads it as F32, so it is copied. `attn_norm` is not BF16-exact (17%) and is
F32.
**The nextn block.** A -MTP file (`nextn_predict_layers 1`, 41 blocks) has `blk.40.*`: an attention layer plus
MoE (its routers BF16, not F32) and `blk.40.nextn.{eh_proj,enorm,hnorm,shared_head_norm}.weight`. 17 non-expert
tensors; none of them, and none of its three expert tensors, is in the trunk's pack. The drafter's pack is the
drafter agent's (`tools/mtp_qwen36_pack.py` per the study).
## 3. The expert profile
`python3 -I tools/make_profile.py --no-base --n-layer 40 --n-expert 256 --text-trace
~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/routes/routes.txt --out data/qwen36-expert-profile.bin`
(the Mac, 14.6 s). The raw `routes.txt` (269 MB, also as `.gz`) was present and used: the E0 trace of the IQ3_XXS
file through llama.cpp 3cf0325 on the M3 Ultra, 214,940 routed tokens (143,091 prefill, 71,849 decode) over the
110-prompt corpus (`README.md`, `summary.json` beside it). Every one of the 10,240 (layer, expert) pairs was routed
at least once (mean entropy 7.37 of 8 bits), so the ranking is wholly from the trace: 10,240 from the trace, 0
filled. The ranking is by count, ties broken by the smaller pair. `read_expert_profile` reads it back on both cards
(section 5).
## 4. Build and test commands
Python (the Mac, `STRATA_GGUF_PY` at the main tree's gguf-py; VM 221 and VM 211 with their own):
python3 -m unittest tools.test_iq_pack tools.test_make_profile # 41 tests: 33 + 8 new, all three hosts
python3 -I tools/iq_pack.py --gguf /models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf --out /models/work/packs/qwen36-iq3
The engine (both cards, the common configure with `-DSTRATA_MMQ_KQUANTS=ON`, the 1080 Ti with
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`):
cmake --build build -j 8 --target strata pack_load_check expert_layout_test model_geometry_test
./build/pack_load_check --native <file>.gguf --pack <dir> # section 5
./build/strata --native <file>.gguf --pack <dir> --tokens 1 --max-context 262144 --kv q4_0 --spec 4 \
--prefill 2048 --expert-profile <dir>/expert-profile.bin # to the step-2 gate, exit 2
## 5. Results
### The packs (both VMs, 2026-10-11)
| Host, file | Pack | Time | `dense.bin` | rows / native / BF16 exact | expert table |
| --- | --- | ---: | ---: | --- | --- |
| VM 221, `/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | `/models/work/packs/qwen36-iq3` | 1.9 s | 54,610,432 B | 613 / 252 / 140 of 140 | == `tests/data/native_experts/qwen36-iq3_xxs.txt`; 11,108,614,144 B of experts |
| VM 221, `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (the plain 40-block file: VM 221's Q4_K_XL is NOT the MTP repo's, see 7) | `/models/work/packs/qwen36-q4` | 2.6 s | same bytes | 613 / 252 / 140 of 140 | 19,671,285,760 B; Q6_K down on layers 1, 34, 38, 39 (the plain file has one more Q6_K layer than the MTP file's 34, 38, 39) |
| VM 221, `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf` (copied from the Mac, sha256 55983c5a..., 22,853,663,008 B, 41 blocks) | `/models/work/packs/qwen36-q4-mtp` | 2.4 s | same bytes | 613 / 252 / 140 of 140; 17 draft tensors left out | == `qwen36-q4_k_xl.txt` up to the file name; 19,635,634,176 B |
| VM 211, `/home/rk/models/Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | `/home/rk/packs/qwen36-iq3` | 2.6 s | same bytes | 613 / 252 / 140 of 140 | == `qwen36-iq3_xxs.txt` |
| VM 211, `/home/rk/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (the MTP repo's file, 41 blocks) | `/home/rk/packs/qwen36-q4` | 2.5 s | same bytes | 613 / 252 / 140 of 140; 17 draft tensors left out | == `qwen36-q4_k_xl.txt` |
The pack is 65 MB (dense 52.1 MiB, tokenizer 9.4 MiB, the rest under 200 KB); nothing of the experts or the
projections is copied. `python3 -m unittest tools.test_iq_pack tools.test_make_profile`: 41 of 41 on the Mac,
VM 221 (numpy 2.2.4) and VM 211.
### VM 221, the RTX 4090 (sm_89), 2026-10-11
Build (`/models/work/qwen36-step4-pack`, the four targets after a fresh configure): 2 min 14 s.
`./build/pack_load_check --native FILE --pack DIR` (`/models/work/logs/qwen36-step4-check-*.log`):
| Pack | arena | native projections | head | embedding (mapped) | check_all | profile | exit |
| --- | ---: | ---: | ---: | ---: | --- | --- | --- |
| qwen36-iq3 | 54,610,432 B, read 11 ms + upload 7 ms | 250 matrices, 1,152,614,400 B (1,099 MiB), 1.8 s | Q6_K 417,177,600 B | Q6_K 417,177,600 B | 40 layers (10 + 30) ok | 10,240 pairs | 0 (3.1 s) |
| qwen36-q4 | same | 250, 1,492,910,080 B (1,424 MiB), 3.2 s | Q8_0 540,344,320 B | Q8_0 540,344,320 B | ok | 10,240 | 0 (5.8 s) |
| qwen36-q4-mtp | same; 259 names in the skip set (the 7 of `blk.40` are not in the index: harmless) | 250 (blk.40's not loaded: the trunk bound), 1,424 MiB | Q8_0 | Q8_0 | ok | 10,240 | 0 (2.4 s) |
Every weight of section 2's table resolves on every layer with the form its site demands (the log lists layers 0
and 3 in full and reports any miss on the other 38: none). The gate run,
`./build/strata --native FILE --pack DIR --tokens 1 --max-context 262144 --kv q4_0 --spec 4 --prefill 2048
--expert-profile DIR/expert-profile.bin` (`qwen36-step4-gate-*.log`): the geometry (31 lines), the VRAM plan
(IQ3_XXS: fixed set 4,019 MiB = weights 1,596 + drafter 520 + KV 1,440 + session 162 + reserve 300; 10,240 of 10,240
slots resident at 19,729 MiB; 9,135 MiB spare), the step-2 gate message, exit 2, for both the IQ3_XXS and the MTP
Q4_K_XL file; no "missing", "wrong form" or other refusal in the 42 lines. `ctest -R "pack_load_check|
expert_layout_test"` with `STRATA_QWEN36_GGUF` / `STRATA_QWEN36_PACK` set: 2 of 2.
### VM 211, the GTX 1080 Ti (sm_61, Pascal), 2026-10-11, under `/home/rk/VM-BUSY`
The same tree (`/home/rk/qwen36-step4-pack`, the submodule copied from the step-3 tree), configured with
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`; the four targets built in 3 min 22 s.
`./build/pack_load_check` (`logs/check-*.log`):
| Pack | arena | native projections | head | embedding | check_all | profile | exit |
| --- | ---: | ---: | ---: | ---: | --- | --- | --- |
| `/home/rk/packs/qwen36-iq3` | 54,610,432 B, read 54 ms + upload 12 ms | 250, 1,099 MiB, 1.7 s | Q6_K 417,177,600 B, 0.5 s | Q6_K, 0.8 s | ok | 10,240 | 0 (3.5 s) |
| `/home/rk/packs/qwen36-q4` (the MTP file) | same | 250, 1,424 MiB, 2.1 s | Q8_0 540,344,320 B, 0.9 s | Q8_0, 1.2 s | ok | 10,240 | 0 (4.7 s) |
The gate run (`logs/gate-*.log`), both packs: the geometry, the VRAM plan, the gate message, exit 2, no refusal.
The plan on the 11 GB card: IQ3_XXS fixed set 4,019 MiB, 6,744 of 10,240 slots (65%) resident at 6,977 MiB;
Q4_K_XL fixed set 4,461 MiB (weights 2,038), 3,573 slots (34%) at 6,535 MiB. `expert_layout_test` all passed;
`ctest -R "pack_load_check|expert_layout_test"` 2 of 2. The lock was held from 20:50 to 20:58 UTC (sync and
packs done beforehand without it: they touch neither the card nor the build cores for more than seconds).
## 7. Not done, surprises, what the brief and the study had differently
- **The gate is before the loads.** `generate.cpp`'s step-2 gate (line 2253) returns before the arena (2510),
the native projections (2520), the head (3282) and the embedding (2424) are touched, so "load every dense weight
... through to the gate" cannot be shown by the gate run alone: `pack_load_check` does those loads in the same
order and is the evidence; the gate run shows the start reaches the gate with the pack in place. The
gate-lifting agent gets section 6's order, including `check_all`, which `generate.cpp` has never called (the
per-layer shape check exists since round 194 and only the parity binaries call it).
- **VM 221's `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` is the plain 40-block file** (733 tensors, 22,360,456,160 B,
no `nextn_predict_layers`), not the MTP repo's as the common file said; the MTP repo's Q4_K_XL (41 blocks, sha256
`55983c5a...`, the file on VM 211 and the Mac, and the one `tests/data/native_experts/qwen36-q4_k_xl.txt` and the
plan's "Q4 number" refer to) was copied to VM 221 as `/models/Qwen3.6-35B-A3B-UD-Q4_K_XL-MTP.gguf` (rsync from the
Mac, 3 min 40 s), so the drafter has `blk.40` on the development card. The two files are different quantization
runs: the plain one has Q6_K down on layers 1, 34, 38, 39 and a 35.6 MB larger expert total.
- **Neither VM's python has `regex`** (PEP 668 refuses `pip install` on VM 221; VM 211 has no pip), hence the lazy
import in `strata_tokenizer.py`. The export is exact without it; `encode` needs it.
- **`check_one` still demanded the indexer rows at hc = 1** (the attention agent's note said the four tensors "are
required only with an indexer", which was true of `qsa_layer` and the window but not of `layout.cpp`). Fixed
here, `[shared]`.
- **The study's step-4 line** had the routers and the SSM gates "F32 to BF16 under `--compat-bf16` with
`compat-bf16.json`"; the census (step3-gdn.md) made that moot and the packs carry no `compat-bf16.json`.
`step2-notes.md` section 3 ("need `--compat-bf16` today, which step 4 decides") is superseded: decided, not needed.
- **`ModelGeometry::n_vocab`** is the Flash-Next default (248,320, which happens to be Qwen3.6's too); the head and
the embedding are sized from `output.weight`'s index row, as `generate.cpp` does.
- Not mine, not done: lifting the gate, the verify window and the first token through this pack, the drafter's pack
from `blk.40`, the chat template check, `generate.cpp` beyond the one-argument dense-load bound.
## 6. The interface other agents consume
- The pack layout of section 2, file by file and row by row. A consumer resolves a tensor by name through
`WeightTable::find`; a native row has `data == nullptr`, `resident == false` after the skip-set load, and
`native_data` / `native_type` after `NativeDense::load`; `output.weight`'s row is shape only and the head is
`NativeHead`; `token_embd.weight` is `NativeEmbed`.
- The load order the gate-lifting agent keeps (it is `generate.cpp`'s after the gate, and `pack_load_check.cpp`'s):
`read_model_geometry` -> `check_model_tensor_forms` -> `expert_layout_load(pack, n_layers, n_expert, n_embd, n_ff)`
-> `NativeDense::served_names(shards, false, skip)` + `output.weight` + `token_embd.weight` -> `pool_bytes(pack,
&skip)` -> `WeightTable::load(pack, arena, pool, &skip)` -> `NativeDense::load(shards, wt, err, false, 0,
n_layers)` -> `check_all(wt, g, err)` (generate.cpp does not call it today; it should, after the dense load) ->
`NativeHead::load(shards, n_embd, wt.find("output.weight")->ne1)` -> `NativeEmbed::load(shards, n_embd, n_vocab)`
-> `read_expert_profile(pack + "/expert-profile.bin", n_layers, n_expert, ...)`.
- `tools/iq_pack.py`: `form_of(name, arch)`, `needs_bf16(name, type, arch)`, `native_type_problem(name, type, arch)`,
`layer_of(name)`, `profile_problem(path, n_layers, n_expert)`, `index_standalone(src, out, model, compat_bf16,
n_trunk)`, `model_arch(model)`; `main` takes `--expert-profile`.
- `tools/make_profile.py`: `read_profile(path, n_expert, n_layer)`, `read_text_trace(path, n_expert, n_layer)`,
`write_profile(path, ranked, n_expert, n_layer)`, `profile_header(path)`, `rank_profile(..., n_layer=)`.
- `tests/core/pack_load_check.cpp`: `pack_load_check --native FILE --pack DIR` (or `STRATA_QWEN36_GGUF` /
`STRATA_QWEN36_PACK`), exit 0 / 1 / 77.
-195
View File
@@ -1,195 +0,0 @@
# Qwen3.6 port, Phase 2 step 4, area `runner`: the gate lifted, the first token held to the oracle and llama.cpp
Working notes, kept as the step was done (2026-10-11, branch `qwen36-step4-runner`, from the step-4 integration
branch `qwen36-step4` = step 3 complete + the pack). The design is `docs/QWEN36-35B-A3B.md` sections 3.5 and 6
(step 4) and 3.5; what the pack carries is `docs/qwen36-port/step4-pack.md` (section 2 the layout, section 6 the load
order); the references are `docs/qwen36-port/oracle-crosscheck.md` (the cases, the tolerance policy, the quantized-mode
gates). This file is the runner half; the drafter is `qwen36-step4-drafter` (mtp.cpp, blk.40), not touched here.
## 1. What this makes the engine do
With `--native <qwen35moe gguf> --pack <dir>` the start no longer stops at the step-2 gate
(`qwen35moe_not_yet`). It makes and prints the VRAM plan as before, then proceeds through the native pack's load
order, the session at hc = 1 with no PLE and no indexer, the expert tiers the plan sized, the prompt path, and the
decode windows, and produces tokens. Measured on the real IQ3_XXS file (VM 221, the 4090), the first token of
"Hello, world! How are you?" (ids 9419,11,1814,0,2500,513,488,30) is 271, and the 16 greedy tokens that follow are
coherent English; the engine's own greedy continuation of the test20 prompt is byte-identical to llama.cpp's.
`--spec 0` / no drafter: the decode windows hold one token each (a window padded with token 0 would verify a draft
nobody made). A native-pack start with `--spec` below 2 raises it to 2 (the verifier's smallest window) and says so;
the drafter plugs in at `generate.cpp`'s `--mtp DIR` block (the `mtp.draft` / `mtp.draft_first` calls in the spec
loop), which is the drafter agent's.
## 2. What changed, where (file:line against `qwen36-step4`)
`generate.cpp` is shared with the drafter agent; every hunk below is in the gate region, the load order, or the
session/decode wiring, in its own commit.
| Site | What | file:line |
| --- | --- | --- |
| the gate | the step-2 gate removed: the qwen35moe block now prints the plan, refuses a plan that does not fit (exit 2), and for a drafter-off start raises `--spec` to 2; it no longer returns at `qwen35moe_not_yet` | `generate.cpp` the `if (g.arch == Qwen35Moe)` block at ~2175 and the drafter-off note at ~2246-2258 |
| the load order | `check_all(wt, g)` after `NativeDense::load`, which `generate.cpp` had never called (step4-pack.md section 6): a pack missing a row or carrying it in the wrong form is refused by name before the first window | `generate.cpp:2532` (after the native projections) |
| the runner | `--teacher-force` (with `--spec-oracle FILE`): every window row commits, the next window starts from the oracle's token, `--dump-logits` writes one row of head logits per position (the window path wrote none), and the run reports the top-1 agreement | `generate.cpp` option 495, flag 1462, usage 671, validation 1910, oracle-length clamp 8128, the window loop 8305-8480 |
| the drafter-off path | one token per window when there is no drafter and no oracle; `--suffix-draft` skipped under teacher forcing | `generate.cpp:8326-8333` |
| `[shared]` verify | the two commit captures skip the indexer key-tail restore when `!g.has_indexer()`: a dense model has no tail, and the first real-file window stopped at "blk.3.indexer.k_norm.weight is missing" after the window had already run | `verify.cpp` `capture_commit` ~1407, `capture_commit_batch` ~1957 |
The Flash-Next path is untouched: the generate.cpp hunks are guarded by `g.arch == Qwen35Moe` or by the native-pack
/ teacher-force conditions, and the verify.cpp change is guarded by `!g.has_indexer()`. The step-3 parity suite is
re-run below as the regression proof.
## 3. The tests (CMake targets)
`cmake/` nothing new; the fixtures are python, in `tests/python/`.
- **`qwen36_runner_fixture.py`** writes the synthetic model at the real per-layer geometry (the prefill harness's
`full4`: 4 layers, three Gated DeltaNet and one full attention, n_embd 2048, GDN 16/32 heads of 128, attention
16/2 of 256, 16 experts top-8 of 512) as a file a native pack can be built from (`token_embd.weight` Q8_0, a type
`iq_embed_rows` serves), builds the pack with `tools/iq_pack.py` and a 4 x 16 expert profile ranking every pair,
and dumps the oracle for the 8-, 11- and 40-token cases both faithfully (`oN`) and with `--act-quant q8`
(`oN_q8`), each with `--all-logits`.
- **`qwen36_verify_test.cpp`** (CTest `qwen36_verify_test`, fixture `qwen36_runner_fixtures`) drives `Verifier` on
that pack as `generate` drives it (the load order, `check_all`, the decode config `layer_verify_compatible`
requires, the cache holding every expert), the step-3 review's HIGH finding (no test drove the window on
qwen35moe). Four parts: one 8-token window's residual after every layer and its head logits per row; the same
rows from eight one-token windows, **bit for bit** equal to the 8-row window (verify.hpp's discipline); 8 + 3
with a commit between; 40 tokens one per window (the oracle's `base_ar` shape).
- **`qwen36_runner_check.py`** (CTest `qwen36_runner_check`) drives the `strata` binary end to end: the 40-token
sequence teacher-forced to the oracle in three chunkings (the oracle's `base_c7`, one chunk, and `base_ar`),
`--dump-logits` per position, and the **mutation-sensitivity gate** (4 KB of `blk.1.ffn_gate_inp.weight` flipped
in a copy of dense.bin must move the logits by more than 1e-2 relative L1).
- The real files: **`tools/qwen36_teacher_llama.cpp`** is llama.cpp's own greedy continuation with the head's
logits per position and the routed experts at probed layers; **`tools/qwen36_compare_logits.py`** is top-1
agreement, KL(ref || engine) per position, the drift gate (one-sided: only a KL that *rises* with position is a
leaking state) and the routed-selection overlap. `ref/qwen36.py` grew `--all-logits` (dump
`result_output_all`, the head at every position); `qwen36_prefill_fixture.py`'s `write` grew `q8_embd`.
### Tolerances
The oracle is F32 weights x F32 activations; the engine runs Q8_0 projections (FP16 GEMV with q8_1 activations) and
Q8_0 experts on int8 dot products, so the reference for the window and runner tests is the **Q8 oracle**
(`--act-quant q8`, oracle-crosscheck.md "Tolerance policy" items 3-4). Per-layer forced (the input forced from the
Q8 oracle's `l_out` of the layer before): 1.5e-2 relative L2 (4x the real file's Q8 `l_out` class, the fixture's
16-expert MoE spreads more). Accumulated over the 4 layers and the recurrence: 5e-2. Argmax must agree with the
Q8 oracle at every position; positions where the F32 and Q8 oracles themselves disagree (near ties) are reported,
not gated.
## 4. Results
### VM 221, the RTX 4090 (sm_89), 2026-10-11
Build: the common configure with `-DSTRATA_MMQ_KQUANTS=ON`, 25 min for the whole tree, 0 errors.
**`qwen36_verify_test`** (the synthetic native pack, 4 layers, 16 experts, every expert resident): PASS, 0 failures.
| check | measured | gate |
| --- | --- | --- |
| 8-token window, `l_out-N` per row accumulated vs the Q8 oracle | 1.9e-3 .. 2.4e-2 | 5e-2 |
| each layer alone, input forced from the Q8 oracle, `l_out-N` | 1.1e-3 .. 3.1e-3 | 1.5e-2 |
| eight one-token windows vs the 8-row window (R and logits) | 0.0 (bitwise) | bitwise |
| 8 + 3 with a commit, `l_out-3` / logits per position (11) vs Q8 | 2.4e-2 / 2.7e-2 | 5e-2 |
| 40 one-token windows, `l_out-3` / logits per position vs Q8 | 3.5e-2 / 3.5e-2 | 5e-2 |
| argmax vs the Q8 oracle (8 / 11 / 40 positions) | 8/8, 11/11, 40/40 | equal |
(Against the F32 oracle the 40-token argmax differs at 3 near-tie positions where the F32 and Q8 oracles disagree.)
**`qwen36_runner_check`** (the `strata` binary, teacher-forced): PASS, 0 failures. Logits per position vs the Q8
oracle: `c7` 2.7e-2, `c40` 2.3e-2, `ar` 4.4e-2 (all <= 5e-2); argmax equal at every unambiguous position (the `ar`
run has 3 near-tie positions excluded, the same 1/4/23); the two prompt chunkings agree (1.4e-2), prompt vs decode
agree (2.1e-2); **the 4 KB mutation moves the logits by 2.1e-1 relative L1** (> 1e-2).
**The real files, greedy, teacher-forced to llama.cpp's own greedy continuation** (3 prompts from the regina
corpus x 64 tokens, context 8192, `--kv fp16`, the full profile-filled cache):
IQ3_XXS on the 4090:
| prompt | top-1 agreement | mean KL | max KL | drift (Spearman) |
| --- | --- | --- | --- | --- |
| test20 | 64 / 64 | 1.1e-3 | 2.1e-2 | -0.63 (falls) |
| task-prime-add-test | 64 / 64 | 6.6e-3 | 1.5e-1 (one near tie) | +0.12 (flat) |
| task-psim-collide | 64 / 64 | 1.9e-3 | 1.8e-2 | -0.06 (flat) |
No monotone positional drift on any prompt (Maya's quantized-mode gate: the drift is one-sided; a falling or flat
KL is not a leaking state). The engine's own greedy text for test20 is byte-identical to llama.cpp's (the
qualitative check). Q4_K_XL on the 4090 (the plain 40-block file, pack `qwen36-q4`):
| prompt | top-1 agreement | mean KL | max KL | drift (Spearman) |
| --- | --- | --- | --- | --- |
| test20 | 61 / 64 (3 near-tie quant flips) | 7.4e-3 | 1.5e-1 | -0.57 (falls) |
| task-prime-add-test | 64 / 64 | 1.7e-3 | 3.5e-2 | -0.08 (flat) |
| task-psim-collide | 64 / 64 | 4.2e-4 | 7.2e-3 | -0.20 (falls) |
The 1080 Ti was not used for the Q4 fit (the card was under a sibling's lock); the 4090 Q4 run is `--expert-cache
auto`, the whole file resident.
The step-3 parity suite, re-run to prove the Flash-Next path and the kernels are unchanged by the gate lift and the
`[shared]` verify edit (`ctest -R` over qsa_parity, qsa_prompt_attn_parity, kv_hybrid_parity, kv_stream_parity,
qsa_topk_parity, qsa_dense_parity, gdn_parity, router_top10_parity, shared_expert_parity, qwen36_seam_parity,
qwen36_block_test, prefill_qwen36, native_expert_parity): **100% of 33 tests passed, 0 failed** (pack_load_check
skipped, it needs the real-file STRATA_QWEN36_GGUF / _PACK env). Every step-3 parity target and both new runner
tests pass; the Flash-Next geometry's parity is unchanged.
### VM 211, the GTX 1080 Ti (sm_61), 2026-10-11 21:38-21:42 UTC
Run after the notes above were first written, once the card's lock freed (held by sibling agents with nothing
running; released 21:34). Tree `/home/rk/qwen36-step4-runner`, logs `/home/rk/logs/step4-runner-*.log`.
- Configure (the common line, `-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=61`) and an incremental
build from the pack tree's objects: 3 min 4 s, 0 errors.
- `qwen36_verify_test`: PASS, 0 failures. `result_output_all` per position (40): worst rel L2 F32 5.65e-02, Q8
3.46e-02 (gate Q8 <= 5e-02); argmax equals the Q8 oracle's at 40 of 40, the F32 oracle's at 37 of 40 (the same
three near ties, positions 1, 4, 23, as on the 4090).
- `qwen36_runner_check.py`: PASS, 0 failures. c7 worst rel L2 F32 2.05e-02 / Q8 2.55e-02; c40 2.32e-02 / 2.26e-02;
ar (positions 1..39) 4.35e-02 / 4.37e-02, argmax 36 of 36 unambiguous; c7 vs c40 rows 35..39 rel L2 1.32e-02; c7
vs ar 2.12e-02; the 4 KB mutation of `blk.1.ffn_gate_inp.weight` moves the logits by rel L1 2.05e-01.
- The real-file comparison against llama.cpp (three prompts, IQ3_XXS) did **not** run: the teacher fixtures
(`/home/rk/qwen36-step4-teacher/<prompt>/prompt_ids.txt`, `eng/*.f32`) were never synced to VM 211, so all three
engine runs exit 2 on "invalid token id" and the comparisons on a missing file. Owed to step 5 along with the Q4
fit at 11 GB; the card has since been taken by another service (section 5).
### VM 221, round 8 (2026-10-11 21:41 UTC): the drafter's VRAM term and the speculation rate
`vram_plan_test` with the drafter's whole share (its K/V over the context, the draft head subset, the ids): all
passed. The real drafter (`--mtp`, 4-token windows, 64 greedy tokens on the `iq3-test20` prompt, `--prefill 2048
--max-context 8192 --kv fp16 --expert-cache auto --suffix-draft 0`):
| file, draft pack | drafts accepted | tokens per round | drafting ms/round | drafter VRAM | decode tok/s |
| --- | --- | --- | --- | --- | --- |
| IQ3_XXS, `qwen36-mtp-draft-full` | 44 of 57 (0.772) | 3.20 | 2.30 | 524 MiB | 317 |
| IQ3_XXS, `qwen36-mtp-draft` (subset head) | 43 of 60 (0.717) | 3.05 | 1.38 | 695 MiB | 326 |
| Q4_K_XL (plain file), `qwen36-mtp-draft` | 40 of 75 (0.533) | 2.54 | 1.54 | 745 MiB | 246 |
| IQ3_XXS, no `--mtp` (one-token windows) | - | 1.00 | - | 0 | 112 (1 token) |
The Q4 file's lower acceptance is expected: the draft pack comes from the Q4_K_XL-MTP file's `blk.40`, drafted
against the plain Q4_K_XL trunk; the drafter notes (step4-drafter.md) measured 77% teacher-forced on the MTP file
itself. Logs `/models/work/logs/spec-*.log`, `r8-vram-plan-test.log`.
## 5. Not done, surprises
- **The 1080 Ti pass** of steps 2-4 ran at 21:38 (section 4): build, verify test and runner check pass; the
llama.cpp real-file comparison is owed (fixtures never synced). Since 2026-10-12 22:04 UTC the card runs another
session's Flash-Next coder service (`unbiased-strata.service`, 10.9 GB, 100% busy) and is off limits.
- **The Q4 fit at 11 GB** was not measured (the same lock, then the service); the Q4 run above is the 4090's. The pack notes
(step4-pack.md section 5) record the plan on the 11 GB card (Q4_K_XL fixed set 4,461 MiB, 34% of slots resident),
so a reduced-context Q4 run there is the remaining 1080 Ti item.
- **The chat template** (`make test-chat-parser MODEL=<gguf>`): on Qwen3.6's template a tool call whose required
parameter is not written first was silently dropped (0 tool calls). Filed REGINA-104. Resolved at integration
(e73adc6): the template does route to the Qwen3-Coder parser the any-argument-order patch covers; the patch was
simply never applied, because only `make build` applied it and every VM tree was configured with cmake directly on
a copied submodule. CMake now applies it at configure time; with the rebuilt `libllama-common` the test passes on
VM 221 for all four orders.
- **The argmax near ties.** On the synthetic 40-token `base_ar` case the F32 and Q8 oracles disagree at 3 positions
(1, 4, 23); the engine matches the Q8 oracle at all 40. A position where the two references disagree cannot
discriminate the engine, so the tests gate against the Q8 oracle and report those positions.
- **The real file's single-position KL spikes** (task-prime-add-test, 1.5e-1 at position 40) are near ties where
top-1 still agrees; the mean KL is 1e-3 to 7e-3.
## 6. The interface other agents consume
- `strata --native FILE --pack DIR [--spec T] [--mtp DIR] --prefill CHUNK` now runs a Qwen3.6 pack to tokens.
Drafter off: omit `--mtp`; the windows are one token each. `--spec-oracle FILE --teacher-force` holds the engine
to a reference continuation and writes one logits row per position with `--dump-logits`.
- `ref/qwen36.py --all-logits` dumps `result_output_all` (n_tok x n_vocab, the head at every position of the last
chunk); `tools/qwen36_teacher_llama.cpp` is the llama.cpp reference (logits.f32, continuation.txt, routes.txt);
`tools/qwen36_compare_logits.py` scores top-1, KL and the drift gate.
- The runner tests: `qwen36_verify_test <fixture dir>`, `qwen36_runner_check.py --strata S --fixture DIR`, both from
`qwen36_runner_fixture.py --out DIR`.
-521
View File
@@ -1,521 +0,0 @@
# Qwen3.6 port, step 5, first part: serving on the 4090, and what broke below full residency
Branch `qwen36-step4`, 2026-10-13, VM 221 (RTX 4090, 24 GB; the user handed the box to this work at 02:05 UTC and the
Flash-Next service on it was stopped). Tree `/models/work/qwen36-step4`, binary `build/unbiased-strata`, logs under
`/models/work/serve/`. The 1080 Ti (VM 211) is off limits: another session's service runs there.
## The serve command
```
./build/unbiased-strata --model /models/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --pack /models/work/packs/qwen36-q4 \
--mtp /models/work/packs/qwen36-mtp-draft-full --ctx 262144 --threads 8 --host 127.0.0.1 --port 18090 -- --kv q4_0
```
`--mtp` takes a Qwen3.6 draft pack (`tools/mtp_qwen36_pack.py`); `qwen36-mtp-draft` carries a `draft_vocab.bin`
subset, `-full` has none. Everything after `--` goes to the engine: `--vram-cap MiB`, `--ram-cap GiB`, `--kv
fp16|q4_0|int8`, `--expert-cache N|auto`, `--pcie-frac F`, `--prompt-cache N`, `--vram-reserve-mib`.
## Faults found in order, all fixed on the branch
| # | Symptom | Cause | Fix |
| --- | --- | --- | --- |
| 1 | `unbiased-strata: missing file: .../qwen36-mtp-draft-full/draft_vocab.bin` | the front end required the Flash-Next draft vocabulary subset | optional in the front end as it already was in the engine (3a806b5) |
| 2 | first request: 220 tokens generated, then `saving a conversation checkpoint failed` (`conversation snapshot: invalid model geometry`, then `invalid indexer running-state target`) | the prompt-cache checkpoint and the snapshot rejected a geometry with no indexer (idx heads / key dim 0) and no hyper-connection rate, and demanded the indexer's tail / dead / block-position / pooled buffers | zeros allowed where `has_indexer()` is false and `hc` is 1, no indexer buffers or block positions for dense attention, pooled rows 0 (3a806b5). Two-turn conversation: 1 then 2 checkpoints, prefix reused |
| 3 | Q4 at 262,144: `2, 3! 5, 7, 11, !!!!!!...` (token 0 forever); IQ3 under any `--vram-cap` the same; both files fine at 8K / 32K; IQ3 at 256K fine | **the pool's native-pack phases iterated the canonical Q2_0 widths (FF 640, H 2560) instead of the layer's (512, 2048)**: every expert miss computed on the CPU wrote 512 rows past its output row. The runner's and drafter's tests all ran with every expert resident, so the miss path had never executed on Qwen3.6 | `run_split_multi_native` at `NativeFmt::n_ff / n_embd`; `native_fmt` refuses wider layers; `pool_native_widths_test` (22d72e6) |
How fault 3 was isolated (each row one serve, the prime-numbers prompt, greedy, `bangs` = count of `!` in 120-200
tokens):
| Run | file | ctx | KV | slots resident | misses on | result |
| --- | --- | --- | --- | --- | --- | --- |
| e1 | Q4 | 8192 | fp16 | 10,240 / 10,240 | - | correct, 362 tok/s |
| e3 | Q4 | 262,144 | q4_0 | 9,980 | CPU + DMA | `2, 3, 5, 7, !!!` |
| e2 | Q4 | 262,144 | q4_0, `--vram-cap 20480` | 8,132 | CPU + DMA | `!!!` from the first token |
| e4 | Q4 | 262,144 | fp16 | 8,120 | CPU + DMA | `!!!` |
| e5 / e6 | Q4 | 8192 / 32,768 | q4_0 | 10,240 | - | correct, 354 / 356 tok/s |
| t1 | IQ3 | 262,144 | q4_0, `--vram-cap 15360` | 10,212 | CPU + DMA | `!!!` |
| t2 | Q4 | 262,144 | q4_0, `--vram-reserve-mib 1200` | 9,838 | CPU + DMA | `!!!` (so not VRAM pressure) |
| t3 | Q4 | 8192 | fp16, `--expert-cache 8000` | 9,587 | CPU + DMA | `!!!` (the cheap reproduction) |
| t4 | Q4 | 8192 | as t3, `--pcie-frac 1.0` | 9,587 | DMA only (GPU computes) | **correct**, 305 tok/s |
| t5 | Q4 | 8192 | as t3, `--pcie-frac 0.0` | 9,587 | CPU only | `!!!` |
| t6 / t7 / t8 | Q4 ggml dots only / IQ3 / one worker | 8192 | as t5 | 9,587 | CPU only | `!!!` all three: not the kernels |
| fix | Q4 | 8192 | as t5 | 9,587 | CPU only | correct, 328 tok/s |
| fix | Q4 | 262,144 | q4_0 | 9,980 | CPU + DMA | correct, 322 tok/s |
| fix | IQ3 | 262,144 | q4_0, `--vram-cap 11264` | 5,762 (56%) | CPU + DMA | correct, 169 tok/s; 63,526 VRAM hits of 73,553 lookups |
| 4 | Pascal host (VM 211, step5-1080ti, REGINA-106): with CPU-computed misses iq3-test20 51/64 top-1, KL 0.84; Q4 52-54/64, KL 0.25; DMA misses correct; deterministic; `--spec 1` changes it | **the multi-token CPU dispatch addressed token t's activation at t x 2560 and its output row at i x 2560** (the canonical widths pulled in by `using namespace`), while the window publishes at the layer's 2048: every token after a group's first used another token's activation. Named by the Codex review of 22d72e6; the 4090's serve looked right because its text was checked, not its logits | the dispatch at the layer's width with refusals (the commit after 22d72e6); after it on VM 211 all three IQ3 prompts 64/64 (KL 1.4e-3 / 4.8e-3 / 2.0e-3), q4-test20 62/64 KL 6e-3, q4-prime 64/64 KL 8e-4, CPU misses forced. The ladder points taken with the old binary are rerun |
| 5 | the 4090 sweep's `--ram-cap 12` points: "ArenaExpertSource: the expert arena needs 18.32 GiB ... memory limit is 12.00 GiB ... --mmap-experts" | the plan chose RAM copies but the arena source still pinned the whole file | the engine picks the mapped tier with profile-ranked RAM copies itself when the arena exceeds the limit or available RAM (same commit) |
| 6 | planner (Codex review): a full-head draft pack charged 515 MiB the drafter never allocates; k8v4 undercounted the drafter's INT8 K/V by 60 MiB; a lowered context was printed but not applied | | all three in the same commit; multi-GPU helpers refused for this geometry |
| 7 | second Codex review of fa69e82: the front end kept validating and advertising the requested `--ctx` when the engine's plan lowered it; the automatic mapped tier ignored an explicit `--shared-expert-arena` and the multi-GPU residency rules; the plan's session term keeps the RoPE table at the requested context | | the front end takes the context from the engine's `READY <n>` line and bounds requests by it; the automatic choice is skipped with a shared arena or the helpers. The RoPE table at a lowered context is left as a conservative overcount (at most 32 MiB from 262,144 to 131,072), noted here rather than threaded through the plan |
## What the 4090 serves now
| file | ctx | fixed set | experts resident | VRAM free after load | short answer decode | drafts accepted |
| --- | --- | --- | --- | --- | --- | --- |
| IQ3_XXS, `-full` draft | 262,144 | 4,331 MiB (weights 1,596, drafter 831, KV 1,440, session 162, reserve 300) | 10,240 / 10,240 (10.35 GiB) | 8,758 MiB | 319-359 tok/s | 157 / 181, 223 / 237 |
| Q4_K_XL, subset draft | 262,144 | 4,823 MiB (weights 2,038, drafter 882, KV 1,440, session 162, reserve 300) | 9,980 / 10,240 | 434 MiB | 322 tok/s | 149 / 152 |
Also checked through the HTTP front end: streaming (SSE chunks, `reasoning_content` deltas), a two-turn
conversation with checkpoint reuse, a tool call (`<tool_call><function=read>` emitted; the earlier "!!!" inside its
arguments was fault 3). The response's `model` field is now the GGUF's base name (was the Flash-Next constant).
## Observations for the measurements
- The RAM tier reports `expert copies in RAM: 0` on this host: with 62 GB the whole expert arena is pinned host
memory (`cudaHostRegister PORTABLE`, 18.3 GiB for Q4), and a miss is served from it by DMA or the CPU; `ram_reads`
and `file_reads` on `/health` stay 0. On a 12 GiB host the arena cannot hold the file and the mapped-from-disk
tier is what the ladder measures (`--ram-cap` emulates it here).
- Checkpoint reuse: the second turn reused 27 of 278 prompt tokens. Cause and the opt-in that lifts it: the A5
section below, check (d).
- `expert cache ... policy is` prints an empty policy name for native packs (cosmetic).
- At 262,144 the Q4 fixed set leaves 19.3 GiB for experts; 9,980 slots fit; the planner's "10240 of 10240 (100%)"
line and the cache's "9980 slots" disagree by the 700 MiB runtime reserve the cache keeps; the plan line should
say what the cache will actually hold.
## A5 on the 4090: the serving checks, after the streaming fix (REGINA-110)
**The fault.** With `"stream": true` the answer arrived as one `content` delta before the final chunk; only
`reasoning_content` streamed. Not the parser: `run()` in `frontend/main.cpp` cleared the content of every partial
parse together with its tool calls, a rule that came with 46c46ec so that partial tool-call JSON (closed and
normalized by the parser on each token) could never change text already sent. That holds for a call's arguments,
not for the answer. c3b41cc: reasoning and content are published as they arrive, tool calls once from the complete
parse (`StreamParse`); a partial parse whose content does not extend what was sent publishes no content until it
does; a non-streaming request is parsed once instead of after every token. **A tool call still arrives whole**, in
one delta (name, id and full arguments) when the message ends; the text before a call streams.
`make test-chat-parser` now feeds seven responses a character at a time (reasoning on and off, tools declared and
not called, text before a call, one and two calls) and requires the pieces to add up to the whole parse, the answer
to arrive in many deltas and each call in one; it passes on the IQ3_XXS and Q4_K_XL files. The ticket's request on
the final binary: 200 content chunks of 203 (was 1 of 3).
**The checks.** VM 221, binary sha256 `46c5747f23dcbdeb` (c3b41cc), `--mtp qwen36-mtp-draft --ctx 262144 --threads
8 ... -- --kv q4_0`, greedy, client and server on the VM (`/models/work/serve/a5-20261013/`: `a5.py`, `serve.sh`,
one `.json` and `.log` per configuration). All nine checks pass in all three configurations.
| check | Q4_K_XL, no cap (9,980 slots) | Q4_K_XL, `--vram-cap 11264` (2,910 slots) | IQ3_XXS, `--vram-cap 6144` (809 slots) |
| --- | --- | --- | --- |
| (a) chat, not streamed, thinking off: "capital of France" | pass, 0.15 s | pass, 0.54 s | pass, 0.54 s |
| (a) chat, not streamed, thinking on: 17 x 23 = 391 | pass, 314 tokens at 313 tok/s | pass, 314 at 76 | pass, 410 at 70 |
| (b) stream, thinking on: reasoning deltas, first, largest gap | 1,087, 0.081 s, 14.1 ms | 467, 0.293 s, 92.8 ms | 418, 0.348 s, 78.6 ms |
| (b) the same request: content deltas, first, largest gap | 89, 3.616 s, 13.8 ms | 82, 5.803 s, 61.6 ms | 53, 6.181 s, 82.3 ms |
| (b) the same request: tokens, decode, largest gap between any two deltas | 1,179 at 303 tok/s, 14.1 ms | 552 at 83, 92.8 ms | 474 at 72, 82.3 ms |
| (b) stream, thinking off (the ticket's request): content deltas, first, largest gap | 212 of 213 tokens, 0.076 s, 11.5 ms | 203 of 204, 0.330 s, 53.8 ms | 209 of 210, 0.345 s, 64.2 ms |
| (c) tool round trip, not streamed: call, result, answer | pass: `get_weather {"city":"Paris"}`, `tool_calls`, then "17 C with light rain", `stop` | pass | pass |
| (c) tool round trip, streamed | pass: reasoning 658 deltas, the call in 1 delta at 2.40 s; the answer in 14 content deltas | pass: 517 reasoning deltas, call in 1 at 5.40 s; 15 content deltas | pass: 173, call in 1 at 2.86 s; 18 content deltas |
| (c) tools declared, not called, streamed, thinking on: content deltas, first, largest gap | 73, 2.597 s, 14.0 ms | 74, 10.318 s, 62.2 ms | 81, 12.442 s, 81.1 ms |
| (c) the same, thinking off | 76, 0.032 s, 11.4 ms | 69, 0.067 s, 41.7 ms | 66, 0.093 s, 41.9 ms |
| (d) three-turn chat, tokens reused of the prompt per turn | 0 / 23, 18 / 129, 124 / 172 | 0 / 23, 18 / 133, 128 / 176 | 0 / 23, 18 / 178, 173 / 246 |
"First" is from the request to that delta, so with thinking on the first content delta comes after the reasoning.
Deltas come in bursts of an accepted draft window (median gap 0.05-0.1 ms); the largest gap is one verify round,
longer under a cap where it waits on expert misses. No keepalive comment was needed in any run.
**(d) Why the reused prefix is short, and what lifts it.** The engine keeps a checkpoint at the last
`<|im_start|>` of each prompt and one at the end of each reply. The next request reuses the second only if it
renders the reply as it was generated, and in a plain chat Qwen3.6's template does not: a reply before the last
user message is rendered without its `<think>` block (with thinking off, without the empty `<think>\n\n</think>`
the generation prompt carried), whether or not the client sends `reasoning_content` back. The tokens leave the
generated ones right after the assistant header, and the reuse is the previous prompt less its 5-token header: 18
of 129, 124 of 172, and the 27 of 278 above. Each turn rereads the last reply and the new message, never the older
history. Not an engine fault. Two cases reuse the reply too:
- a tool loop: a reply after the last user message keeps its reasoning in the template. pi's three requests (check
e): 0 of 1,604, then 1,867 of 1,948 and 2,047 of 2,118;
- `"chat_template_kwargs": {"preserve_thinking": true}` with `reasoning_content` sent back, which the front end now
passes to the template (3aa9eed; binary `e4d8ec0c07473e13`): four turns reuse 0 / 22, 551 / 569, 1,010 / 1,027,
1,365 / 1,382. Opt-in, because the earlier reasoning then stays in the context the model reads. Not every turn
hits: in two of eight such turns the re-rendered reply did not match the generated tokens (578 of 1,330; 18 of
1,138) and the request fell back to the header checkpoint; which replies re-tokenize differently was not traced.
**(e) pi.** pi 0.85.1 on the Mac, its own agent directory (`PI_CODING_AGENT_DIR`, the user's `~/.pi` untouched),
provider `openai-completions` at the engine through an SSH tunnel, Q4_K_XL no cap, `pi -p --mode json`: it wrote
`primes.py` with its `write` tool, ran it with `bash`, and reported `2 3 5 ... 71`. Three requests, two tool calls,
80 thinking deltas and 82 text deltas seen by pi; nothing dropped by the parser.
**Tests.** The Qwen3.6 ctest subset on the free card (`ctest -R "qwen36|vram_plan_test|pool_native_widths_test"`):
21 of 21. `make test-frontend` and `make test-chat-parser` pass. The engine is untouched by these two commits, so
no logits comparison was owed.
**Seen, then chased.** The same greedy request does not always generate the same tokens on one server (check b,
thinking on, Q4 no cap: 632 tokens in one pass, 1,179 in the next). Traced in the next section: not a fault.
Images (mmproj) were out of scope.
## The same greedy request, different tokens: which paths differ, and by how much
2026-10-13, VM 221, binary `11da5388afdfabcb`. The engine was driven on its own stdin protocol (`unbiased-strata
--engine --serve ...` with the front end's arguments, `GEN <max_new> <ids>`), so the record is token ids. Two
prompts from A5, rendered by the front end: `think` (26 tokens, "What is 2+2? Answer, then write three sentences
about addition.", thinking on) and `nothink` (25 tokens, the lighthouse request, thinking off), `max_new` 3,000.
Material in `/models/work/serve/nd-20261013/` (`nd.py` the driver, `cmp.py`, `trdiff.py`, `acc.py`, one `.jsonl` of
token ids and one engine log per run, 23 GB of logit dumps).
**Verdict: benign.** No state leaks between requests. The output is a pure function of the request and of which
of three numerically different, individually correct paths each number went through; two things move a request
between those paths from one pass to the next:
1. **Where an expert is computed.** A resident expert and one read over PCIe (DMA) run the GPU kernel (llama.cpp's
CUDA arithmetic: activations as Q8_1); a miss computed on the CPU runs ggml's CPU kernel (activations as Q8_K).
The two round differently, as llama.cpp's own CPU and CUDA back ends do. The adaptive tier (`--adapt-every`, 4
rounds) swaps routed-but-missing experts into VRAM and keeps them across requests, so the second pass of a
request finds experts on the card that the first computed on the CPU. It settles: once the cache stops
changing the output stops changing.
2. **How the prompt's state was built.** A part of at most `--short-read` (64) tokens and everything a checkpoint
or the live session supplies went through the verify windows; a longer part read from token 0 goes through the
batched prompt path, which is different arithmetic (step4-runner.md: the two agree to 2.1e-2 on the fixture).
Restoring a checkpoint is exact; what differs is a state made by decode against the same state re-read in a batch.
With misses present a third input reaches the output through (1): the lookup drafter's policy picks window sizes
from measured round times, the adaptive tier counts rounds, and the PCIe share of a layer's misses is a fraction
of the misses in that window. With `--suffix-draft 0` a fresh engine gave the same tokens with and without the
tracing below (which slows every window); with the default it gave 557, 554 and 555 tokens for `think`. With
every expert resident the window shape does not reach the output (the window is bitwise independent of its shape).
**Which configurations repeat.** Ten requests of each prompt, alternating, on one engine unless noted:
| configuration | misses run on | distinct outputs, `think` / `nothink` | tokens generated |
| --- | --- | --- | --- |
| IQ3_XXS, 262,144, q4_0, no cap (10,240 resident) | - | 1 / 1 | 480 / 197 |
| the same, `think` alone 10 times (21 of 26 reused) and with `--prompt-cache 0` | - | 1, the same tokens | 480 |
| Q4_K_XL, 8,192, fp16 (10,240 resident) | - | 1 / 1 | 664 / 218 |
| Q4, 8,192, `--expert-cache 8000 --pcie-frac 1.0`, adaptive tier on or off | GPU (DMA) | 1 / 1, **the all-resident tokens** | 664 / 218 |
| Q4, 8,192, `--expert-cache 8000 --pcie-frac 0.0 --adapt-every 0` | CPU, fixed set | 1 / 1 | 632 / 191 |
| the same with the adaptive tier | CPU, changing set | 7 / 6, the same from the 7th request | 511, 557, 639, 633, 1,451, 478, 479 x 4 |
| Q4, 262,144, q4_0, no cap (9,980 slots): the A5 configuration | CPU (0.05% of lookups) | 3 / 3, the same from the 3rd | 557, 620, 553 x 8 / 221, 213, 214 x 8 |
| the same, `--prompt-cache 0` | CPU | the tokens of the row above | |
| the same, `--adapt-every 0` | CPU, fixed set | 1 / 1 | 558 / 211 |
| the same, `--suffix-draft 0` | CPU | 2 / 3 | 550, 551 x 9 |
| the same, `--mtp-max-t 1 --suffix-draft 0` (6 requests) | CPU | 4 / 2 | 561, 552, 1,014, 552 x 3 |
| the same, a new engine for every request | CPU | 1 / 1 | 557 / 196 |
Every configuration with one path is bit-repeatable; the only ones that are not have CPU misses and a cache that
is still changing. The checkpoint cache, the drafter and the lookup drafter are not sources. The second cause,
with every expert resident (IQ3 no cap; Q4 at 8,192), one engine against a new engine reading from token 0:
| request | state from | tokens | first difference |
| --- | --- | --- | --- |
| 258-token prompt, three times | 0 reused, then 253 reused + 5 | identical, and identical to a new engine | - |
| `think`, its 480 / 664 generated tokens and a second user turn (529 / 713) | the live session (505 / 690 reused) or the header checkpoint (524 / 708) | identical to each other | |
| the same on a new engine | the batched prompt path, all of it | IQ3 554 against 495, Q4 437 against 401 | token 191 / 140 |
| a 73-token second turn | 21 reused + 52 through the windows, or 68 reused | identical to each other | |
| the same on a new engine | 73 read from 0 | IQ3 890 against 494, Q4 465 against 438 | token 61 / 61 |
**The margins where they part, and the accuracy of every state.** `STRATA_SERVE_LOGIT_TRACE=FILE` (new, off by
default) writes the head's five largest logits, the window and its misses per emitted token, and
`STRATA_SERVE_LOGIT_DUMP=PREFIX` the whole row (the last window's rows past the stop token included);
`tools/qwen36_teacher_llama.cpp` grew `--prompt-ids` and `--force-ids`, so llama.cpp (F16 K/V, the 4090) is
teacher-forced along each run's own tokens and every position of every run is scored, with the path that run took. Margins are logit differences between the two tokens chosen.
| first difference | this pass | the other pass | llama.cpp |
| --- | --- | --- | --- |
| Q4 no cap, `think`, request 1 against 2, token 249 | 0.03 for A | 0.23 for B | 0.16 for B |
| request 1 against 3, token 245 | 0.10 for A | 0.78 for B | 0.09 for B |
| request 3 against 4, token 531 | 0.007 for A | 0.20 for B | 0.31 for B (its own pick is a third token, 0.12 above B) |
| IQ3 no cap, session state against a batched re-read, token 191 | 0.27 | 0.34 | 0.03 |
| Q4 8,192, the same, token 140 | 0.08 | 0.03 | 0.012 |
| IQ3 / Q4 second turn, windows against batched, token 61 | 0.09 / 0.11 | 0.37 / 0.08 | 0.32 / 0.03 |
Over the common prefix two passes differ by a mean of 0.12-0.13 logits on the reference's 20 largest (KL 1.4e-3
to 2.1e-3 between them), the size of each pass's distance from llama.cpp. Every state against llama.cpp, the
whole run and its first 64 positions (the rule: 62 of 64, mean KL below 1e-2):
| run, path | positions | top-1 | mean KL | max KL | first 64: top-1, mean KL |
| --- | --- | --- | --- | --- | --- |
| Q4 8,192 fp16, all resident (serve) | 664 | 660 (99.4%) | 8.3e-4 | 0.077 | 64, 5.6e-4 |
| Q4 8,192, CPU misses, `--expert-cache 8000`, fixed (0.7% of lookups) | 632 | 624 (98.7%) | 8.9e-4 | 0.053 | 64, 5.5e-4 |
| Q4 8,192, CPU misses, `--expert-cache 4000`, fixed (33% of lookups) | 547 | 542 (99.1%) | 8.9e-4 | 0.046 | 64, 1.3e-3 |
| Q4 no cap 262,144 q4_0, requests 1 / 2 / 3 / 4 of `think` | 555 / 630 / 557 / 553 | 98.4 / 98.4 / 98.7 / 98.6% | 3.4e-3 / 3.3e-3 / 4.0e-3 / 3.8e-3 | 0.08 / 0.30 / 0.16 / 0.13 | 63, 1.8e-3 to 2.1e-3 |
| IQ3 no cap 262,144 q4_0, second turn: session state / batched re-read | 495 / 554 | 98.8 / 99.3% | 3.4e-3 / 4.7e-3 | 0.11 / 0.10 | 64, 1.4e-3 / 64, 1.0e-3 |
| IQ3, 73-token second turn: windows / batched | 494 / 890 | 98.2 / 98.5% | 4.1e-3 / 4.0e-3 | 0.15 / 0.14 | 62, 3.5e-3 / 63, 1.4e-3 |
| Q4 8,192, second turn: session state / batched re-read | 401 / 437 | 99.8 / 99.3% | 9.4e-4 / 8.1e-4 | 0.023 / 0.033 | 64, 2.5e-4 / 64, 2.0e-4 |
| Q4 8,192, 73-token second turn: windows / batched | 438 / 465 | 99.3 / 99.4% | 9.0e-4 / 1.5e-3 | 0.021 / 0.12 | 64, 8.3e-4 / 63, 6.2e-4 |
| `strata --teacher-force`, 400 tokens of the all-resident run: resident / DMA / CPU 8000 / CPU 4000 / CPU 4000 fixed | 400 | 393 / 393 / 396 / 396 / 395 | 9.2e-4 / 9.2e-4 / 9.6e-4 / 7.9e-4 / 8.8e-4 | 0.028 to 0.036 | 63 or 64, 3.6e-4 to 5.9e-4 |
Every top-1 disagreement with llama.cpp in these runs (113 in 9,912 positions) sits where llama.cpp's own margin is
under 0.75 logits; one position in 20 to 25 has a top-2 gap under 0.5, so a greedy run of 500 tokens meets some
twenty places where a pass can turn. The teacher-forced resident and DMA dumps are the same bytes (`cmp`). No
rising drift: Spearman(position, KL) is between 0.00 and +0.13 in every run but the IQ3 batched re-read (+0.20, KL
3.2e-3 in its first half and 6.1e-3 in its second).
The 262,144 rows carry the q4_0 K/V against llama.cpp's F16 (mean KL 3-5e-3 where the fp16 rows have 8e-4 to
1.5e-3); the K/V format is the likely reason (not isolated here), and it is in every pass alike.
**For a run that must repeat.** `--pcie-frac 1.0` (every miss on the GPU: the all-resident tokens whatever the
cache holds, at the DMA path's cost; only while no layer of a window has more than 16 distinct misses, past which the
rest run on the CPU, see the REGINA-111 section at the end), or `--adapt-every 0 --suffix-draft 0` (the miss set fixed, no timed policy).
A conversation that continues on one engine still differs from the same prompt read from token 0 on another.
**Not checked.** The 1080 Ti (VM 211, off limits); a capped Q4 or IQ3 with thousands of misses per request beyond
the `--expert-cache 4000` rows; sampled (temperature above 0) requests; requests cancelled mid-generation followed
by the same prompt; the q4_0 K/V's own share of the 262,144 rows' KL. `--teacher-force` with `--mtp` committed
the drafter's guesses as if they were the oracle's tokens (70 of 400 top-1 on a run that scores 394 without it): it
is now refused.
## A5 on the 1080 Ti: the serving checks at the branch head
2026-10-13, VM 211 (GTX 1080 Ti 11,264 MiB, sm_61, 14 vCPU, 52 GB; the box was free), tree at 542b53b (the streaming
fix c3b41cc, `preserve_thinking` 3aa9eed, the logit diagnostics c7825b4), built by `/home/rk/build-step4.sh`:
`unbiased-strata` sha256 `4e161358c8fd20c1`, `strata` `a44d896ccb25ff98`. The ladder on this card was measured with
7ebc9e5 (`e6c8bbf4cfb16e09`); the engine source differs from it by the diagnostics and the `--teacher-force --mtp`
refusal only (`generate.cpp`, 52 lines). Material: `/home/rk/bench/a5-1080ti-20261013/` (`logits/`, one `.json`,
`.log`, `.summ.txt` per configuration, `speed/`), drivers `/home/rk/bench/a5-1080ti-job1a.sh` and `job1b.sh` there.
**Tests.** `ctest -R "qwen36|vram_plan_test|pool_native_widths_test"` on the free card: 21 of 21 (668 s).
**The accuracy rule on this binary** (teacher-forced logits against llama.cpp's, `tools/qwen36_compare_logits.py`,
fixtures `/home/rk/qwen36-step4-teacher`, the command of the REGINA-108 check: context 8,192, `--kv fp16`, `--spec 4
--suffix-draft 0`, 64 positions; pass = top-1 at least 62 and mean KL below 1e-2). Every miss forced onto one path:
`--pcie-frac 0.0` the CPU pool, `1.0` DMA with the GPU computing. `auto` holds 8,061 of 10,240 slots for IQ3 and
4,240 for Q4 on this card; `--expert-cache 2000` holds 2,263 and 2,399. Cells are top-1 of 64, mean KL; **bold**
misses the rule.
| fixture | auto, CPU misses | auto, DMA | 2000, CPU misses | 2000, DMA | the 4090, all resident |
| --- | --- | --- | --- | --- | --- |
| iq3-test20 | 64, 1.3e-3 | 63, 9.1e-4 | 64, 1.4e-3 | 64, 8.0e-4 | 64, 1.1e-3 |
| iq3-task-prime-add-test | 64, 4.5e-3 | **64, 1.26e-2** | 64, 4.8e-3 | **63, 1.18e-2** | 64, 6.6e-3 |
| iq3-task-psim-collide | 64, 2.3e-3 | 64, 2.1e-3 | 64, 2.0e-3 | 64, 2.0e-3 | 64, 1.9e-3 |
| q4-test20 | 62, 6.0e-3 | **61**, 8.5e-3 | **61**, 8.3e-3 | **62, 1.17e-2** | 61, 7.4e-3 |
| q4-task-prime-add-test | 64, 8.1e-4 | 64, 1.2e-3 | 64, 1.1e-3 | 64, 7.2e-4 | 64, 1.7e-3 |
| q4-task-psim-collide | 64, 1.3e-3 | 64, 7.0e-4 | 64, 1.3e-3 | 64, 7.7e-4 | 64, 4.2e-4 |
**19 of 24 runs pass; 5 do not, all on two fixtures** (REGINA-111). Not a regression of this binary, and not broad:
- the CPU column at `auto` is the REGINA-108 post-fix table again (1.4e-3 / 4.8e-3 / 2.0e-3, q4-test20 62 at 6e-3,
q4-prime-add 8e-4), and q4-test20 `auto` DMA has the pre-fix binary's figures to the last printed digit (61, 0.00845,
0.13765 at position 8): neither path moved;
- each miss is one position. q4-test20: positions 8, 9, 13, the near ties where the 4090 with every expert resident
also reads 61 of 64 (KL 0.147 at position 8; here 0.086 to 0.323 in the three runs that miss). iq3-prime-add: position 40, 0.152 on the 4090,
0.416 / 0.467 on this card's GPU path, under 0.05 with CPU misses at `auto`; the median KL of those runs is 3e-5;
- this card against the 4090's all-resident dumps (`eng/*.f32`): mean KL 5.2e-3 to 1.2e-2 on these two fixtures, 5e-4
to 2.7e-3 on the other four, the size of either engine's distance from llama.cpp;
- the four DMA runs repeated: byte-identical dumps.
Open in the ticket: on the 4090 the resident and DMA dumps were the same bytes; here `auto` DMA and `2000` DMA differ
from each other although the GPU computes every miss (the adaptive tier was on: 139 to 384 experts swapped in during the 64
tokens), and no all-resident run fits this card at fp16 to compare against. Closed in the REGINA-111 section at the end: the
`2000, DMA` column is not a GPU-only path (its logs read `CPU experts` 0.22 to 0.73 per layer), and the five misses are
the reference's own spread.
**The checks.** `a5.py` of the 4090 section unchanged, the measured ladder's launch (`--mtp qwen36-mtp-draft-full
--ctx 262144 --threads 8 ... -- --kv q4_0`; the 4090 table used the subset head), greedy, client and server on the VM.
All nine checks pass in all three configurations.
| check | Q4_K_XL, no cap (3,141 slots) | Q4_K_XL, `--vram-cap 6144` (397 slots) | IQ3_XXS, `--vram-cap 6144` (1,258 slots) |
| --- | --- | --- | --- |
| (a) chat, not streamed, thinking off: "capital of France" | pass, 0.61 s | pass, 0.74 s | pass, 0.77 s |
| (a) chat, not streamed, thinking on: 17 x 23 = 391 | pass, 314 tokens at 63 tok/s | pass, 321 at 43 | pass, 412 at 53 |
| (b) stream, thinking on: reasoning deltas, first, largest gap | 520, 0.345 s, 108.6 ms | 466, 0.528 s, 131.9 ms | 420, 0.491 s, 105.1 ms |
| (b) the same request: content deltas, first, largest gap | 89, 8.328 s, 82.6 ms | 89, 11.604 s, 142.8 ms | 55, 8.323 s, 108.1 ms |
| (b) the same request: tokens, decode, largest gap between any two deltas | 612 at 63 tok/s, 108.6 ms | 558 at 41, 142.8 ms | 478 at 54, 108.1 ms |
| (b) stream, thinking off (the ticket's request): content deltas, first, largest gap | 207 of 208 tokens, 0.364 s, 73.0 ms | 213 of 214, 0.515 s, 83.2 ms | 204 of 205, 0.471 s, 84.1 ms |
| (c) tool round trip, not streamed: call, result, answer | pass: `get_weather {"city":"Paris"}`, `tool_calls`, then "17°C with light rain", `stop` | pass | pass |
| (c) tool round trip, streamed | pass: reasoning 585 deltas, the call in 1 delta at 9.28 s; the answer in 14 content deltas | pass: 546 reasoning deltas, call in 1 at 13.72 s; 14 content deltas | pass: 169, call in 1 at 3.73 s; 18 content deltas |
| (c) tools declared, not called, streamed, thinking on: content deltas, first, largest gap | 73, 11.704 s, 101.4 ms | 83, 23.747 s, 135.1 ms | 80, 14.626 s, 71.4 ms |
| (c) the same, thinking off | 71, 0.102 s, 68.4 ms | 76, 0.164 s, 85.5 ms | 69, 0.140 s, 79.2 ms |
| (d) three-turn chat, tokens reused of the prompt per turn | 0 / 23, 18 / 111, 106 / 154 | 0 / 23, 18 / 143, 138 / 184 | 0 / 23, 18 / 165, 160 / 221 |
The largest gap between any two deltas in any stream is 142.8 ms, a hundredth of the 15 s keepalive; no keepalive
comment was sent in any run. The longest silence a client sees is the wait for the first content delta with thinking
on, during which reasoning deltas arrive: 23.7 s at Q4 `--vram-cap 6144` (974 tokens at 43 tok/s). A streamed tool
call still arrives whole, 9.3 to 13.7 s after the request for Q4, with reasoning deltas before it. `/health` after
each run: `ram_reads` and `file_reads` 0 (the arena is pinned), VRAM hits per lookup 78% / 29% / 51%. VRAM after
load 10,615 / 10,617 / 10,603 MiB (the cap holds the rest of the card back itself), 10,747 / 10,749 / 10,735 at the end.
(d) as on the 4090: the previous prompt less its 5-token header. `reuse.py` on Q4 no cap: with
`preserve_thinking` and `reasoning_content` sent back, 942 of 961 and 1,267 of 1,285; without it 18 of 127 and 122 of
170; thinking off 18 of 236 and 229 of 294.
**Decode speed with this binary** (`sweep_engine_ladder.py --host vm211 --threads 8 --no-depth --no-stability`, the
ladder's method: cache dropped, fresh launch, regina twice and the short request; `speed/`):
| | regina rep 0 / rep 1, decode tok/s | short, decode tok/s | prefill 3.1K / 203 tokens, tok/s | drafts accepted (regina rep 1) | the ladder with 7ebc9e5: regina rep 1 / short |
| --- | --- | --- | --- | --- | --- |
| Q4_K_XL, full card | 66.2 / **66.4** | 66.3 | 942 / 132 | 802 / 967 | 66.3 / 65.3 |
| IQ3_XXS, full card | 83.3 / **81.2** | 77.8 | 911 / 193 | 792 / 958 | 81.0 / 77.4 |
No regression.
**Not checked.** pi against this card (check e); images; `--vram-cap 8192`; IQ3 at the full card through `a5.py`
(its decode is in the speed row); the nondeterminism section's ten-request repeats on this card.
## REGINA-111: the five misses on the 1080 Ti
2026-10-13. **Verdict: no fault in the engine, on either card.** Two findings: the `2000, DMA` column above was not a
forced path, and the two fixtures that miss are ones llama.cpp fails against itself. No engine source changed; the
binaries are the ones above (`a44d896ccb25ff98` on VM 211, `b1575740af995a78` on VM 221). Material:
`rk@192.168.50.43:/home/rk/bench/r111/` and `rk@192.168.50.151:/models/work/r111/` (`r111-*.sh` the drivers, `pos.py`
and `dist.py` the per-position tables, `oracle_rows.py`, `SHA256.txt`).
**Why two "all GPU" configurations differed.** They were not both all GPU. The window's PCIe share is staged in 16
VRAM blobs (`kStagingBlobs`, `verify.hpp:358`; 8 per group when a window runs as two groups, `verify.cpp:1705`), and
the pool sends a miss to DMA only while `fetches < P.staging_cap` (`expert_source.cpp:2100`). A layer of a window with
more than 16 distinct misses computes the rest on the CPU, whatever `--pcie-frac` says. A 4-token window routes 32
experts; with 2,399 of 10,240 slots resident that limit is reached, with 4,240 or 8,061 it is not.
- `STRATA_POOL_TRACE=1` on q4-test20, `--expert-cache 2000 --pcie-frac 1.0`: 46 of 680 layer calls publish 16 fetches
and then run 1 to 16 CPU jobs; no call with fewer than 16 fetches runs any. The first is window 1 (positions 1 to
4), layer 0: 16 by DMA, 12 on the CPU. The first logits row that differs from the `auto` run is position 3.
- With `--spec 2` (at most 16 routed experts a window) the log reads `CPU experts 0.00`, and the `2000` and `auto`
dumps are the same bytes, for both fixtures; for q4-test20 they are also the bytes of the `auto` run at `--spec 4`
(`790e501683ea6af6`). The GPU path on sm_61 does not depend on what is resident or on the window's shape.
- The 4090 does the same: `--expert-cache 2000 --pcie-frac 1.0` at `--spec 4` reads `CPU experts` 0.33 (Q4) and 0.68
(IQ3) per layer and its dumps differ from the all-resident ones; at `--spec 2` they are the all-resident bytes
(`e4e5fdc81b4bc604`, `de2fd0e08c2e6679`). The earlier resident-against-DMA identity there was measured at
`--expert-cache 8000`, which never reaches 16 misses. Nothing here is specific to Pascal.
So in the A5 table the `auto, DMA` column is the GPU path (`CPU experts 0.00` in all six logs) and the `2000, DMA`
column is the GPU path with 0.22 to 0.73 CPU-computed experts per layer mixed in. A run meant to force the GPU path
has to show `CPU experts 0.00`; `--spec 2` guarantees it.
**The soft positions.** The fixtures' reference is llama.cpp on the 4090, every layer offloaded. The same pinned
llama.cpp was teacher-forced along the same ids on VM 211, once with no layer offloaded (`--ngl 0`, "CPU" below) and once on the 1080 Ti with
what fits (28 of 41 layers for IQ3, 15 of 42 for Q4), and `ref/qwen36.py` (the numpy oracle: F32 weights as
dequantized, F32 activations, its own routing) was run over prompt and continuation in one pass, plain and with
`--act-quant q8`. Each run against the fixture's reference, and against the F32 oracle (top-1 of 64, mean KL, the
largest KL and its position; **bold** misses the rule's thresholds):
| run | q4-test20 vs llama.cpp 4090 | q4-test20 vs F32 oracle | iq3-prime-add vs llama.cpp 4090 | iq3-prime-add vs F32 oracle |
| --- | --- | --- | --- | --- |
| llama.cpp, the 4090 (the reference) | - | **61**, 6.1e-3, 0.141 (8) | - | 64, 7.6e-3, 0.316 (40) |
| llama.cpp, CPU | **60**, 9.2e-3, 0.174 (8) | 63, 5.5e-3, 0.079 (8) | 62, **2.72e-2**, 1.400 (40) | 62, **1.48e-2**, 0.626 (40) |
| llama.cpp, the 1080 Ti, partly offloaded | **60**, 9.9e-3, 0.199 (8) | 63, 5.7e-3, 0.087 (8) | 62, **2.70e-2**, 1.368 (40) | 62, **1.31e-2**, 0.570 (40) |
| engine, 1080 Ti, GPU only (`auto`, DMA) | **61**, 8.5e-3, 0.138 (8) | 64, 4.3e-3, 0.050 (10) | 64, **1.26e-2**, 0.416 (40) | 64, 4.5e-3, 0.066 (48) |
| engine, 1080 Ti, `auto`, CPU misses | 62, 6.0e-3, 0.049 (10) | 62, 7.0e-3, 0.161 (8) | 64, 4.5e-3, 0.062 (54) | 64, 5.9e-3, 0.244 (40) |
| engine, 1080 Ti, `2000`, GPU with the CPU overflow | 62, **1.17e-2**, 0.323 (8) | 63, 6.5e-3, 0.122 (8) | 63, **1.18e-2**, 0.467 (40) | 63, 7.4e-3, 0.141 (40) |
| engine, 1080 Ti, `2000`, CPU misses | **61**, 8.3e-3, 0.086 (8) | 62, 5.7e-3, 0.083 (8) | 64, 4.8e-3, 0.073 (45) | 64, **1.22e-2**, 0.612 (40) |
| engine, 4090, all resident | **61**, 7.4e-3, 0.147 (8) | 64, 3.8e-3, 0.040 (8) | 64, 6.6e-3, 0.152 (40) | 64, 3.5e-3, 0.082 (40) |
| Q8 oracle | | 63, 7.5e-3, 0.109 (8) | | 64, 7.6e-3, 0.186 (45) |
llama.cpp on another back end misses the rule against its own 4090 run on both fixtures, by more than any engine run
does. Against the F32 oracle the engine's GPU path is inside the thresholds on both cards (1080 Ti 64 of 64 at 4.3e-3
and 4.5e-3; 4090 64 of 64 at 3.8e-3 and 3.5e-3) and nearer the oracle than the reference is (61 at 6.1e-3; 64 at
7.6e-3). The 1080 Ti is 0.5e-3 and 1.0e-3 farther from the oracle than the 4090, 64 of 64 on both.
The positions themselves (margins are logits, first candidate minus second; KL against the reference / the F32 oracle):
| position | llama.cpp 4090 | llama.cpp CPU | llama.cpp 1080 Ti | engine 1080 Ti, GPU only | engine 4090, resident | F32 oracle |
| --- | --- | --- | --- | --- | --- | --- |
| q4-test20, 8: " operation" / " expression" / " list"; entropy 4.2 nats | " operation" by 0.21 (p 0.21 / 0.17); - / 0.141 | " list"; 0.174 / 0.079 | " list"; 0.199 / 0.087 | " list"; 0.138 / 0.029 | " list"; 0.147 / 0.040 | " list" (p 0.15) |
| q4-test20, 9: ":" / "?" | ":" by 0.15 | "?" by 0.14 | "?" by 0.18 | "?" by 0.27 | "?" by 0.30 | "?" by 0.13 |
| q4-test20, 13: " Extract" / " Take" | " Extract" by 0.13 | " Take" by 0.08 | " Take" by 0.12 | " Take" by 0.28 | " Take" by 0.20 | " Take" by 0.07 |
| iq3-prime-add, 40: "user" / `<\|im_start\|>` | "user" by 2.70 (p 0.86); - / 0.316 | `<\|im_start\|>` by 1.57; 1.400 / 0.626 | `<\|im_start\|>` by 1.26; 1.368 / 0.570 | "user" by 0.30; 0.416 / 0.053 | "user" by 0.96; 0.152 / 0.082 | "user" by 0.77 (p 0.55) |
At q4-test20 positions 8, 9 and 13 every other source, the F32 oracle included, picks what the engine picks: the three
"misses" are the 4090 llama.cpp run standing alone at near ties. iq3-prime-add position 40 is the fifth token after
the reply's `<|im_end|>` (position 35), in `<|im_end|>\n<|endoftext|><|im_start|><|im_start|>user`: text no request
is ever served, where llama.cpp's own back ends differ by 4.3 logits on the margin (+2.70 to -1.57) and the engine sits
between them, next to the oracle. On that fixture positions 0 to 35 read mean KL 2.7e-3 (largest 0.025) for the 1080
Ti's GPU path and 3.4e-3 (0.071) for the 4090; positions 36 to 63 read 2.5e-2 and 1.1e-2, and llama.cpp's CPU run
5.5e-2.
**Is 0.4 at one position acceptable.** Per-position KL against the reference, the 24 runs of the table above and
the 4090's six: the median is 1e-6 to 2.5e-3 in every run and the 90th percentile at most 2.4e-2. 17 of 30 runs
have no position above 0.05. Positions above 0.1 exist only on these two fixtures: position 8 of q4-test20 (0.138 to
0.323 in three of five runs) and positions 40, 42 and 48 of iq3-prime-add (0.416, 0.128, 0.119 in the GPU-only run;
0.467 with the overflow; 0.152 on the 4090). With its largest position left out no run's mean is above 7.1e-3. A KL
of 0.4 at a position where two llama.cpp back ends are 1.4 apart measures the reference, not the engine; the same
0.4 at a position where they agree to 1e-2 would be a fault; no position of the other four fixtures is above 0.1.
**Proposed for the rule, not adopted** (the thresholds 62 of 64 and 1e-2 stand as written until decided):
1. Score positions up to and including the reference's first stop token only (36 of 64 on iq3-prime-add; the other five
fixtures do not stop), or regenerate that fixture to hold 64 positions before the stop.
2. Keep a second llama.cpp run per fixture (`--ngl 0`, forced along the same ids; under half a minute each) and
report, not gate, the positions where the two llama.cpp runs disagree on top-1 or differ by more than 0.05 KL, as
the runner tests already do where the F32 and Q8 oracles disagree. q4-test20 loses positions 6, 8, 9, 13, 15;
iq3-prime-add loses 0, 2, 8, 40. The thresholds become shares of what is left (96.9% and 1e-2).
3. A forced-GPU run counts only with `CPU experts 0.00` in its log.
With 1 and 2 all eight 1080 Ti runs of the two fixtures pass: q4-test20 59 of 59 in each, mean KL 5.2e-3 to 5.8e-3;
iq3-prime-add 33 of 33 in each, 8.9e-4 to 2.1e-3.
**Left as it is, for a decision.** `--pcie-frac 1.0` does not force the GPU past 16 distinct misses per layer and
window (8 per group). README line 232 and the paragraph "For a run that must repeat" above promise repeats from that
flag; with a small cache (the 1080 Ti at `--expert-cache 2000`, or a `--vram-cap` configuration) the overflow runs
on the CPU and the adaptive tier can then move a request between passes as in the CPU rows of that section. Sizing the
staging to the window (8 blobs per token: 16 more at 4 tokens, under 58 MiB at Q4) would make the flag exact; it also moves
the default share's ceiling, so it changes what the ladder measured and was not done here.
**Not checked.** A Pascal-against-Ada bisect by layer: the two cards run different kernels from the prompt on (the
BF16 GEMM through fp32 and no tensor-core MoE on sm_61), so they are not expected to agree in bytes, and each agrees
with the F32 oracle to 4e-3; the other four fixtures against the oracle or a second llama.cpp run; llama.cpp fully
offloaded on a second card (neither file fits the 1080 Ti); whether the overflow makes a served request differ between
passes (inferred from the CPU rows above, not run); the 262,144 q4_0 configuration.
## Flash-Next regression check
2026-10-13, VM 221 (RTX 4090, 62 GB RAM), card otherwise idle. Does the branch still serve Qwen3.8-Flash-Next as the
production binary does? Production: `/tank/nvme/strata/unbiased-strata`, sha256 `abbe990f4e3c658e` (main's lineage
with 121d23a). Branch: `/models/work/qwen36-step4/build/unbiased-strata`, `11da5388afdfabcb` at d00d383 and
`5428c8d791f7a697` at 0513d5b. Both started by hand with the command line of `unbiased-strata.service` on
127.0.0.1:18091 (`--ctx 196608 --mmproj ... --threads 8 -- --kv-resident 32768 --ple-io mmap --kv int8`,
`CUDA_MODULE_LOADING=EAGER`, memlock unlimited; the unit's first-prompt capture variable left out so the captured file
was not overwritten). Scripts and logs: `/models/work/flashcheck/`.
**One fault, fixed (REGINA-112).** The branch took f07b81e from main but not 121d23a, so its front end sized
`max_new` as context - prompt and the engine (prompt + max_new + 8 <= context) refused every request that sent no
`max_tokens`, and any with `max_tokens` at or above context - prompt - 7, with a 500. The serving checks below did
not see it because each sets `max_tokens`. 0513d5b carries main's hunk and `tests/python/serve_max_tokens_check.py`
(`make test-serve PORT=...`): 0 of 5 on `11da5388`, 5 of 5 on production and on `5428c8d7`, the latter on Flash-Next
at 196,608 and on Qwen3.6 Q4_K_XL at 262,144.
**Serving**, `a5.py` of the A5 section and one image request, on both branch binaries:
| check | d00d383 | 0513d5b |
| --- | --- | --- |
| start, plan | 10,368 expert slots (production 10,373), 430 MiB free, KV 32,768 of 196,608 cells resident | the same |
| `/health`, `/v1/models` | ok, tiers; `input_modalities` text, image | ok |
| chat, not streamed, thinking off / on | pass / pass (391) | pass / pass |
| stream, thinking on: reasoning deltas, content deltas | 84, 41 of 128 tokens, largest gap 77 ms | 90, 50 of 143 |
| stream, thinking off: content deltas | 193 of 194 tokens | 200 of 201 |
| tool round trip, not streamed / streamed | pass / pass (the call in 1 delta, the answer in 14) | pass / pass (16) |
| tools declared, not called, streamed, thinking on / off | 79 / 90 content deltas | pass / pass |
| three turns, tokens reused of the prompt | 0 / 65, 60 / 138, 133 / 169 | 0 / 65, 60 / 145, 140 / 176 |
| image (96 x 96 PNG, red left, blue right) | pass, 1.0 s, 41 prompt tokens | pass |
**Speed**, greedy, reasoning off: 4 prompts of 400 tokens and 2 prompts of 19,593 and 20,820 tokens, five passes per
start, production, branch (d00d383), production, branch. The host holds 62 GB against 76 GB of model files, so
14,208 of the 24,576 experts and the n-gram table are read through the file cache and the first two passes of a start
measure the cache (60 tokens/s and 700 prompt tokens/s on both binaries on the first pass). The table is passes 3 to
5, tokens over time, per start:
| | Generation, tokens/s | Prompt, tokens/s |
| --- | --- | --- |
| Production | 89.5, 92.1 (74 to 109 per prompt) | 2,093, 2,098 |
| Branch | 89.0, 89.2 (74 to 107) | 2,092, 2,094 |
| Branch / production | 0.98 | 1.00 |
Drafts accepted 0.61 to 0.62 of those offered on both. The 2% in generation is inside the spread between the two
production starts.
**ctest**, the branch build at d00d383 on the free card: 94 of 98 pass, `pack_load_check` skipped, and the three
host failures (`ple_parity`, `platform_memory_test`, `expert_multi_test`).
**On main.** main at e7ae2c8 builds the same binary as 0513d5b (`5428c8d791f7a697`). One more start of each, same
requests, passes 3 to 5: production 90.6 tokens/s and 2,097 prompt tokens/s, main 90.4 and 2,091 (1.00, 1.00).
### Both models on the one 4090, two processes
One process serves one model: the front end loads one `--model`, starts one engine child, and answers every request
with it whatever the request's `model` field says. Two models are two processes on two ports. Tried once, main's
binary, Flash-Next on 18091 and Qwen3.6 IQ3_XXS at 262,144 on 18092, `--threads 8` each on 16 vCPUs:
- **`--vram-cap` does not partition a card.** It allocates a blocker of total - cap, so one capped engine holds the
whole card. What works: start Flash-Next first with a fixed `--expert-cache N`, then Qwen3.6 uncapped, whose plan
takes what is free. `--expert-cache 4000` gave Flash-Next 5,357 slots and 15.4 GB of the card, with 8.8 GB free;
Qwen3.6 then planned a 4,331 MiB fixed set and 3,187 of 10,240 expert slots (8.1 GB), 447 MiB left. At
`--expert-cache 6000` (8,053 slots) 4.3 GB stayed free, below Qwen3.6's fixed set.
- **RAM binds first on this host.** Flash-Next alone uses 47 of 62 GB (its 40 GiB expert arena is pinned). With
Qwen3.6 beside it 60 GB were used and 2 GB available; Qwen3.6 found too little to pin its 7,053 off-card experts
and mapped them from the file, and took 239 s to start. No swap, no OOM kill in this run.
- **Idle costs nothing, concurrency costs most of both.** An idle engine shows 0% GPU. 4 prompts of 400 tokens,
greedy, reasoning off, tokens/s:
| | Flash-Next | Qwen3.6 IQ3_XXS |
| --- | --- | --- |
| Alone on the card, service configuration (10,368 slots) | 90 | |
| Alone, `--expert-cache 4000` (5,357 slots) | 54 | |
| The other engine loaded and idle | 45 | 133 |
| Both generating | 12 | 27 |
Requests to both at once complete without error; each engine runs at about a quarter of its speed with the other
idle. Two CUDA contexts time-slice the card, each engine's verify graph spins on the GPU while it waits for its
host, and 16 pool workers plus two host threads share 16 vCPUs. Not separated which of the three costs what.
-106
View File
@@ -1,106 +0,0 @@
# Upstream Strata tooling the Qwen3.6 port needs back
Surveyed 2026-10-11. Read-only references:
- `/Users/robertkarl/Code/strata-upstream-6f32ec0`: exact snapshot, exported with `git archive 12a7825` from this repository's first commit ("Import Strata at 6f32ec0, unmodified"). Use this one.
- `/Users/robertkarl/Code/strata-upstream`: a clone of `Niko1221/Strata` main (1859 commits). **Commit `6f32ec0` is not in the public history**: `git checkout` fails with "unable to read tree", so the pinned commit was force-rewritten or never public. Main still carries the same tooling and adds `bench/bench_vs_llama.py`.
Nothing was built. UnbiasedStrata was not modified.
## 1. The finding that changes the plan
Upstream's Python oracle is **not** published. `ref/` contains only `ref/load.py`, in the snapshot and in main, in every commit. The engine source cites `ref/gdn.py` (22 times), `ref/qsa.py` (26), `ref/moe.py` (12), `ref/gr.py` (11), `ref/ngram.py` (10), `ref/model.py` (9) and `ref/quant.py` (7), and `docs/semantics.md` and `docs/activation-contract.md` do not exist in any commit. The same holds for `bench/micro/` (the ggml-oracle tests), `tests/python/gen_ple_oracle.py`, `scripts/_gen_f16_oracle.py` and `tests/CMakeLists.txt`. The published CMake says so: "the test suite and the micro benchmarks live in tests/ and bench/micro/, which the published source leaves out".
So the Maya recipe (`ref/glm.py` plus a synthetic GGUF and dumps) has no upstream Strata counterpart to restore for the mixers or the MoE. What is restorable is `ref/load.py`, the pack tools, the in-C++ parity tests, and the discipline. The Qwen3.6 oracle is new code. It is specified from the pinned llama.cpp graph `third_party/llama.cpp/src/models/qwen35moe.cpp`, as Maya specified `ref/glm.py` from `glm5-next.cpp`.
## 2. Inventory
### `ref/`
- `ref/load.py` (212 lines). `Gguf(path)`: a demand-paged view of a possibly sharded GGUF (shard discovery from the `-0000N-of-0000M` suffix, a directory, or a list). `tensor(name)` returns FP32 shaped (out, in[, experts]). `expert(name, e)` decodes one expert of a fused `[in, out, experts]` tensor without touching the others. `rows(name, idx)` gathers rows of a 2-D tensor (built for the 27 GB PLE table; Qwen3.6 has no PLE). One dequant dispatch `_dequant_flat`: F32, F16, BF16 by hand; Q2_0 through `tools/gguf_writer.dequantize_q2_0`; everything else through gguf-py `quants.dequantize` (the table GEOM holds 13 entries: F32 F16 BF16 Q4_0 Q5_0 Q8_0 IQ4_NL Q3_K Q4_K Q5_K Q6_K IQ4_XS Q2_0). It lacks Q4_1, Q5_1, Q2_K and the IQ1/IQ2/IQ3 types the engine itself serves; a Q4_K_M or UD-Q4_K_XL Qwen3.6 file needs only Q4_K, Q5_K, Q6_K, Q8_0, F32, BF16 or F16, all present. It imports `gguf` without adding it to `sys.path`, so `PYTHONPATH` or `STRATA_GGUF_PY` must point at gguf-py (see section 5).
### `tools/` (the ones a port uses)
- `tools/iq_pack.py` (602 lines). The native-pack builder, described in section 4. Hardcodes Flash-Next assumptions listed in section 6.
- `tools/gguf_reader.py` (142). A GGUF v3 header reader with no gguf-py dependency; knows ggml type ids to 42 (Q2_0). Used by `iq_pack`, the tokenizer exporter and `ref/load.py`. It is the Python twin of `src/artifact/gguf_reader.cpp`.
- `tools/gguf_writer.py` (234). A minimal GGUF v3 writer with a Q2_0 quantizer. Its self-test writes a synthetic file with `general.architecture = qwen4exp`. Not a model generator.
- `tools/iq_fixture.py` (137). Writes deterministic i-quant blocks plus gguf-py's dequantized reference for `iq_parity` (see section 3). It is the one fixture generator upstream ships.
- `tools/test_iq_pack.py` (528). The closest thing to a synthetic-GGUF generator upstream ships: `write_gguf()` builds tiny sharded GGUFs with gguf-py's `GGUFWriter` and `quants.quantize`, then asserts pack behaviour (BF16 rounding to even, refused inexact F32 routers, split shards, a layer split across shards, interrupted packs, stale `experts.bin`). Arch string is `qwen4exp`.
- `tools/make_profile.py` (119). Writes `expert-profile.bin`, a ranking of every (layer, expert) pair, from the base profile plus routing traces from `generate --dump-routing FILE`. Has `--n-expert` but `N_LAYER = 48` is hardcoded (line 26) and the output header carries layer and expert counts that the engine checks. Test: `tools/test_make_profile.py`. The shipped `data/expert-profile.bin` is for Flash-Next and is useless for Qwen3.6 (40 layers, 256 experts).
- `tools/mtp_fetch.py` (308). Range-reads the 31 `mtp.*` tensors out of the 131-shard BF16 checkpoint over HTTP and verifies SHA256s (`inventory`, `fetch`, `verify`). Pinned to Qwen3.8-Flash-Next.
- `tools/mtp_pack.py` (193). Quantizes those tensors into an MTP GGUF (`--experts q2_0|q4_0|q8_0`). Hardcodes the Flash-Next tensor names and the 512-expert fused shapes.
- `tools/mtp_rt.py` (111). Turns the MTP GGUF into the engine's runtime files: `experts.bin`, `dense.bin`, `dense.txt`. Applies Gemma-style `+1` to RMSNorm weights.
- `tools/draft_vocab.py` (+ `test_draft_vocab.py`). Extends `draft_vocab.bin`, the token subset the draft head may propose, by script (`--add han|kana|...`) or corpus (`--corpus`, `--coverage`). Data files `data/draft_vocab*.bin` are tied to the Flash-Next vocabulary of 248,320 tokens.
- `tools/strata_tokenizer.py` (331). Exports `tokenizer/` (vocab, merges, chat template) from GGUF metadata. Refuses pre-tokenizer schemes it has not transcribed; Qwen3.6 uses `qwen35`, same family as Flash-Next. Called by `iq_pack` when `<out>/tokenizer/` is missing. Needs `regex`.
- `tools/strata_pack.py`, `pack_layer.py`, `pack_index.py`, `canonical_xcheck.py`. The canonical Q2_0 pack (bakes in the 1,382,400-byte Flash-Next blob). The plan says Qwen3.6 rides the native pack instead, so these are reference only. `canonical_xcheck.py` shows the "bit-exact against gguf-py over every block" style.
- `tools/calibrate.py`, `needle_bench.py`, `batch_test.py`, `test_conversation_cache_*.py`. Server-level measurement and regression harnesses. `calibrate.py` tunes `--pcie-frac`, `--spec-min-p`, `--pool-workers` through an engine's per-request keys. `needle_bench.py` is recall at 32K to 262K through the HTTP API. `batch_test.py` checks batched against solo greedy tokens.
- `tools/_paths.py`. Finds gguf-py: `$STRATA_GGUF_PY`, then `<repo>/third_party/llama.cpp/gguf-py`. That second path exists in this fork's submodule, so the tools work unmodified.
- Not needed: `setup.py`/`test_setup_*.py` (the installer), `strata_mcp.py`, `embd_bf16_pack.py`, `ple_fp8_pack.py` (Flash-Next PLE), `hip/`, `vision/`.
### `tests/` and the parity sources
- `tests/` in the snapshot has 30 files and no `CMakeLists.txt`: `tests/core/*.cpp` (loader and cache tests, `gguf_fixture.hpp` is a C++ synthetic-GGUF writer with pattern-filled tensors), `tests/cuda/prefill_*_test.cpp`, `tests/hip/*`, `tests/data/native_experts/*.txt` (golden `native_experts.txt` files for q2_0, iq2_xs, iq3_s, iq3_xxs, coder-iq1_m, swift-iq2_xs).
- The root `CMakeLists.txt` references 23 `tests/` sources that are **absent in UnbiasedStrata** (the snapshot has 30 files there), and four `bench/micro/*` sources that upstream never published. Configuring this fork with `-DSTRATA_BUILD_TESTS=ON` would fail at `tests/core/gguf_split_test.cpp` (line 231). Restoring `tests/` fixes all but the `bench/micro` ones, which sit under the oracle option.
- The 36 `src/kernels/*_parity.cpp` files, `src/prefill/gdn_rec_parity.cu`, `src/prefill/gemm_bf16_parity.cu` and `src/kernels/cpu/*_parity.cpp` are **still in UnbiasedStrata**. Relevant to the port: `gdn_parity.cpp`, `router_top10_parity.cpp`, `shared_expert_parity.cpp`, `gr_parity.cpp` (the Flash-Next hyper-connection residual, which Qwen3.6 lacks), `rope_parity.cpp`, `qsa_parity.cpp` (indexer path, bypassed for dense attention), `native_expert_parity.cpp`, `native_grouped_parity.cpp`, `sampler_parity.cpp`, `kv_*_parity.cpp`, `iq_parity.cpp`, `gdn_rec_parity.cu`.
### Docs
- `docs/semantics.md`, `docs/activation-contract.md`: **do not exist upstream** (no commit). The semantics live in comments in the parity files and in the unpublished `ref/*.py`.
- `docs/ORCA.md` (95 lines) and `ORCA_Q4_K_S.md` (36). These are the precedent for a **different quantization of the same geometry** (512 experts), not for a different expert count: `iq_pack.py --compat-bf16` rounds the small projections the engine reads as BF16, records each in `compat-bf16.json`, and the pack carries its own tokenizer and `dense.bin`. The precedent for a **different expert count** is the Coder (256 of 512 experts): `iq_pack` reads `n_expert` from the router's shape, `make_profile.py --n-expert 256`, and `tests/data/native_experts/coder-iq1_m.txt`. `docs/MODELS.md` describes it.
- `docs/DETAILS.md` (1127 lines; this fork keeps it as `docs/upstream/DETAILS.md`), `docs/HOW_IT_WORKS.md`, `docs/OLDER_GPUS.md`, `docs/NVIDIA_V100.md`, `docs/paper/`.
### `bench/`
- Snapshot: results only (`bench/results/<date>-<topic>/` with `README.md`, `matrix.md`, `matrix.json`). Useful as the format for reporting. The speed matrix of `2026-09-28-speed-0114` records the flags the setup writes (`--prefill auto`, `--expert-cache auto`, `--kv-resident`, `--spec 4 --spec-min-p 0.5`).
- Main only: `bench/bench_vs_llama.py` drives Strata's and llama.cpp's OpenAI-compatible servers with the same prompts and GGUF, takes server-side prompt and decode tokens per second, peak VRAM from `nvidia-smi` polling, RSS from `psutil`, interleaves engines across rounds, and has `prompts`, `run`, `quality`, `summary` subcommands. Needs `psutil`. This is the closest match for the plan's baseline-versus-engine comparison, and it is not in the pinned snapshot.
- The engine itself prints a `strata decode GPU stages (ms/window)` line and takes `--dump-routing` (`src/program/generate.cpp:1310`).
## 3. How upstream produces oracle dumps for a parity test today
1. There is no dump pipeline for the model. No script in the published tree runs a forward pass of the model and writes per-seam tensors. Everything below is what exists.
2. Most parity tests are self-contained: the oracle is a **host C++ transcription of the spec**, inside the test file. `gdn_parity.cpp` has `ref_step()` and `ref_conv()` "a transcription of `ref/gdn.py`", in double precision, with boolean switches for the rival readings. `router_top10_parity.cpp` has `reference()` (softmax, stable sort, renormalise). Random inputs come from `std::mt19937(2024)`. Nothing is read from `data/`.
3. Registration: `add_test(NAME gdn_parity COMMAND gdn_parity --selftest)` in the root `CMakeLists.txt` under `if(STRATA_BUILD_TESTS)` and a CUDA or HIP backend. `STRATA_BUILD_TESTS` defaults ON only when `tests/CMakeLists.txt` and `bench/micro` both exist, so a published checkout builds none of it unless `-DSTRATA_BUILD_TESTS=ON` is given. Run with `ctest` or the binary with `--selftest`. Exit 0 pass, 1 fail, 77 or 3 skip (`SKIP_RETURN_CODE`).
4. Vector tests embed the oracle as a generated header: `ple_oracle_vectors.inc` ("GENERATED by tests/python/gen_ple_oracle.py") holds token windows and expected hash rows; `qsa_oracle_vectors.inc` holds float32-to-float16 bit pairs from `np.float16(np.float32(x))`. Both generators are unpublished. Regenerating means rewriting them.
5. Fixture tests generate files into the build directory at test time: `iq_parity_fixtures` runs `tools/iq_fixture.py --out <build>/iq_fixture`, which writes `<name>.bin` (int32 header: kernel type id, rows, cols, then raw block bytes) and `<name>.f32` (reference values from gguf-py). `iq_parity <dir>` reads them. CMake probes interpreters for numpy (`-DIQ_FIXTURE_PYTHON` overrides) and uses `FIXTURES_SETUP`/`FIXTURES_REQUIRED` for ordering. This is the only dump-like flow in the published tree, and only for dequantization.
6. Real-GGUF tests take a path from an environment variable or argument: `STRATA_PLE_GGUF` (default `../../Q2_0/...-00002-of-00002.gguf`) and `--pack`, plus binary captures `bench/micro/ple_in.bin` and `ple_out.bin` recorded from ggml's graph by an unpublished `ple_layer_xcheck.cpp`, which "records EVERY intermediate" so a failure is attributable to a stage.
7. The independent-oracle tests (`bench/micro/native_{mmvq,bf16,shared,gr_norm,moe,gdn,gr_postops,router,gdn_preprocess,gdn_pipeline,qsa,rope,ple_postops,flash_attn,qsa_indexer,qsa_score}_parity.cpp`) link a pinned llama.cpp CUDA build as the oracle: `-DSTRATA_ORACLE_SOURCE_DIR=<llama.cpp>` and `-DSTRATA_ORACLE_BUILD_DIR=<build>` (CMake lines 387 to 408; libraries `ggml`, `ggml-base`, `ggml-cpu`, `ggml-cuda` located with `find_library`). These sources are unpublished, so the 16 names are a list of what to rewrite, and the CMake foreach is the wiring to restore.
8. No dump file naming convention exists upstream. Maya's convention (llama.cpp `cb()` names, files under `data/glm5-synth-dumps/`) is the one to adopt.
**Negative-test discipline, from `gdn_parity.cpp`.** Before the kernel is judged, each wrong reading of the spec is computed with the same reference and must differ from the right one by more than 5 % (relative L1). Four traps are pinned: modulo versus interleaved head pairing, decay before versus after the rank-1 update, conv slide direction (state rows labelled so every position is identifiable), and `l2_norm`'s epsilon on the squared norm versus the mean. It prints `yes` or `*** NO ***` for "is the rival observable" and counts a failure when it is not. The first fixture for the decay trap showed only 3.25 % apart, so the gate and the input range were changed (decay in (0.0025, 0.135], beta in [0, 1)) until the trap was clearly visible. The state layout test fills the state with `0.001*(i + 2j + 3h) - 1` so a layout mix-up yields a different number, not a plausible one. `router_top10_parity.cpp` shows the same idea for selection: all-equal logits, a 12-way tie, a dominant expert, and an assertion that the 2^-14 renormalisation clamp is unreachable (top-k sum at least k/n). Comparisons are NaN-safe (`le`/`gt` demand finite values first) after a NaN fixture once printed a perfect score.
## 4. How a native pack is built from a GGUF
Entry point: `python tools/iq_pack.py --gguf <first-shard>.gguf --out <dir> [--compat-bf16] [--experts-bin] [--skip-experts] [--base <pack>]`. All sibling shards must exist (`Model.__init__` reads `-0000N-of-0000M`, a missing one is an error). `main()` runs `expert_layout()` first so a model that cannot be packed is refused before any file changes, then `index_standalone()`, then the tokenizer export, then writes `native_experts.txt` last.
- **`native_experts.txt`** is the completion marker and the expert map. One line per layer: `layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]`. `gu_type` and `d_type` are ggml type ids (gate and up must match; down may differ, e.g. IQ3_XXS gate/up with Q2_0 down). `offset` is the layer's start in the virtual `experts.bin`. `blob_bytes` is the per-expert size of gate + up + down. The last three are absolute byte offsets of the three role tensors in their GGUF shard. Header `v3`; `v4` only if one layer's roles sit in different shards (column becomes `gate,up,down`). The engine reads the experts straight from the GGUF unless `experts.bin` exists. Golden examples: `tests/data/native_experts/*.txt`.
- **`index.txt`**: "strata pack index v3", one row per non-expert tensor: `name, ?, kind, offset, bytes, arena_offset, arena_bytes, ne0, ne1, ...`. Kind 4 = BF16, 5 = F16, 2 = F32, 3 = F32 narrowed to F16 by the loader. A quantized tensor the engine serves natively from the GGUF has zero offsets and only its shape. The arena is 64-byte aligned.
- **`dense.bin`**: the float tensors the engine reads from the pack, in the form it reads them (table `FORM`: routers, hyper-connection and indexer projections, SSM gates BF16; norms, `ssm_a`, `ssm_conv1d`, `ssm_dt.bias`, `ssm_norm` F32; PLE conv F16). Exact conversions are the default (F32 whose low 16 bits are zero to BF16; F16 or BF16 widened to F32). Rounding conversions need `--compat-bf16`. Anything the engine requires in a form the GGUF does not hold, without the flag, is a hard error.
- **`conversions.json`** (schema 1): every converted tensor: shard, source and destination types, method, exact or not, max absolute error, SHA-256 of the source bytes, plus the source shard names and sizes.
- Also: `experts.bin` plus `experts.bin.src.json` (optional, only with `--experts-bin`, reuse is checked by shard sizes, the hash of `native_experts.txt` and six sampled blobs), `tokenizer/`, and `compat-bf16.json` with the flag. All files are written under `.tmp` names and renamed, so an interrupted run leaves no completion marker.
## 5. Dependencies and GPU
- Pack tools and `ref/load.py`: Python 3.10+, `numpy`, gguf-py from llama.cpp (the submodule's `third_party/llama.cpp/gguf-py` works through `_paths.py`; `ref/load.py` needs `PYTHONPATH` set to it). `regex` for the tokenizer export. `requirements.txt` pins numpy, jinja2, regex, pyyaml, tqdm. `psutil` for `bench_vs_llama.py`. `mtp_fetch.py` uses the standard library's HTTP client.
- **No torch, no safetensors library, no GPU** anywhere in `tools/` or `ref/`. The oracle is NumPy on the CPU. Maya's `ref/glm.py` is also NumPy; the full-attention and GDN loops are slow but small models are fine, and the synthetic GGUF keeps them fast.
- GPU is needed only to run the C++ parity binaries and the engine.
- For cross-checking, the submodule has `examples/eval-callback`, `src/models/qwen35moe.cpp`, `src/models/delta-net-base.cpp` and `convert_hf_to_gguf.py`. llama.cpp's `cb()` names in `qwen35moe.cpp` include `conv_output_silu`, `gate_sigmoid`, `beta_sigmoid` and `shared_expert_gate_sigmoid`.
## 6. Hardcoded Flash-Next assumptions found while reading (each must be generalized or bypassed)
- `iq_pack.py`: `FORM`/`ROUTERS` name Flash-Next tensors (`hc_*`, `indexer.*`, `ple_*`); `is_expert()` matches any `*_exps.weight`; `expert_layout()` takes `n_expert` from `blk.0.ffn_gate_inp.weight` and demands every layer to have all three expert tensors (true for qwen35moe, which has no dense-lead layers); tensors with more than two dimensions outside experts are refused; the `FORM` table has no qwen35moe entries, so SSM and attention tensors are served natively from the GGUF where quantized and copied as stored where float. Whether the engine needs `ssm_alpha`/`ssm_beta`, the router and the shared-expert gate as BF16 for the GDN and router kernels is a step 3 and 4 question; the `FORM` table is where that gets decided. `ffn_gate_inp_shexp.weight` is already in `ROUTERS`.
- `make_profile.py`: `N_LAYER = 48`, `N_EXPERT = 512`.
- `mtp_fetch.py`, `mtp_pack.py`, `mtp_rt.py`: Flash-Next tensor names, the 512-expert fused shapes, the revision pin. The Qwen3.6 MTP head comes from the MTP GGUF's `nextn` tensors per the plan.
- `gdn_parity.cpp` and `src/kernels/cuda/gdn.cu`: the out-norm is `rms_norm(o) * ssm_norm * sigmoid(z)` (`gdn.cu:148`), and the parity test's negative case asserts SiLU is the wrong reading. llama.cpp's `qwen35moe` `build_norm_gated` uses `ggml_silu(gate)`. The test's geometry is fixed at S = 128, h_k = 16, h_v = 48 against Qwen3.6's 32 v-heads. Re-pin both before reusing either.
- `tests/data/native_experts/` and `data/*.bin`: Flash-Next only.
## 7. What to restore and what to write
Restore into a dev checkout (copy from `/Users/robertkarl/Code/strata-upstream-6f32ec0`; a dev branch, or keep out of the fork's release tree):
1. `ref/load.py`.
2. `tools/`: `_paths.py`, `gguf_reader.py`, `gguf_writer.py`, `iq_pack.py`, `test_iq_pack.py`, `make_profile.py`, `test_make_profile.py`, `strata_tokenizer.py`, `mtp_pack.py`, `mtp_rt.py`, `mtp_fetch.py` (for reference), `draft_vocab.py`, `iq_fixture.py`, `needle_bench.py`, `calibrate.py`, `batch_test.py`.
3. `tests/` whole (30 files), so that `-DSTRATA_BUILD_TESTS=ON` configures. `bench/micro/` cannot be restored; the CMake foreach for the llama.cpp-oracle parity tests stays dormant.
4. `requirements.txt` (numpy, regex, jinja2).
5. From upstream main only: `bench/bench_vs_llama.py`.
Write new (nothing upstream to copy): `ref/qwen36.py`, `tools/qwen36_synth_gguf.py`, the oracle invariant tests, qwen35moe parity binaries (GDN at 32 v-heads with SiLU gating, the top-8 over 256 router with shared-expert gate, the gated full-attention layer), the layer composition test, and the streaming runner test.
+1 -137
View File
@@ -66,143 +66,7 @@ int main(int argc, char** argv) {
assert(parsed.tool_calls[0].name == "read");
assert(parsed.tool_calls[0].arguments.find("\"path\":\"/tmp/a.txt\"") != std::string::npos);
}
// Streaming (REGINA-110): the response's text grows a UTF-8 character at a time, as it does token by token
// in run(); the answer must be published as it grows, not in one piece at the end, and the pieces must add
// up to the parse of the whole message. Tool calls are published once, complete.
struct StreamCase { const char* name; bool thinking; bool tools; std::string output; size_t calls; };
const std::string call_ls = "<tool_call>\n<function=bash>\n<parameter=command>\nls -l \"a b\" | head -n 3\n"
"</parameter>\n</function>\n</tool_call>";
const std::string answer = "A lighthouse stands on the cape: caf\xC3\xA9 lights, 2 < 3 and <b>bold</b>.\n\n"
"```json\n{\"a\": [1, 2], \"s\": \"x\\ny\"}\n```\nIt writes <tool and <function= as text.";
const StreamCase cases[] = {
{"reasoning then answer", true, false, "The user asks.\nTwo steps.\n</think>\n\n" + answer, 0},
{"answer, thinking off", false, false, answer, 0},
{"answer, tools declared", true, true, "No tool is needed.\n</think>\n\n" + answer, 0},
{"answer, tools declared, thinking off", false, true, answer, 0},
{"text then a tool call", true, true, "List first.\n</think>\n\nI will list the files.\n\n" + call_ls, 1},
{"a tool call alone", false, true, call_ls, 1},
{"two tool calls", true, true, "Both.\n</think>\n\n" + call_ls + "\n" + call_ls, 2},
};
for (const StreamCase& c : cases) {
auto body = common_json::parse_no_throw(R"({"messages":[{"role":"user","content":"Describe a lighthouse."}],
"stream":true})");
if (c.tools) body["tools"] = request.at("tools");
body["chat_template_kwargs"] = common_json::object();
body["chat_template_kwargs"]["enable_thinking"] = c.thinking;
Prepared prepared;
assert(server.prepare(body, prepared, error));
const common_chat_msg whole = common_chat_parse(c.output, false, prepared.parser);
StreamParse parse;
std::string content, reasoning;
size_t content_deltas = 0, reasoning_deltas = 0, call_deltas = 0, steps = 0;
bool calls_only_at_end = true;
auto take = [&](const std::vector<common_chat_msg_diff>& diffs, bool partial) {
for (const auto& d : diffs) {
if (!d.content_delta.empty()) { content += d.content_delta; ++content_deltas; }
if (!d.reasoning_content_delta.empty()) { reasoning += d.reasoning_content_delta; ++reasoning_deltas; }
if (d.tool_call_index != std::string::npos) { ++call_deltas; if (partial) calls_only_at_end = false; }
}
};
for (size_t n = 1; n < c.output.size(); ++n) {
if (utf8_complete_prefix(c.output.substr(0, n)) != n) continue;
take(parse.step(c.output.substr(0, n), true, prepared.parser), true);
++steps;
}
take(parse.step(c.output, false, prepared.parser), false);
std::printf("stream case '%s': %zu steps, %zu reasoning deltas, %zu content deltas, %zu tool-call deltas\n",
c.name, steps, reasoning_deltas, content_deltas, call_deltas);
if (std::getenv("STREAM_TEST_VERBOSE"))
std::printf(" whole content [%s]\n streamed [%s]\n", whole.content.c_str(), content.c_str());
assert(reasoning == whole.reasoning_content);
// the streamed answer is the whole one; before a tool call it may keep the white space the parser trims
assert(content.compare(0, whole.content.size(), whole.content) == 0);
assert(content.find_first_not_of(" \n", whole.content.size()) == std::string::npos);
assert(whole.content.size() < 20 || content_deltas * 2 >= whole.content.size());
assert(whole.reasoning_content.size() < 10 || reasoning_deltas * 2 >= whole.reasoning_content.size());
assert(whole.tool_calls.size() == c.calls && parse.msg.tool_calls.size() == c.calls);
assert(calls_only_at_end && call_deltas == c.calls);
for (size_t i = 0; i < c.calls; ++i) {
assert(parse.msg.tool_calls[i].arguments == "{\"command\":\"ls -l \\\"a b\\\" | head -n 3\"}");
assert(!parse.msg.tool_calls[i].id.empty());
}
}
// #123: reasoning_budget_tokens / reasoning_budget_message - the request's value wins over the command line's,
// a bad value is refused, thinking off leaves no budget, and the template's end-of-thinking tags are captured.
server.opt.reasoning_budget = 64;
server.opt.reasoning_budget_message = "server default";
Prepared budgeted;
assert(server.prepare(request, budgeted, error));
assert(budgeted.thinking);
assert(budgeted.reasoning_budget == 64);
assert(budgeted.reasoning_budget_message == "server default");
assert(!budgeted.thinking_end_tags.empty());
request["reasoning_budget_tokens"] = 128;
request["reasoning_budget_message"] = "You exhausted your reasoning tokens, come to a conclusion, now!";
assert(server.prepare(request, budgeted, error));
assert(budgeted.reasoning_budget == 128);
assert(budgeted.reasoning_budget_message == "You exhausted your reasoning tokens, come to a conclusion, now!");
request.erase("reasoning_budget_message");
request.erase("reasoning_budget_tokens");
request["reasoning_budget_tokens"] = -1;
assert(!server.prepare(request, budgeted, error));
request["reasoning_budget_tokens"] = "lots";
assert(!server.prepare(request, budgeted, error));
request.erase("reasoning_budget_tokens");
request["reasoning_effort"] = "none";
assert(server.prepare(request, budgeted, error));
assert(!budgeted.thinking && budgeted.reasoning_budget == 0);
request.erase("reasoning_effort");
// Sampling header: the launch-time defaults, overridden by a request's own fields; greedy is preserved;
// penalties apply even in greedy and get llama.cpp's 64-token window when none is set.
{
const common_json empty = common_json::parse_no_throw(R"({"messages":[]})");
Options neutral;
assert(sampling_keys(empty, neutral, server.vocab).empty()); // greedy, no penalties: exactly the old header
Options tuned = neutral;
tuned.temperature = 0.7; tuned.top_p = 0.9; tuned.top_k = 40; tuned.min_p = 0.05;
tuned.repeat_penalty = 1.05; tuned.presence_penalty = 0.3; tuned.frequency_penalty = 0.2;
tuned.repeat_last_n = 256; tuned.seed = 42;
const std::string k = sampling_keys(empty, tuned, server.vocab);
for (const char* s : {" temperature=0.7", " top_p=0.9", " top_k=40", " seed=42", " min_p=0.05",
" penalty_repeat=1.05", " penalty_present=0.3", " penalty_freq=0.2",
" penalty_last_n=256"})
assert(k.find(s) != std::string::npos);
// a request's own fields win; the ones it omits keep the launch default
const common_json override_body = common_json::parse_no_throw(
R"({"messages":[],"temperature":0.2,"top_k":8,"repeat_penalty":1.1,"repeat_last_n":512})");
const std::string ko = sampling_keys(override_body, tuned, server.vocab);
for (const char* s : {" temperature=0.2", " top_k=8", " top_p=0.9", " penalty_repeat=1.1",
" penalty_last_n=512"})
assert(ko.find(s) != std::string::npos);
// the greedy path honors penalties too, so a penalty applies with no temperature
const common_json penalty_body = common_json::parse_no_throw(R"({"messages":[],"presence_penalty":0.5})");
const std::string kp = sampling_keys(penalty_body, neutral, server.vocab);
assert(kp.find("temperature") == std::string::npos);
assert(kp.find(" penalty_present=0.5") != std::string::npos);
assert(kp.find(" penalty_last_n=64") != std::string::npos);
// DRY: emitted only when the multiplier and the window are both set; the default breakers are tokenized
// here (the engine has no tokenizer) and encoded as ids; a request's own list wins.
Options dry = neutral;
dry.dry_multiplier = 0.8; dry.dry_base = 1.75; dry.dry_allowed_length = 2; dry.dry_penalty_last_n = 256;
const std::string kd = sampling_keys(empty, dry, server.vocab);
for (const char* s : {" dry_multiplier=0.8", " dry_base=1.75", " dry_allowed_length=2",
" dry_penalty_last_n=256", " dry_breakers="})
assert(kd.find(s) != std::string::npos);
assert(sampling_keys(empty, neutral, server.vocab).find("dry_") == std::string::npos);
const common_json dry_body = common_json::parse_no_throw(
R"({"messages":[],"dry_multiplier":0.5,"dry_penalty_last_n":128,"dry_sequence_breakers":["\n"]})");
const std::string kb = sampling_keys(dry_body, neutral, server.vocab);
assert(kb.find(" dry_multiplier=0.5") != std::string::npos);
assert(kb.find(" dry_penalty_last_n=128") != std::string::npos);
assert(kb.find(" dry_breakers=") != std::string::npos);
}
llama_model_free(server.model);
std::puts("PASS: omitted parallel_tool_calls uses the model capability; explicit false remains honored; "
"tool arguments parse in any order; the answer streams as it grows and tool calls arrive whole; "
"reasoning_budget_tokens and its message override the command line; the sampling header honors the "
"launch defaults, a request's overrides, greedy and the penalty window");
"tool arguments parse in any order");
}
+4 -65
View File
@@ -9,7 +9,6 @@
#include <mutex>
#include <string>
#include <vector>
#include <chrono>
#include <csignal>
#include <unistd.h>
@@ -19,7 +18,6 @@ struct GenResult {
std::string error;
std::string finish = "length";
long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0;
long long reasoning_tokens = 0; // #123: tokens generated inside the thinking block (a budget wrap-up included)
double prompt_ms = 0, decode_ms = 0;
};
@@ -48,19 +46,11 @@ public:
return out_ != nullptr;
}
/// Reads the engine's start-up lines until it says READY. Loading the model takes minutes. The READY line
/// carries the context the engine actually allocated (`READY <max_context> stop`): its VRAM plan may have
/// lowered the request, and the front end's request limit and /v1/models follow that figure, not --ctx.
bool wait_ready(std::string& err, long long* context = nullptr) {
/// Reads the engine's start-up lines until it says READY. Loading the model takes minutes.
bool wait_ready(std::string& err) {
std::string line;
while (read_line(line)) {
if (line.rfind("READY", 0) == 0) {
if (context != nullptr) {
const long long n = std::atoll(line.c_str() + 5);
if (n > 0) *context = n;
}
return true;
}
if (line.rfind("READY", 0) == 0) return true;
if (line.rfind("ERR", 0) == 0) { err = line; return false; }
}
err = "the engine exited before it was ready (its messages are above)";
@@ -81,26 +71,6 @@ public:
}
req += '\n';
if (!send(req)) { r.error = "the engine is not running"; return r; }
// Live progress (llama.cpp prints while it works; the engine does not). The engine is silent for the whole
// of a long prompt - a 154k-token prompt is minutes at a few tens of tokens a second - and a request that is
// merely slow then reads as hung. One stderr line per STRATA_PROGRESS seconds (default 5, 0 = off), between
// the request's start line and the engine's own end-of-request summary, which is unchanged.
static const double progress_s = [] {
const char* v = std::getenv("STRATA_PROGRESS");
if (v == nullptr) return 5.0;
const double x = std::atof(v);
return x > 0.0 ? x : 0.0;
}();
auto last_report = std::chrono::steady_clock::now();
auto decode_t0 = last_report;
long long pp_done = 0, pp_total = (long long) ids.size(), n_out = 0;
auto report_ok = [&]() -> bool {
if (progress_s <= 0.0) return false;
const auto now = std::chrono::steady_clock::now();
if (std::chrono::duration<double>(now - last_report).count() < progress_s) return false;
last_report = now;
return true;
};
bool stopped = false;
std::string callback_error;
std::string line;
@@ -119,22 +89,6 @@ public:
send("STOP\n");
}
}
if (++n_out == 1) decode_t0 = std::chrono::steady_clock::now();
if (report_ok()) {
const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - decode_t0).count();
std::fprintf(stderr, "unbiased-strata: decoding: %lld tokens, %.1f tok/s\n",
n_out, s > 0.0 ? (double) n_out / s : 0.0);
}
} else if (line.rfind("PP ", 0) == 0) {
long long done = 0, total = 0;
double ms = 0.0, tps = 0.0;
std::sscanf(line.c_str(), "PP %lld %lld %lf %lf", &done, &total, &ms, &tps);
if (done > 0) pp_done = done;
if (total > 0) pp_total = total;
if (report_ok())
std::fprintf(stderr, "unbiased-strata: prompt processing: %lld/%lld (%.1f%%), %.1f tok/s\n",
pp_done, pp_total,
pp_total > 0 ? 100.0 * (double) pp_done / (double) pp_total : 0.0, tps);
} else if (line.rfind("DONE ", 0) == 0) {
char finish[32] = {0};
std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld", &r.produced, &r.prompt_n, &r.prompt_ms,
@@ -154,28 +108,13 @@ public:
r.error = line.size() > 4 ? line.substr(4) : "the engine reported an error";
return r;
}
// RESUME, REUSED and INFO lines need no action here (PP is reported above)
// PP (prompt progress), RESUME, REUSED and INFO lines need no action here
}
alive_ = false;
r.error = "the engine exited during the request";
return r;
}
/// One command line between requests (the caller holds `mu`): the engine's one-line reply whose first word is
/// `reply_prefix` lands in `reply`; an ERR line is the error. `STATS` is the one in use (the server's /health).
bool command(const std::string& line, const char* reply_prefix, std::string& reply, std::string& err) {
if (!alive_) { err = "the engine is not running"; return false; }
if (!send(line + "\n")) { err = "the engine is not running"; return false; }
std::string got;
while (read_line(got)) {
if (got.rfind(reply_prefix, 0) == 0) { reply = got; return true; }
if (got.rfind("ERR", 0) == 0) { err = got.size() > 4 ? got.substr(4) : "the engine reported an error"; return false; }
}
alive_ = false;
err = "the engine exited";
return false;
}
void quit() {
if (pid_ > 0) {
send("QUIT\n");
-13
View File
@@ -10,12 +10,6 @@ int main(int argc, char** argv) {
const std::string request(line);
if (request == "QUIT\n") break;
if (request == "STOP\n") continue;
if (request == "STATS\n") { // the tier census and counters, one line (the server's /health)
std::printf("STATS {\"experts\":10240,\"vram_slots\":3555,\"ram_copies\":4954,\"mapped\":1731}\n");
std::fflush(stdout);
continue;
}
if (request == "STATS BAD\n") { std::printf("ERR STATS: no such form\n"); std::fflush(stdout); continue; }
if (request.rfind("GEN ", 0) != 0) continue;
if (request.find("88") != std::string::npos) {
std::printf("T 88\nDONE 1 2 1 1 stop 0 0\n");
@@ -45,13 +39,6 @@ int main(int argc, char** argv) {
tokens.clear();
next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; });
assert(next.ok && (tokens == std::vector<int32_t>{99,100}));
// STATS between requests: the one-line reply by its prefix, an ERR as the error, and the next request unharmed
std::string reply;
assert(engine.command("STATS", "STATS ", reply, error) && reply.find("\"vram_slots\":3555") != std::string::npos);
assert(!engine.command("STATS BAD", "STATS ", reply, error) && error.find("no such form") != std::string::npos && engine.alive());
tokens.clear();
next = engine.generate("GEN 2 ", {99}, [&](int32_t token) { tokens.push_back(token); return true; });
assert(next.ok && (tokens == std::vector<int32_t>{99,100}));
auto mismatched = engine.generate("GEN 2 ", {88}, [](int32_t) { return true; });
assert(!mismatched.ok && !engine.alive());
assert(mismatched.error.find("prompt size mismatch") != std::string::npos);
+81 -423
View File
@@ -19,7 +19,6 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
@@ -40,26 +39,12 @@ int strata_engine_main(int argc, char** argv);
namespace {
// the model id reported on /v1/models and in every completion: the GGUF's base name (`Qwen3.6-35B-A3B-UD-IQ3_XXS`,
// `Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS` for shard 1 without its `-00001-of-00002`), set once the options are parsed
std::string g_model_name = "unbiased-strata";
std::string model_name_of(const std::string& path) {
std::string b = path.substr(path.find_last_of('/') == std::string::npos ? 0 : path.find_last_of('/') + 1);
if (b.size() > 5 && b.compare(b.size() - 5, 5, ".gguf") == 0) b.resize(b.size() - 5);
const size_t at = b.rfind("-00001-of-");
if (at != std::string::npos) b.resize(at);
return b.empty() ? std::string("unbiased-strata") : b;
}
const char* const kModelName = "qwen3.8-flash-next-iq3_xxs";
// The engine's serve loop refuses a request unless prompt + max_new + this margin fits --ctx
// (src/program/generate.cpp:6403): the last cells are the engine's own, not ours to hand out.
constexpr long long kEngineReserve = 8;
// #123: what is injected before the thinking's end tag when reasoning_budget_tokens is reached. The wording is
// switchable (--reasoning-budget-message, or the request's reasoning_budget_message); the default is upstream
// Strata's own wrap-up line.
const char* const kDefaultReasoningBudgetMessage = "I have thought about this long enough; time to give my answer.";
struct Options {
std::string model; // shard 1 of the GGUF
std::string pack; // the prepared pack directory
@@ -71,29 +56,6 @@ struct Options {
long long ctx = 32768;
int threads = 0; // CPU expert workers; 0 = the engine's default (every physical core)
bool fit_max_tokens = true; // shorten a request's max_tokens to the room left instead of refusing it
long long vram_cap_mib = 0; // --vram-cap: the engine limits itself to a smaller card's VRAM
double ram_cap_gib = 0.0; // --ram-cap: bounds the engine's RAM expert tier and pinned arena
long long reasoning_budget = 0; // cap the thinking of every request (0: no cap; a request can set its own)
std::string reasoning_budget_message = kDefaultReasoningBudgetMessage; // injected before the end tag
// Sampling defaults: a request's own fields win over these. Temperature <= 0 keeps the documented default
// (greedy) and emits no filters, exactly as before; the rest are the engine's own neutral values, so an
// unconfigured front end changes nothing.
double temperature = 0.0; // > 0 samples; 0 (default) is greedy
double top_p = 0.95;
long long top_k = 20; // the engine's sampler takes 1..64
double min_p = 0.0; // 0 disables
long long repeat_last_n = 0; // penalty window; 0 with a penalty set falls back to 64
double repeat_penalty = 1.0; // 1.0 disables
double presence_penalty = 0.0; // 0.0 disables
double frequency_penalty = 0.0; // 0.0 disables
// DRY (llama.cpp's `dry` sampler): breaks looping generations by penalising a token that would extend a
// repeat longer than `dry_allowed_length`. Off unless the multiplier and the window are both set.
double dry_multiplier = 0.0; // 0.0 disables
double dry_base = 1.75; // the exponent base (>= 1)
long long dry_allowed_length = 2; // repeats of this length or less are free
long long dry_penalty_last_n = 0; // the DRY window in tokens (0 disables)
std::vector<std::string> dry_breakers; // restart sequences; empty uses "\n", ":", "\"", "*"
long long seed = -1; // -1: a fresh random seed per request
std::vector<std::string> extra; // after `--`: passed to the engine as they are
};
@@ -108,40 +70,11 @@ void usage() {
" --ctx N context length in tokens (default 32768)\n"
" --fit-max-tokens / --no-fit-max-tokens\n"
" shorten a request's max_tokens to the room left instead of refusing it (default: on)\n"
" --reasoning-budget-tokens N\n"
" cap the thinking of every request at N tokens (default: 0, no cap; a request's own\n"
" reasoning_budget_tokens wins)\n"
" --reasoning-budget-message TEXT\n"
" injected before the end-of-thinking tag when the budget is reached (default: a short\n"
" wrap-up line; a request's own reasoning_budget_message wins)\n"
" --threads N CPU threads for the experts the GPU does not hold (default: every physical core,\n"
" or half the CPU quota inside a container that has one)\n"
" --host ADDR address to listen on (default 127.0.0.1)\n"
" --port N port to listen on (default 8080)\n"
" --vram-cap MIB emulate a smaller card: the engine uses at most MIB of VRAM (a 1080 Ti as 6 GB: 5722)\n"
" --ram-cap GIB bound the engine's RAM expert tier and pinned arena to GIB\n\n"
"Sampling defaults (a request's own temperature/top_p/top_k/min_p/seed/presence_penalty/\n"
"frequency_penalty/repeat_penalty/repeat_last_n wins; greedy unless the effective temperature is > 0):\n"
" --temperature F sampling temperature (default 0 = greedy)\n"
" --top-k N top-k shortlist, 1..64 (default 20)\n"
" --top-p F nucleus probability, 0..1 (default 0.95)\n"
" --min-p F min-p floor, 0..1 (default 0, off)\n"
" --repeat-last-n N repetition-penalty window in tokens (default 0; a penalty set here or in a\n"
" request forces at least 64)\n"
" --repeat-penalty F repetition penalty, > 0 (default 1.0, off)\n"
" --presence-penalty F presence penalty (default 0.0, off)\n"
" --frequency-penalty F frequency penalty (default 0.0, off)\n"
" --dry-multiplier F DRY repetition penalty; 0 disables (default 0.0)\n"
" --dry-base F DRY exponent base, >= 1 (default 1.75)\n"
" --dry-allowed-length N free repeat length before DRY applies (default 2)\n"
" --dry-penalty-last-n N the DRY window in tokens; 0 disables (default 0)\n"
" --dry-breakers LIST restart sequences as literal text separated by '|' (default \n:|\"|*)\n"
" --seed N sampling seed (default: a fresh random seed per request)\n\n"
"Serves POST /v1/chat/completions (OpenAI style, with streaming), GET /v1/models and GET /health (with the\n"
"engine's expert tiers and per-token counters: VRAM slots, RAM copies, mapped experts, hits, warm hints,\n"
"major page faults).\n"
"STRATA_PROGRESS=SECONDS prints a prompt-processing/decoding line to stderr every SECONDS while a request\n"
"runs (default 5; 0 turns it off).\n");
" --port N port to listen on (default 8080)\n\n"
"Serves POST /v1/chat/completions (OpenAI style, with streaming), GET /v1/models and GET /health.\n");
}
bool file_exists(const std::string& p) {
@@ -199,137 +132,12 @@ struct Prepared {
std::shared_ptr<strata_frontend::ImageFile> images;
std::vector<llama_token> ids;
std::string header; // "GEN <max_new> key=value ... " - the ids follow
std::string gen_prefix; // "GEN " / "GENI ": the header without max_new and the keys
std::string gen_suffix; // the sampling keys (and the image path): the rest of the header
std::string request_id;
common_chat_parser_params parser; // how to split the output into reasoning, answer and tool calls
std::vector<std::string> thinking_end_tags; // from the chat template: what ends the reasoning block
std::string reasoning_budget_message; // injected before the end tag at the budget
bool thinking = true; // the template was rendered with thinking on
long long reasoning_budget = 0; // #123: cap the thinking at this many tokens (0: off)
bool stream = false;
long long max_new = 0;
};
/// The sampling keys of one request's engine header: the launch-time defaults (`opt`) with the request's own
/// OpenAI / llama.cpp fields winning. Greedy is preserved: an effective temperature <= 0 emits no temperature
/// and no filters, and the penalties and their window are emitted only when a penalty is actually set (a
/// non-neutral value). The order is fixed, so the header is reproducible for a given input.
std::string sampling_keys(const common_json& body, const Options& opt, const llama_vocab* vocab) {
auto number = [&](const char* key, double fallback) {
return body.contains(key) && body.at(key).is_number() ? body.at(key).get<double>() : fallback;
};
auto integer = [&](const char* key, long long fallback) {
return body.contains(key) && body.at(key).is_number() ? body.at(key).get<long long>() : fallback;
};
auto text = [](double v) { char b[32]; std::snprintf(b, sizeof b, "%g", v); return std::string(b); };
std::string keys;
const double temperature = number("temperature", opt.temperature);
if (temperature > 0.0) {
const double top_p = number("top_p", opt.top_p);
const long long top_k = std::max(1LL, std::min(64LL, integer("top_k", opt.top_k)));
const double min_p = number("min_p", opt.min_p);
const unsigned long long seed = body.contains("seed") && body.at("seed").is_number()
? (unsigned long long) body.at("seed").get<long long>()
: (opt.seed >= 0 ? (unsigned long long) opt.seed : (unsigned long long) std::random_device{}());
keys += " temperature=" + text(temperature) + " top_p=" + text(top_p) +
" top_k=" + std::to_string(top_k) + " seed=" + std::to_string(seed);
if (min_p > 0.0) keys += " min_p=" + text(min_p);
}
// llama.cpp's names: presence_penalty, frequency_penalty, repeat_penalty; repeat_last_n is the window.
const double penalty_repeat = number("repeat_penalty", opt.repeat_penalty);
const double penalty_freq = number("frequency_penalty", opt.frequency_penalty);
const double penalty_present = number("presence_penalty", opt.presence_penalty);
if (penalty_repeat != 1.0 || penalty_freq != 0.0 || penalty_present != 0.0) {
if (penalty_repeat != 1.0) keys += " penalty_repeat=" + text(penalty_repeat);
if (penalty_freq != 0.0) keys += " penalty_freq=" + text(penalty_freq);
if (penalty_present != 0.0) keys += " penalty_present=" + text(penalty_present);
// a penalty with a zero window is a no-op in the sampler, so give it llama.cpp's default of 64
const long long window = integer("repeat_last_n", integer("penalty_last_n", opt.repeat_last_n));
keys += " penalty_last_n=" + std::to_string(window > 0 ? window : 64);
}
// DRY (llama.cpp's `dry`): emitted only when it is actually on (multiplier and window both set). The restart
// sequences are tokenized here - the engine has no tokenizer - and sent as ids ("id,id|id|...", sequences by
// '|'); a request's own `dry_sequence_breakers` array wins over the launch-time list, else llama.cpp's default.
const double dry_multiplier = number("dry_multiplier", opt.dry_multiplier);
const long long dry_window = integer("dry_penalty_last_n", opt.dry_penalty_last_n);
if (dry_multiplier != 0.0 && dry_window != 0) {
const double dry_base = number("dry_base", opt.dry_base);
const long long dry_allowed = std::max(0LL, integer("dry_allowed_length", opt.dry_allowed_length));
std::vector<std::string> breakers = opt.dry_breakers;
if (body.contains("dry_sequence_breakers") && body.at("dry_sequence_breakers").is_array()) {
breakers.clear();
for (const auto& e : body.at("dry_sequence_breakers"))
if (e.is_string()) breakers.push_back(e.get<std::string>());
}
if (breakers.empty()) breakers = {"\n", ":", "\"", "*"};
std::string enc;
for (const std::string& s : breakers) {
if (s.empty()) continue;
const std::vector<llama_token> ids = common_tokenize(vocab, s, /*add_special=*/false, /*parse_special=*/true);
if (ids.empty()) continue;
if (!enc.empty()) enc += '|';
for (size_t k = 0; k < ids.size(); ++k) { if (k) enc += ','; enc += std::to_string((long long) ids[k]); }
}
keys += " dry_multiplier=" + text(dry_multiplier) + " dry_base=" + text(dry_base) +
" dry_allowed_length=" + std::to_string(dry_allowed) +
" dry_penalty_last_n=" + std::to_string(dry_window);
if (!enc.empty()) keys += " dry_breakers=" + enc;
}
return keys;
}
/// The parse of one response as its text grows: what has been published, and what to publish next.
///
/// Reasoning and answer text are published as they arrive. Tool calls are published once, from the parse of the
/// complete message: while a call is being written its arguments are partial JSON that the parser closes and
/// normalizes on every token, so text already parsed can change (an escape, a number still being written), and
/// an OpenAI stream cannot take back what it sent. The same rule keeps the answer text sound: a partial parse
/// whose content does not extend what was published (the parser reread the tail as the start of a tool call)
/// publishes nothing for the content until it does. This changes delivery, never generated tokens.
struct StreamParse {
common_chat_msg msg; // what has been published
std::vector<std::string> call_ids;
std::vector<common_chat_msg_diff> step(const std::string& text, bool partial, const common_chat_parser_params& parser) {
common_chat_msg now;
try {
now = common_chat_parse(text, partial, parser);
} catch (const std::exception&) {
if (partial) return {}; // not parseable yet: wait for more text
now = common_chat_msg();
now.role = "assistant";
now.content = text;
}
now.content_parts.clear();
if (partial) {
now.tool_calls.clear();
if (now.content.compare(0, msg.content.size(), msg.content) != 0) now.content = msg.content;
if (now.reasoning_content.compare(0, msg.reasoning_content.size(), msg.reasoning_content) != 0)
now.reasoning_content = msg.reasoning_content;
} else {
// the complete parse decides; text it no longer holds was already sent and stays sent (the parser
// trims the white space before a tool call, which the partial parses still carried)
for (auto field : {&common_chat_msg::content, &common_chat_msg::reasoning_content}) {
const std::string& sent = msg.*field;
std::string& whole = now.*field;
if (whole.compare(0, sent.size(), sent) == 0) continue;
if (sent.compare(0, whole.size(), whole) != 0)
std::fprintf(stderr, "unbiased-strata: the complete message's %s differs from the %zu bytes "
"already streamed; the stream keeps what it sent\n",
field == &common_chat_msg::content ? "content" : "reasoning", sent.size());
whole = sent;
}
}
if (now.empty()) return {};
now.set_tool_call_ids(call_ids, [] { return "call_" + make_id().substr(9); });
std::vector<common_chat_msg_diff> diffs = common_chat_msg_diff::compute_diffs(msg, now);
msg = now;
return diffs;
}
};
struct Server {
Options opt;
Engine engine;
@@ -384,36 +192,8 @@ struct Server {
in.enable_thinking = kw.at("enable_thinking").get<bool>();
if (kw.contains("reasoning_effort") && kw.at("reasoning_effort").is_string())
in.chat_template_kwargs["reasoning_effort"] = kw.at("reasoning_effort").dump();
// Qwen3.6's template drops the reasoning of every reply before the last user message unless this is
// set; with it (and the client sending reasoning_content back) the history renders as it was
// generated, so the next turn reuses the checkpoint at the end of the reply, not only the one at
// its header
if (kw.contains("preserve_thinking") && kw.at("preserve_thinking").is_boolean())
in.chat_template_kwargs["preserve_thinking"] = kw.at("preserve_thinking").dump();
}
// #123: a hard thinking cap. The request's own reasoning_budget_tokens / reasoning_budget_message win; the
// command line sets the default for every request. A bad value is a 400 before anything is generated.
p.thinking = in.enable_thinking;
p.reasoning_budget = opt.reasoning_budget;
p.reasoning_budget_message = opt.reasoning_budget_message;
if (body.contains("reasoning_budget_tokens")) {
const common_json& v = body.at("reasoning_budget_tokens");
if (!v.is_number_integer() || v.get<long long>() < 0) {
err = "reasoning_budget_tokens must be 0 or more (0: no budget)";
return false;
}
p.reasoning_budget = v.get<long long>();
}
if (body.contains("reasoning_budget_message")) {
if (!body.at("reasoning_budget_message").is_string()) {
err = "reasoning_budget_message must be a string";
return false;
}
p.reasoning_budget_message = body.at("reasoning_budget_message").get<std::string>();
}
if (!p.thinking) p.reasoning_budget = 0; // thinking off: nothing to cap
const common_chat_params cp = common_chat_templates_apply(tmpls.get(), in);
p.thinking_end_tags = cp.thinking_end_tags;
std::string rendered = cp.prompt;
if (images.empty()) {
p.ids = common_tokenize(vocab, rendered, false, true);
@@ -454,10 +234,6 @@ struct Server {
p.parser.parse_tool_calls = true;
if (!cp.parser.empty()) p.parser.parser.load(cp.parser);
// The engine refuses a request unless prompt + max_new + 8 <= context (generate.cpp, the GEN handler), so
// the slots it keeps back are not ours to promise. Without this a client that asks for "as much as fits"
// (pi sends max_tokens 32768 on a 64K card) was refused on every prompt longer than ctx - max_tokens.
constexpr long long kEngineReserve = 8;
const long long n = (long long) p.ids.size();
const long long room = opt.ctx - n - kEngineReserve;
if (room < 1) {
@@ -484,13 +260,36 @@ struct Server {
p.max_new = max_new;
p.stream = body.value("stream", false);
// sampling: the launch-time defaults with the request's own fields winning (see sampling_keys)
const std::string keys = sampling_keys(body, opt, vocab);
// The header's parts are kept so a continuation (a thinking budget wrap-up) can rebuild it with a smaller
// max_new; the assembled header is byte-for-byte the one this fork always sent.
p.gen_prefix = p.images ? "GENI " : "GEN ";
p.gen_suffix = keys + " " + (p.images ? p.images->path + " " : "");
p.header = p.gen_prefix + std::to_string(max_new) + p.gen_suffix;
// sampling: greedy unless the request sets a temperature above zero
std::string keys;
const double temperature = body.contains("temperature") && body.at("temperature").is_number()
? body.at("temperature").get<double>() : 0.0;
if (temperature > 0.0) {
const double top_p = body.contains("top_p") && body.at("top_p").is_number() ? body.at("top_p").get<double>() : 0.95;
long long top_k = body.contains("top_k") && body.at("top_k").is_number() ? body.at("top_k").get<long long>() : 20;
top_k = std::max(1LL, std::min(64LL, top_k)); // the engine's sampler takes 1..64
unsigned long long seed;
if (body.contains("seed") && body.at("seed").is_number()) seed = (unsigned long long) body.at("seed").get<long long>();
else seed = std::random_device{}();
char b[160];
std::snprintf(b, sizeof b, " temperature=%g top_p=%g top_k=%lld seed=%llu", temperature, top_p, top_k, seed);
keys += b;
if (body.contains("min_p") && body.at("min_p").is_number()) {
std::snprintf(b, sizeof b, " min_p=%g", body.at("min_p").get<double>());
keys += b;
}
}
for (const auto& kv : {std::pair<const char*, const char*>{"presence_penalty", "penalty_present"},
std::pair<const char*, const char*>{"frequency_penalty", "penalty_freq"},
std::pair<const char*, const char*>{"repeat_penalty", "penalty_repeat"}})
if (body.contains(kv.first) && body.at(kv.first).is_number()) {
char b[64];
std::snprintf(b, sizeof b, " %s=%g", kv.second, body.at(kv.first).get<double>());
keys += b;
if (keys.find("penalty_last_n") == std::string::npos) keys += " penalty_last_n=64";
}
p.header = (p.images ? "GENI " : "GEN ") + std::to_string(max_new) + keys + " " +
(p.images ? p.images->path + " " : "");
// Opt-in provenance capture: the exact first rendered request this
// process serves, including token IDs and the engine sampling header.
if (const char* path = std::getenv("SUGMEOFF_CAPTURE_FIRST_PROMPT")) {
@@ -514,8 +313,6 @@ struct Server {
u["prompt_tokens"] = r.prompt_n;
u["completion_tokens"] = r.produced;
u["total_tokens"] = r.prompt_n + r.produced;
u["completion_tokens_details"] = common_json::object();
u["completion_tokens_details"]["reasoning_tokens"] = r.reasoning_tokens;
return u;
}
@@ -533,104 +330,54 @@ struct Server {
}
/// Runs one request. The text produced so far is parsed by llama.cpp's chat parser after every token, and
/// `emit` gets what changed (reasoning and answer text as they grow, tool calls once the message is complete:
/// see StreamParse); it returns false when the client has gone. `final_msg` is the whole parsed message.
/// `keepalive`, when given, is called whenever 15 s pass without an emit (a long tool call is silent while
/// its arguments are written): the stream writes an SSE comment, which keeps clients with an idle timeout
/// (pi: 5 minutes) attached and notices a client that has gone, so the generation is cancelled instead of
/// running to the end for nobody.
/// `emit` gets what changed (reasoning, answer text, tool-call pieces); it returns false when the client has
/// gone. `final_msg` is the whole parsed message.
GenResult run(const Prepared& p, common_chat_msg& final_msg,
const std::function<bool(const std::vector<common_chat_msg_diff>&)>& emit,
const std::function<bool()>& keepalive = {}) {
const std::function<bool(const std::vector<common_chat_msg_diff>&)>& emit) {
std::lock_guard<std::mutex> lk(engine.mu);
std::fprintf(stderr, "unbiased-strata: request %s start: prompt=%zu header=%s\n",
p.request_id.c_str(), p.ids.size(), p.header.c_str());
std::string text, pending;
StreamParse parse;
common_chat_msg& msg = parse.msg;
common_chat_msg msg;
std::vector<std::string> call_ids;
bool client_ok = true;
auto last_write = std::chrono::steady_clock::now();
auto update = [&](bool partial) {
const std::vector<common_chat_msg_diff> diffs = parse.step(text, partial, p.parser);
if (client_ok && !diffs.empty()) {
client_ok = emit(diffs);
last_write = std::chrono::steady_clock::now();
common_chat_msg now;
try {
now = common_chat_parse(text, partial, p.parser);
} catch (const std::exception&) {
if (partial) return; // not parseable yet: wait for more text
now = common_chat_msg();
now.role = "assistant";
now.content = text;
}
// Partial tool JSON is reparsed and normalized as tokens arrive.
// Escapes and incomplete arguments can change already-parsed text,
// which cannot be retracted from an OpenAI stream. Publish content
// and tool calls once, after the full message is parsed; reasoning
// can still stream. This changes delivery, never generated tokens.
if (partial) {
now.content.clear();
now.content_parts.clear();
now.tool_calls.clear();
}
if (now.empty()) return;
now.set_tool_call_ids(call_ids, [] { return "call_" + make_id().substr(9); });
const std::vector<common_chat_msg_diff> diffs = common_chat_msg_diff::compute_diffs(msg, now);
msg = now;
if (client_ok && !diffs.empty()) client_ok = emit(diffs);
};
// #123: a hard thinking cap (reasoning_budget_tokens). When the thinking reaches the budget it is closed
// with the budget message and the model's end tag, and the model answers from there. The wrap-up is fed
// like generated text and the engine is asked again with prompt + generated + wrap-up, continuing from the
// prefix it already holds, so nothing is read twice. Off unless thinking is on and a budget is set.
bool budget_on = p.thinking && p.reasoning_budget > 0;
long long thought = 0; // reasoning tokens generated so far (the budget's count)
long long produced = 0; // every generated token, the wrap-up included
bool seen_end = false; // an end-of-thinking tag is in `text`
auto reasoning_over = [&]() {
for (const std::string& tag : p.thinking_end_tags)
if (!tag.empty() && text.find(tag) != std::string::npos) return true;
return false;
};
auto feed = [&](llama_token id) {
GenResult r = engine.generate(p.header, p.ids, [&](llama_token id) {
if (llama_vocab_is_eog(vocab, id)) return client_ok;
pending += common_token_to_piece(vocab, id, /*special=*/true);
const size_t n = utf8_complete_prefix(pending);
if (n > 0) {
text.append(pending, 0, n);
pending.erase(0, n);
if (p.stream) update(true); // a whole response is parsed once, at the end
update(true);
}
};
GenResult r;
r.ok = true;
std::vector<llama_token> prompt_ids = p.ids;
while (true) {
bool budget_reached = false;
std::vector<llama_token> pass_ids;
const std::string header = p.gen_prefix + std::to_string(p.max_new - produced) + p.gen_suffix;
GenResult pass = engine.generate(header, prompt_ids, [&](llama_token id) {
if (llama_vocab_is_eog(vocab, id)) return client_ok;
pass_ids.push_back(id);
if (budget_on && !seen_end) ++thought;
feed(id);
if (!seen_end && reasoning_over()) seen_end = true;
if (budget_on && !seen_end && thought >= p.reasoning_budget && pending.empty()) {
budget_reached = true; // engine STOP; the client is still here
return false;
}
if (client_ok && keepalive) {
const auto now = std::chrono::steady_clock::now();
if (now - last_write >= std::chrono::seconds(15)) {
client_ok = keepalive();
last_write = now;
}
}
return client_ok;
});
if (!pass.ok) { r = pass; break; }
produced += pass.produced;
r.ok = true;
r.finish = pass.finish;
r.prompt_ms += pass.prompt_ms;
r.decode_ms += pass.decode_ms;
r.draft_accepted += pass.draft_accepted;
r.draft_offered += pass.draft_offered;
if (!budget_reached || !client_ok) break;
budget_on = false; // wrap the thinking up at most once
const std::string end_tag = p.thinking_end_tags.empty() ? std::string(" response")
: p.thinking_end_tags.front();
const std::vector<llama_token> extra =
common_tokenize(vocab, "\n\n" + p.reasoning_budget_message + end_tag + "\n\n", false, true);
if (p.max_new - produced - (long long) extra.size() < 1) break; // no room to answer: "length"
std::fprintf(stderr, "unbiased-strata: request %s thinking budget reached (%lld tokens): wrapping up\n",
p.request_id.c_str(), thought);
for (llama_token t : extra) { pass_ids.push_back(t); feed(t); }
prompt_ids.insert(prompt_ids.end(), pass_ids.begin(), pass_ids.end());
produced += (long long) extra.size();
}
if (r.ok) {
r.prompt_n = (long long) p.ids.size(); // usage reports the request's own prompt, not a continuation's
r.produced = produced;
r.reasoning_tokens = thought;
}
return client_ok;
});
text += pending;
try {
update(false);
@@ -691,7 +438,7 @@ struct Server {
out["id"] = id;
out["object"] = "chat.completion";
out["created"] = created;
out["model"] = g_model_name;
out["model"] = kModelName;
out["choices"] = common_json::array();
out["choices"].push_back(choice);
out["usage"] = usage_json(r);
@@ -712,7 +459,7 @@ struct Server {
out["id"] = id;
out["object"] = "chat.completion.chunk";
out["created"] = created;
out["model"] = g_model_name;
out["model"] = kModelName;
out["choices"] = common_json::array();
out["choices"].push_back(choice);
if (done) { out["usage"] = usage_json(*done); out["timings"] = timings_json(*done); }
@@ -744,10 +491,6 @@ struct Server {
ok = ok && chunk(d, nullptr, nullptr);
}
return ok;
}, [&]() {
static const std::string ka = ": keepalive\n\n"; // an SSE comment: every client ignores it
ok = ok && sink.write(ka.data(), ka.size());
return ok;
});
if (ok) {
if (r.ok) {
@@ -826,35 +569,7 @@ bool parse_args(int argc, char** argv, Options& o) {
else if (a == "--ctx") o.ctx = std::atoll(next("--ctx").c_str());
else if (a == "--fit-max-tokens") o.fit_max_tokens = true;
else if (a == "--no-fit-max-tokens") o.fit_max_tokens = false;
else if (a == "--reasoning-budget-tokens") o.reasoning_budget = std::atoll(next("--reasoning-budget-tokens").c_str());
else if (a == "--reasoning-budget-message") o.reasoning_budget_message = next("--reasoning-budget-message");
else if (a == "--threads") o.threads = std::atoi(next("--threads").c_str());
else if (a == "--vram-cap") o.vram_cap_mib = std::atoll(next("--vram-cap").c_str());
else if (a == "--ram-cap") o.ram_cap_gib = std::atof(next("--ram-cap").c_str());
else if (a == "--temperature" || a == "--temp") o.temperature = std::atof(next("--temperature").c_str());
else if (a == "--top-k") o.top_k = std::atoll(next("--top-k").c_str());
else if (a == "--top-p") o.top_p = std::atof(next("--top-p").c_str());
else if (a == "--min-p") o.min_p = std::atof(next("--min-p").c_str());
else if (a == "--repeat-last-n") o.repeat_last_n = std::atoll(next("--repeat-last-n").c_str());
else if (a == "--repeat-penalty") o.repeat_penalty = std::atof(next("--repeat-penalty").c_str());
else if (a == "--presence-penalty") o.presence_penalty = std::atof(next("--presence-penalty").c_str());
else if (a == "--frequency-penalty") o.frequency_penalty = std::atof(next("--frequency-penalty").c_str());
else if (a == "--dry-multiplier") o.dry_multiplier = std::atof(next("--dry-multiplier").c_str());
else if (a == "--dry-base") o.dry_base = std::atof(next("--dry-base").c_str());
else if (a == "--dry-allowed-length") o.dry_allowed_length = std::atoll(next("--dry-allowed-length").c_str());
else if (a == "--dry-penalty-last-n") o.dry_penalty_last_n = std::atoll(next("--dry-penalty-last-n").c_str());
else if (a == "--dry-breakers") {
const std::string list = next("--dry-breakers");
o.dry_breakers.clear();
for (size_t p = 0; p <= list.size();) {
const size_t bar = list.find('|', p);
const size_t end = bar == std::string::npos ? list.size() : bar;
o.dry_breakers.push_back(list.substr(p, end - p));
if (bar == std::string::npos) break;
p = bar + 1;
}
}
else if (a == "--seed") o.seed = std::atoll(next("--seed").c_str());
else if (a == "--") {
for (++i; i < argc; ++i) {
const std::string e = argv[i];
@@ -871,20 +586,6 @@ bool parse_args(int argc, char** argv, Options& o) {
else if (a == "-h" || a == "--help") return false;
else { std::fprintf(stderr, "unbiased-strata: unknown option %s\n\n", a.c_str()); return false; }
}
if (o.reasoning_budget < 0) {
std::fprintf(stderr, "unbiased-strata: --reasoning-budget-tokens must be 0 or more (0: no budget)\n\n");
return false;
}
if (!std::isfinite(o.temperature) || !std::isfinite(o.top_p) || !std::isfinite(o.min_p) ||
!std::isfinite(o.repeat_penalty) || !std::isfinite(o.presence_penalty) || !std::isfinite(o.frequency_penalty) ||
!std::isfinite(o.dry_multiplier) || !std::isfinite(o.dry_base) ||
o.repeat_penalty <= 0.0 || o.top_p <= 0.0 || o.top_p > 1.0 || o.min_p < 0.0 || o.min_p > 1.0 ||
o.repeat_last_n < 0 || o.dry_base < 1.0 || o.dry_allowed_length < 0 || o.dry_penalty_last_n < 0) {
std::fprintf(stderr, "unbiased-strata: sampling options must be finite (--repeat-penalty positive, "
"--top-p/--min-p in 0..1, --repeat-last-n 0 or more, --dry-base >= 1, "
"--dry-allowed-length/--dry-penalty-last-n 0 or more)\n\n");
return false;
}
return !o.model.empty() && !o.pack.empty() && !o.mtp.empty();
}
@@ -896,20 +597,19 @@ int main(int argc, char** argv) {
Server srv;
Options& o = srv.opt;
if (!parse_args(argc, argv, o)) { usage(); return 2; }
g_model_name = model_name_of(o.model);
// every file the engine needs must already be here: nothing is fetched
// Flash-Next ships as two shards and the second holds the PLE table, so it is the engine's --ple-gguf; a one-file
// model (Qwen3.6-35B-A3B) has no PLE and no second shard, and the engine decides from the file's architecture
std::string shard2 = o.model;
const size_t at = shard2.rfind("-00001-of-00002");
if (at != std::string::npos) shard2.replace(at, 15, "-00002-of-00002");
else shard2.clear();
if (at == std::string::npos) {
std::fprintf(stderr, "unbiased-strata: --model must be the first shard (...-00001-of-00002.gguf)\n");
return 2;
}
shard2.replace(at, 15, "-00002-of-00002");
const std::string profile = o.pack + "/expert-profile.bin";
// draft_vocab.bin is the draft head's vocabulary subset; a Qwen3.6 draft pack built with the full head
// (tools/mtp_qwen36_pack.py --full-head) has none and the engine then drafts over the whole vocabulary
for (const std::string& f : {o.model, shard2, o.pack + "/index.txt", profile, o.mtp + "/experts.bin"})
if (!f.empty() && !file_exists(f)) { std::fprintf(stderr, "unbiased-strata: missing file: %s\n", f.c_str()); return 2; }
for (const std::string& f : {o.model, shard2, o.pack + "/index.txt", profile, o.mtp + "/experts.bin",
o.mtp + "/draft_vocab.bin"})
if (!file_exists(f)) { std::fprintf(stderr, "unbiased-strata: missing file: %s\n", f.c_str()); return 2; }
if (o.ctx < 1024) { std::fprintf(stderr, "unbiased-strata: --ctx must be at least 1024\n"); return 2; }
if (!o.mmproj.empty() && (!file_exists(o.mmproj) || o.vision_tokens < 16 || o.vision_tokens > 4096)) {
@@ -917,12 +617,9 @@ int main(int argc, char** argv) {
}
// the engine, started first: loading takes minutes, and it must be forked before any thread exists
std::vector<std::string> eargs = {
"unbiased-strata", "--engine", "--serve", "--pack", o.pack, "--native", o.model,
"unbiased-strata", "--engine", "--serve", "--pack", o.pack, "--native", o.model, "--ple-gguf", shard2,
"--expert-profile", profile, "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5",
"--mtp", o.mtp, "--max-context", std::to_string(o.ctx)};
if (!shard2.empty()) { eargs.push_back("--ple-gguf"); eargs.push_back(shard2); eargs.push_back("--ple-io"); eargs.push_back("ram"); }
if (o.vram_cap_mib > 0) { eargs.push_back("--vram-cap"); eargs.push_back(std::to_string(o.vram_cap_mib)); }
if (o.ram_cap_gib > 0.0) { eargs.push_back("--ram-cap"); eargs.push_back(std::to_string(o.ram_cap_gib)); }
"--mtp", o.mtp, "--max-context", std::to_string(o.ctx), "--ple-io", "ram"};
if (!o.mmproj.empty()) eargs.push_back("--vision");
if (o.ctx > 8192) { eargs.push_back("--kv"); eargs.push_back("int8"); }
if (o.threads <= 0) {
@@ -958,62 +655,23 @@ int main(int argc, char** argv) {
}
std::fprintf(stderr, "unbiased-strata: loading the model (this takes a few minutes)...\n");
long long engine_ctx = 0;
if (!srv.engine.wait_ready(err, &engine_ctx)) {
if (!srv.engine.wait_ready(err)) {
std::fprintf(stderr, "unbiased-strata: %s\n", err.c_str());
srv.engine.quit();
return 1;
}
if (engine_ctx > 0 && engine_ctx != o.ctx) { // the engine's VRAM plan lowered the context: serve that one
std::fprintf(stderr, "unbiased-strata: the engine allocated a context of %lld tokens, not the %lld requested; "
"requests are bounded by %lld\n", engine_ctx, o.ctx, engine_ctx);
o.ctx = engine_ctx;
}
httplib::Server http;
g_server = &srv;
g_http = &http;
// /health: ok or error, plus the engine's expert tiers and counters when it is between requests (STATS: VRAM
// slots and how many hold an expert, RAM copies, mapped experts, tokens served, VRAM hits of lookups, RAM-copy
// and file reads, warm hints, major page faults). During a request the last reading is served, marked stale.
// httplib serves /health from several threads: the last reading has its own lock (engine.mu is the engine's,
// taken only to ask), and every read of it is a copy under that lock.
static std::mutex stats_mu;
static std::string last_stats;
http.Get("/health", [&](const httplib::Request&, httplib::Response& res) {
res.status = srv.engine.alive() ? 200 : 503;
std::string body = srv.engine.alive() ? "{\"status\":\"ok\"" : "{\"status\":\"error\"";
if (srv.engine.alive()) {
std::unique_lock<std::mutex> lk(srv.engine.mu, std::try_to_lock);
if (lk.owns_lock()) {
std::string reply, err;
const bool got = srv.engine.command("STATS", "STATS ", reply, err);
lk.unlock();
std::string stats;
{
std::lock_guard<std::mutex> sl(stats_mu);
if (got) last_stats = reply.substr(6);
stats = last_stats;
}
if (!got && stats.empty()) body += ",\"tiers_error\":\"" + err + "\"";
if (!stats.empty()) body += ",\"tiers\":" + stats;
} else {
std::string stats;
{
std::lock_guard<std::mutex> sl(stats_mu);
stats = last_stats;
}
if (!stats.empty()) body += ",\"tiers\":" + stats + ",\"tiers_stale\":true";
else body += ",\"busy\":true";
}
}
body += "}";
res.set_content(body, "application/json");
res.set_content(srv.engine.alive() ? "{\"status\":\"ok\"}" : "{\"status\":\"error\"}", "application/json");
});
http.Get("/v1/models", [&](const httplib::Request&, httplib::Response& res) {
if (!srv.engine.alive()) return json_error(res, 503, "the engine is not running", "server_error");
common_json m = common_json::object();
m["id"] = g_model_name;
m["id"] = kModelName;
m["object"] = "model";
m["owned_by"] = "local";
m["context_length"] = srv.opt.ctx;
+1 -11
View File
@@ -74,17 +74,7 @@ public:
auto key = gg ? gguf_find_key(gg.get(), "clip.vision.projection_dim") : -1;
if (key < 0) throw std::runtime_error("vision encoder has no projection_dim");
width_ = (int) gguf_get_val_u32(gg.get(), key);
// the projector must produce rows of the model's own width (2560 for Flash-Next, 2048 for Qwen3.6-35B-A3B);
// the tokenizer-only model the front end holds has no hparams, so the width is read from its metadata
char arch[64] = {0}, val[32] = {0};
int want = 0;
if (llama_model_meta_val_str(model, "general.architecture", arch, sizeof arch) > 0 &&
llama_model_meta_val_str(model, (std::string(arch) + ".embedding_length").c_str(), val, sizeof val) > 0)
want = std::atoi(val);
if (want <= 0) throw std::runtime_error("cannot read the model's embedding width");
if (width_ != want)
throw std::runtime_error("vision projector width " + std::to_string(width_) +
" does not match the model's embedding width " + std::to_string(want));
if (width_ != 2560) throw std::runtime_error("vision projector does not match Flash-Next's 2560 embedding width");
max_tokens_ = max_tokens;
auto cp = mtmd_context_params_default();
cp.use_gpu = false; cp.print_timings = false; cp.warmup = false;
+17 -38
View File
@@ -570,12 +570,8 @@ private:
std::map<std::string, std::pair<size_t, const TensorInfo*>> index_;
};
// ---- architecture guard (P1.S2). The engine is specialised to ONE family; anything else must be refused
// with a precise error rather than silently mis-run. Two architecture strings pass: `qwen4exp` (Qwen3.8-Flash-Next,
// the model the kernels were written for: its six keys are checked against the compiled-in values) and `qwen35moe`
// (Qwen3.6-35B-A3B, Phase 2 of docs/PLAN-qwen36-35b-a3b.md: the file is the authority on every size, so its keys
// are checked for PRESENCE only, and `strata::core::read_model_geometry` reads them). Passing this guard says the
// metadata is readable, not that the engine runs the model: the Qwen3.6 start stops at its own gate afterwards.
// ---- architecture guard (P1.S2). The engine is specialised to ONE model; anything else must be
// refused with a precise error rather than silently mis-run.
struct Qwen4ExpGuard {
uint32_t block_count = 48, hidden = 2560, experts = 0, experts_used = 0, head_count = 24,
head_count_kv = 2; // 0 = presence-only: pruned variants (GSQ-RCO Coder) legitimately ship
@@ -585,43 +581,26 @@ struct Qwen4ExpGuard {
inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& want = {}) {
const MetaValue* arch = g.get("general.architecture");
if (!arch) return "missing general.architecture";
if (arch->s != "qwen4exp") return "architecture is '" + arch->s + "', this engine requires 'qwen4exp'";
struct Req {
const char* key;
uint64_t want;
};
if (arch->s == "qwen4exp") {
const Req reqs[] = {
{"qwen4exp.block_count", want.block_count},
{"qwen4exp.embedding_length", want.hidden},
{"qwen4exp.expert_count", want.experts},
{"qwen4exp.expert_used_count", want.experts_used},
{"qwen4exp.attention.head_count", want.head_count},
{"qwen4exp.attention.head_count_kv", want.head_count_kv},
};
for (const auto& r : reqs) {
const MetaValue* v = g.get(r.key);
if (!v) return std::string("missing ") + r.key;
if (r.want && v->u != r.want)
return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want);
}
return {}; // empty == ok
const Req reqs[] = {
{"qwen4exp.block_count", want.block_count},
{"qwen4exp.embedding_length", want.hidden},
{"qwen4exp.expert_count", want.experts},
{"qwen4exp.expert_used_count", want.experts_used},
{"qwen4exp.attention.head_count", want.head_count},
{"qwen4exp.attention.head_count_kv", want.head_count_kv},
};
for (const auto& r : reqs) {
const MetaValue* v = g.get(r.key);
if (!v) return std::string("missing ") + r.key;
if (r.want && v->u != r.want)
return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want);
}
if (arch->s == "qwen35moe") {
// llama.cpp's qwen35moe loader requires these (src/models/qwen35moe.cpp:4-34, llama-model.cpp:1254-1380);
// the engine's geometry reader derives everything else from them
static const char* const keys[] = {
"qwen35moe.block_count", "qwen35moe.embedding_length", "qwen35moe.expert_count",
"qwen35moe.expert_used_count", "qwen35moe.attention.head_count", "qwen35moe.attention.head_count_kv",
"qwen35moe.attention.key_length", "qwen35moe.full_attention_interval", "qwen35moe.ssm.conv_kernel",
"qwen35moe.ssm.state_size", "qwen35moe.ssm.group_count", "qwen35moe.ssm.time_step_rank",
"qwen35moe.ssm.inner_size", "qwen35moe.expert_feed_forward_length",
};
for (const char* k : keys)
if (!g.get(k)) return std::string("missing ") + k + " (a qwen35moe file llama.cpp's own loader would refuse)";
return {};
}
return "architecture is '" + arch->s + "', this engine requires 'qwen4exp' (Qwen3.8-Flash-Next) or 'qwen35moe' "
"(Qwen3.6-35B-A3B)";
return {}; // empty == ok
}
} // namespace strata
-7
View File
@@ -80,10 +80,6 @@ struct HostMemory {
bool host_available_memory(HostMemory& m, const std::string& meminfo = "/proc/meminfo",
const std::string& self_cgroup = "/proc/self/cgroup",
const std::string& cgroup_root = "/sys/fs/cgroup");
/// --ram-cap (Qwen3.6 port, step 2): every `host_available_memory` answer is clamped to this many bytes, so the RAM
/// tier is sized as a machine of that much RAM would size it. 0 = no cap.
void set_host_ram_cap(uint64_t bytes);
uint64_t host_ram_cap();
/// Build compact offsets for experts absent from both the primary GPU cache and an optional second GPU tier.
/// Kept CPU-only so selection and byte accounting can be tested without initializing a GPU.
@@ -470,8 +466,6 @@ public:
uint64_t resident_bytes() const { return complement_bytes_; }
bool complement_pinned() const { return complement_pinned_; }
bool complement_ready() const { return complement_ready_; }
/// How many experts the RAM copy holds (the RAM tier's count for the start-up log and /health; 0 before it is built).
int64_t complement_count() const;
uint64_t locked_bytes() const { return complement_locked_; }
/// Lend-region slots whose experts the compact copy holds (the last ones of the cache).
int64_t resident_lent_slots() const { return complement_lent_slots_; }
@@ -615,7 +609,6 @@ private:
const uint8_t* complement_device_ = nullptr;
uint64_t complement_bytes_ = 0;
std::vector<uint64_t> complement_offsets_;
int64_t complement_count_ = 0; ///< experts in the RAM copy (counted when it is built)
bool complement_pinned_ = false;
bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered
uint64_t complement_pin_limit_ = 0;
-31
View File
@@ -277,10 +277,6 @@ uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_ro
/// resident state).
void qsa_set_kv_resident(int64_t cells);
int64_t qsa_kv_resident();
/// Whether KV streaming applies to this geometry. Dense attention (Qwen3.6, no indexer) reads every cell every
/// token, so streaming would copy the whole KV over PCIe per token: false, with `why` for the CLI's refusal.
/// `qsa_state_init` refuses the same way as a backstop.
bool qsa_kv_streaming_applies(const ModelGeometry& g, std::string& why);
/// The fewest resident cells a streamed layer may have: one verify window's selections (8 queries x 2,051 cells
/// in whole blocks) must fit at once, with room to spare.
int64_t qsa_kv_resident_min();
@@ -483,35 +479,8 @@ void layer_set_fast_select(bool enabled);
/// Plan v0.3 P6: whether the current decode configuration is the one the speculative verify window reproduces
/// bit for bit (native projections, fused GR and GDN, split-K attention, block selection, native indexer).
bool layer_verify_compatible(std::string& why);
/// The same for a model's geometry: at `hc = 1` (Qwen3.6) there is no hyper-connection read to fuse and, without an
/// indexer, no block selection and no native indexer to require. The no-geometry form above is Flash-Next's.
bool layer_verify_compatible(const ModelGeometry& g, std::string& why);
uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b);
// ================================ THE PLAIN BLOCK (hc = 1, Qwen3.6) ================================
//
// `hc = 1` (`ModelGeometry::hc`, set by the architecture string: docs/QWEN36-35B-A3B.md section 3.5) means NO
// hyper-connections: `R` is one n_embd stream and the block is llama.cpp's `qwen35moe` pre-norm residual block
//
// x = rms_norm(R) * attn_norm -> mixer -> R += out
// x = rms_norm(R) * post_attention_norm -> MoE -> R += out head: rms_norm(R) * output_norm -> output
//
// **IT IS A SECOND PATH CHOSEN BY `hc`, NOT THE GR PATH AT hc = 1.** `gr_read` on one stream is not a plain norm
// (its bottleneck gates the normed stream with a sigmoid and its norm weight is stored as `1 + w`), so the GR
// kernels are never entered for this model; `block_layer_pre`, `block_layer_post`, `lm_head_mix` and the verify
// window each branch on `g.hc == 1` to the two helpers below. There is no pending write either: the residual is
// added where the reference adds it, so `R` never lags between halves.
//
// The two helpers take a ROW COUNT so the verify window (T rows) and the single-token path (1 row) call the same
// kernels: row t of the T-row call is bitwise the one-row call (the norm has independent per-row statistics in a
// fixed reduction order; the add is elementwise). tests/cuda/qwen36_block_test.cpp asserts that.
/// `mixed[t] = rms_norm(R[t], eps) * w` over n_embd, for `n_tok` rows at stride n_embd (`w` is the F32 norm weight,
/// n_embd long; ggml's `rms_norm` then `mul`). `mixed` may equal `R` (in place) or must be disjoint.
void plain_norm_rows(const float* R, const float* w, float* mixed, int64_t n_embd, float eps, int n_tok, void* stream);
/// `R[t] += block_out[t]` over n_embd, for `n_tok` rows at stride n_embd.
void plain_residual_rows(float* R, const float* block_out, int64_t n_embd, int n_tok, void* stream);
// ================================ THE TWO ENDS OF A TOKEN ================================
/// THE EMBEDDING LOOKUP, done as a COLUMN DEQUANT rather than a GEMV.
+20 -62
View File
@@ -16,88 +16,46 @@
#pragma once
#include "strata/core/weights.hpp"
#include "strata/kernels/gdn.hpp"
#include <cstdint>
#include <string>
namespace strata::core {
/// Which architecture the model file declares. The engine was written for ONE model (Qwen3.8-Flash-Next,
/// `qwen4exp`); Qwen3.6-35B-A3B (`qwen35moe`) is the same family one generation earlier with the hyper-connection
/// residual, the sparse-attention indexer and the PLE table removed. The string decides what the file cannot say:
/// `hc`, the indexer and the PLE (docs/QWEN36-35B-A3B.md section 3.8).
enum class ModelArch { Qwen4Exp, Qwen35Moe };
inline const char* model_arch_name(ModelArch a) { return a == ModelArch::Qwen4Exp ? "qwen4exp" : "qwen35moe"; }
/// The model's geometry. Every field here is a number a kernel depends on, so a change is a change to a kernel
/// contract and not a tuning knob. The defaults are Qwen3.8-Flash-Next's (`docs/semantics.md`); a model file
/// overrides every one of them through `read_model_geometry` (strata/core/model_geometry.hpp), which reads the
/// `<arch>.*` keys of the GGUF and derives the dependent members below with `derive()`.
/// The model's geometry, taken from `docs/semantics.md` and the artifact's own metadata. Every field here
/// is a number a kernel depends on, so a change is a change to a kernel contract and not a tuning knob.
struct ModelGeometry {
ModelArch arch = ModelArch::Qwen4Exp;
int64_t n_embd = 2560;
int64_t n_layers = 48; ///< trunk layers: `block_count` minus the draft (`nextn_predict_layers`) blocks
int64_t nextn_layers = 0; ///< MTP draft blocks at the end of the file (0 when the key is absent)
int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... (`full_attention_interval`)
int64_t n_vocab = 248320; ///< rows of `token_embd.weight` (both models share the tokenizer)
int64_t n_layers = 48;
int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... 47
// GDN (36 of 48 layers; 30 of 40 for Qwen3.6)
int64_t ssm_state_size = 128; ///< `ssm.state_size`: the head dim of k and v
int64_t ssm_k_heads = 16; ///< `ssm.group_count`
int64_t ssm_v_heads = 48; ///< `ssm.time_step_rank` (32 for Qwen3.6)
int64_t ssm_d_conv = 4; ///< `ssm.conv_kernel`
int64_t ssm_conv_channels = 10240; ///< DERIVED: 2*S*k_heads + S*v_heads (`derive()`); 8192 for Qwen3.6
int64_t ssm_value_dim = 6144; ///< DERIVED: S*v_heads (`ssm.inner_size` in the file); 4096 for Qwen3.6
// GDN (36 layers)
int64_t ssm_state_size = 128;
int64_t ssm_k_heads = 16;
int64_t ssm_v_heads = 48;
int64_t ssm_d_conv = 4;
int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48
int64_t ssm_value_dim = 6144; ///< 128 * 48
// full attention (QSA for Flash-Next: with an indexer; dense for Qwen3.6: no indexer)
int64_t n_head = 24; ///< `attention.head_count` (16 for Qwen3.6)
int64_t n_head_kv = 2; ///< `attention.head_count_kv`
int64_t head_dim = 256; ///< `attention.key_length`
int64_t n_rot = 64; ///< `rope.dimension_count`: the partial rotary width (0.25 * head_dim)
int64_t rope_sections[4] = {11, 11, 10, 0}; ///< `rope.dimension_sections` (IMRoPE), sum == n_rot / 2
double rope_base = 1e7; ///< `rope.freq_base`
double rms_eps = 1e-6; ///< `attention.layer_norm_rms_epsilon`
int64_t idx_q_heads = 4; ///< the QSA indexer's query heads (Flash-Next only; meaningless at hc 1)
int64_t idx_key_dim = 128; ///< the QSA indexer's key width (Flash-Next only)
// QSA (12 layers)
int64_t n_head = 24;
int64_t n_head_kv = 2;
int64_t head_dim = 256;
int64_t idx_q_heads = 4;
int64_t idx_key_dim = 128;
// gated residual, on every layer. `hc = 1` means NO hyper-connections: a plain residual with `attn_norm`,
// `post_attention_norm` and `output_norm` (Qwen3.6). No key says this; the architecture string does.
// gated residual, on every layer
int64_t hc = 4;
int64_t hc_lr = 320;
// MoE, on every layer
int64_t n_expert = 512; ///< `expert_count` (256 for Qwen3.6)
int64_t n_expert_used = 10; ///< `expert_used_count`, the router's k (8 for Qwen3.6)
int64_t n_ff = 640; ///< `expert_feed_forward_length` (512 for Qwen3.6)
int64_t n_ff_shexp = 640; ///< `expert_shared_feed_forward_length` (512 for Qwen3.6)
/// The per-layer token embedding (PLE) and its n-gram table: Flash-Next has one, Qwen3.6 has none. Decides
/// whether `--ple-gguf` is required and whether the session carves the PLE history (strata/core/session.hpp).
bool has_ple = true;
int64_t n_expert = 512;
int64_t n_ff = 640;
int64_t hc_dim() const { return hc * n_embd; }
/// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list.
int64_t n_qsa_layers() const { return n_layers / qsa_interval; }
int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); }
/// Whether the full-attention layers carry the sparse indexer (QSA). Qwen3.6's attention is dense.
bool has_indexer() const { return arch == ModelArch::Qwen4Exp; }
/// The GDN output gate: `rms_norm(o) * ssm_norm * act(z)` with act = sigmoid for Flash-Next and SiLU for Qwen3.6
/// (geometry-inventory.md row 39; `kernels::GdnGate`). From the architecture, like `hc` and the indexer: no key
/// says it. Every GDN output kernel takes this value from the layer; none reads a global.
kernels::GdnGate gdn_gate() const {
return arch == ModelArch::Qwen35Moe ? kernels::GdnGate::Silu : kernels::GdnGate::Sigmoid;
}
/// The members that follow from others: conv channels `2*S*k_heads + S*v_heads` and the value dim
/// `S*v_heads`. They are stored (the kernels read them as plain members) and derived here, so a file that
/// changes `ssm_v_heads` cannot leave them at the defaults (geometry-inventory.md row 2).
void derive() {
ssm_value_dim = ssm_state_size * ssm_v_heads;
ssm_conv_channels = 2 * ssm_state_size * ssm_k_heads + ssm_value_dim;
}
};
/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval
-262
View File
@@ -1,262 +0,0 @@
// include/strata/core/model_geometry.hpp - `ModelGeometry` from the model file's own metadata.
//
// Until Phase 2 step 2 of docs/PLAN-qwen36-35b-a3b.md the geometry was a struct of Flash-Next defaults and only
// `expert_count`, `expert_used_count` and the rope keys were read, under the `qwen4exp.` prefix and only with
// `--native` (docs/qwen36-port/geometry-inventory.md rows 7 to 10). This header reads every field from the
// `<arch>.*` keys llama.cpp's own loader reads (`src/llama-model.cpp:1231-1424`, `src/models/qwen35moe.cpp:4-34`
// in the pinned submodule; the key set is docs/QWEN36-35B-A3B.md section 3.8), for both architectures, and names
// the tensor forms this engine refuses rather than mis-reads.
//
// Header-only and CUDA-free on purpose: the unit test (tests/core/model_geometry_test.cpp) links nothing but the
// GGUF reader, and the engine's start-up reads the geometry BEFORE any weight moves.
#pragma once
#include "strata/artifact/gguf_reader.hpp"
#include "strata/core/layout.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace strata::core {
namespace detail {
/// One integer key: `<arch>.<suffix>`. `required`: absent is an error; otherwise the default stays.
inline bool geometry_int(const strata::GgufFile& meta, const std::string& prefix, const char* suffix, int64_t& out,
bool required, std::string& err) {
const strata::MetaValue* v = meta.get(prefix + suffix);
if (v == nullptr) {
if (required) err = "missing " + prefix + suffix;
return !required;
}
if (!v->is_num()) {
err = prefix + suffix + " is not a number";
return false;
}
out = (int64_t) v->num();
return true;
}
inline bool geometry_num(const strata::GgufFile& meta, const std::string& prefix, const char* suffix, double& out,
bool required, std::string& err) {
const strata::MetaValue* v = meta.get(prefix + suffix);
if (v == nullptr) {
if (required) err = "missing " + prefix + suffix;
return !required;
}
if (!v->is_num()) {
err = prefix + suffix + " is not a number";
return false;
}
out = v->num();
return true;
}
} // namespace detail
/// Fills `g` from the metadata shard. Every field of `ModelGeometry` comes from the file where the file has a
/// key for it; the two models' keys differ only in the prefix. What the file cannot say is decided by the
/// architecture string: `hc` (4 with hyper-connections, 1 without), the indexer, the PLE. `n_layers` is
/// `block_count` minus the draft blocks (`nextn_predict_layers`, 0 when absent). A missing key the kernels
/// depend on, a value that is not a number, or a derived quantity the file states differently (`ssm.inner_size`
/// against `state_size * time_step_rank`) is an error that names the key.
inline bool read_model_geometry(const strata::GgufFile& meta, ModelGeometry& g, std::string& err) {
const strata::MetaValue* arch = meta.get("general.architecture");
if (arch == nullptr) { err = "missing general.architecture"; return false; }
if (arch->s == "qwen4exp") {
g = ModelGeometry{}; // Flash-Next's defaults, every one of them overridable below
g.arch = ModelArch::Qwen4Exp;
} else if (arch->s == "qwen35moe") {
g = ModelGeometry{};
g.arch = ModelArch::Qwen35Moe;
g.hc = 1; // plain residual: attn_norm / post_attention_norm / output_norm
g.hc_lr = 0;
g.has_ple = false; // no per-layer token embedding, no n-gram table
g.idx_q_heads = 0; // no sparse indexer: the attention is dense
g.idx_key_dim = 0;
} else {
err = "architecture is '" + arch->s + "', this engine reads 'qwen4exp' (Qwen3.8-Flash-Next) and 'qwen35moe' "
"(Qwen3.6-35B-A3B)";
return false;
}
const std::string p = arch->s + ".";
const bool q36 = g.arch == ModelArch::Qwen35Moe;
// the keys both loaders require (the architecture guard already demands the first six)
int64_t block_count = 0;
if (!detail::geometry_int(meta, p, "block_count", block_count, true, err)) return false;
if (!detail::geometry_int(meta, p, "nextn_predict_layers", g.nextn_layers, false, err)) return false;
if (!detail::geometry_int(meta, p, "embedding_length", g.n_embd, true, err)) return false;
if (!detail::geometry_int(meta, p, "attention.head_count", g.n_head, true, err)) return false;
if (!detail::geometry_int(meta, p, "attention.head_count_kv", g.n_head_kv, true, err)) return false;
if (!detail::geometry_int(meta, p, "expert_count", g.n_expert, true, err)) return false;
if (!detail::geometry_int(meta, p, "expert_used_count", g.n_expert_used, true, err)) return false;
// the keys Flash-Next's files may leave to the defaults (its loader has them hard-coded in places) and Qwen3.6's
// must carry: the GDN shape, the expert widths, the layer pattern, the attention widths
if (!detail::geometry_int(meta, p, "attention.key_length", g.head_dim, q36, err)) return false;
if (!detail::geometry_int(meta, p, "full_attention_interval", g.qsa_interval, q36, err)) return false;
if (!detail::geometry_int(meta, p, "ssm.conv_kernel", g.ssm_d_conv, q36, err)) return false;
if (!detail::geometry_int(meta, p, "ssm.state_size", g.ssm_state_size, q36, err)) return false;
if (!detail::geometry_int(meta, p, "ssm.group_count", g.ssm_k_heads, q36, err)) return false;
if (!detail::geometry_int(meta, p, "ssm.time_step_rank", g.ssm_v_heads, q36, err)) return false;
if (!detail::geometry_int(meta, p, "expert_feed_forward_length", g.n_ff, q36, err)) return false;
g.n_ff_shexp = g.n_ff;
if (!detail::geometry_int(meta, p, "expert_shared_feed_forward_length", g.n_ff_shexp, false, err)) return false;
if (!detail::geometry_int(meta, p, "rope.dimension_count", g.n_rot, false, err)) return false;
if (!detail::geometry_num(meta, p, "rope.freq_base", g.rope_base, false, err)) return false;
if (!detail::geometry_num(meta, p, "attention.layer_norm_rms_epsilon", g.rms_eps, false, err)) return false;
if (const strata::MetaValue* v = meta.get(p + "rope.dimension_sections")) {
if (v->type != strata::MetaType::ARRAY || v->items.size() != 4) {
err = p + "rope.dimension_sections is not an array of 4";
return false;
}
for (size_t i = 0; i < 4; ++i) g.rope_sections[i] = (int64_t) v->items[i].num();
}
// derived, then checked against what the file says of the same quantity
g.n_layers = block_count - g.nextn_layers;
g.derive();
int64_t inner = g.ssm_value_dim;
if (!detail::geometry_int(meta, p, "ssm.inner_size", inner, false, err)) return false;
auto bad = [&](const std::string& what) { err = p.substr(0, p.size() - 1) + ": " + what; return false; };
if (g.n_layers <= 0 || g.nextn_layers < 0)
return bad("block_count " + std::to_string(block_count) + " minus nextn_predict_layers " +
std::to_string(g.nextn_layers) + " leaves no trunk layer");
if (inner != g.ssm_value_dim)
return bad("ssm.inner_size is " + std::to_string(inner) + ", but ssm.state_size * ssm.time_step_rank is " +
std::to_string(g.ssm_value_dim));
if (g.qsa_interval <= 0 || g.n_layers % g.qsa_interval != 0)
return bad("block_count " + std::to_string(g.n_layers) + " is not a multiple of full_attention_interval " +
std::to_string(g.qsa_interval));
if (g.ssm_k_heads <= 0 || g.ssm_v_heads % g.ssm_k_heads != 0)
return bad("ssm.time_step_rank " + std::to_string(g.ssm_v_heads) + " is not a multiple of ssm.group_count " +
std::to_string(g.ssm_k_heads) + " (the recurrence pairs v-heads to k-heads by h % h_k)");
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv != 0)
return bad("attention.head_count " + std::to_string(g.n_head) + " is not a multiple of head_count_kv " +
std::to_string(g.n_head_kv));
if (g.n_expert_used <= 0 || g.n_expert_used > g.n_expert)
return bad("expert_used_count " + std::to_string(g.n_expert_used) + " over expert_count " +
std::to_string(g.n_expert));
if (g.n_rot <= 0 || g.n_rot > g.head_dim || g.n_rot % 2 != 0)
return bad("rope.dimension_count " + std::to_string(g.n_rot) + " does not fit attention.key_length " +
std::to_string(g.head_dim));
if (g.rope_sections[0] + g.rope_sections[1] + g.rope_sections[2] + g.rope_sections[3] != g.n_rot / 2)
return bad("rope.dimension_sections do not sum to rope.dimension_count / 2 = " + std::to_string(g.n_rot / 2));
// the vocabulary: `output.weight`'s rows are what the engine samples over (generate.cpp takes n_vocab from that
// tensor), `token_embd.weight`'s rows are what the native embedding loads with g.n_vocab, and the tokenizer's
// token list is the third statement of the same number. Whichever of the three the metadata shard carries must
// agree; the default (248,320, the shipped files') stands only when none is present (a metadata-only fixture).
{
int64_t seen[3] = {-1, -1, -1};
const char* names[3] = {"output.weight", "token_embd.weight", "tokenizer.ggml.tokens"};
if (const strata::TensorInfo* t = meta.find(names[0])) seen[0] = t->shape.size() >= 2 ? (int64_t) t->shape[1] : 0;
if (const strata::TensorInfo* t = meta.find(names[1])) seen[1] = t->shape.size() >= 2 ? (int64_t) t->shape[1] : 0;
if (const strata::MetaValue* v = meta.get(names[2]))
seen[2] = v->type == strata::MetaType::ARRAY ? (int64_t) v->count : 0; // `count` is the full length; `items` is capped
int64_t vocab = -1;
const char* from = nullptr;
for (int i = 0; i < 3; ++i) {
if (seen[i] < 0) continue;
if (seen[i] <= 0) return bad(std::string(names[i]) + " gives no vocabulary size");
if (vocab < 0) { vocab = seen[i]; from = names[i]; continue; }
if (seen[i] != vocab)
return bad(std::string(from) + " says " + std::to_string(vocab) + " tokens but " + names[i] + " says " +
std::to_string(seen[i]));
}
if (vocab > 0) g.n_vocab = vocab;
}
return true;
}
/// Reads the geometry from `any_shard`'s model (every shard found beside it; the metadata shard decides).
inline bool read_model_geometry(const std::string& any_shard, ModelGeometry& g, std::string& err) {
try {
const strata::GgufModel model = strata::GgufModel::open(any_shard);
return read_model_geometry(model.meta(), g, err);
} catch (const std::exception& e) {
err = e.what();
return false;
}
}
/// The tensor FORMS this engine refuses by name. llama.cpp accepts two fused layouts that no shipped Qwen3.6 file
/// uses (`gguf-metadata.md`, "What was unexpected"): experts fused as `ffn_gate_up_exps` (gate rows then up rows)
/// and an attention layer's projections fused as `attn_qkv` (Q | K | V rows). The engine reads three separate
/// expert tensors (`expert_source.cpp`, check_experts_gguf) and separate `attn_q` / `attn_k` / `attn_v`; `attn_qkv`
/// is legitimate ONLY in a GDN layer, where it is the conv input. A file in a fused form is refused here, naming
/// the tensor, instead of failing later on a shape or being split silently. Returns true when nothing is fused.
inline bool check_model_tensor_forms(const strata::GgufModel& model, const ModelGeometry& g, std::string& err) {
for (int64_t l = 0; l < g.n_layers + g.nextn_layers; ++l) {
const std::string blk = "blk." + std::to_string(l) + ".";
if (model.find(blk + "ffn_gate_up_exps.weight") != nullptr) {
err = blk + "ffn_gate_up_exps.weight: the experts are fused (llama.cpp's gate-then-up form); this engine "
"reads separate ffn_gate_exps / ffn_up_exps / ffn_down_exps tensors. No shipped Qwen3.6 file is "
"fused; re-convert the model without the fused experts";
return false;
}
const bool attention = l >= g.n_layers || is_qsa_layer(g, l);
if (attention && model.find(blk + "attn_qkv.weight") != nullptr && model.find(blk + "attn_q.weight") == nullptr) {
err = blk + "attn_qkv.weight: the attention projections are fused (llama.cpp's Q|K|V form); this engine "
"reads separate attn_q / attn_k / attn_v tensors in an attention layer (attn_qkv is the conv "
"input of a GDN layer only). No shipped Qwen3.6 file is fused; re-convert the model without it";
return false;
}
}
return true;
}
/// One line per field, for the start-up log and the test's --real mode.
inline std::string model_geometry_text(const ModelGeometry& g) {
std::string s;
auto add = [&](const char* k, int64_t v) { s += std::string(" ") + k + " " + std::to_string(v) + "\n"; };
s += std::string(" arch ") + model_arch_name(g.arch) + "\n";
add("n_embd", g.n_embd);
add("n_vocab", g.n_vocab);
add("n_layers", g.n_layers);
add("nextn_layers", g.nextn_layers);
add("qsa_interval", g.qsa_interval);
add("n_qsa_layers", g.n_qsa_layers());
add("n_gdn_layers", g.n_gdn_layers());
add("ssm_state_size", g.ssm_state_size);
add("ssm_k_heads", g.ssm_k_heads);
add("ssm_v_heads", g.ssm_v_heads);
add("ssm_d_conv", g.ssm_d_conv);
add("ssm_conv_channels", g.ssm_conv_channels);
add("ssm_value_dim", g.ssm_value_dim);
add("n_head", g.n_head);
add("n_head_kv", g.n_head_kv);
add("head_dim", g.head_dim);
add("n_rot", g.n_rot);
s += " rope_sections " + std::to_string(g.rope_sections[0]) + "," + std::to_string(g.rope_sections[1]) + "," +
std::to_string(g.rope_sections[2]) + "," + std::to_string(g.rope_sections[3]) + "\n";
s += " rope_base " + std::to_string(g.rope_base) + "\n";
s += " rms_eps " + std::to_string(g.rms_eps) + "\n";
add("idx_q_heads", g.idx_q_heads);
add("idx_key_dim", g.idx_key_dim);
add("hc", g.hc);
add("hc_lr", g.hc_lr);
add("n_expert", g.n_expert);
add("n_expert_used", g.n_expert_used);
add("n_ff", g.n_ff);
add("n_ff_shexp", g.n_ff_shexp);
s += std::string(" has_ple ") + (g.has_ple ? "yes" : "no") + "\n";
s += std::string(" has_indexer ") + (g.has_indexer() ? "yes" : "no") + "\n";
return s;
}
/// Phase 2 step 2's gate (docs/PLAN-qwen36-35b-a3b.md section 5): what this engine can and cannot yet do with a
/// `qwen35moe` file, said once and precisely, so a start fails here and not inside a kernel. Empty when the
/// architecture needs no gate.
inline std::string qwen35moe_not_yet(const ModelGeometry& g) {
if (g.arch != ModelArch::Qwen35Moe) return {};
return "this is a Qwen3.6-35B-A3B file (qwen35moe, " + std::to_string(g.n_layers) + " layers, " +
std::to_string(g.n_embd) + " wide, " + std::to_string(g.n_expert) + " experts x top-" +
std::to_string(g.n_expert_used) + "): Phase 2 step 2 (geometry, metadata, the VRAM plan above) is done, "
"but the engine cannot run it yet. Not done: step 3 (kernels and the block: the GDN gate SiLU(z) "
"instead of sigmoid(z), dense attention at " + std::to_string(g.n_head) + " heads with no indexer, the "
"block and the verify window without hyper-connections, prefill at this geometry), step 4 (the native "
"pack and the MTP drafter from blk." + std::to_string(g.n_layers) + ", the expert profile at " +
std::to_string(g.n_layers) + " x " + std::to_string(g.n_expert) + "). See docs/PLAN-qwen36-35b-a3b.md "
"section 5 and docs/qwen36-port/step2-notes.md";
}
} // namespace strata::core
+1 -45
View File
@@ -26,7 +26,6 @@
#include <cuda_runtime.h>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
@@ -80,9 +79,6 @@ public:
/// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a
/// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off.
void set_draft_sampling(const strata::kernels::SamplerParams& sp);
/// Coupled mode: the request's DRY sequence breakers (device pointers, alive across the request), used by the
/// draft chain so a drafted token follows the same DRY rule the verifying row's sample does. Empty for none.
void set_draft_breakers(const strata::kernels::DryBreakers& br) { draft_br_ = br; }
/// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the
/// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0).
void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);
@@ -97,37 +93,6 @@ public:
const float* tensor_f32(const char* name) const { return f32(name); }
const uint16_t* tensor_bf16(const char* name) const { return bf16(name); }
const void* tensor_q8(const char* name) const { return q8(name); }
/// A projection of the pack in its GGUF form (Qwen3.6's pack keeps every projection as stored: `nextn.eh_proj.weight`,
/// `attn_k.weight`, ...): its blocks and ggml type (`*type`), null when the name is not a native projection.
const void* tensor_native(const char* name, int* type) const;
// ---- QWEN3.6 (qwen35moe; docs/qwen36-port/step4-drafter.md). The drafter is the -MTP file's nextn block through
// the plain graph: concat(rms_norm(embed(tok)) * enorm, rms_norm(h) * hnorm) (embedding first), eh_proj, one plain
// attention + MoE block over the drafter's own dense KV, shared_head_norm, the main head. `h` is the trunk's
// OUTPUT-NORMED hidden state (llama.cpp's h_nextn): the drafter applies `output_norm` to the residual rows it is
// handed, so the caller passes the same final residual it passes for Flash-Next. Pairing: token k with the hidden
// state of position k-1 (common/speculative.cpp), the cell convention `prefill` / `draft` already use. The second
// path is chosen by the geometry's architecture; the Flash-Next path is unchanged.
bool qwen36() const;
/// The harness's one-row forward, outside any graph: the row's seams by llama.cpp's cb() names (`mtp_tok_embd`,
/// `mtp_enorm`, `mtp_hnorm`, `mtp_concat`, `mtp_eh_proj`, `mtp_attn_norm`, `mtp_Vcur`, `mtp_Kcur_normed` (before
/// RoPE), `mtp_Qcur_full`, `mtp_Qcur_normed` (before RoPE), `mtp_attn_pregate`, `mtp_attn_out`, `mtp_attn_residual`,
/// `mtp_attn_post_norm`, `ffn_moe_logits`, `ffn_moe_topk` (int32 ids behind the float pointer), `ffn_moe_weights_norm`,
/// `mtp_ffn_shexp_gated`, `mtp_ffn_out`, `mtp_post_ffn`, `mtp_shared_head_norm`, `result_output`), each handed to
/// `seam` after a stream sync with the device pointer and the element count; `top1` gets the draft (a vocabulary
/// id). `R_row` is the trunk's final residual (device), the K/V is written at `cell`, RoPE at `pos`. The rival
/// readings of `DebugOpts` are the harness's negative controls and nothing else sets them.
struct DebugOpts {
bool hidden_first = false; ///< concat(hnorm, enorm): the wrong order
bool skip_hnorm = false; ///< the hidden state's second norm (hnorm) left out
};
using SeamFn = std::function<void(const char* seam, const float* dev, int64_t n)>;
bool debug_row(const float* R_row, int32_t token, int64_t cell, int32_t pos, const DebugOpts& o, const SeamFn& seam,
int32_t* top1, std::string& err);
/// The draft block's expert blob (Qwen3.6): the native layout's types and bytes, for a reader of `experts.bin`.
int expert_gu_type() const { return exp_gu_type_; }
int expert_d_type() const { return exp_d_type_; }
int64_t expert_blob_bytes() const { return exp_blob_; }
QsaState& kv_state_rw() { return st_; }
int64_t first_needed() const { return (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; }
int device() const { return device_; }
@@ -138,14 +103,6 @@ public:
private:
bool record_forward(int T, int step_row0, cudaStream_t cs, std::string& err);
bool record_forward_qwen36(int T, int step_row0, cudaStream_t cs, std::string& err);
bool load_qwen36_experts(const std::string& rt_dir, const ModelGeometry& g, uint64_t& bytes, std::string& err);
bool check_qwen36_pack(const std::string& rt_dir, const ModelGeometry& g, std::string& err);
int exp_gu_type_ = -1, exp_d_type_ = -1; ///< Qwen3.6: the draft experts' GGUF types (native_expert_layout)
int64_t exp_blob_ = 0; ///< Qwen3.6: bytes per expert blob in experts_
float* cat_ = nullptr; ///< Qwen3.6: concat(enorm, hnorm), T x 2 n_embd
const DebugOpts* dbg_ = nullptr; ///< set by debug_row only
const SeamFn* seam_ = nullptr; ///< set by debug_row only
bool capture_prefill(int T, std::string& err);
bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device)
bool capture_round(int T, bool coupled, std::string& err);
@@ -160,7 +117,6 @@ private:
bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_)
int coupled_j_ = 0;
strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr;
strata::kernels::DryBreakers draft_br_ = {}; ///< set_draft_breakers: the coupled chain's DRY breakers
int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr;
void* cscratch_ = nullptr;
const float* f32(const char* name) const;
@@ -185,7 +141,7 @@ private:
int64_t pf_cap_ = 0; ///< its capacity in ints
cudaGraphExec_t round_exec_[9] = {};
struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; int type = -1; };
struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; };
std::vector<Tensor> tensors_;
uint8_t* dense_ = nullptr;
uint8_t* experts_ = nullptr;
-30
View File
@@ -1,30 +0,0 @@
// include/strata/core/qsa_shapes.hpp - THE ONE builder of a `QsaShapes` from a `ModelGeometry`.
//
// Five sites used to transcribe the same six assignments by hand (layer.cpp, verify.cpp, mtp.cpp, session.cpp and
// prefill.cpp), and the Qwen3.6 port showed what that costs: the geometry says "no indexer" with two zeros
// (`idx_q_heads`, `idx_key_dim`) while the kernels' dense predicate (`qsa_dense`) wants the selection budget
// `idx_top_k` zero as well - a builder that copies the two and keeps `qsa_real_shapes()`'s 2,048 makes a shape
// that is neither sparse nor dense, which `qsa.cu`'s guard refuses as "not set up" at the first KV append.
// Header-only so the parity test can build the shape without linking the engine.
#pragma once
#include "strata/core/layout.hpp"
#include "strata/kernels/qsa.hpp"
namespace strata::core {
/// The kernels' geometry for this model: the attention widths from the file, `n_rot`, `idx_block`, `page_size` and
/// (with an indexer) `idx_top_k` from the kernel contracts in `qsa_real_shapes()`; without an indexer the three
/// indexer widths are zero together, which is what `qsa_dense()` and the kernels' guard test.
inline strata::kernels::QsaShapes qsa_shapes(const ModelGeometry& g) {
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head;
s.n_head_kv = g.n_head_kv;
s.head_dim = g.head_dim;
s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
if (!g.has_indexer()) { s.idx_n_head = 0; s.idx_dim = 0; s.idx_top_k = 0; }
return s;
}
} // namespace strata::core
-23
View File
@@ -42,13 +42,6 @@ namespace strata::core {
class NativeHead;
class RemoteExpertOpt;
/// The geometry a verify window reproduces: at hc > 1 the fused hyper-connection read's shape (Flash-Next's
/// 2560 / 4 / 320), at hc = 1 the plain block (any width: layer.hpp, "the plain block"); `k` equal to the file's
/// `expert_used_count` (the window routes and combines with the session's k, and top-10 on a file that routes
/// top-8 is a different model, finite and fluent); GDN state 128 and conv 4 (the T-token GDN kernels' shapes).
/// False with `why` naming the number that differs. `Verifier::init` refuses on it; tests call it directly.
bool verify_geometry_supported(const ModelGeometry& g, int64_t k, std::string& why);
/// The CPU pool for a window: x_f (n_tok, n_embd), ids (n_tok, k) -> out (n_tok * k, n_embd), hit rows zeroed.
using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out,
int64_t layer);
@@ -89,13 +82,6 @@ public:
/// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t.
/// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use.
bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err);
/// Capture the T-token window graph NOW instead of on its first `run`. cudaGraphInstantiate allocates device
/// memory per window size and the exec is never freed (measured ~22-26 MiB per size on a GTX 1070 Ti,
/// 2026-10-15), so a size captured lazily spent the reserve one request at a time until an instantiate ran out
/// mid-request and the engine died. `serve` captures every size it can ask for (1..max_t) up front; `run` still
/// captures any size that was missed. False with `err` when the capture fails (the buffers or the exec did not
/// fit). Set `set_split`/`set_pcie_mode` first: the recorded graph depends on them.
bool capture_window(int T, std::string& err) { return capture(T, err); }
/// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run().
bool copy_logits(int t, float* host) const;
int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; }
@@ -107,14 +93,6 @@ public:
if (next_) next_->set_sampling(sp);
}
/// The DRY restart sequences (tokenized; device pointers) the head's sampler uses. Only the last stage
/// holds the head, so this forwards down a layer split like set_sampling; null (`n == 0`) is the default and
/// leaves the sampler byte-for-byte neutral. The buffers must stay alive across the request.
void set_breakers(const strata::kernels::DryBreakers& b) {
br_ = b;
if (next_) next_->set_breakers(b);
}
/// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len`
/// int32 slots at that stride (`strata::kernels::penalty_rows` builds them), most recent token LAST, unused
/// front slots -1 (the kernel reads only the tail window). Row t follows the window's drafts 1..t - staging
@@ -275,7 +253,6 @@ private:
const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply
int hist_len_ = 0;
bool head_sampling_ = true; ///< set_head_sampling
strata::kernels::DryBreakers br_ = {}; ///< DRY sequence breakers for the head's sampling (set_breakers)
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows
bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph
-3
View File
@@ -130,9 +130,6 @@ public:
const WeightRef* find(const std::string& name) const;
const std::map<std::string, WeightRef>& all() const { return table_; }
/// A test seam: one row, as `load` would have made it (the Qwen3.6 prefill harness builds a table from a synthetic
/// GGUF without a pack). The caller owns the device memory the row points at.
void set(const std::string& name, const WeightRef& ref) { table_[name] = ref; }
const LoadReport& report() const { return report_; }
private:
+1 -6
View File
@@ -74,12 +74,7 @@ void act_quant_any(const float* x, int n, ActQ& a);
const ExpertLayout& expert_layout();
/// Reads `<pack_dir>/native_experts.txt` when it exists (a native pack), else sets the canonical layout.
/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it).
/// `n_embd` / `n_ff` are the MODEL's widths (ModelGeometry, read from the model file): each layer's `NativeFmt` is
/// built with them and its byte count checked against the pack's blob size, so a pack of another geometry is refused
/// here by its numbers. Until Phase 2 step 2 of the Qwen3.6 port this passed the compile-time 2560/640
/// (geometry-inventory.md row 108), which refused every 2048/512 pack as "blob is X B but its formats make Y".
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff,
std::string& err);
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`,
/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte).
inline constexpr int kExpertLayoutVersion = 4;
+3 -8
View File
@@ -9,11 +9,9 @@
//
// S <- g S + k (beta (v - g S^T k))^T (g = exp(gate[head]), per value head; q/k shared by h_v / h_k heads)
// o = (S^T q) / sqrt(128)
// y = rmsnorm(o) * gamma * act(z) (act = sigmoid for Flash-Next, SiLU for Qwen3.6: `GdnGate`, gdn.hpp)
// y = rmsnorm(o) * gamma * sigmoid(z)
#pragma once
#include "strata/kernels/gdn.hpp"
#include <cstdint>
namespace strata::kernels {
@@ -30,11 +28,8 @@ void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, fl
void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
float* gate, float* beta, int n_embd, int h_v, void* stream);
/// The step and the output norm in one kernel: state (S, h_v, S) in place, q/k (h_k, 128) L2-normalised and NOT
/// pre-scaled (the 1/sqrt(S) goes on the readout), v/z/y (h_v, 128), gate/beta (h_v), gamma (128). `act` is the
/// model's output gate (`GdnGate`); `h_v % h_k == 0`, any h_v (Flash-Next 48, Qwen3.6 32).
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, GdnGate act, float* y,
int h_k, int h_v, void* stream);
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream);
} // namespace strata::kernels
+4 -17
View File
@@ -34,26 +34,13 @@
namespace strata::kernels {
/// Geometry of one GDN layer. Flash-Next: S = 128, h_k = 16, h_v = 48 (VPK 3); Qwen3.6-35B-A3B: S = 128,
/// h_k = 16, h_v = 32 (VPK 2). Every kernel here takes these at runtime; `h_v % h_k == 0` is the one rule.
/// Geometry of one GDN layer. The real artifact: S = 128, h_k = 16, h_v = 48.
struct GdnShapes {
int64_t S = 0; ///< head dim, and the state's contracted axis
int64_t h_k = 0; ///< key/query heads (q and k are (h_k, S))
int64_t h_v = 0; ///< value heads (v, z, o are (h_v, S)); h_v must be a multiple of h_k
};
/// The output gate's activation on `z` in `y = rms_norm(o) * ssm_norm * act(z)`. Flash-Next (`qwen4exp`) multiplies
/// by sigmoid(z); Qwen3.6 (`qwen35moe`) by SiLU(z) = z * sigmoid(z) - llama.cpp `qwen35moe.cpp:273` is `ggml_silu`,
/// and `qwen4exp.cpp:481` calls it "the one numerical difference". The oracle's negative control puts the two
/// readings 1.07 relative L1 apart at `final_output-0` (docs/qwen36-port/oracle-crosscheck.md), so this is a
/// per-model contract, not a tuning knob: the layer picks it from `ModelGeometry::arch`
/// (`ModelGeometry::gdn_gate()`), never from a global, so one process can serve both models. Every GDN output
/// kernel takes it as an argument (`gdn_out_norm`, `fused_gdn_step_norm`, `native_gdn_out_norm`,
/// `gdn_step_norm_multi`); the sigmoid arithmetic is bitwise what it was before the parameter existed.
enum class GdnGate : int { Sigmoid = 0, Silu = 1 };
inline const char* gdn_gate_name(GdnGate g) { return g == GdnGate::Silu ? "silu" : "sigmoid"; }
/// One step of the delta-rule recurrence, IN PLACE on `state`.
///
/// state (S, h_v, S) f32, j fastest, updated in place
@@ -100,11 +87,11 @@ void gdn_l2_norm(float* x, int64_t rows, int64_t cols, float eps, void* stream);
/// `ref/gdn.py` and `ref/model.py` both sigmoid it; this call is what makes the C++ agree with them.
void gdn_beta_gate(float* beta, int64_t h_v, void* stream);
/// The layer's closing norm: `y = rms_norm(o, eps) * ssm_norm * act(z)`, `act` per `GdnGate`.
/// The layer's closing norm: `y = rms_norm(o, eps) * ssm_norm * sigmoid(z)`.
///
/// SIGMOID for Flash-Next (`ref/gdn.py` says so outright), SiLU for Qwen3.6 (`ref/qwen36.py`, qwen35moe.cpp:273).
/// Note SIGMOID, not SiLU - qwen3.5 used SiLU and this artifact does not, and `ref/gdn.py` says so outright.
/// The norm is over the LAST axis: one RMS per head, so it is per-ROW here and not over the whole (h_v, S).
void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S,
float eps, GdnGate act, void* stream);
float eps, void* stream);
} // namespace strata::kernels
+1 -2
View File
@@ -1,7 +1,6 @@
// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S,
// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's
// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding). Qwen3.6-35B-A3B's files add Q6_K and
// the 256-value down types (IQ3_XXS, Q5_K, Q6_K down at n_ff 512; docs/qwen36-port/step3-experts.md).
// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding).
//
// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh,
// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it
@@ -1,6 +1,4 @@
#pragma once
#include "strata/kernels/gdn.hpp"
#include <cstdint>
namespace strata::kernels {
@@ -30,11 +28,10 @@ void native_gdn_beta_gate(float* beta, int64_t heads, void* stream);
void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
float* gate, int64_t heads, void* stream);
// [heads,128]: rms_norm(output,epsilon)*gamma*act(z), act sigmoid (qwen4exp) or
// SiLU (qwen35moe) per `GdnGate`. Gamma contains only 128 floats and broadcasts
// across heads. Destination is disjoint from inputs.
// [heads,128]: rms_norm(output,epsilon)*gamma*sigmoid(z). Gamma contains only
// 128 floats and broadcasts across heads. Destination is disjoint from inputs.
void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
float* destination, int64_t heads, int64_t cols,
float epsilon, GdnGate act, void* stream);
float epsilon, void* stream);
} // namespace strata::kernels
+2 -26
View File
@@ -87,7 +87,6 @@
// The RAW tail is fp32 for the same reason and because it is only `idx_block - 1` rows.
#pragma once
#include <cstddef>
#include <cstdint>
namespace strata::kernels {
@@ -125,36 +124,17 @@ inline float qsa_rms_eps() { return 1e-6f; }
/// constant is what that config's `freq_base` defaults to and what CLI `--rope-freq-base` overrides.
inline double qsa_freq_base() { return 1e7; }
/// DENSE attention (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.3): the full-attention layers have no indexer, so
/// every cell is selected every token. The signal is the three indexer widths ZERO TOGETHER, which is what the
/// one builder (`strata/core/qsa_shapes.hpp`) writes for a geometry without an indexer; a shape with some of them
/// zero is half set up and `qsa_shapes_valid` refuses it, so the same predicate decides here and in the kernels'
/// guard. Under it the selection width is `n_kv`, the capacity is the state's `max_cells` (`qsa_selection_cap`),
/// and the attention kernels take a null `ids` as the identity.
inline bool qsa_dense(const QsaShapes& s) { return s.idx_n_head == 0 && s.idx_dim == 0 && s.idx_top_k == 0; }
/// What every kernel's geometry guard checks (`qsa.cu`'s `validate`, which exits on a refusal): the head counts,
/// `n_rot`, the page size, and either a full indexer geometry or a dense one - never a half-set shape. The test
/// calls this; the kernels call the exiting form.
bool qsa_shapes_valid(const QsaShapes& s, char* why, size_t why_len);
/// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`; `n_kv` itself for dense attention.
/// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`.
///
/// The `r - 1 = 3` is not slack, it is the incomplete tail: the budget is whole blocks PLUS whatever cells do
/// not fill one. So the plan's "selection skipped when context <= 2,048" is conservative by two - the source's
/// own bound is 2,051, and `ref/qsa.py` L292-294 records the disagreement. Below the bound the selection is
/// the IDENTITY, which `topk_512` is required to reproduce exactly rather than approximately.
inline int64_t qsa_selection_width(int64_t n_kv, const QsaShapes& s) {
if (qsa_dense(s)) return n_kv;
const int64_t w = s.idx_top_k + s.idx_block - 1;
return n_kv < w ? n_kv : w;
}
/// The CAPACITY of every per-selection buffer (`ids`, the attention scratch, the gather scratch): the largest
/// width a token can have. Sparse: `qsa_selection_width(kTopkMaxCells, s)` = 2,051 (the number every caller used
/// to spell out). Dense: the state's `max_cells`, because the width is the context itself.
int64_t qsa_selection_cap(int64_t max_cells, const QsaShapes& s);
/// THE PER-TOKEN VALUES EVERY QSA KERNEL NEEDS, IN DEVICE MEMORY.
///
/// This exists so the QSA layer can be a CUDA graph. A graph bakes kernel ARGUMENTS in at capture time, so any
@@ -177,7 +157,7 @@ enum QsaStep : int {
kStepPos = 0, ///< the new cell's sequence position
kStepNKv = 1, ///< pos + 1: how many cells are in the cache
kStepNBid = 2, ///< n_kv / idx_block: how many blocks have COMPLETED
kStepWidth = 3, ///< qsa_selection_width(n_kv, s): how many cells the selection returns (n_kv when dense)
kStepWidth = 3, ///< qsa_selection_width(n_kv, s): how many cells the selection returns
kStepCount = 4,
};
@@ -301,10 +281,6 @@ void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const flo
/// radix select and Phase 7 raises the cap; until then a longer context is refused loudly.
inline constexpr int64_t kTopkMaxCells = 32768;
inline int64_t qsa_selection_cap(int64_t max_cells, const QsaShapes& s) {
return qsa_dense(s) ? max_cells : qsa_selection_width(kTopkMaxCells, s);
}
void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids,
void* stream);
+8 -41
View File
@@ -6,27 +6,16 @@
// selection ids (no gather copy), in chunks of CHUNK cells per block, and serves all `n_head / n_head_kv` query
// heads that share a KV head from one read of the chunk:
//
// grid (min(ceil(cap / 64), 128), n_head_kv): s = q.k * scale for G heads x 64 cells per sub-chunk, the
// running max m and sum l, acc = p . V -> one partial per block
// grid (n_head): merge the partials with the usual log-sum-exp rescale
// grid (ceil(cap / CHUNK), n_head_kv): s = q.k * scale for 12 heads x CHUNK cells, chunk max m and sum l,
// acc = p . V -> partials
// grid (n_head): merge the chunks with the usual log-sum-exp rescale
//
// FP16 pools or INT8 pools (codes + fp16 scale per 64 values, `kv_q8.hpp`), Q4_0 and K8V4. The grid is sized by
// the capacity; the real count comes from `step[kStepWidth]` as for every other capturable QSA kernel.
//
// Qwen3.6 (docs/QWEN36-35B-A3B.md 3.3): `G`, the query heads per KV head, is a template parameter (2, 8, 12;
// `qsa_attn_group` picks it from the geometry and refuses any other ratio by name); a NULL `ids` is the identity
// selection, cell j = j for j < step[kStepWidth], which is dense attention without an ids buffer (prefill at
// 2,048 queries x 262,144 cells would otherwise carry 2 GiB of ids); and the number of blocks per KV head is
// capped at 128 FOR DENSE SHAPES so the split-K partials are bounded at 2.02 MiB per query row (16 heads) instead
// of growing to 64.5 MiB at 262,144 cells - each block walks its share of the selection in 64-cell sub-chunks with
// an online rescale, computed from the token's width on the device, so a short selection keeps one block per 64
// cells. A sparse shape keeps one block per 64 cells at any capacity: the QSA layers (cap 2,051) and the MTP
// drafter's ring (its window, 32,768 by default) run the previous grid, scratch and summation order.
// FP16 pools or INT8 pools (codes + fp16 scale per 64 values, `kv_q8.hpp`). The grid is sized by the capacity;
// the real count comes from `step[kStepWidth]` as for every other capturable QSA kernel.
#pragma once
#include "strata/kernels/qsa.hpp"
#include <cstddef>
#include <cstdint>
namespace strata::kernels {
@@ -43,37 +32,15 @@ struct QsaAttnPools {
const int32_t* page_table = nullptr;
};
/// The query heads per KV head the kernels are instantiated for, from the geometry: 2, 8 or 12, else 0 with the
/// refusal in `why` (naming the heads). The entry points below call this and exit(1) on 0.
int qsa_attn_group(const QsaShapes& s, char* why, size_t why_len);
/// Whether `G` is a built group AND the geometry is `n_head == G * n_head_kv`: a 16-head model asked for G = 12
/// is refused here by name, never run mis-indexed (the negative test of docs/QWEN36-35B-A3B.md section 6, step 3).
bool qsa_attn_group_check(const QsaShapes& s, int G, char* why, size_t why_len);
/// Blocks per KV head for `cap` cells: `ceil(cap / 64)` for a sparse shape (the kernel before Qwen3.6, at any
/// capacity: the MTP drafter's ring runs it at its window), `min(ceil(cap / 64), 128)` for a dense one. The scratch
/// holds one partial per block.
int64_t qsa_decode_attn_chunks(int64_t cap, const QsaShapes& s);
/// Scratch floats per query row for `cap` selected cells: `chunks(cap, s) * n_head * 258 + 64` (partial
/// accumulators, maxima and sums). Dense: bounded at 528,448 floats (2.02 MiB) at 16 heads for any cap >= 8,192.
/// Sparse: the previous formula, unchanged.
/// Scratch floats for `cap` selected cells: partial accumulators, maxima and sums.
uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s);
/// `ids` (cap,) i32 or NULL for the identity selection (every cell up to step[kStepWidth]).
void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step,
int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream);
/// Plan v0.3 P5: `n_q` queries at once, each with its own selection: q [n_q, n_head, 256], ids [n_q, cap] or NULL
/// (the identity for every query), steps [n_q, kStepCount], attn [n_q, n_head, 256]; scratch is `n_q` times the
/// single-query size.
/// Plan v0.3 P5: `n_q` queries at once, each with its own selection: q [n_q, n_head, 256], ids [n_q, cap], steps
/// [n_q, kStepCount], attn [n_q, n_head, 256]; scratch is `n_q` times the single-query size.
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);
/// The explicit form of the identity selection: `ids[q * cap + j] = j` for `j < steps[q][kStepWidth]`, for `n_q`
/// rows. Capturable (the widths are read on the device). The engine's dense paths pass NULL instead; this exists
/// for a caller that must hand a buffer to something else (the KV-streaming resolver, a dump) and for the parity
/// test, which holds the two forms bit for bit equal.
void qsa_identity_ids(int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, void* stream);
} // namespace strata::kernels
+3 -37
View File
@@ -25,39 +25,8 @@ struct SamplerParams {
uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index)
uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls
bool greedy = false;
// DRY (llama.cpp's `dry` sampler, applied straight after the penalties above): a token that would EXTEND a
// repeat longer than `dry_allowed_length` loses `dry_multiplier * dry_base^(repeat - allowed_length)`, over
// the last `dry_penalty_last_n` history tokens. Restart sequences cap the repeat length. `dry_multiplier`
// 0, `dry_base` < 1, or `dry_penalty_last_n` 0 disables it (llama.cpp's `dry_enabled`). Only the last
// `kDryWindowCap` window tokens are examined; a longer `dry_penalty_last_n` is clamped there.
float dry_multiplier = 0.0f;
float dry_base = 1.75f;
int dry_allowed_length = 2;
int dry_penalty_last_n = 0; // 0 disables; the window over `history`, the same row the penalties count
};
// The DRY Z-algorithm runs in DEVICE SHARED memory, one window per row: the cap bounds that window (and the
// sequence-breaker scan). llama.cpp's default is 256; the engine's penalty window may be wider (up to 4096).
constexpr int kDryWindowCap = 512;
// DRY sequence breakers, tokenized (llama.cpp's `dry_processed_breakers`): `n` restart sequences, sequence k is
// `flat[off[k] .. off[k+1])`, its head `flat[off[k]]` and its tail the rest. A head with an empty tail is a
// single-token sequence and is never penalised. DEVICE pointers; `n == 0` means no breakers.
struct DryBreakers {
const int* flat = nullptr;
const int* off = nullptr;
int n = 0;
};
// `dry_enabled` (llama.cpp's condition): the multiplier, the base and a non-zero window must all agree. Both the
// host launch path and the device kernels call it, so it is host-and-device (the header is not CUDA-only).
#if defined(__CUDACC__)
__host__ __device__
#endif
inline bool dry_enabled(const SamplerParams& p) {
return p.dry_multiplier != 0.0f && p.dry_base >= 1.0f && p.dry_penalty_last_n != 0;
}
// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`.
//
// **`logits` AND `out` ARE DEVICE POINTERS.** This is a CUDA kernel launch, not a host function, and nothing
@@ -68,12 +37,10 @@ inline bool dry_enabled(const SamplerParams& p) {
//
// `history` is (n_tokens, history_len) int32 - ONE ROW PER TOKEN ROW, at a stride of `history_len` - the most
// recent tokens that row's pick follows, with any unused slots set to -1; only the last `p.penalty_last_n` of
// each row are counted, and ids outside [0, n_vocab) are ignored. DRY counts over the last `p.dry_penalty_last_n`
// of the SAME row; `breakers` are its tokenized restart sequences (a head with an empty tail is a single-token
// sequence and is never penalised), `n == 0` for none. Pass history nullptr and 0 when no penalties apply.
// each row are counted, and ids outside [0, n_vocab) are ignored. Pass nullptr and 0 when no penalties apply.
// A verify window's rows need DIFFERENT histories: row t follows the window's drafts 1..t (`penalty_rows`).
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream, const DryBreakers& breakers = DryBreakers{});
const SamplerParams& p, int* out, void* stream);
// The greedy pick (no penalties) on a thread-block cluster of 8 CTAs per row (sm_90+, CUDA; S19): the same token as
// sample_tokens' one-block argmax, which takes it unless STRATA_ARGMAX_MULTI=0. False (nothing launched) where it
@@ -96,8 +63,7 @@ void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapp
// the id to ring[cap + j].
void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
void* scratch, int32_t* out_id, float* out_prob, void* stream,
const DryBreakers& breakers = DryBreakers{});
void* scratch, int32_t* out_id, float* out_prob, void* stream);
// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h`
// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots.
+2 -5
View File
@@ -14,8 +14,6 @@
// Everything that varies per window (token ids, `n_keep`) is read from DEVICE memory so the kernels can be captured.
#pragma once
#include "strata/kernels/gdn.hpp"
#include <cstdint>
namespace strata::kernels {
@@ -33,10 +31,9 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet
float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream);
/// The recurrence + output norm for T tokens (h = (T, conv_channels) as q|k|v, gate/beta (T, h_v), z/y
/// (T, value_dim)). With `n_keep == nullptr` the state is read and NOT written (verify); otherwise the first
/// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`,
/// including its output gate `act` (sigmoid for Flash-Next, SiLU for Qwen3.6: `GdnGate`).
/// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`.
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, GdnGate act, float* y, int h_k, int h_v, int n_tok,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
const int32_t* n_keep, void* stream, int t_out_begin = 0);
/// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be
/// outstanding at once (the split verify window keeps two).
-178
View File
@@ -1,178 +0,0 @@
// include/strata/plan/vram_plan.hpp - the VRAM planner's arithmetic, as a pure function (Qwen3.6 port, step 2).
//
// docs/QWEN36-35B-A3B.md section 4.2, in order: the fixed set first (the non-expert weights, the drafter, the KV
// cache for the requested context, the session, the CUDA context, the reserve, the prompt buffers unless prefill
// borrows cache slots); when it does not fit, the context is lowered toward the floor (131,072), and below the
// floor the start refuses with the numbers and the smaller file's name - never a silently shorter context; every
// remaining byte becomes expert slots; then the RAM tier from the available RAM minus a headroom; whatever is left
// stays mapped from the model file on disk. KV streaming is not a lever for this model: dense attention reads
// every cell, so the KV stays in VRAM (3.3 item 6).
//
// Header-only and GPU-free on purpose: the engine feeds it `cudaMemGetInfo` (clamped by --vram-cap) and the file's
// census, the unit test (tests/core/vram_plan_test.cpp) feeds it the study's table 4.1 and checks table 4.3, and
// `strata-plan` can print it for any budget. The slot count is at the MEAN blob: the engine's per-layer sizing
// (generate.cpp, `sized_slots`) prices the same bytes at each profile entry's own blob and lands within a few slots
// of it; the table's ladder is at the mean, so the check is at the mean.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace strata::plan {
struct VramPlanInput {
uint64_t budget_bytes = 0; ///< VRAM the engine may use: free at start, or `cap - used` under --vram-cap
uint64_t weights_bytes = 0; ///< the non-expert weights on the GPU (census of the file, token_embd excluded)
uint64_t drafter_bytes = 0; ///< the MTP draft block's weights in VRAM (dense + experts); 0 without --mtp
/// Qwen3.6 step 4 (docs/qwen36-port/step4-drafter.md section 7): the drafter's K/V is the WHOLE context, not a
/// ring (dense attention: no --kv-resident), in the format --kv asks for, over its one attention layer; counted
/// per token here so a lowered context lowers it too. 0 without --mtp.
uint64_t drafter_kv_bytes_per_token = 0;
/// the draft head over the draft vocabulary's subset (n_dvocab x the head's row bytes) plus the draft logits:
/// what MtpDrafter::bind allocates; 0 without --mtp
uint64_t drafter_head_bytes = 0;
/// the drafter's identity selection ids, T x max_cells x 4 B (T = --spec): per token; 0 without --mtp
uint64_t drafter_ids_bytes_per_token = 0;
uint64_t kv_bytes_per_token = 0; ///< the KV format's bytes per token over every attention layer
uint64_t session_bytes = 0; ///< rope table, GDN state, scratch
uint64_t cuda_context_bytes = 0; ///< the driver's own share, ~230 to 300 MiB, when `budget_bytes` is a card's
///< size (the study's table); 0 when it is cudaMemGetInfo's free figure, which
///< is read after the context exists and so is already net of it
uint64_t reserve_bytes = 0; ///< --vram-reserve-mib (700 default, 300 on a small card)
uint64_t prompt_bytes = 0; ///< the prompt path's chunk buffers; 0 when prefill borrows cache slots
int64_t context = 262144; ///< requested
int64_t context_floor = 131072; ///< never below this without refusing
int64_t context_step = 4096; ///< a lowered context is a multiple of this
int64_t n_experts = 0; ///< n_layers x n_expert
uint64_t mean_blob = 0; ///< bytes per expert slot (the census mean)
uint64_t ram_available_bytes = 0; ///< host RAM the tier may take (MemAvailable, clamped by --ram-cap)
uint64_t ram_headroom_bytes = 0; ///< left to the OS, the page cache and the KV stream
std::string smaller_file; ///< named in a refusal (the IQ3_XXS file for the Q4 arm)
};
struct VramPlan {
bool fits = false;
int64_t context = 0; ///< the context the plan holds (the request, or lowered)
bool lowered = false; ///< the context is below the request
uint64_t kv_bytes = 0; ///< at `context`
uint64_t fixed_bytes = 0; ///< everything but the expert slots, at `context`
uint64_t expert_bytes = 0; ///< budget - fixed (0 when it does not fit)
int64_t vram_slots = 0; ///< expert slots in VRAM (at most n_experts)
uint64_t spare_bytes = 0; ///< left over when every expert fits
int64_t ram_copies = 0; ///< experts the RAM tier holds (the next by profile rank)
int64_t mapped = 0; ///< the rest: read from the model file on a miss
uint64_t ram_tier_bytes = 0; ///< ram_copies x mean_blob
int64_t context_needed_bytes_short = 0; ///< on a refusal: how many bytes short at the floor
std::string refusal; ///< non-empty when !fits: the numbers and the smaller file
};
/// Everything that grows with the context: the trunk's KV and the drafter's K/V and ids, per token.
inline uint64_t vram_plan_per_token(const VramPlanInput& in) {
return in.kv_bytes_per_token + in.drafter_kv_bytes_per_token + in.drafter_ids_bytes_per_token;
}
/// The drafter's whole share at `context` tokens: its weights, its K/V over the context, its head and ids.
inline uint64_t vram_plan_drafter(const VramPlanInput& in, int64_t context) {
return in.drafter_bytes + in.drafter_head_bytes +
(in.drafter_kv_bytes_per_token + in.drafter_ids_bytes_per_token) * (uint64_t) context;
}
/// The fixed set at `context` tokens.
inline uint64_t vram_plan_fixed(const VramPlanInput& in, int64_t context) {
return in.weights_bytes + vram_plan_drafter(in, context) + in.kv_bytes_per_token * (uint64_t) context +
in.session_bytes + in.cuda_context_bytes + in.reserve_bytes + in.prompt_bytes;
}
inline VramPlan make_vram_plan(const VramPlanInput& in) {
VramPlan p;
p.context = in.context;
p.fixed_bytes = vram_plan_fixed(in, in.context);
if (p.fixed_bytes > in.budget_bytes) {
// lower the context toward the floor: the largest multiple of `context_step` the budget holds
const uint64_t without_kv = vram_plan_fixed(in, 0);
const uint64_t per_token = vram_plan_per_token(in);
int64_t ctx = 0;
if (in.budget_bytes > without_kv && per_token > 0) {
ctx = (int64_t) ((in.budget_bytes - without_kv) / per_token);
ctx -= ctx % (in.context_step > 0 ? in.context_step : 1);
}
if (ctx < in.context_floor) {
const uint64_t at_floor = vram_plan_fixed(in, in.context_floor);
p.context_needed_bytes_short = (int64_t) (at_floor > in.budget_bytes ? at_floor - in.budget_bytes : 0);
const auto mib = [](uint64_t b) { return std::to_string((b + (1u << 20) - 1) >> 20); };
p.refusal = "the fixed set does not fit: at " + std::to_string(in.context) + " tokens it is " +
mib(p.fixed_bytes) + " MiB (weights " + mib(in.weights_bytes) + ", drafter " +
mib(vram_plan_drafter(in, in.context)) + " (weights " + mib(in.drafter_bytes) + ", K/V " +
mib(in.drafter_kv_bytes_per_token * (uint64_t) in.context) + ", head " + mib(in.drafter_head_bytes) +
", ids " + mib(in.drafter_ids_bytes_per_token * (uint64_t) in.context) + "), KV " +
mib(in.kv_bytes_per_token * (uint64_t) in.context) +
", session " + mib(in.session_bytes) + ", CUDA context " + mib(in.cuda_context_bytes) +
", reserve " + mib(in.reserve_bytes) + ", prompt buffers " + mib(in.prompt_bytes) +
"), at the floor of " + std::to_string(in.context_floor) + " tokens " + mib(at_floor) +
" MiB, and this card gives " + mib(in.budget_bytes) + " MiB: " +
mib((uint64_t) p.context_needed_bytes_short) + " MiB short even at the floor. " +
(in.smaller_file.empty() ? std::string("Use a smaller quantization of the model")
: "Use the smaller file " + in.smaller_file) +
(in.prompt_bytes > 0 ? ", or an expert profile (prefill then borrows cache slots instead of its "
"own " + mib(in.prompt_bytes) + " MiB of prompt buffers)"
: std::string()) +
"; a context below " + std::to_string(in.context_floor) + " is not chosen for you";
p.fits = false;
p.context = in.context_floor;
p.kv_bytes = in.kv_bytes_per_token * (uint64_t) in.context_floor;
p.fixed_bytes = at_floor;
p.mapped = in.n_experts;
return p;
}
p.context = ctx;
p.lowered = true;
p.fixed_bytes = vram_plan_fixed(in, ctx);
}
p.fits = true;
p.kv_bytes = in.kv_bytes_per_token * (uint64_t) p.context;
p.expert_bytes = in.budget_bytes - p.fixed_bytes;
const int64_t slots = in.mean_blob > 0 ? (int64_t) (p.expert_bytes / in.mean_blob) : 0;
p.vram_slots = slots < in.n_experts ? slots : in.n_experts;
if (p.vram_slots == in.n_experts) p.spare_bytes = p.expert_bytes - (uint64_t) in.n_experts * in.mean_blob;
const int64_t rest = in.n_experts - p.vram_slots;
const uint64_t ram_budget = in.ram_available_bytes > in.ram_headroom_bytes ? in.ram_available_bytes - in.ram_headroom_bytes : 0;
const int64_t ram_fit = in.mean_blob > 0 ? (int64_t) (ram_budget / in.mean_blob) : 0;
p.ram_copies = ram_fit < rest ? ram_fit : rest;
p.mapped = rest - p.ram_copies;
p.ram_tier_bytes = (uint64_t) p.ram_copies * in.mean_blob;
return p;
}
/// The start-up log's lines (and `/health`'s counts): the three tiers and what they were sized from.
inline std::string vram_plan_text(const VramPlanInput& in, const VramPlan& p, const char* indent = " ") {
const auto mib = [](uint64_t b) { return std::to_string(b >> 20); };
std::string s;
s += std::string(indent) + "VRAM budget " + mib(in.budget_bytes) + " MiB\n";
s += std::string(indent) + "fixed set at " + std::to_string(p.context) + " tokens: " + mib(p.fixed_bytes) +
" MiB = weights " + mib(in.weights_bytes) + " + drafter " + mib(vram_plan_drafter(in, p.context)) +
(vram_plan_drafter(in, p.context) ? " (weights " + mib(in.drafter_bytes) + ", K/V " +
mib(in.drafter_kv_bytes_per_token * (uint64_t) p.context) + ", head " +
mib(in.drafter_head_bytes) + ", ids " +
mib(in.drafter_ids_bytes_per_token * (uint64_t) p.context) + ")"
: std::string(" (no --mtp)")) +
" + KV " + mib(p.kv_bytes) +
" + session " + mib(in.session_bytes) + " + CUDA context " + mib(in.cuda_context_bytes) + " + reserve " +
mib(in.reserve_bytes) + (in.prompt_bytes ? " + prompt buffers " + mib(in.prompt_bytes) : std::string(" (prefill borrows cache slots)")) + "\n";
if (!p.fits) {
s += std::string(indent) + "REFUSED: " + p.refusal + "\n";
return s;
}
if (p.lowered)
s += std::string(indent) + "context LOWERED from " + std::to_string(in.context) + " to " + std::to_string(p.context) +
": the fixed set at the request would not fit (the floor is " + std::to_string(in.context_floor) + ")\n";
s += std::string(indent) + "expert slots in VRAM: " + std::to_string(p.vram_slots) + " of " + std::to_string(in.n_experts) +
" (" + std::to_string(in.n_experts ? 100 * p.vram_slots / in.n_experts : 0) + "%) at " + mib(p.expert_bytes) +
" MiB, " + std::to_string(in.mean_blob) + " B mean blob" +
(p.vram_slots == in.n_experts ? ", every expert resident, " + mib(p.spare_bytes) + " MiB spare" : std::string()) + "\n";
s += std::string(indent) + "expert copies in RAM: " + std::to_string(p.ram_copies) + " (" + mib(p.ram_tier_bytes) +
" MiB of " + mib(in.ram_available_bytes) + " MiB available minus " + mib(in.ram_headroom_bytes) + " headroom)\n";
s += std::string(indent) + "experts mapped from the model file: " + std::to_string(p.mapped) +
(p.mapped ? " (read from disk on a miss)" : "") + "\n";
return s;
}
} // namespace strata::plan
+18 -41
View File
@@ -5,7 +5,6 @@
// the kernel walks the chunk's tokens in order inside one launch.
#pragma once
#include "strata/kernels/gdn.hpp"
#include "strata/kernels/kv_stream.hpp"
#include "strata/kernels/rope_scaling.hpp"
@@ -38,48 +37,26 @@ void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64
/// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast).
void gr_broadcast(const float* e, float* R, int64_t T, void* stream);
// ---- the plain residual block (hc = 1: Qwen3.6). x = rms_norm(R, w) -> mixer -> R += out, per half.
/// mixed[t, :] = R[t, :] * rsqrt(mean R[t, :]^2 + eps) * w over rows of n, with its BF16 and FP16 images (any output
/// may be null); `mixed16_lo` as in gr_norm.
void rms_norm_images(const float* R, const float* w, float eps, float* mixed, uint16_t* mixed16, uint16_t* mixed_h,
int64_t T, int64_t n, void* stream, uint16_t* mixed16_lo = nullptr);
/// R[i] += bo[i] over n values (the residual write of a plain block).
void residual_add(float* R, const float* bo, int64_t n, void* stream);
// ---- GDN (state 128, 4 taps; the head geometry per model: Flash-Next 48 v heads / 16 k heads / 10240 conv
// channels with the sigmoid(z) output gate, Qwen3.6 32 / 16 / 8192 with SiLU(z)). The kernels are built for those
// two geometries (gdn_geometry_supported); any other stops the process, as the kernels' convention is. The gate is
// the decode kernels' `GdnGate` (strata/kernels/gdn.hpp), from `ModelGeometry::gdn_gate()`: required, no default, so
// the prompt path and the decode path agree by construction.
struct GdnGeom {
int hv; ///< value heads (ssm_v_heads)
int hk; ///< key heads (ssm_k_heads); v-head h uses k-head h % hk
int c; ///< conv channels: 2 * hk * 128 + hv * 128 (q | k | v)
strata::kernels::GdnGate gate; ///< the output gate: Silu (Qwen3.6) or Sigmoid (Flash-Next)
};
bool gdn_geometry_supported(int hv, int hk, int c);
/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, hv + h]) (ab: [T, 2 hv])
void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, const GdnGeom& g,
void* stream);
// ---- GDN (state 128, 16 k heads, 48 v heads, 10240 conv channels, 4 taps)
/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, 48 + h]) (ab: [T, 96])
void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream);
/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then
/// the L2 norm of the q and k heads of every token. h: [T, C].
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, const GdnGeom& g,
void* stream);
/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * gate(z) in FP16 (what the
/// out projection reads; gate = sigmoid or SiLU per `g`); y is FP32 scratch. State: [128 k][hv][128 v] floats.
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream);
/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the
/// out projection reads); y is FP32 scratch.
void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, const GdnGeom& g, void* stream);
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream);
// ---- MoE
/// softmax over n_expert, top-k (ties to the lower id), the k weights renormalised (the native router's semantics;
/// k <= 32 and k <= n_expert). 512 and 256 experts take the warp kernel, any other count router_top10.
void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, int64_t k, void* stream);
/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router).
void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream);
/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640].
void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);
/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up, rows of 2 n_ff)
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, int64_t n_ff, void* stream);
/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width n_ff)
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, int64_t n_ff, void* stream);
/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up)
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream);
/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640)
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream);
/// dst[i] = src[i] for n int32s, as a kernel: either side may be mapped host memory, and the copy never waits
/// behind the copy engine's queue (the prompt path's grouping tables, while the expert stream fills it).
void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream);
@@ -88,9 +65,9 @@ void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream);
void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream);
/// Gather rows: dst16[i, :] = x16[src[i], :] (n rows of `width` BF16).
void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream);
/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_j w[t, j] * D[slot[t, j], :] over j < k, rows of n
/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :]
void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
int64_t T, int64_t n, int64_t k, void* stream);
int64_t T, void* stream);
// ---- QSA helpers
/// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`).
@@ -99,10 +76,10 @@ void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld,
/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly.
void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0,
const strata::kernels::RopeScaling& scaling, void* stream);
/// q_full [T, n_head, 512] (q | gate per head) -> q [T, n_head, 256]
void split_q(const float* q_full, float* q, int64_t T, int64_t n_head, void* stream);
/// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256]
void split_q(const float* q_full, float* q, int64_t T, void* stream);
/// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized)
void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, int64_t n_head, void* stream);
void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream);
/// K and V of T consecutive cells (positions pos0..pos0+T-1; K normed and rotated) into the paged pools: FP16
/// (`k_pool`/`v_pool`) or INT8 codes + FP16 scale per 64 (`k_q`...), the decode append's arithmetic.
+1 -3
View File
@@ -19,13 +19,11 @@
namespace strata::prefill::fused {
/// One layer's native expert geometry (cpu::NativeFmt's fields the kernels read). The widths are the model's
/// (Flash-Next 2560 / 640, Qwen3.6 2048 / 512): n_embd a multiple of 256, n_ff of 64, and 2 n_ff a multiple of 256.
/// One layer's native expert geometry (cpu::NativeFmt's fields the kernels read; n_embd 2560, n_ff 640).
struct NativeGeom {
int gu_type = -1, d_type = -1; ///< ggml types
size_t gu_row = 0, d_row = 0; ///< bytes per gate/up row and per down row
size_t up_off = 0, down_off = 0; ///< inside the blob
int64_t n_embd = 2560, n_ff = 640;
};
/// enabled() (STRATA_PF_FUSED=1 on sm_80+), and the kernels cover this gate/up and down pair on this device.
-11
View File
@@ -135,17 +135,6 @@ public:
/// Checked before every chunk: true stops the prompt early (`run` returns false with err "cancelled").
std::function<bool()> should_stop;
/// A test's view of the layer loop (null, the default: never called; nothing else changes). Called on the
/// compute stream's order with a DEVICE buffer of `rows` x `cols` floats at the chunk's first position `p0`,
/// named by llama.cpp's seam names (docs/qwen36-port/oracle-crosscheck.md): "l_in" (the layer's input residual
/// rows, hc * n_embd wide, before anything of the layer ran: a test may overwrite them, which is how the
/// Qwen3.6 harness teacher-forces every layer's input), "attn_norm" / "attn_post_norm" (the plain block's normed
/// input of each half, n_embd), "linear_attn_out" / "attn_output" / "ffn_out" (the mixer's output before the
/// residual, n_embd), "ffn_moe_topk" (the router's ids as int32 [rows, k], passed as floats), "l_out" (the
/// residual after the layer). The callback may synchronize the stream; false with `err` stops the prompt.
std::function<bool(const char* seam, int64_t layer, float* rows_dev, int64_t rows, int64_t cols, int64_t p0,
std::string& err)> on_seam;
/// The vision path: HOST rows (n_embd floats) indexed by absolute position, read in place of the token
/// embedding where non-null (an image's <|image_pad|> cells). Null (default): every position embeds its token.
const float* const* embd_rows = nullptr;
-217
View File
@@ -1,217 +0,0 @@
"""ref/load.py - P1.S4: GGUF -> FP32 tensors on demand, with LAZY per-expert dequantization.
The plan is explicit: "experts are dequantized lazily per (layer, expert) - do not materialize 120B
parameters". That is the whole design constraint here, and it is what `expert()` below exists for: the
routed-expert tensors are fused `[in, out, experts]`, and touching one expert must not touch the other
511.
Dequantization itself is NOT reimplemented. `gguf-py` handles the twelve standard encodings and is
already the reference this project validates its C++ against; `Q2_0` (type 42) is the one gguf-py
cannot represent at all, so it is served by this project's own decoder. That split is deliberate: it
means a bug in `tools/gguf_writer.dequantize_q2_0` cannot hide behind gguf-py and vice versa.
from ref.load import Gguf
g = Gguf("path.gguf")
w = g.tensor("blk.0.attn_gate.weight") # (out, in) fp32, whole tensor
e = g.expert("blk.0.ffn_gate_exps.weight", 7) # (out, in) fp32, ONE expert only
"""
from __future__ import annotations
import pathlib
import re
import sys
import numpy as np
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "tools"))
from gguf_reader import GGUFFile # noqa: E402
from gguf_writer import dequantize_q2_0 # noqa: E402
# gguf-py names differ from our reader's names in a few places; map only what differs.
_GGUF_PY_NAME = {"Q4_0": "Q4_0", "Q8_0": "Q8_0", "Q4_K": "Q4_K", "Q5_K": "Q5_K", "Q6_K": "Q6_K",
"Q3_K": "Q3_K", "IQ4_NL": "IQ4_NL", "IQ4_XS": "IQ4_XS", "Q5_0": "Q5_0",
# added for Qwen3.6 (UD-IQ3_XXS ships IQ2_S gate/up and IQ3_XXS down experts; the MTP build IQ3_S / Q3_K / Q4_K):
"Q4_1": "Q4_1", "Q5_1": "Q5_1", "Q2_K": "Q2_K", "IQ2_XXS": "IQ2_XXS", "IQ2_XS": "IQ2_XS",
"IQ2_S": "IQ2_S", "IQ3_XXS": "IQ3_XXS", "IQ3_S": "IQ3_S", "IQ1_S": "IQ1_S", "IQ1_M": "IQ1_M"}
# (elements per block, bytes per block) - mirrors block_geometry() in src/artifact/gguf_reader.cpp
GEOM = {"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2),
"Q4_0": (32, 18), "Q5_0": (32, 22), "Q8_0": (32, 34), "IQ4_NL": (32, 18),
"Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), "Q6_K": (256, 210),
"IQ4_XS": (256, 136), "Q2_0": (64, 18),
"Q4_1": (32, 20), "Q5_1": (32, 24), "Q2_K": (256, 84), "IQ2_XXS": (256, 66), "IQ2_XS": (256, 74),
"IQ2_S": (256, 82), "IQ3_XXS": (256, 98), "IQ3_S": (256, 110), "IQ1_S": (256, 50), "IQ1_M": (256, 56)}
def _dequant_flat(type_name: str, raw: np.ndarray) -> np.ndarray:
"""One dequantization dispatch, shared by tensor()/expert()/rows().
Q2_0 is this project's own decoder because gguf-py's enum cannot represent type 42 at all;
everything else goes through gguf-py, which is already the reference this project validates its
C++ against. Keeping one dispatch means a type added in one path cannot be forgotten in another.
"""
if type_name == "Q2_0":
return dequantize_q2_0(raw.tobytes())
if type_name == "BF16":
return _bf16_to_f32(raw)
if type_name == "F32":
return raw.view(np.float32)
if type_name == "F16":
return raw.view(np.float16).astype(np.float32)
from gguf import quants, GGMLQuantizationType as Q
return quants.dequantize(raw, Q[_GGUF_PY_NAME[type_name]]).astype(np.float32)
def _bf16_to_f32(raw: np.ndarray) -> np.ndarray:
return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32)
def _discover_shards(path) -> list[pathlib.Path]:
"""Resolve a GGUF argument to its shard list.
The real artifact is TWO files and the split is not incidental: shard 2 holds exactly one tensor,
`per_layer_token_embd.weight` (26.82 GiB). A reader that opens one file can therefore load the
whole model EXCEPT the PLE table and will not fail until a forward pass reaches layer 1 - so
shard discovery is not a convenience, it is a correctness requirement for the real model.
Accepts a directory (all `*.gguf` in it), any single shard (siblings found by the
`-NNNNN-of-MMMMM` suffix), or an explicit list.
"""
if isinstance(path, (list, tuple)):
return [pathlib.Path(p) for p in path]
p = pathlib.Path(path)
if p.is_dir():
# A directory is ambiguous in practice: the project root holds BOTH the model shards (in a
# subdirectory) and an unrelated `mmproj-*.gguf`. Globbing `*.gguf` there silently loaded
# the multimodal projector instead of the model. So prefer an explicit shard set, accept a
# single unambiguous file, and REFUSE to guess otherwise.
shards = sorted(p.glob("*-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].gguf"))
if shards:
totals = {re.match(r"^.*-(\d{5})-of-(\d{5})\.gguf$", s.name).group(2) for s in shards}
if len(totals) != 1:
raise ValueError(f"{p}: shard files from more than one split: {sorted(totals)}")
return shards
found = sorted(p.glob("*.gguf"))
if len(found) == 1:
return found
if not found:
raise FileNotFoundError(f"no .gguf files in {p}")
raise ValueError(
f"{p}: {len(found)} .gguf files and none is a shard set, so which is the model is "
f"ambiguous: {[f.name for f in found]}. Pass one file explicitly.")
m = re.match(r"^(.*)-(\d{5})-of-(\d{5})\.gguf$", p.name)
if m:
stem, _, total = m.groups()
sibs = sorted(p.parent.glob(f"{stem}-*-of-{total}.gguf"))
if len(sibs) != int(total):
raise FileNotFoundError(
f"{p.name}: expected {total} shards, found {len(sibs)} in {p.parent}")
return sibs
return [p]
class Gguf:
"""Read-only, demand-paged view of a (possibly multi-shard) GGUF.
Nothing is dequantized until asked for. `g` is the FIRST shard's `GGUFFile`, so metadata and the
tensor directory are reachable as before; reads route to whichever shard owns the tensor.
"""
def __init__(self, path):
self.paths = _discover_shards(path)
self.path = self.paths[0]
self.shards: list[tuple[GGUFFile, object]] = []
self._by_name: dict[str, tuple[int, object]] = {}
for i, sp in enumerate(self.paths):
gf = GGUFFile(sp)
self.shards.append((gf, sp.open("rb")))
for t in gf.tensors:
if t.name in self._by_name:
raise ValueError(f"{sp.name}: duplicate tensor {t.name} across shards")
self._by_name[t.name] = (i, t)
self.g = self.shards[0][0] # metadata / directory / alignment live in shard 1
# ---- raw bytes
def _raw(self, name: str, nbytes: int, byte_offset: int = 0) -> bytes:
i, t = self._by_name[name]
gf, fh = self.shards[i]
fh.seek(gf.data_start + t.offset + byte_offset)
return fh.read(nbytes)
def info(self, name: str):
return self._by_name[name][1]
def row_bytes(self, t) -> int:
el, by = GEOM[t.type_name]
return t.shape[0] // el * by
# ---- full tensors
def tensor(self, name: str) -> np.ndarray:
"""Dequantize a whole tensor to FP32, shape as GGUF order reversed to (out, in[, experts])."""
t = self.info(name)
el, by = GEOM[t.type_name]
if t.elements % el:
raise ValueError(f"{name}: {t.elements} not a multiple of block {el}")
raw = np.frombuffer(self._raw(name, t.elements // el * by), dtype=np.uint8)
flat = _dequant_flat(t.type_name, raw)
# GGUF dim 0 varies fastest; numpy's last axis does, so reverse and transpose to (out, in).
return flat.reshape(tuple(reversed(t.shape)))
# ---- the lazy row path
def rows(self, name: str, idx) -> np.ndarray:
"""Gather specific ROWS of a 2-D tensor without decoding the rest of it.
This exists for `per_layer_token_embd.weight`, which is `[160, 320001536]` IQ4_NL = **26.82
GiB** - 43% of the artifact, the entire second shard - and is read 16 rows per token by one
layer (see round 98's finding). Calling `tensor()` on it would dequantize 320 million rows to
FP32, about 205 GB, to use 2.5 KB of them.
A row is contiguous in GGUF (ne0 varies fastest), so one row is `row_bytes` at
`row * row_bytes`. The type's block size must divide the row width; for this table it does
(160 = 5 x 32 for IQ4_NL).
"""
t = self.info(name)
if len(t.shape) != 2:
raise ValueError(f"{name}: rows() needs a 2-D tensor, got shape {t.shape}")
el, by = GEOM[t.type_name]
width = t.shape[0]
if width % el:
raise ValueError(f"{name}: row width {width} is not a multiple of block {el}")
rb = self.row_bytes(t)
idx = np.asarray(idx, dtype=np.int64).ravel()
if idx.size and (idx.min() < 0 or idx.max() >= t.shape[1]):
raise ValueError(f"{name}: row index out of range (0..{t.shape[1] - 1})")
out = np.empty((idx.size, width), dtype=np.float32)
for k, r in enumerate(idx):
raw = np.frombuffer(self._raw(name, rb, int(r) * rb), dtype=np.uint8)
out[k] = _dequant_flat(t.type_name, raw)
return out
# ---- the lazy path
def expert(self, name: str, expert_id: int) -> np.ndarray:
"""One expert out of a fused `[in, out, experts]` tensor, WITHOUT touching the others.
In GGUF order the expert index is the LAST axis, so expert e's matrix occupies a contiguous
run of `in*out` elements at offset e*in*out. Only that run is read and decoded - which is the
plan's "do not materialize 120B parameters" requirement, and the reason the engine can run at
all on a machine where the expert set is 34 GB.
"""
t = self.info(name)
if len(t.shape) != 3:
raise ValueError(f"{name}: not a fused expert tensor (shape {t.shape})")
in_f, out_f, n_exp = t.shape
if not 0 <= expert_id < n_exp:
raise ValueError(f"{name}: expert {expert_id} out of range (0..{n_exp - 1})")
el, by = GEOM[t.type_name]
per_expert = in_f * out_f
if per_expert % el:
raise ValueError(f"{name}: per-expert element count {per_expert} not a multiple of {el}")
# byte offset of expert e: whole experts before it, in blocks
start = expert_id * (per_expert // el) * by
raw = np.frombuffer(self._raw(name, per_expert // el * by, start), dtype=np.uint8)
flat = _dequant_flat(t.type_name, raw)
return flat.reshape((out_f, in_f))
def close(self) -> None:
for _, fh in self.shards:
fh.close()
-683
View File
@@ -1,683 +0,0 @@
#!/usr/bin/env python3
"""ref/qwen36.py - the numpy oracle for Qwen3.6-35B-A3B (llama.cpp arch `qwen35moe`).
A teacher-forced forward pass over a token sequence, written from the pinned llama.cpp graph and nothing
else: third_party/llama.cpp/src/models/qwen35moe.cpp (the layer loop and both mixers), delta-net-base.cpp
(the Gated DeltaNet), src/llama-graph.cpp (build_moe_ffn, build_norm, build_qkv) and ggml-cpu/ops.cpp (the op
semantics). Weights come through `ref/load.py`, so a real quantized GGUF dequantizes lazily (one expert at a
time) and the synthetic F32 fixture from `tools/qwen36_synth_gguf.py` loads the same way.
python3 ref/qwen36.py MODEL.gguf --tokens 104,101,108,108,111 --dump OUTDIR
python3 ref/qwen36.py MODEL.gguf --text hello --dump OUTDIR # synthetic vocab: token id = ASCII code
python3 ref/qwen36.py MODEL.gguf --tokens ... --dump OUTDIR --mtp # also run the nextn block (needs one)
Every tensor llama.cpp names with cb() is written to OUTDIR/<name>.f32 (float32, C order of the numpy array,
which is ggml memory order: ne0 fastest), named exactly as llama.cpp names it ("attn_norm-0", "ffn_moe_topk-3",
"result_output"; a name set twice gets "#2", "#3" - llama.cpp names "Kcur" and "Vcur" twice). I32 tensors
(the router's argsort and top-k) are written as float32 holding the integer. OUTDIR/manifest.txt lists
"<stem> <f32|i32> <ne0>,<ne1>,<ne2>,<ne3>". `tools/qwen36_dump_llama.cpp` writes the same format from the real
llama.cpp graph; `tools/qwen36_compare_dumps.py` compares them and docs/qwen36-port/oracle-crosscheck.md records the result.
Shapes. Numpy shapes are tokens-major: a (T, n_embd) activation is ggml ne [n_embd, T]. Weights are
(out, in) so y = x @ W.T. Per-head tensors are (T, heads, dim).
The recurrence implemented for Gated DeltaNet (one layer, one v-head h, key head hk = h % n_k_heads, state
S in R^{S_v x S_k} with S[j, i] = v index j, k index i, the layout ggml calls "state is stored transposed"):
qkv = Wqkv x ; z = Wgate x ; beta = sigmoid(Wbeta x) ; a = Walpha x
g = softplus(a + dt_bias) * ssm_a (ssm_a < 0, so g < 0) qwen35moe.cpp:386-397
c = silu(causal_conv1d(qkv)) per channel, kernel [K], zero or carried (K-1)-state qwen35moe.cpp:402-419
q,k,v = split(c) -> [Hk,S], [Hk,S], [Hv,S]; q,k /= sqrt(sum(x^2) + eps) (build_gdn_l2_norm, models.h:14)
per token t:
S *= exp(g[t, h]) ops.cpp:11012 (decay first)
d = (v[t, h] - S @ k[t, hk]) * beta[t, h] ops.cpp:11016-11020 (delta rule)
S += d (x) k[t, hk] ops.cpp:11023-11025
o[t,h]= (S @ q[t, hk]) / sqrt(S_v) ops.cpp:11028-11032
out = (rms_norm(o) * ssm_norm) * SiLU(z) <- SiLU, not sigmoid qwen35moe.cpp:272-275, 478
y = Wout out
Scope: one sequence, causal, fresh or carried state, no sliding window, no YaRN (ext_factor 0, attn_factor 1:
the context's defaults for this architecture), F32 throughout (the fixture is F32; a quantized file is
dequantized to F32 first, so this is the "what the weights say" oracle, not a bit-exact quantized path).
"""
from __future__ import annotations
import argparse
import pathlib
import sys
from dataclasses import dataclass, field
import numpy as np
_ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(_ROOT))
sys.path.insert(0, str(_ROOT / "tools"))
from _paths import add_gguf_py # noqa: E402
add_gguf_py()
from ref.load import Gguf # noqa: E402
F32 = np.float32
ARCH = "qwen35moe"
# ------------------------------------------------------------------------------------------------ hparams
@dataclass
class HParams:
"""What llama.cpp's loader derives from the GGUF (src/llama-model.cpp:1231-1424, qwen35moe.cpp:4-34)."""
n_embd: int
n_layer_all: int # block_count: trunk + nextn blocks
n_nextn: int # nextn_predict_layers (0 when absent)
n_head: int
n_head_kv: int
head_dim: int
n_rot: int
sections: tuple # rope.dimension_sections, 4 entries
rope_base: float
eps: float
n_expert: int
n_expert_used: int
n_ff_exp: int
n_ff_shexp: int
ssm_conv: int
ssm_inner: int
ssm_state: int
ssm_k_heads: int # ssm.group_count
ssm_v_heads: int # ssm.time_step_rank
interval: int
recurrent: tuple | None # attention.recurrent_layers, when the file carries it
# llama.cpp behaviours for this architecture that the GGUF cannot change:
expert_weights_norm: bool = True # qwen35moe.cpp:506 passes norm_w = true
expert_weights_scale: float = 0.0 # hparams default; the qwen35moe loader never reads the key (0 -> no scaling)
@property
def n_layer(self) -> int:
return self.n_layer_all - self.n_nextn
@property
def head_v_dim(self) -> int:
return self.ssm_inner // self.ssm_v_heads
@property
def key_dim(self) -> int:
return self.ssm_state * self.ssm_k_heads
@property
def value_dim(self) -> int:
return self.head_v_dim * self.ssm_v_heads
@property
def conv_dim(self) -> int:
return 2 * self.key_dim + self.value_dim
def is_recr(self, il: int) -> bool:
"""qwen35moe.cpp:20-26: recurrent unless (il+1) % interval == 0; the nextn block is never recurrent."""
if il >= self.n_layer:
return False
if self.recurrent is not None:
return bool(self.recurrent[il])
return (il + 1) % self.interval != 0
def attn_layers(self) -> list[int]:
return [il for il in range(self.n_layer) if not self.is_recr(il)]
def read_hparams(md: dict) -> HParams:
assert md.get("general.architecture") == ARCH, f"architecture is {md.get('general.architecture')!r}, not {ARCH!r}"
k = lambda s, d=None: md.get(f"{ARCH}.{s}", d)
need = lambda s: md[f"{ARCH}.{s}"]
n_head, n_embd = need("attention.head_count"), need("embedding_length")
head_dim = k("attention.key_length", n_embd // n_head) # llama-model.cpp:1371-1372
n_head_kv = k("attention.head_count_kv", n_head)
first = lambda v: v[0] if isinstance(v, (list, tuple)) else v # get_key_or_arr accepts a scalar or per-layer array
sec = list(k("rope.dimension_sections", [0, 0, 0, 0]))
sec = tuple((sec + [0] * 4)[:4])
rec = k("attention.recurrent_layers")
return HParams(
n_embd=n_embd, n_layer_all=need("block_count"), n_nextn=k("nextn_predict_layers", 0),
n_head=first(n_head), n_head_kv=first(n_head_kv), head_dim=head_dim,
n_rot=k("rope.dimension_count", head_dim), sections=sec,
rope_base=k("rope.freq_base", 10000.0), eps=need("attention.layer_norm_rms_epsilon"),
n_expert=need("expert_count"), n_expert_used=first(need("expert_used_count")),
n_ff_exp=first(need("expert_feed_forward_length")),
n_ff_shexp=k("expert_shared_feed_forward_length", 0),
ssm_conv=need("ssm.conv_kernel"), ssm_inner=need("ssm.inner_size"), ssm_state=need("ssm.state_size"),
ssm_k_heads=need("ssm.group_count"), ssm_v_heads=need("ssm.time_step_rank"),
interval=k("full_attention_interval", 4), recurrent=tuple(rec) if rec is not None else None,
)
# ------------------------------------------------------------------------------------------------ op semantics
def rms_norm(x: np.ndarray, eps: float) -> np.ndarray:
"""ggml_rms_norm over the last axis: x / sqrt(mean(x^2) + eps), mean accumulated in double (ops.cpp rms_norm)."""
ms = (x.astype(np.float64) ** 2).mean(axis=-1, keepdims=True)
return (x * (1.0 / np.sqrt(ms + eps)).astype(F32)).astype(F32)
def l2_norm_gdn(x: np.ndarray, eps: float) -> np.ndarray:
"""build_gdn_l2_norm (models.h:14-18) = scale(rms_norm(x, eps/n), 1/sqrt(n)) = x / sqrt(sum(x^2) + eps)."""
n = x.shape[-1]
return (rms_norm(x, eps / n) * F32(1.0 / np.sqrt(F32(n)))).astype(F32)
def silu(x):
return (x / (F32(1.0) + np.exp(-x))).astype(F32) # vec.h:1046-1048
def sigmoid(x):
return (F32(1.0) / (F32(1.0) + np.exp(-x))).astype(F32)
def softplus(x):
return np.where(x > 20.0, x, np.log1p(np.exp(np.minimum(x, 20.0)))).astype(F32) # unary-ops.cpp:80-82
def softmax(x):
e = np.exp(x - x.max(axis=-1, keepdims=True))
return (e / e.sum(axis=-1, keepdims=True)).astype(F32)
def mm(x, w):
"""y = x @ w.T with w (out, in), float32."""
return (x.astype(F32) @ w.astype(F32).T).astype(F32)
_K_FAMILY = ("Q2_K", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "IQ1_S", "IQ1_M", "IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ4_XS")
_Q8_0_FAMILY = ("Q4_0", "Q4_1", "Q5_0", "Q5_1", "Q8_0", "IQ4_NL")
def quantize_act(x: np.ndarray, weight_type: str) -> np.ndarray:
"""What ggml's quantized matmul sees of an F32 activation: rows rounded to the weight type's vec_dot_type, then
dequantized (the integer dot product equals the float dot of these values, up to summation order).
K-quant and IQ weights use Q8_K (blocks of 256, float scale from the signed max, quantize_row_q8_K_ref);
Q4_0/Q5_0/Q8_0/IQ4_NL use Q8_0 (blocks of 32, fp16 scale, quantize_row_q8_0_ref). F32/F16/BF16 weights: unchanged."""
if weight_type in _K_FAMILY:
bs = 256
elif weight_type in _Q8_0_FAMILY:
bs = 32
else:
return x
shp = x.shape
b = x.reshape(-1, bs).astype(F32)
if bs == 256:
i = np.abs(b).argmax(axis=1)
mx = b[np.arange(len(b)), i] # signed value of largest magnitude
with np.errstate(divide="ignore", invalid="ignore"):
iscale = np.where(mx != 0, F32(-127.0) / mx, F32(0)).astype(F32)
q = np.minimum(127, np.rint(iscale[:, None] * b)) # nearest_int: round half to even
d = np.where(iscale != 0, F32(1.0) / iscale, F32(0)).astype(F32)
return (q * d[:, None]).astype(F32).reshape(shp)
amax = np.abs(b).max(axis=1)
d = (amax / F32(127.0)).astype(F32)
d16 = d.astype(np.float16).astype(F32) # block_q8_0 stores the scale as fp16
with np.errstate(divide="ignore", invalid="ignore"):
idv = np.where(d != 0, F32(1.0) / d, F32(0)).astype(F32)
q = np.sign(b * idv[:, None]) * np.floor(np.abs(b * idv[:, None]) + F32(0.5)) # roundf: half away from zero
return (q * d16[:, None]).astype(F32).reshape(shp)
def rope_multi(x: np.ndarray, pos4: np.ndarray, n_rot: int, sections: tuple, base: float, pairs: str = "neox") -> np.ndarray:
"""ggml_rope_multi in GGML_ROPE_TYPE_IMROPE mode (ggml-cpu/ops.cpp:5991-6059, 6143-6233), ext_factor 0, freq_scale 1.
x: (T, heads, head_dim); pos4: (4, T) = text position broadcast to t/h/w and 0 for e (llama-graph.cpp:131-141).
Rotates the first n_rot dims as NeoX pairs (p, p + n_rot/2); the rest pass through.
"""
T, H, D = x.shape
half = n_rot // 2
ts = F32(np.power(F32(base), F32(-2.0) / F32(n_rot))) # theta_scale = powf(freq_base, -2/n_dims)
sect = sum(sections)
out = x.copy()
for t in range(T):
th = [F32(pos4[a, t]) for a in range(4)] # theta_t, theta_h, theta_w, theta_e
cs = np.empty(half, F32)
sn = np.empty(half, F32)
for p in range(half):
sector = p % sect
if sector % 3 == 1 and sector < 3 * sections[1]:
theta = th[1]
elif sector % 3 == 2 and sector < 3 * sections[2]:
theta = th[2]
elif sector % 3 == 0 and sector < 3 * sections[0]:
theta = th[0]
else:
theta = th[3]
cs[p], sn[p] = np.cos(theta), np.sin(theta) # attn_factor 1: mscale = 1
th = [F32(v * ts) for v in th] # every theta advances each pair
if pairs == "neox": # rotate_pairs(n_dims, n_dims/2): dim p with dim p + n_rot/2
x0, x1 = x[t, :, :half], x[t, :, half:n_rot]
out[t, :, :half] = x0 * cs - x1 * sn
out[t, :, half:n_rot] = x0 * sn + x1 * cs
else: # the rival: adjacent pairs (2p, 2p+1), GGML_ROPE_TYPE_NORMAL
x0, x1 = x[t, :, 0:n_rot:2], x[t, :, 1:n_rot:2]
out[t, :, 0:n_rot:2] = x0 * cs - x1 * sn
out[t, :, 1:n_rot:2] = x0 * sn + x1 * cs
return out
# ------------------------------------------------------------------------------------------------ dump sink
class Dump:
"""Writes cb()-named tensors; a no-op when constructed without a directory."""
def __init__(self, path=None):
self.dir = pathlib.Path(path) if path else None
self.seen: dict[str, int] = {}
self.lines: list[str] = []
if self.dir:
self.dir.mkdir(parents=True, exist_ok=True)
def __call__(self, name: str, il: int, arr: np.ndarray, kind: str = "f32") -> np.ndarray:
stem = f"{name}-{il}" if il >= 0 else name
n = self.seen[stem] = self.seen.get(stem, 0) + 1
if n > 1:
stem += f"#{n}"
if self.dir:
a = np.ascontiguousarray(arr, dtype=F32)
ne = list(reversed(a.shape)) + [1] * (4 - a.ndim)
a.tofile(self.dir / f"{stem}.f32")
self.lines.append(f"{stem} {kind} {','.join(map(str, ne))}")
return arr
def close(self):
if self.dir:
(self.dir / "manifest.txt").write_text("\n".join(self.lines) + "\n")
# ------------------------------------------------------------------------------------------------ model
@dataclass
class LayerState:
conv: np.ndarray | None = None # GDN: (conv_dim, K-1)
ssm: np.ndarray | None = None # GDN: (H_v, S_v, S_k) [v index, k index]
k: np.ndarray | None = None # attention: (n_kv_tokens, n_head_kv, head_dim), post-norm, post-rope
v: np.ndarray | None = None
@dataclass
class State:
layers: dict = field(default_factory=dict)
n_past: int = 0
class Model:
def __init__(self, path):
self.g = Gguf(path)
self.hp = read_hparams(self.g.g.metadata)
self.names = set(self.g._by_name)
self._cache: dict[str, np.ndarray] = {}
self.md = self.g.g.metadata
# The faithful reading of every choice in the graph. Each entry has a named rival (the reading a port could
# plausibly get wrong); tools/test_qwen36_oracle.py flips them one at a time to prove the fixture can tell.
self.opts = dict(
gdn_gate="silu", # rival "sigmoid": the Flash-Next engine's gate (qwen4exp.cpp:481)
head_pairing="tiled", # rival "interleaved": v-head h pairs with k-head h // (Hv/Hk) instead of h % Hk
decay="before", # rival "after": S += d k^T on the undecayed state, then S *= exp(g)
conv="causal", # rival "flipped": the kernel window applied in the opposite direction
attn_gate=True, # rival False: skip the sigmoid output gate of the full-attention layer
router_norm=None, # None: llama.cpp's norm_w = true; rival False: raw softmax weights
rope_pairs="neox", # rival "adjacent"
act_quant="none", # "q8": quantize activations as ggml does before each quantized matmul (a noise model, not a rival)
force_inputs=None, # directory of a llama.cpp dump: every layer starts from ITS l_out-(il-1), so each layer's error is local
force_topk=None, # {layer: (T, K) int array}: use these experts instead of the router's own top-k
gqa_map="grouped", # rival "interleaved": query head h reads kv head h % n_head_kv instead of h // (n_head/n_head_kv)
)
# ---- tensor access (small tensors cached; experts always lazy per expert)
def qtype(self, name):
return self.g.info(name).type_name
def mm(self, x, wname):
"""y = x @ W.T for the named weight; with opts["act_quant"] == "q8" the activation first goes through the
rounding ggml's quantized matmul applies (see quantize_act)."""
if self.opts["act_quant"] == "q8":
x = quantize_act(x, self.qtype(wname))
return mm(x, self.t(wname))
def has(self, name):
return name in self.names
def t(self, name):
"""A whole tensor as float32. Small ones are cached; the big dense matrices of a real file (tens of MB each
in float32) are dequantized again on each use so a 40-layer pass stays within a few GB."""
if name in self._cache:
return self._cache[name]
a = self.g.tensor(name)
if a.size <= 4_000_000:
self._cache[name] = a
return a
def expert_ffn_weights(self, il, e):
"""(gate (ff, n_embd), up (ff, n_embd), down (n_embd, ff)) of expert e in block il."""
p = f"blk.{il}"
ff = self.hp.n_ff_exp
if self.has(f"{p}.ffn_gate_up_exps.weight"): # create_tensor_gate_up_exps: gate rows first, then up
gu = self.g.expert(f"{p}.ffn_gate_up_exps.weight", e)
gate, up = gu[:ff], gu[ff:]
else:
gate = self.g.expert(f"{p}.ffn_gate_exps.weight", e)
up = self.g.expert(f"{p}.ffn_up_exps.weight", e)
return gate, up, self.g.expert(f"{p}.ffn_down_exps.weight", e)
def embed(self, ids, name="token_embd.weight"):
return self.g.rows(name, ids)
# ---- the pieces of the graph
def norm(self, x, wname, il, dump):
"""build_norm(LLM_NORM_RMS) (llama-graph.cpp:1583-1616): cb("norm") on the unweighted result, then * weight."""
n = dump("norm", il, rms_norm(x, self.hp.eps))
return (n * self.t(wname)).astype(F32)
def gdn(self, x, il, st: LayerState, dump):
"""build_layer_attn_linear (qwen35moe.cpp:359-492) over x (T, n_embd), already attn_norm'ed."""
hp = self.hp
p = f"blk.{il}"
T = x.shape[0]
Hk, Hv, S, K = hp.ssm_k_heads, hp.ssm_v_heads, hp.ssm_state, hp.ssm_conv
assert hp.head_v_dim == S, "the graph assumes head_v_dim == head_k_dim == ssm.state_size"
assert Hv % Hk == 0
if st.conv is None:
st.conv = np.zeros((hp.conv_dim, K - 1), F32)
st.ssm = np.zeros((Hv, S, S), F32)
dump("conv_states", il, st.conv.reshape(1, -1)) # ne [(K-1)*C, 1]: ggml's [K-1, C] flattened
dump("conv_states_reshaped", il, st.conv) # ne [K-1, C]
qkv = dump("linear_attn_qkv_mixed", il, self.mm(x, f"{p}.attn_qkv.weight")) # (T, conv_dim)
dump("qkv_mixed_transposed", il, qkv.T)
z = dump("z", il, self.mm(x, f"{p}.attn_gate.weight")) # (T, value_dim)
beta_raw = dump("beta", il, self.mm(x, f"{p}.ssm_beta.weight")[:, :, None]) # ne [1, Hv, T]
beta = dump("beta_sigmoid", il, sigmoid(beta_raw))[:, :, 0]
alpha = dump("alpha", il, self.mm(x, f"{p}.ssm_alpha.weight")) # (T, Hv)
sp = dump("a_softplus", il, softplus(alpha + self.t(f"{p}.ssm_dt.bias")))
gate = dump("gate", il, (sp * self.t(f"{p}.ssm_a")).astype(F32)) # (T, Hv), < 0
# causal conv1d over [state | qkv], per channel (ggml_ssm_conv, ggml-cpu/ops.cpp:9703-9754)
conv_in = dump("conv_input", il, np.concatenate([st.conv, qkv.T], axis=1)) # (C, K-1+T)
w = self.t(f"{p}.ssm_conv1d.weight") # (C, K)
if self.opts["conv"] == "flipped":
w = w[:, ::-1]
raw = np.zeros((T, hp.conv_dim), F32)
for t in range(T):
acc = np.zeros(hp.conv_dim, F32)
for i in range(K):
acc = acc + conv_in[:, t + i] * w[:, i] # sequential float32 sum over the window, as ops.cpp:9747
raw[t] = acc
new_conv = dump("conv_state_last", il, conv_in[:, -(K - 1):].copy())
dump("conv_output_raw", il, raw)
c = dump("conv_output_silu", il, silu(raw))
kd = hp.key_dim
q = dump("q_conv", il, c[:, :kd].reshape(T, Hk, S))
k = dump("k_conv", il, c[:, kd:2 * kd].reshape(T, Hk, S))
v = c[:, 2 * kd:].reshape(T, Hv, S)
q = dump("q_conv_predelta", il, l2_norm_gdn(q, hp.eps)) # fused GDN: no repeat to Hv heads (qwen35moe.cpp:462)
k = dump("k_conv_predelta", il, l2_norm_gdn(k, hp.eps))
dump("v_conv_predelta", il, v)
# the recurrence (ggml-cpu/ops.cpp:10967-11045, the fused op; delta-net-base.cpp:289-371 is the same math)
dump("state_predelta", il, st.ssm)
S_ = st.ssm.copy()
out = np.empty((T, Hv, S), F32)
rep = np.arange(Hv) % Hk if self.opts["head_pairing"] == "tiled" else np.arange(Hv) // (Hv // Hk) # ggml_repeat tiling / iv1 % nek1
scale = F32(1.0 / np.sqrt(F32(S)))
for t in range(T):
kt, qt = k[t][rep], q[t][rep] # (Hv, S)
if self.opts["decay"] == "before":
S_ = S_ * np.exp(gate[t])[:, None, None] # decay
sk = np.einsum("hji,hi->hj", S_, kt).astype(F32)
d = ((v[t] - sk) * beta[t][:, None]).astype(F32) # delta rule
S_ = (S_ + d[:, :, None] * kt[:, None, :]).astype(F32)
if self.opts["decay"] == "after":
S_ = (S_ * np.exp(gate[t])[:, None, None]).astype(F32)
out[t] = np.einsum("hji,hi->hj", S_, qt) * scale
st.ssm = S_
dump("new_state", il, S_)
o = dump("attn_output", il, out) # (T, Hv, S)
# gated norm (build_norm_gated, qwen35moe.cpp:267-276): rms_norm(o) * ssm_norm * SiLU(z)
normed = (dump("norm", il, rms_norm(o, hp.eps)) * self.t(f"{p}.ssm_norm.weight")).astype(F32)
act = silu if self.opts["gdn_gate"] == "silu" else sigmoid
gated = (normed * act(z.reshape(T, Hv, S))).astype(F32)
fo = dump("final_output", il, gated.reshape(T, hp.value_dim))
st.conv = new_conv
return dump("linear_attn_out", il, self.mm(fo, f"{p}.ssm_out.weight"))
def attention(self, x, il, st: LayerState, pos, dump, mtp=False):
"""build_layer_attn (qwen35moe.cpp:278-357): joint Q+gate projection, Q/K RMS norm, IMRoPE on 25%, causal
GQA softmax attention, sigmoid output gate, output projection. x (T, n_embd); pos (T,) absolute positions.
mtp=True emits only the names graph_mtp (qwen35moe.cpp:621-668) sets, under its "mtp_" spelling."""
hp = self.hp
p = f"blk.{il}"
T, hd, nh, nkv = x.shape[0], hp.head_dim, hp.n_head, hp.n_head_kv
def emit(trunk, mtp_name, arr): # a name the trunk graph sets, and the spelling (or None) in graph_mtp
if mtp and mtp_name is None:
return arr
return dump(mtp_name if mtp else trunk, il, arr)
if self.has(f"{p}.attn_qkv.weight"): # build_qkv fused path (llama-graph.cpp:1649-1686)
qkv = emit("wqkv", None, self.mm(x, f"{p}.attn_qkv.weight"))
nq, nk = hd * 2 * nh, hd * nkv
qfull, kc, vc = qkv[:, :nq], qkv[:, nq:nq + nk], qkv[:, nq + nk:nq + 2 * nk]
else:
qfull = self.mm(x, f"{p}.attn_q.weight")
kc = self.mm(x, f"{p}.attn_k.weight")
vc = self.mm(x, f"{p}.attn_v.weight")
qfull = emit("Qcur_full", "mtp_Qcur_full", qfull)
kc = emit("Kcur", None, kc)
vc = emit("Vcur", None, vc)
qh = qfull.reshape(T, nh, 2, hd) # per head: [q (hd) | gate (hd)]
q = emit("Qcur_reshaped", None, qh[:, :, 0, :])
q = emit("Qcur_normed", "mtp_Qcur_normed",
(dump("norm", il, rms_norm(q, hp.eps)) * self.t(f"{p}.attn_q_norm.weight")).astype(F32))
gate = emit("gate_reshaped_pre", "mtp_gate", qh[:, :, 1, :].reshape(T, nh * hd)) if mtp else qh[:, :, 1, :].reshape(T, nh * hd)
k = kc.reshape(T, nkv, hd)
k = emit("Kcur_normed", "mtp_Kcur_normed",
(dump("norm", il, rms_norm(k, hp.eps)) * self.t(f"{p}.attn_k_norm.weight")).astype(F32))
v = emit("Vcur", "mtp_Vcur", vc.reshape(T, nkv, hd))
pos4 = np.stack([pos, pos, pos, np.zeros_like(pos)]).astype(np.int64)
q = emit("Qcur", None, rope_multi(q, pos4, hp.n_rot, hp.sections, hp.rope_base, self.opts["rope_pairs"]))
k = emit("Kcur", None, rope_multi(k, pos4, hp.n_rot, hp.sections, hp.rope_base, self.opts["rope_pairs"]))
if st.k is None:
st.k = np.zeros((0, nkv, hd), F32)
st.v = np.zeros((0, nkv, hd), F32)
n_past = st.k.shape[0]
st.k = np.concatenate([st.k, k]); st.v = np.concatenate([st.v, v])
n_kv = st.k.shape[0]
grp = nh // nkv
kvmap = np.arange(nh) // grp if self.opts["gqa_map"] == "grouped" else np.arange(nh) % nkv
scale = F32(1.0 / np.sqrt(F32(hd))) # hparams.f_attention_scale == 0 -> 1/sqrt(head_dim)
# kq[h, t, j] = k_j . q_t (ggml: ne [n_kv, T, n_head]); causal mask j <= n_past + t
kq = np.einsum("tnd,jnd->ntj", q, st.k[:, kvmap]).astype(F32)
dump("kq", il, kq)
mask = np.arange(n_kv)[None, :] > (n_past + np.arange(T))[:, None]
sc = np.where(mask[None], F32(-np.inf), kq * scale)
pr = dump("kq_soft_max", il, softmax(sc))
kqv = dump("kqv", il, np.einsum("ntj,jnd->ntd", pr, st.v[:, kvmap]).astype(F32))
pre = emit("attn_pregate", "mtp_attn_pregate", kqv.transpose(1, 0, 2).reshape(T, nh * hd))
if not mtp:
gate = dump("gate_reshaped", il, gate)
gs = dump("gate_sigmoid", il, sigmoid(gate))
else:
gs = sigmoid(gate)
gated = emit("attn_gated", None, (pre * gs).astype(F32) if self.opts["attn_gate"] else pre)
return emit("attn_output", "mtp_attn_out", self.mm(gated, f"{p}.attn_output.weight"))
def moe(self, x, il, dump, mtp=False):
"""build_layer_ffn (qwen35moe.cpp:494-548) with build_moe_ffn (llama-graph.cpp:1993-2355): softmax router,
top-k, weights renormalised to sum 1 (norm_w = true), SwiGLU experts, plus the sigmoid-gated shared expert."""
hp = self.hp
p = f"blk.{il}"
T, E, K = x.shape[0], hp.n_expert, hp.n_expert_used
logits = dump("ffn_moe_logits", il, self.mm(x, f"{p}.ffn_gate_inp.weight")) # (T, E)
probs = dump("ffn_moe_probs", il, softmax(logits)) # SOFTMAX gating
order = np.argsort(-probs, axis=1, kind="stable") # argsort descending
dump("ffn_moe_argsort", il, order, "i32")
sel = order[:, :K] if self.opts["force_topk"] is None else self.opts["force_topk"][il]
topk = dump("ffn_moe_topk", il, sel, "i32") # (T, K)
w = dump("ffn_moe_weights", il, np.take_along_axis(probs, topk, 1)[:, :, None]) # ne [1, K, T]
w2 = w[:, :, 0]
ssum = dump("ffn_moe_weights_sum", il, w2.sum(axis=1, keepdims=True, dtype=F32)) # ne [1, T]
sc = dump("ffn_moe_weights_sum_clamped", il, np.maximum(ssum, F32(6.103515625e-5))) # clamp (llama-graph.cpp:2141)
do_norm = hp.expert_weights_norm if self.opts["router_norm"] is None else self.opts["router_norm"]
wn = dump("ffn_moe_weights_norm", il, (w2 / sc).astype(F32)) if do_norm else w2
if hp.expert_weights_scale not in (0.0, 1.0):
wn = dump("ffn_moe_weights_scaled", il, (wn * F32(hp.expert_weights_scale)).astype(F32))
q8 = self.opts["act_quant"] == "q8"
gu_name = f"{p}.ffn_gate_up_exps.weight" if self.has(f"{p}.ffn_gate_up_exps.weight") else f"{p}.ffn_gate_exps.weight"
gate_all = np.empty((T, K, hp.n_ff_exp), F32)
up_all = np.empty_like(gate_all)
for t in range(T):
for j in range(K):
g_, u_, _ = self.expert_ffn_weights(il, int(topk[t, j]))
xt = quantize_act(x[t], self.qtype(gu_name)) if q8 else x[t]
gate_all[t, j], up_all[t, j] = xt @ g_.T, xt @ u_.T
if self.has(f"{p}.ffn_gate_up_exps.weight"):
dump("ffn_moe_gate_up", il, np.concatenate([gate_all, up_all], axis=2)) # ne [2*ff, K, T]: gate then up
dump("ffn_moe_gate", il, gate_all)
dump("ffn_moe_up", il, up_all)
act = dump("ffn_moe_swiglu", il, (silu(gate_all) * up_all).astype(F32))
down = np.empty((T, K, hp.n_embd), F32)
for t in range(T):
for j in range(K):
_, _, d_ = self.expert_ffn_weights(il, int(topk[t, j]))
at = quantize_act(act[t, j], self.qtype(f"{p}.ffn_down_exps.weight")) if q8 else act[t, j]
down[t, j] = at @ d_.T
dump("ffn_moe_down", il, down)
weighted = dump("ffn_moe_weighted", il, (down * wn[:, :, None]).astype(F32))
moe_out = weighted[:, 0]
for j in range(1, K): # sequential adds in top-k order (llama-graph.cpp:2339-2345)
moe_out = (moe_out + weighted[:, j]).astype(F32)
# graph_mtp renames these tensors (cb sets the final name), so only the "mtp_" spelling is ever visible there
nm = (lambda trunk, m: (m or trunk) if mtp else trunk)
moe_out = dump(nm("ffn_moe_out", "mtp_ffn_moe_out"), il, moe_out)
# shared expert, build_ffn(LLM_FFN_SILU, LLM_FFN_PAR) then a per-token sigmoid gate (qwen35moe.cpp:516-545)
up = dump("ffn_up", il, self.mm(x, f"{p}.ffn_up_shexp.weight"))
gt = dump("ffn_gate", il, self.mm(x, f"{p}.ffn_gate_shexp.weight"))
sw = dump("ffn_swiglu", il, (silu(gt) * up).astype(F32))
sh = dump(nm("ffn_shexp", "mtp_ffn_shexp"), il, self.mm(sw, f"{p}.ffn_down_shexp.weight"))
sg = mm(x, self.t(f"{p}.ffn_gate_inp_shexp.weight")[None, :]) # F32 weight: never activation-quantized # (T, 1)
if not mtp:
dump("shared_expert_gate", il, sg)
sgs = dump(nm("shared_expert_gate_sigmoid", "mtp_shared_expert_gate_sigmoid"), il, sigmoid(sg))
shg = dump(nm("ffn_shexp_gated", "mtp_ffn_shexp_gated"), il, (sh * sgs).astype(F32))
return dump(nm("ffn_out", "mtp_ffn_out"), il, (moe_out + shg).astype(F32))
# ---- the trunk
def forward(self, tokens, dump: Dump | None = None, state: State | None = None, all_logits=False):
"""Teacher-forced pass over `tokens` (list of ids) from `state` (fresh when None). Returns
(logits of the last token (n_vocab,), hidden (T, n_embd) after the output norm [= h_nextn], state)."""
dump = dump or Dump()
hp = self.hp
st = state or State()
ids = np.asarray(tokens, dtype=np.int64)
T = len(ids)
pos = st.n_past + np.arange(T)
x = dump("model.input_embed", -1, self.embed(ids))
for il in range(hp.n_layer):
ls = st.layers.setdefault(il, LayerState())
if self.opts["force_inputs"] and il > 0:
x = np.fromfile(f"{self.opts['force_inputs']}/l_out-{il - 1}.f32", dtype=F32).reshape(T, -1)
inp = x
an = (dump("norm", il, rms_norm(x, hp.eps)) * self.t(f"blk.{il}.attn_norm.weight")).astype(F32)
an = dump("attn_norm", il, an)
mix = self.gdn(an, il, ls, dump) if hp.is_recr(il) else self.attention(an, il, ls, pos, dump)
res = dump("attn_residual", il, (mix + inp).astype(F32))
pn = (dump("norm", il, rms_norm(res, hp.eps)) * self.t(f"blk.{il}.post_attention_norm.weight")).astype(F32)
pn = dump("attn_post_norm", il, pn)
ffn = self.moe(pn, il, dump)
x = dump("l_out", il, (ffn + res).astype(F32))
st.n_past += T
h = dump("norm", -1, rms_norm(x, hp.eps))
h = dump("h_nextn", -1, (h * self.t("output_norm.weight")).astype(F32))
out_name = "output.weight" if self.has("output.weight") else "token_embd.weight" # tied head (qwen35moe.cpp:47-52)
last = dump("result_norm", -1, h[-1:])
logits = dump("result_output", -1, self.mm(last, out_name))
if all_logits:
dump("result_output_all", -1, self.mm(h, out_name))
return logits[0], h, st
# ---- the nextn (MTP) block, graph_mtp (qwen35moe.cpp:550-741)
def mtp_forward(self, tokens, h, dump: Dump | None = None, state: State | None = None, pos0=None):
"""One pass of the draft head. `tokens`: the T token ids whose embeddings are paired with `h`; `h`: (T, n_embd)
trunk hidden states after the output norm (the trunk's h_nextn). Which trunk position pairs with which token
is the caller's choice (speculative decoding feeds the NEXT token with the hidden of the one before).
Attention is causal over the MTP block's own KV at positions pos0.. (default: the block's own n_past). Returns (logits (T, n_vocab), state)."""
dump = dump or Dump()
hp = self.hp
assert hp.n_nextn == 1, "no nextn block in this file"
il = hp.n_layer
p = f"blk.{il}"
st = state or State()
ls = st.layers.setdefault(il, LayerState())
ids = np.asarray(tokens, dtype=np.int64)
T = len(ids)
pos = (st.n_past if pos0 is None else pos0) + np.arange(T)
emb_name = f"{p}.nextn.embed_tokens.weight" if self.has(f"{p}.nextn.embed_tokens.weight") else "token_embd.weight"
tok = dump("mtp_tok_embd", il, self.embed(ids, emb_name))
# dump order is graph execution order, and ggml_concat(e_norm, h_norm) pulls e_norm first, so "norm-4" is the
# embedding norm and "norm-4#2" the hidden norm even though graph_mtp builds h_norm first.
en = dump("mtp_enorm", il, (dump("norm", il, rms_norm(tok, hp.eps)) * self.t(f"{p}.nextn.enorm.weight")).astype(F32))
hn = dump("mtp_hnorm", il, (dump("norm", il, rms_norm(h, hp.eps)) * self.t(f"{p}.nextn.hnorm.weight")).astype(F32))
cat = dump("mtp_concat", il, np.concatenate([en, hn], axis=1)) # ggml_concat(e_norm, h_norm, dim 0)
cur = dump("mtp_eh_proj", il, self.mm(cat, f"{p}.nextn.eh_proj.weight"))
an = dump("mtp_attn_norm", il, (dump("norm", il, rms_norm(cur, hp.eps)) * self.t(f"{p}.attn_norm.weight")).astype(F32))
att = self.attention(an, il, ls, pos, dump, mtp=True)
res = dump("mtp_attn_residual", il, (att + cur).astype(F32))
pn = dump("mtp_attn_post_norm", il, (dump("norm", il, rms_norm(res, hp.eps)) * self.t(f"{p}.post_attention_norm.weight")).astype(F32))
ffn = self.moe(pn, il, dump, mtp=True)
post = dump("mtp_post_ffn", il, (ffn + res).astype(F32))
hw = f"{p}.nextn.shared_head_norm.weight" if self.has(f"{p}.nextn.shared_head_norm.weight") else "output_norm.weight"
hh = dump("h_nextn", -1, (dump("norm", -1, rms_norm(post, hp.eps)) * self.t(hw)).astype(F32))
dump("mtp_shared_head_norm", -1, hh)
head = f"{p}.nextn.shared_head_head.weight" if self.has(f"{p}.nextn.shared_head_head.weight") else (
"output.weight" if self.has("output.weight") else "token_embd.weight")
logits = dump("result_output", -1, self.mm(hh, head))
st.n_past += T
return logits, st
def main() -> int:
ap = argparse.ArgumentParser(description="Qwen3.6 (qwen35moe) numpy oracle: forward pass + cb()-named dumps")
ap.add_argument("gguf")
ap.add_argument("--tokens", help="comma-separated token ids")
ap.add_argument("--text", help="synthetic vocabulary only: token id = ASCII code")
ap.add_argument("--dump", help="directory for the .f32 dumps and manifest.txt")
ap.add_argument("--split", type=int, default=0, help="feed the tokens CHUNK at a time, carrying GDN and KV state; dump only the last chunk")
ap.add_argument("--opt", action="append", default=[], metavar="KEY=VALUE",
help="flip one reading to its rival (see Model.opts), e.g. gdn_gate=sigmoid; for negative controls")
ap.add_argument("--act-quant", choices=["none", "q8"], default="none", help="q8: round activations to Q8_K / Q8_0 before quantized matmuls, as ggml does")
ap.add_argument("--force-topk", metavar="DIR", help="use the expert choices in DIR/ffn_moe_topk-<layer>.f32 (e.g. a llama.cpp dump) instead of the router's own")
ap.add_argument("--force-inputs", metavar="DIR", help="start every layer from DIR/l_out-<il-1>.f32 (a llama.cpp dump of the same tokens): measures per-layer, not accumulated, error")
ap.add_argument("--mtp", action="store_true", help="also run the nextn block on (tokens[1:], trunk hidden[:-1])")
ap.add_argument("--all-logits", action="store_true",
help="also dump result_output_all: the head's logits at every position of the (last) chunk, for a runner held to the oracle position by position")
a = ap.parse_args()
toks = [int(t) for t in a.tokens.split(",")] if a.tokens else [ord(c) for c in a.text]
m = Model(a.gguf)
for kv in a.opt:
k, v = kv.split("=", 1)
assert k in m.opts, f"unknown option {k!r}; known: {sorted(m.opts)}"
m.opts[k] = {"True": True, "False": False, "None": None}.get(v, v)
m.opts["act_quant"] = a.act_quant
m.opts["force_inputs"] = a.force_inputs
if a.force_topk:
m.opts["force_topk"] = {il: np.fromfile(f"{a.force_topk}/ffn_moe_topk-{il}.f32", dtype=F32).astype(np.int64).reshape(len(toks), -1)
for il in range(m.hp.n_layer)}
d = Dump(a.dump)
if a.split:
st = None
for i in range(0, len(toks), a.split):
last = i + a.split >= len(toks)
logits, h, st = m.forward(toks[i:i + a.split], d if last else None, st, all_logits=a.all_logits)
else:
logits, h, _ = m.forward(toks, d, all_logits=a.all_logits)
print(f"{len(toks)} tokens; last-token logits: argmax {int(logits.argmax())}, max {logits.max():.6f}, sum {logits.sum():.6f}")
d.close()
if a.mtp:
d2 = Dump((a.dump + "_mtp") if a.dump else None)
lg, _ = m.mtp_forward(toks[1:], h[:-1], d2, pos0=1) # token k with the hidden of k-1, at position k
print(f"mtp: {len(toks) - 1} positions; last argmax {int(lg[-1].argmax())}")
d2.close()
return 0
if __name__ == "__main__":
sys.exit(main())
+2 -3
View File
@@ -32,7 +32,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index
}
const auto s = strata::kernels::qsa_real_shapes();
const bool int8_keys = st.kv_int8 || st.kv_hybrid;
if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim < 0 ||
if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 ||
(st.kv_q4 && g.head_dim % 32) || (int8_keys && !st.kv_q4 && g.head_dim % 64)) {
error = "conversation snapshot: invalid K/V geometry";
return false;
@@ -42,8 +42,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index
: (size_t) g.head_dim * (int8_keys ? 1 : 2);
// Include the moving spare row, not only completed blocks. The checkpoint
// restore reconstructs that row when rewinding to an earlier prefix.
// (a dense-attention model has no indexer and so no pooled rows: idx_key_dim 0)
const int64_t pooled = index && g.has_indexer() && upto > 0 ? upto / s.idx_block + 1 : 0;
const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0;
// Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293,
// STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a
// snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse.
+3 -11
View File
@@ -61,10 +61,6 @@ bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t t
const auto& st = owned(ss, j);
const auto block = strata::kernels::qsa_real_shapes().idx_block;
size_t pooled_bytes = 0;
if (!g.has_indexer()) { // dense attention: no indexer buffers to carry, only the cell bound
if (st.max_cells < 0 || tokens > (uint64_t) st.max_cells) return fail(error, "invalid running-state cell bound");
continue;
}
if (!st.idx_tail || !st.idx_dead || !st.idx_block_pos || !st.idx_pooled ||
st.max_cells < 0 || tokens > (uint64_t) st.max_cells ||
(tokens && tokens / (uint64_t) block >= (uint64_t) std::max<int64_t>(0, st.idx_pooled_rows)) ||
@@ -110,12 +106,8 @@ bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) {
bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) {
z = {};
const auto key = geometry_key(g);
// A plain-residual model (hc 1) has no hyper-connection rate (key 15) and a dense-attention model has no
// indexer (keys 12 and 13, the indexer heads and key width): those zeros are the geometry, not an error.
for (size_t i = 0; i < key.size(); ++i) {
const bool may_be_zero = i == 1 || (!g.has_indexer() && (i == 12 || i == 13)) || (g.hc == 1 && i == 15);
if (key[i] < 0 || (!may_be_zero && key[i] == 0)) return fail(error, "invalid model geometry");
}
for (size_t i = 0; i < key.size(); ++i)
if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry");
size_t recurrence = 0, convolution = 0;
if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) ||
!product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) ||
@@ -126,7 +118,7 @@ bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z,
(uint64_t) g.idx_key_dim, sizeof(float)}) ||
!product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)}))
return fail(error, "running-state byte count overflow");
z.block_pos = g.has_indexer() ? sizeof(int32_t) : 0; // no indexer: no block position, no tail, no dead row
z.block_pos = sizeof(int32_t);
size_t total = 0;
if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) ||
!product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) ||
+5 -50
View File
@@ -223,31 +223,8 @@ bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current
namespace detail {
namespace {
uint64_t g_host_ram_cap = 0;
bool host_available_memory_raw(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
const std::string& cgroup_root);
} // namespace
void set_host_ram_cap(uint64_t bytes) { g_host_ram_cap = bytes; }
uint64_t host_ram_cap() { return g_host_ram_cap; }
bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
const std::string& cgroup_root) {
if (!host_available_memory_raw(m, meminfo, self_cgroup, cgroup_root)) return false;
// --ram-cap: the machine this engine pretends to run on. The cap is what that machine would report AVAILABLE,
// so "a 12 GiB machine" is --ram-cap 12 only if nothing else is resident; the 12 GiB VM 211 reports ~10 GiB
// available with its kernel and services, and emulating it exactly is --ram-cap 10.
if (g_host_ram_cap > 0) {
m.available = std::min(m.available, g_host_ram_cap);
m.cgroup_limit = std::min(m.cgroup_limit, g_host_ram_cap);
}
return m.available > 0;
}
namespace {
bool host_available_memory_raw(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
const std::string& cgroup_root) {
m = HostMemory{};
#if defined(_WIN32)
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
@@ -343,7 +320,6 @@ bool host_available_memory_raw(HostMemory& m, const std::string& meminfo, const
return m.available > 0;
#endif
}
} // namespace
} // namespace detail
@@ -1734,8 +1710,6 @@ bool FileExpertSource::pin_cache_complement(
complement_lock_off_ = lock_off;
complement_lent_slots_ = lend ? n_slots - keep_from : 0;
complement_ready_ = true;
complement_count_ = 0;
for (const uint64_t off : complement_offsets_) complement_count_ += off != kNoComplement;
std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n",
complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident",
(double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0,
@@ -1852,8 +1826,6 @@ const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
return result;
}
int64_t FileExpertSource::complement_count() const { return complement_ready_ ? complement_count_ : 0; }
bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 ||
layer >= n_layers_ || expert >= n_expert_) return false;
@@ -2029,23 +2001,6 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
const ExpertLayout& lay = expert_layout();
const bool native = lay.native;
if (native && d.nact_multi.size() < (size_t) MAXT * kNativeActBytes) d.nact_multi.resize((size_t) MAXT * kNativeActBytes);
// The activation and output row width. A native pack's is the layer's own (NativeFmt n_embd: 2048 for
// Qwen3.6-35B-A3B); the canonical Q2_0 pack's is H. The window publishes its rows at that width, so reading
// token t at t * H or writing its row at i * H addressed the wrong token for every t > 0 and ran past the
// window's buffers (the single-token dispatch above refuses n_embd != H; this one took the width for granted).
if (native && (d.layers < 0 || (size_t) d.layers >= lay.fmt.size())) {
d.failed = true;
d.fail = "the expert pool was asked for a layer the pack does not have";
d.fail_layer = d.layers;
return;
}
const int64_t W = native ? lay.fmt[(size_t) d.layers].n_embd : (int64_t) H;
if (W <= 0 || W > (int64_t) H) {
d.failed = true;
d.fail = "the expert pool's activation buffers are compiled for at most a 2560-wide activation";
d.fail_layer = d.layers;
return;
}
if (d.job_of.size() != (size_t) d.n_expert) d.job_of.assign((size_t) d.n_expert, (int16_t) -1);
if (d.jobs_multi.size() < (size_t) (n_tok * k)) d.jobs_multi.resize((size_t) (MAXT * k));
static const bool ptrace = std::getenv("STRATA_POOL_TRACE") != nullptr;
@@ -2188,11 +2143,11 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
for (int64_t t = 0; t < n_tok; ++t) {
if (ep && std::all_of(kind + t * k, kind + (t + 1) * k, [](int32_t v) { return v >= 0; })) continue;
if (native && strata::kernels::cpu::q2_native_kernels(lay.fmt[(size_t) d.layers].gu_type)) // a native Q2_0 pack: the Q2_0 kernels' activations
act_quant_any(x_f + (size_t) t * W, (int) W, d.act_multi[(size_t) t]);
act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
else if (native)
native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * W, d.nact_multi.data() + (size_t) t * kNativeActBytes);
native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes);
else
act_quant_q8_1(x_f + (size_t) t * W, (int) W, d.act_multi[(size_t) t]);
act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
}
}
const auto c2 = std::chrono::steady_clock::now();
@@ -2210,7 +2165,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
for (int64_t j = 0; j < k; ++j) {
const int64_t i = t * k + j;
const int64_t e = ids[i];
float* row = out + (size_t) i * W;
float* row = out + (size_t) i * H;
if (e < 0 || e >= d.n_expert) {
d.failed = true;
d.fail = "a routed expert id is out of range";
@@ -2226,7 +2181,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
// dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU
if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) ||
(gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1))))
std::memset(row, 0, (size_t) W * sizeof(float));
std::memset(row, 0, (size_t) H * sizeof(float));
continue;
}
++d.cache_refused;
+22 -190
View File
@@ -1,7 +1,6 @@
// src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps.
#include "strata/core/layer.hpp"
#include "strata/core/qsa_shapes.hpp"
#include "strata/core/native_head.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/bf16_gemv.hpp"
@@ -315,15 +314,15 @@ st_begin(layer, 12, stream);
st_end(layer, 13, stream); st_begin(layer, 14, stream);
// ---- 6. the recurrence. q and k are the (16, 128) views; v is the (48, 128) view. The stage marks for
// it live at the end of the alpha/beta/gate line above, because the gate and the step are one sequence.
// ---- 7. z, then y = rms_norm(o) * ssm_norm * act(z). SIGMOID for Flash-Next, SiLU for Qwen3.6: `g.gdn_gate()`.
// ---- 7. z, then y = rms_norm(o) * ssm_norm * sigmoid(z). SIGMOID, not SiLU.
// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between.
if (!gemv_quantized(*w_gate, p_gate, f_gate, b.x_q8_0, b.x_q8k, b.z, g.n_embd, g.ssm_value_dim, v.name("attn_gate.weight"), stream, err, mixed,
w_qkv->native_data != nullptr && w_gate->native_data != nullptr)) return false;
try {
if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS,
g.gdn_gate(), b.y, (int) g.ssm_k_heads, (int) g.ssm_v_heads, stream);
else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, g.gdn_gate(), stream);
else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, g.gdn_gate(), stream);
if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS, b.y,
(int) g.ssm_k_heads, (int) g.ssm_v_heads, stream);
else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream);
else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream);
} catch (const std::exception& error) { err = v.name("gdn_out_norm") + ": " + error.what(); return false; }
st_end(layer, 14, stream);
// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for
@@ -474,22 +473,17 @@ bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer
if (!moe_shared(tables, g, layer, b, x, stream, err)) return false;
return moe_combine_parts(g, layer, k, b, parts, out, stream, err);
}
bool layer_verify_compatible(const ModelGeometry& g, std::string& why) {
// Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic. At hc = 1 the
// block has no hyper-connection read (the plain path, below) and without an indexer no selection to make.
bool layer_verify_compatible(std::string& why) {
// Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic.
if (!native_bf16_projections) why = "the native BF16 projections are off";
else if (g.hc > 1 && !g_fused_gr) why = "the fused hyper-connection read is off";
else if (!g_fused_gr) why = "the fused hyper-connection read is off";
else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled()) why = "the fused native GDN kernels are off";
else if (!g_fast_attn || native_flash_attn_short) why = "the split-K decode attention is off";
else if (g.has_indexer() && !g_fast_select) why = "the block top-k selection is off";
else if (g.has_indexer() && !strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off";
else if (!g_fast_select) why = "the block top-k selection is off";
else if (!strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off";
else return true;
return false;
}
bool layer_verify_compatible(std::string& why) {
const ModelGeometry flash_next; // the defaults: hc 4 with the indexer
return layer_verify_compatible(flash_next, why);
}
void layer_set_publish_kernel(bool enabled) { g_publish_kernel = enabled; }
void layer_set_fused_gdn(bool enabled) { g_fused_gdn = enabled; }
void layer_set_fast_select(bool enabled) { g_fast_select = enabled; }
@@ -508,7 +502,7 @@ if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false; ret
namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes;
/// The geometry the QSA kernels want, from the one place that defines it. `ModelGeometry` carries the widths
/// the LAYOUT needs; `QsaShapes` adds `n_rot`, `idx_block` and `idx_top_k`, which are kernel contracts.
using strata::core::qsa_shapes; // the one builder (strata/core/qsa_shapes.hpp): dense = the three indexer widths zero
QsaShapes qsa_shapes(const ModelGeometry& g) { QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; s.idx_dim = g.idx_key_dim; return s;}
uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; }
/// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets.
struct Cursor { uint8_t* p; uint64_t used = 0; template <typename T> T* take(uint64_t count) { T* r = (T*) (p + used); used = align_up16(used + count * sizeof(T)); return r; } uint8_t* take_bytes(uint64_t n) { uint8_t* r = p + used; used = align_up16(used + n); return r; }};
@@ -530,7 +524,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) {
KvPlan p;
p.pages = (max_cells + s.page_size - 1) / s.page_size;
p.slots = p.pages;
p.pooled_rows = strata::kernels::qsa_dense(s) ? 2 : max_cells / s.idx_block + 2; // dense: as the ring, no indexer
p.pooled_rows = max_cells / s.idx_block + 2;
if (g_kv_resident <= 0 || ring_cells < 0) return p; // ring_cells < 0: always fully resident
// A/B only: STRATA_KV_RING_OFF keeps the drafter fully resident, STRATA_KV_MAIN_OFF the main layers
static const bool ring_off = std::getenv("STRATA_KV_RING_OFF") != nullptr;
@@ -558,14 +552,6 @@ uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8
} // namespace
void qsa_set_kv_resident(int64_t cells) { g_kv_resident = cells > 0 ? cells : 0; }
bool qsa_kv_streaming_applies(const ModelGeometry& g, std::string& why) {
if (g.has_indexer()) return true;
why = "KV streaming (--kv-resident) does not apply to " + std::string(model_arch_name(g.arch)) +
": its attention is dense (no indexer), so every token reads every cell and every block would have to be "
"made resident every token - the whole KV over PCIe per token, not a saving (docs/QWEN36-35B-A3B.md 3.3 "
"item 6, 4.2). Hold the KV in VRAM or lower --max-context";
return false;
}
int64_t qsa_kv_resident() { return g_kv_resident; }
int64_t qsa_kv_resident_min() { return 20480; }
uint64_t qsa_kv_host_bytes() { return g_kv_host_bytes; }
@@ -598,12 +584,6 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
st.kv_q4 = g_kv_q4;
// Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 -
// mtp.cpp). Streamed mode is refused outright; generate.cpp validates it too, this is the backstop.
if (g_kv_resident > 0 && ring_cells <= 0 && !g.has_indexer()) { // dense attention: generate.cpp asks first, this is the backstop
std::string why;
qsa_kv_streaming_applies(g, why);
std::fprintf(stderr, "strata: %s\n", why.c_str());
return 0;
}
if (g_kv_hybrid && ring_cells <= 0) {
if (p.mode == 1) {
std::fprintf(stderr, "strata: hybrid K8V4 KV does not support --kv-resident streaming\n");
@@ -778,13 +758,9 @@ void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* i
qsa_shapes(g), stream);
}
uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_cap(max_cells, s); const bool dense = strata::kernels::qsa_dense(s); uint64_t n = 0; n += (uint64_t) q8k_bytes(g.n_embd); n += (uint64_t) (g.n_embd / 32) * 34;
uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); uint64_t n = 0; n += (uint64_t) q8k_bytes(g.n_embd); n += (uint64_t) (g.n_embd / 32) * 34;
// block_q8_0
n += (uint64_t) g.n_embd * 2; n += (uint64_t) g.n_head * 2 * g.head_dim * 4; n += (uint64_t) g.n_head * g.head_dim * 4; n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2; n += (uint64_t) g.idx_key_dim * 4; n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4;
// dense attention has no cell scores, no ids (a null is the identity) and no gather scratch (the split-K kernel
// reads the pools): at 262,144 cells those three would be 1 + 1 + 512 MiB
if (!dense) { n += (uint64_t) max_cells * 4; n += (uint64_t) cap * 4; n += (uint64_t) cap * g.n_head_kv * g.head_dim * 2 * 2; }
n += (uint64_t) g.n_head * g.head_dim * 4;
n += (uint64_t) g.n_embd * 2; n += (uint64_t) g.n_head * 2 * g.head_dim * 4; n += (uint64_t) g.n_head * g.head_dim * 4; n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2; n += (uint64_t) g.idx_key_dim * 4; n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4; n += (uint64_t) max_cells * 4; n += (uint64_t) cap * 4; n += (uint64_t) cap * g.n_head_kv * g.head_dim * 2 * 2; n += (uint64_t) g.n_head * g.head_dim * 4;
// attn
n += (uint64_t) g.n_head * g.head_dim * 2;
// attn16
@@ -795,8 +771,7 @@ n += (uint64_t) q8k_bytes(g.n_head * g.head_dim);
n += strata::kernels::qsa_decode_attn_scratch_floats(cap, s) * 4 + 16;
// attn_scratch
return align_up16(n) + 256;}
uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_cap(max_cells, s); const bool dense = strata::kernels::qsa_dense(s); Cursor c{(uint8_t*) base}; b.x_q8k = c.take_bytes(q8k_bytes(g.n_embd)); b.x_q8_0 = c.take_bytes((uint64_t) (g.n_embd / 32) * 34); b.x_bf16 = c.take<uint16_t>((uint64_t) g.n_embd); b.q_full = c.take<float>((uint64_t) g.n_head * 2 * g.head_dim); b.qcur = c.take<float>((uint64_t) g.n_head * g.head_dim); b.kcur = c.take<float>((uint64_t) g.n_head_kv * g.head_dim); b.vcur = c.take<float>((uint64_t) g.n_head_kv * g.head_dim); b.idx_raw = c.take<float>((uint64_t) g.idx_key_dim); b.q_idx = c.take<float>((uint64_t) g.idx_q_heads * g.idx_key_dim); if (!dense) { // dense attention: no scores, no ids (null = identity), no gather scratch (see qsa_buffers_bytes)
b.cell_scores = c.take<float>((uint64_t) max_cells); b.ids = c.take<int32_t>((uint64_t) cap); b.k_scratch = c.take<uint16_t>((uint64_t) cap * g.n_head_kv * g.head_dim); b.v_scratch = c.take<uint16_t>((uint64_t) cap * g.n_head_kv * g.head_dim); } b.attn = c.take<float>((uint64_t) g.n_head * g.head_dim); b.attn16 = c.take<uint16_t>((uint64_t) g.n_head * g.head_dim); b.attn32 = c.take<float>((uint64_t) g.n_head * g.head_dim); b.attn_q8k = c.take_bytes(q8k_bytes(g.n_head * g.head_dim)); b.attn_scratch = c.take<float>(strata::kernels::qsa_decode_attn_scratch_floats(cap, s)); return c.used;}
uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); Cursor c{(uint8_t*) base}; b.x_q8k = c.take_bytes(q8k_bytes(g.n_embd)); b.x_q8_0 = c.take_bytes((uint64_t) (g.n_embd / 32) * 34); b.x_bf16 = c.take<uint16_t>((uint64_t) g.n_embd); b.q_full = c.take<float>((uint64_t) g.n_head * 2 * g.head_dim); b.qcur = c.take<float>((uint64_t) g.n_head * g.head_dim); b.kcur = c.take<float>((uint64_t) g.n_head_kv * g.head_dim); b.vcur = c.take<float>((uint64_t) g.n_head_kv * g.head_dim); b.idx_raw = c.take<float>((uint64_t) g.idx_key_dim); b.q_idx = c.take<float>((uint64_t) g.idx_q_heads * g.idx_key_dim); b.cell_scores = c.take<float>((uint64_t) max_cells); b.ids = c.take<int32_t>((uint64_t) cap); b.k_scratch = c.take<uint16_t>((uint64_t) cap * g.n_head_kv * g.head_dim); b.v_scratch = c.take<uint16_t>((uint64_t) cap * g.n_head_kv * g.head_dim); b.attn = c.take<float>((uint64_t) g.n_head * g.head_dim); b.attn16 = c.take<uint16_t>((uint64_t) g.n_head * g.head_dim); b.attn32 = c.take<float>((uint64_t) g.n_head * g.head_dim); b.attn_q8k = c.take_bytes(q8k_bytes(g.n_head * g.head_dim)); b.attn_scratch = c.take<float>(strata::kernels::qsa_decode_attn_scratch_floats(cap, s)); return c.used;}
// ================================ PER-STAGE TIMING, DEBUG ONLY ================================
//
// **THE ENGINE SPENDS 1.047 ms PER LAYER WITH THE EXPERTS OFF, AND EVERY COST MODEL IN `bench/` PREDICTS LESS
@@ -898,10 +873,7 @@ void stage_timing_report(int64_t n_layers) {
// needs nothing from the layer it is called for beyond its index.
static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off,
uint64_t n, void* stream);
bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_cap(st.max_cells, s);
// Qwen3.6 (3.3): dense attention. No indexer tensors, no raw key, no pooled scores, no top-k: the split-K
// kernel reads every cell (a null `ids` is the identity) with the width n_kv from the step.
const bool has_idx = g.has_indexer();
bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s);
const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) {
try {
if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream);
@@ -916,16 +888,16 @@ const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows,
};
// ---- resolve every tensor by name, and REFUSE rather than reading a null. `check_layer` has already
// asserted the shapes at load time; a missing name here is a wiring mistake.
struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_proj.weight"); const WeightRef* w_attnq = v.get("attn_q.weight"); const WeightRef* w_attnk = v.get("attn_k.weight"); const WeightRef* w_attnv = v.get("attn_v.weight"); const WeightRef* w_attno = v.get("attn_output.weight"); const WeightRef* w_idxq = v.get("indexer.q_proj.weight"); const WeightRef* w_qn = v.get("attn_q_norm.weight"); const WeightRef* w_kn = v.get("attn_k_norm.weight"); const WeightRef* w_iqn = v.get("indexer.q_norm.weight"); const WeightRef* w_ikn = v.get("indexer.k_norm.weight"); const char* missing = (has_idx && !w_idxk) ? "indexer.k_proj.weight" : !w_attnq ? "attn_q.weight" : !w_attnk ? "attn_k.weight" : !w_attnv ? "attn_v.weight" : !w_attno ? "attn_output.weight" : (has_idx && !w_idxq) ? "indexer.q_proj.weight" : !w_qn ? "attn_q_norm.weight" : !w_kn ? "attn_k_norm.weight" : (has_idx && !w_iqn) ? "indexer.q_norm.weight" : (has_idx && !w_ikn) ? "indexer.k_norm.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } if (pos < 0 || pos >= st.max_cells) { err = "qsa_layer: pos " + std::to_string(pos) + " is outside the state's 0.." + std::to_string(st.max_cells - 1); return false; }
struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_proj.weight"); const WeightRef* w_attnq = v.get("attn_q.weight"); const WeightRef* w_attnk = v.get("attn_k.weight"); const WeightRef* w_attnv = v.get("attn_v.weight"); const WeightRef* w_attno = v.get("attn_output.weight"); const WeightRef* w_idxq = v.get("indexer.q_proj.weight"); const WeightRef* w_qn = v.get("attn_q_norm.weight"); const WeightRef* w_kn = v.get("attn_k_norm.weight"); const WeightRef* w_iqn = v.get("indexer.q_norm.weight"); const WeightRef* w_ikn = v.get("indexer.k_norm.weight"); const char* missing = !w_idxk ? "indexer.k_proj.weight" : !w_attnq ? "attn_q.weight" : !w_attnk ? "attn_k.weight" : !w_attnv ? "attn_v.weight" : !w_attno ? "attn_output.weight" : !w_idxq ? "indexer.q_proj.weight" : !w_qn ? "attn_q_norm.weight" : !w_kn ? "attn_k_norm.weight" : !w_iqn ? "indexer.q_norm.weight" : !w_ikn ? "indexer.k_norm.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } if (pos < 0 || pos >= st.max_cells) { err = "qsa_layer: pos " + std::to_string(pos) + " is outside the state's 0.." + std::to_string(st.max_cells - 1); return false; }
// THE TWO BF16 PROJECTIONS: the arena holds them re-rounded to 2 B/elem, which is what `bf16_gemv` wants.
// Reading one as f32 would walk 2x its length inside the arena without faulting.
if (has_idx && (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32)) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; }
if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; }
// ---- 1. the three activation formats, once each
if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) {
quantize_q8_K(x, b.x_q8k, g.n_embd, stream);
quantize_q8_0(x, b.x_q8_0, g.n_embd, stream);
}
if (!native_bf16_projections && has_idx) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
// ---- 2. the step state: ONE H2D carries every per-token count the kernels need. Nothing below passes a
// per-token scalar as an argument, which is what keeps this layer capturable.
//
@@ -943,7 +915,7 @@ if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) {
} else
if (cudaMemcpyAsync(st.step, st.host_step, qsa_step_bytes(), cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(st.pos_dev, st.host_pos, (size_t) g.n_head * 4, cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the step-state upload failed"; return false; } }
// ---- 3. the indexer's RAW key: appended before any norm, pooled later once per block
if (has_idx) project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
// ---- 4. K and V, in Q8_K, then norm and rotate K only
SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"), err)) return false; if (!sform_of(*w_attnv, f_v, v.name("attn_v.weight"), err)) return false; if (!sform_of(*w_attno, f_o, v.name("attn_output.weight"), err)) return false; if (!sform_of(*w_attnq, f_q, v.name("attn_q.weight"), err)) return false; Planes p_k, p_v, p_o, p_q; if (!plane_ptrs(*w_attnk, v.name("attn_k.weight"), p_k, err)) return false; if (!plane_ptrs(*w_attnv, v.name("attn_v.weight"), p_v, err)) return false; if (!plane_ptrs(*w_attno, v.name("attn_output.weight"), p_o, err)) return false; if (!plane_ptrs(*w_attnq, v.name("attn_q.weight"), p_q, err)) return false;
// k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this
@@ -968,7 +940,7 @@ if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV
}
if (st.kv_q4) {
strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);
} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */ { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } if (has_idx) { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) {
} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */ { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) {
try {
native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base,
(const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream);
@@ -987,27 +959,12 @@ if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g
// case A) and needs no kernel.
if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4, (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the q/gate split failed"; return false; } if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false;
// ---- 7. the indexer's query: BF16, then norm and rotate
if (has_idx) {
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream);
if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false;
}
// ---- 8. score, select, gather, attend. `max_blocks` and `cap` are CAPACITIES from the state, not this
// token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured
// graph, and the kernels guard for the surplus. const
int64_t max_blocks = (st.max_cells / s.idx_block) + 2;
if (!has_idx) {
// dense: every cell, no ids buffer (the kernels take null as the identity); only the split-K pool reader
// exists at this width - the gather + shared-memory softmax path is sized for 2,051 cells and the short
// flash adapter for 256
if (!g_fast_attn || native_flash_attn_short) {
err = v.name("attention") + ": dense attention runs only through the split-K decode kernel (the gather "
"path and the short flash adapter are sized for the sparse selection)";
return false;
}
if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // <Hq, Hk> = <q, k>
const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st);
strata::kernels::qsa_decode_attn_step(b.qcur, pools, nullptr, st.step, cap, s, b.attn_scratch, b.attn, stream);
} else {
if (g_fast_select) {
// Plan v0.3 P7: block-level FP32 scores and a radix selection over blocks (qsa_select.hpp).
qsa_block_scores(st.idx_pooled, st.idx_dead, b.q_idx, st.step, 1, max_blocks, s, b.cell_scores, stream);
@@ -1044,7 +1001,6 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2;
}
} else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream);
}
} /* has_idx */
if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse
dump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc, (uint64_t) g.n_head * g.head_dim, stream); { const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 2 * g.n_head_kv * g.head_dim; dump_slot(dump, g, layer, (const float*) b.v_scratch, vs, (uint64_t) g.n_head_kv * g.head_dim / 2, stream); dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream); dump_slot(dump, g, layer, (const float*) st.step, vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream); }
// ---- 9. Gate the attention output before its projection. Native CUDA keeps F32
@@ -1131,20 +1087,6 @@ bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token,
}
bool lm_head_mix(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb,
void* stream, std::string& err) {
if (g.hc == 1) {
// the plain head: `result_norm = rms_norm(R) * output_norm` (qwen35moe.cpp:230-233), one stream, no mix
const WeightRef* wn = tables.find("output_norm.weight");
if (!wn) { err = "lm_head: output_norm.weight is missing (the plain block's head norm)"; return false; }
if (wn->kind != WeightKind::F32 || wn->elements != g.n_embd) {
err = "lm_head: output_norm.weight is engine form " + std::to_string((int) wn->kind) + " of " +
std::to_string(wn->elements) + " elements; the plain head reads F32 x " + std::to_string(g.n_embd);
return false;
}
try {
plain_norm_rows(bb.R, (const float*) wn->data, bb.mixed, g.n_embd, (float) g.rms_eps, 1, stream);
} catch (const std::exception& e) { err = std::string("lm_head output_norm: ") + e.what(); return false; }
return true;
}
const WeightRef* wn = tables.find("output_hc_norm.weight");
const WeightRef* wd = tables.find("output_hc_down.weight");
const WeightRef* wu = tables.find("output_hc_up.weight");
@@ -1225,115 +1167,7 @@ static void dump_half(const BlockBuffers& bb, const ModelGeometry& g, int64_t la
uint64_t off, uint64_t n, void* stream) {
dump_slot(bb.dump, g, layer, src, off, n, stream);
}
// ================================ THE PLAIN BLOCK (hc = 1, Qwen3.6) ================================
// See layer.hpp: the pre-norm residual block of `qwen35moe`, a second path chosen by `g.hc`, never the GR kernels
// on one stream. The verify window (verify.cpp) calls the same two row helpers over its T rows.
void plain_norm_rows(const float* R, const float* w, float* mixed, int64_t n_embd, float eps, int n_tok, void* stream) {
if (n_tok <= 0) return;
// ggml's `rms_norm` (per row: x * rsqrt(mean(x^2) + eps)) then `mul` by the weight, in that order; one block per
// row with a fixed reduction order, so row t of n rows is bitwise the one-row call (native_qsa.cu).
strata::kernels::native_qsa_rms_norm_weighted(R, w, mixed, (int) n_embd, n_tok, eps, stream);
}
void plain_residual_rows(float* R, const float* block_out, int64_t n_embd, int n_tok, void* stream) {
if (n_tok <= 0) return;
strata::kernels::add_inplace(R, block_out, n_embd * n_tok, stream); // elementwise: rows are independent
}
namespace {
/// The F32 norm weight `suffix` of layer `v`, or null with `err` naming the tensor and the form found. The plain
/// block reads it as `const float*`, so the ENGINE FORM must be F32 (4 B/elem): the pack keeps Qwen3.6's norms as
/// the F32 they are in the file. A BF16 row (2 B/elem) read as f32 would walk 2x the tensor inside the arena and
/// produce a finite wrong norm - the layout.cpp failure in a new coat - so the form is checked here as well.
const float* plain_norm_weight(const LayerView& v, const char* suffix, int64_t n_embd, std::string& err) {
const WeightRef* w = v.get(suffix);
if (w == nullptr) { err = v.name(suffix) + " is missing (the plain block's norm; hc = 1)"; return nullptr; }
if (w->kind != WeightKind::F32 || w->elements != n_embd || w->data == nullptr) {
err = v.name(suffix) + " is engine form " + std::to_string((int) w->kind) + " of " +
std::to_string(w->elements) + " elements; the plain block reads F32 x " + std::to_string(n_embd);
return nullptr;
}
return (const float*) w->data;
}
/// `block_layer_pre` at hc = 1. The stages and the `half` / `stage_prefix` selection are the GR path's (0 read,
/// 1 mixer, 2 write, 3 read, 4 route), so `session_replay_stages` and the measurement splits apply unchanged.
bool plain_block_pre(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base,
const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb, int64_t k,
const BlockBuffers& bb, void* stream, std::string& err, const Doorbell* db, const PleRun* ple,
int half, int stage_prefix) {
if (ple != nullptr && ple->ready()) {
err = "block_layer_pre: the plain block (hc = 1) has no per-layer embedding, but a PLE run was supplied";
return false;
}
const LayerView v(tables, layer);
const float* w_attn = plain_norm_weight(v, "attn_norm.weight", g.n_embd, err);
if (w_attn == nullptr) return false;
const float* w_post = plain_norm_weight(v, "post_attention_norm.weight", g.n_embd, err);
if (w_post == nullptr) return false;
const float eps = (float) g.rms_eps;
const bool qsa = is_qsa_layer(g, layer);
const bool run0 = stage_prefix > 0 ? (stage_prefix >= 1) : (half == 0 || half == 1);
const bool run1 = stage_prefix > 0 ? (stage_prefix >= 2) : (half == 0 || half == 1);
const bool run2 = stage_prefix > 0 ? (stage_prefix >= 3) : (half == 0 || half == 1);
const bool run3 = stage_prefix > 0 ? (stage_prefix >= 4) : (half == 0 || half == 2);
const bool run4 = stage_prefix > 0 ? (stage_prefix >= 5) : (half == 0 || half == 2);
try {
if (run0) { // x = rms_norm(R) * attn_norm (the oracle's `attn_norm-N`)
st_begin(layer, 0, stream);
plain_norm_rows(bb.R, w_attn, bb.mixed, g.n_embd, eps, 1, stream);
st_end(layer, 0, stream);
}
} catch (const std::exception& e) { err = v.name("attn_norm") + ": " + e.what(); return false; }
if (run1) { // the mixer: whatever `qsa_layer` / `gdn_layer` produce for this geometry (their own branches)
st_begin(layer, 1, stream);
if (qsa) {
if (!qsa_layer(tables, g, layer, pos, pos_base, qst, qb, bb.mixed, bb.block_out, stream, err, bb.dump))
return false;
} else if (!gdn_layer(tables, g, layer, gb, bb.mixed, bb.block_out, stream, err)) return false;
st_end(layer, 1, stream);
dump_half(bb, g, layer, bb.block_out, 0, g.n_embd, stream);
}
try {
if (run2) { // R += out (`attn_residual-N`): applied here, no pending write
st_begin(layer, 2, stream);
plain_residual_rows(bb.R, bb.block_out, g.n_embd, 1, stream);
st_end(layer, 2, stream);
}
if (run3) { // x = rms_norm(R) * post_attention_norm (`attn_post_norm-N`)
st_begin(layer, 3, stream);
plain_norm_rows(bb.R, w_post, bb.mixed, g.n_embd, eps, 1, stream);
st_end(layer, 3, stream);
}
} catch (const std::exception& e) { err = v.name("post_attention_norm") + ": " + e.what(); return false; }
if (run4) { // the router (rings the doorbell), then the shared expert while the host runs the pool
st_begin(layer, 4, stream);
const bool ok = moe_route(tables, g, layer, k, mb, bb.mixed, stream, err, db);
st_end(layer, 4, stream);
if (!ok) return false;
if (g_shared_early && !moe_shared(tables, g, layer, mb, bb.mixed, stream, err)) return false;
}
return true;
}
/// `block_layer_post` at hc = 1: combine, then `R += out` (`l_out-N`), then a control vector if one covers the layer.
bool plain_block_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& mb,
const BlockBuffers& bb, const float* parts, void* stream, std::string& err) {
st_begin(layer, 5, stream);
if (g_shared_early ? !moe_combine_parts(g, layer, k, mb, parts, bb.block_out, stream, err)
: !moe_finish(tables, g, layer, k, mb, bb.mixed, parts, bb.block_out, stream, err)) return false;
st_end(layer, 5, stream);
dump_half(bb, g, layer, bb.block_out, (uint64_t) g.n_embd, g.n_embd, stream);
st_begin(layer, 6, stream);
try {
plain_residual_rows(bb.R, bb.block_out, g.n_embd, 1, stream);
if (strata::kernels::cvec().covers(layer))
strata::kernels::cvec_apply(bb.R, layer, 1, g.n_embd, nullptr, 0, nullptr, 0, false, stream);
} catch (const std::exception& e) { err = std::string("block_layer_post: ") + e.what(); return false; }
st_end(layer, 6, stream);
return true;
}
} // namespace
bool block_layer_pre(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb, int64_t k, const BlockBuffers& bb, void* stream, std::string& err, const Doorbell* db, const PleRun* ple, int half, int stage_prefix) {
if (g.hc == 1) // Qwen3.6: the plain pre-norm block, not the hyper-connection read on one stream
return plain_block_pre(tables, g, layer, pos, pos_base, gb, qst, qb, mb, k, bb, stream, err, db, ple, half,
stage_prefix);
// ================================ THE PLE, AT LAYER 1 ONLY ================================
//
// **THIS IS THE CALL WHOSE ABSENCE FAILED GATE C1.** Layer 1 carries the six `blk.1.ple_*` tensors and no
@@ -1482,9 +1316,7 @@ uint64_t ple_run_scratch_bytes() {
return strata::kernels::ple_block_scratch_bytes() + strata::kernels::NG_HC_DIM * sizeof(float);
}
bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream, std::string& err) {
if (g.hc == 1) return plain_block_post(tables, g, layer, k, mb, bb, parts, stream, err);
const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr};
bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream, std::string& err) { const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr};
// `bb.mixed` and `bb.inject` are what `block_layer_pre` left, and NOTHING between the two calls may touch
// them - that is what makes `post[l]` safe to launch after the host has run the pool.
st_begin(layer, 5, stream);
-16
View File
@@ -2,7 +2,6 @@
#include "strata/core/layout.hpp"
#include <cstdio>
#include <cstring>
namespace strata::core {
namespace {
@@ -82,12 +81,6 @@ bool check_one(const WeightTable& t, const ModelGeometry& g, int64_t layer, std:
for (const Want2& w : want2) {
if (w.qsa_only && !qsa) continue;
if (w.gdn_only && qsa) continue;
// hc = 1 (Qwen3.6): no hyper-connections, so no `hc_*` tensors - the plain block reads `attn_norm` and
// `post_attention_norm` instead (the 1-D set below; docs/QWEN36-35B-A3B.md section 3.5)
if (g.hc == 1 && std::strncmp(w.suffix, "hc_", 3) == 0) continue;
// dense attention (Qwen3.6): no sparse indexer, so no `indexer.*` tensors in the file or the pack; `qsa_layer`
// and the verify window ask for them only with `g.has_indexer()` (step3-attn.md), and so does this check
if (!g.has_indexer() && std::strncmp(w.suffix, "indexer.", 8) == 0) continue;
const WeightRef* r = v.get(w.suffix);
if (!r) {
err = "layer " + std::to_string(layer) + ": missing " + v.name(w.suffix);
@@ -103,10 +96,6 @@ bool check_one(const WeightTable& t, const ModelGeometry& g, int64_t layer, std:
const Want1 want1[] = {
{"hc_attn_norm.weight", g.hc_dim(), WeightKind::F32, false, false},
{"hc_ffn_norm.weight", g.hc_dim(), WeightKind::F32, false, false},
// the plain block's two norms (hc = 1 only; F32 in the file, kept F32 in the pack: layer.cpp reads them as
// `const float*`). At hc > 1 these names do not exist and are skipped below.
{"attn_norm.weight", g.n_embd, WeightKind::F32, false, false},
{"post_attention_norm.weight", g.n_embd, WeightKind::F32, false, false},
{"ffn_gate_inp_shexp.weight", g.n_embd, WeightKind::Bf16InF32, false, false},
{"ssm_a", g.ssm_v_heads, WeightKind::F32, false, true},
{"ssm_dt.bias", g.ssm_v_heads, WeightKind::F32, false, true},
@@ -119,11 +108,6 @@ bool check_one(const WeightTable& t, const ModelGeometry& g, int64_t layer, std:
for (const Want1& w : want1) {
if (w.qsa_only && !qsa) continue;
if (w.gdn_only && qsa) continue;
const bool hc_tensor = std::strncmp(w.suffix, "hc_", 3) == 0;
const bool plain_norm = std::strcmp(w.suffix, "attn_norm.weight") == 0 ||
std::strcmp(w.suffix, "post_attention_norm.weight") == 0;
if (g.hc == 1 ? hc_tensor : plain_norm) continue;
if (!g.has_indexer() && std::strncmp(w.suffix, "indexer.", 8) == 0) continue;
const WeightRef* r = v.get(w.suffix);
if (!r) {
err = "layer " + std::to_string(layer) + ": missing " + v.name(w.suffix);
+25 -406
View File
@@ -1,5 +1,4 @@
// src/core/mtp.cpp - see include/strata/core/mtp.hpp.
#include "strata/core/qsa_shapes.hpp"
#include "strata/core/mtp.hpp"
#include "strata/core/coupled_draft.hpp"
#include "strata/core/on_device.hpp"
@@ -11,7 +10,6 @@
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/gr.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/native_moe.hpp"
@@ -70,8 +68,15 @@ bool mapped(size_t bytes, void** h, void** d) {
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
}
// the one builder (strata/core/qsa_shapes.hpp): a dense geometry has its three indexer widths zero together
strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return strata::core::qsa_shapes(g); }
strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) {
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head;
s.n_head_kv = g.n_head_kv;
s.head_dim = g.head_dim;
s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
return s;
}
// 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB.
#if defined(_WIN32)
@@ -82,30 +87,6 @@ strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return strata::co
#define STRATA_FILE_TELL64(f) ftello(f)
#endif
/// dense.txt's `kind` -> ggml type id for a projection kept in its GGUF form (Qwen3.6's pack: tools/mtp_qwen36_pack.py
/// writes the type's name in lowercase); -1 for `f32`, `bf16` and anything else.
int ggml_type_of_kind(const std::string& k) {
static const struct { const char* name; int type; } kinds[] = {
{"q4_0", 2}, {"q4_1", 3}, {"q5_0", 6}, {"q5_1", 7}, {"q8_0", 8}, {"q2_k", 10}, {"q3_k", 11}, {"q4_k", 12},
{"q5_k", 13}, {"q6_k", 14}, {"iq2_xxs", 16}, {"iq2_xs", 17}, {"iq3_xxs", 18}, {"iq1_s", 19}, {"iq4_nl", 20},
{"iq3_s", 21}, {"iq2_s", 22}, {"iq4_xs", 23}, {"iq1_m", 29}, {"q2_0", 42}};
for (const auto& e : kinds) if (k == e.name) return e.type;
return -1;
}
/// `"key": <integer>` in a small JSON text (mtp.json), or `missing` when absent. The pack's geometry record is flat
/// integers; a real parser is not needed for a check that refuses by name.
long long json_int(const std::string& text, const char* key, long long missing = -1) {
const std::string k = "\"" + std::string(key) + "\":";
size_t at = text.find(k);
if (at == std::string::npos) return missing;
at += k.size();
while (at < text.size() && (text[at] == ' ' || text[at] == '\t')) ++at;
char* end = nullptr;
const long long v = std::strtoll(text.c_str() + at, &end, 10);
return end == text.c_str() + at ? missing : v;
}
bool read_file(const std::string& path, std::vector<uint8_t>& out) {
// Loader fix (0.1.15+loaderfix.2): `ifstream::read` reaches the disk as 4095-byte reads on MSVC - the same
// split `load_experts_ranges` had - so the drafter's 111 MiB dense blob paid 4 KiB per operation on a cold
@@ -165,116 +146,6 @@ const void* MtpDrafter::q8(const char* name) const {
for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;
return nullptr;
}
const void* MtpDrafter::tensor_native(const char* name, int* type) const {
for (const auto& t : tensors_)
if (t.name == name && t.type >= 0) {
if (type) *type = t.type;
return dense_ + t.off;
}
return nullptr;
}
bool MtpDrafter::qwen36() const { return g_ != nullptr && g_->arch == ModelArch::Qwen35Moe; }
// ---- Qwen3.6: the pack's record of the block it was cut from (mtp.json), held against the trunk's geometry
bool MtpDrafter::check_qwen36_pack(const std::string& rt_dir, const ModelGeometry& g, std::string& err) {
std::vector<uint8_t> raw;
if (!read_file(rt_dir + "/mtp.json", raw)) { err = "mtp: cannot read " + rt_dir + "/mtp.json (a Qwen3.6 draft pack is written by tools/mtp_qwen36_pack.py)"; return false; }
const std::string text(raw.begin(), raw.end());
if (text.find("\"arch\": \"qwen35moe\"") == std::string::npos) {
err = "mtp: " + rt_dir + " is not a qwen35moe draft pack (mtp.json names another architecture or none)";
return false;
}
const struct { const char* key; int64_t want; } fields[] = {
{"n_embd", g.n_embd}, {"n_head", g.n_head}, {"n_head_kv", g.n_head_kv}, {"head_dim", g.head_dim},
{"n_rot", g.n_rot}, {"n_expert", g.n_expert}, {"n_expert_used", g.n_expert_used}, {"n_ff", g.n_ff},
{"n_ff_shexp", g.n_ff_shexp}};
for (const auto& f : fields) {
const long long have = json_int(text, f.key);
if (have != (long long) f.want) {
err = "mtp: the draft pack " + rt_dir + " was cut for " + f.key + " " + std::to_string(have) +
" but the trunk has " + std::to_string((long long) f.want) + " (the geometry follows the target)";
return false;
}
}
static const char* required[] = {"nextn.eh_proj.weight", "nextn.enorm.weight", "nextn.hnorm.weight",
"nextn.shared_head_norm.weight", "attn_norm.weight", "post_attention_norm.weight",
"attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight",
"attn_q_norm.weight", "attn_k_norm.weight", "ffn_gate_inp.weight",
"ffn_gate_inp_shexp.weight", "ffn_gate_shexp.weight", "ffn_up_shexp.weight",
"ffn_down_shexp.weight"};
for (const char* n : required) {
const Tensor* t = nullptr;
for (const auto& c : tensors_) if (c.name == n) t = &c;
if (t == nullptr) { err = std::string("mtp: ") + n + " is missing from " + rt_dir + "/dense.txt"; return false; }
const bool norm = std::strstr(n, "norm") != nullptr;
const bool router = std::strcmp(n, "ffn_gate_inp.weight") == 0 || std::strcmp(n, "ffn_gate_inp_shexp.weight") == 0;
const char* want = norm ? "f32" : router ? "bf16" : "a native projection type";
const bool ok = norm ? t->kind == "f32" : router ? t->kind == "bf16" : t->type >= 0;
if (!ok) { err = std::string("mtp: ") + n + " is kind " + t->kind + " in dense.txt; the drafter reads it as " + want; return false; }
if (!norm && !router && !strata::kernels::native_mmvq_supported(t->type)) {
err = std::string("mtp: ") + n + " is " + t->kind + ", which the native MMVQ has no kernel for";
return false;
}
if (norm) {
const bool head_norm = std::strcmp(n, "attn_q_norm.weight") == 0 || std::strcmp(n, "attn_k_norm.weight") == 0;
const int64_t want_n = head_norm ? g.head_dim : g.n_embd;
if (t->cols != want_n) {
err = std::string("mtp: ") + n + " has " + std::to_string(t->cols) + " elements, expected " + std::to_string(want_n);
return false;
}
}
}
const Tensor* eh = nullptr;
for (const auto& c : tensors_) if (c.name == "nextn.eh_proj.weight") eh = &c;
if (eh->rows != g.n_embd || eh->cols != 2 * g.n_embd) {
err = "mtp: nextn.eh_proj.weight is " + std::to_string(eh->rows) + " x " + std::to_string(eh->cols) +
", expected n_embd x 2 n_embd (" + std::to_string(g.n_embd) + " x " + std::to_string(2 * g.n_embd) + ")";
return false;
}
return true;
}
// ---- Qwen3.6: the draft block's experts, native GGUF blobs [gate | up | down], every one resident
bool MtpDrafter::load_qwen36_experts(const std::string& rt_dir, const ModelGeometry& g, uint64_t& bytes, std::string& err) {
std::ifstream in(rt_dir + "/native_experts.txt");
if (!in) { err = "mtp: cannot open " + rt_dir + "/native_experts.txt"; return false; }
std::string line, header;
int64_t layer = -1, gu = -1, d = -1, off = -1, blob = -1, g_off = -1, u_off = -1, d_off = -1;
int rows = 0;
while (std::getline(in, line)) {
if (line.empty()) continue;
if (line[0] == '#') { header = line; continue; }
std::istringstream is(line);
if (!(is >> layer >> gu >> d >> off >> blob >> g_off >> u_off >> d_off)) { err = "mtp: malformed native_experts.txt line: " + line; return false; }
++rows;
}
if (rows != 1) { err = "mtp: native_experts.txt has " + std::to_string(rows) + " layer lines; the drafter is one block"; return false; }
const size_t ne_at = header.find("n_expert ");
const long long n_expert = ne_at == std::string::npos ? -1 : std::strtoll(header.c_str() + ne_at + 9, nullptr, 10);
if (n_expert != (long long) g.n_expert) {
err = "mtp: the draft pack's experts.bin holds " + std::to_string(n_expert) + " experts, the trunk routes over " +
std::to_string((long long) g.n_expert);
return false;
}
if (!strata::kernels::native_expert_supported((int) gu, (int) d, g.n_embd, g.n_ff)) {
err = "mtp: the draft experts are ggml types " + std::to_string(gu) + " (gate/up) / " + std::to_string(d) +
" (down) at " + std::to_string((long long) g.n_embd) + " x " + std::to_string((long long) g.n_ff) +
", which the native expert kernels (iq_kernels.cu) have no pair for";
return false;
}
const strata::kernels::NativeExpertLayout L = strata::kernels::native_expert_layout((int) gu, (int) d, g.n_embd, g.n_ff);
if ((int64_t) L.bytes != blob || (int64_t) L.up_off != u_off || (int64_t) L.down_off != d_off || g_off != 0 || off != 0) {
err = "mtp: native_experts.txt says blob " + std::to_string(blob) + " B (roles at " + std::to_string(g_off) + ", " +
std::to_string(u_off) + ", " + std::to_string(d_off) + "), the native layout is " + std::to_string(L.bytes) +
" B (0, " + std::to_string(L.up_off) + ", " + std::to_string(L.down_off) + ")";
return false;
}
exp_gu_type_ = (int) gu;
exp_d_type_ = (int) d;
exp_blob_ = blob;
bytes = (uint64_t) blob * (uint64_t) g.n_expert;
return true;
}
bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
int64_t window) {
@@ -299,7 +170,6 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
Tensor t;
is >> t.name >> t.kind >> t.rows >> t.cols >> t.off >> t.bytes;
if (!is) { err = "mtp: malformed dense.txt line: " + line; return false; }
t.type = ggml_type_of_kind(t.kind);
tensors_.push_back(t);
}
std::vector<uint8_t> blob;
@@ -316,13 +186,9 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
vram_ += blob.size();
}
const bool qwen = g.arch == ModelArch::Qwen35Moe;
if (qwen && !check_qwen36_pack(rt_dir, g, err)) return false;
// ---- the routed experts, one blob each: Flash-Next's 512 canonical Q2_0 blobs, or Qwen3.6's 256 native GGUF blobs
uint64_t exp_bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
if (qwen && !load_qwen36_experts(rt_dir, g, exp_bytes, err)) return false;
// ---- the 512 routed experts, one blob each
{
const uint64_t bytes = exp_bytes;
const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
// Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under
// MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes.
FILE* f = std::fopen((rt_dir + "/experts.bin").c_str(), "rb");
@@ -331,7 +197,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
FILE* f;
~Closer() { if (f != nullptr) std::fclose(f); }
} closer{f};
if (cudaMalloc((void**) &experts_, bytes) != cudaSuccess) { err = "mtp: the " + std::to_string((long long) g.n_expert) + " draft experts (" + std::to_string(bytes >> 20) + " MiB) do not fit in VRAM"; return false; }
if (cudaMalloc((void**) &experts_, bytes) != cudaSuccess) { err = "mtp: the 512 experts do not fit in VRAM"; return false; }
std::vector<uint8_t> chunk(64u << 20);
for (uint64_t off = 0; off < bytes;) {
const uint64_t n = std::min<uint64_t>(chunk.size(), bytes - off);
@@ -341,12 +207,10 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
}
vram_ += bytes;
}
if (!qwen) {
const char* required[] = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight",
"self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight",
"mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"};
for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; }
}
const char* required[] = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight",
"self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight",
"mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"};
for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; }
// ---- the layer's own K/V (dense attention: no indexer state is read)
const strata::kernels::QsaShapes s = shapes_of(g);
@@ -403,8 +267,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
mixed_ = b.take<float>(T * N); inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); bo_ = b.take<float>(T * N);
xn_ = b.take<float>(T * HC * N);
xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes((int) std::max<uint64_t>(NH * HD, qwen ? 2 * N : 0), 8));
cat_ = qwen ? b.take<float>(T * 2 * N) : nullptr; // Qwen3.6: concat(enorm, hnorm)
xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes((int) (NH * HD), 8));
qfull_ = b.take<float>(T * NH * 2 * HD); qcur_ = b.take<float>(T * NH * HD);
kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD);
attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD);
@@ -416,10 +279,8 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
grp_ptr_ = b.take<unsigned long long>(T * K); grp_start_ = b.take<int32_t>(T * K + 1);
grp_counts_ = b.take<int32_t>(4);
hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
hit_scratch_ = b.take<uint8_t>(std::max<uint64_t>(
strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff),
qwen ? strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff) : 0));
sh_scratch_ = (float*) b.take<uint8_t>(strata::kernels::shared_expert_scratch_bytes(std::max(g.n_ff, g.n_ff_shexp)));
hit_scratch_ = b.take<uint8_t>(strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff));
sh_scratch_ = (float*) b.take<uint8_t>(strata::kernels::shared_expert_scratch_bytes(g.n_ff));
x_bf16_ = b.take<uint16_t>(N);
out_ids_ = b.take<int32_t>(T + 4);
probs_ = b.take<float>(T + 4);
@@ -441,10 +302,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
}
if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; }
const double files_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_files).count();
std::fprintf(stderr, "strata mtp: draft layer loaded (%s), %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",
qwen ? "qwen35moe: the nextn block, native experts" : "qwen4exp", (double) vram_ / 1048576.0,
(double) exp_bytes / 1048576.0, (double) tensors_.back().off / 1048576.0, files_s,
files_s > 0 ? ((double) exp_bytes + (double) tensors_.back().off) / 1048576.0 / files_s : 0.0);
std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",
(double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,
(double) tensors_.back().off / 1048576.0, files_s,
files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /
1048576.0 / files_s : 0.0);
return true;
}
@@ -598,7 +460,6 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float
// The layer for T rows. full = false stops after the K/V append (the prompt only needs the cache).
bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::string& err) {
if (qwen36()) return record_forward_qwen36(T, step_row0, cs, err);
using namespace strata::kernels;
const ModelGeometry& g = *g_;
SessionState& ss = *ss_;
@@ -772,8 +633,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs,
draft_br_);
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);
return true;
}
SamplerParams sp;
@@ -789,247 +649,6 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
return true;
}
// ---- QWEN3.6: the nextn block on the plain graph (ref/qwen36.py mtp_forward; llama.cpp's graph_mtp). T rows for the
// K/V-only pass, one row for the full layer, as record_forward. `emit` hands a seam to the harness's hook (debug_row);
// in a graph capture no hook is set and it is nothing.
bool MtpDrafter::record_forward_qwen36(int T, int step_row0, cudaStream_t cs, std::string& err) {
using namespace strata::kernels;
const ModelGeometry& g = *g_;
SessionState& ss = *ss_;
const bool full = step_row0 >= 0;
const int row0 = full ? step_row0 : -1 - step_row0;
if (full && T != 1) { err = "mtp: the full layer runs one row at a time (its attention scratch is sized for one)"; return false; }
const int64_t N = g.n_embd, K = ss.k, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv, NE = g.n_expert;
const float eps = (float) g.rms_eps;
const QsaShapes s = shapes_of(g);
const int32_t* step = step_ + row0 * 4;
const int32_t* pos = pos_ + row0 * NH;
const DebugOpts* dbg = dbg_;
auto emit = [&](const char* name, const float* p, int64_t n) {
if (seam_ == nullptr) return;
cudaStreamSynchronize(cs);
(*seam_)(name, p, n);
};
// ---- the weights: the pack's (dense.txt), and the trunk's output norm
const float* w_enorm = f32("nextn.enorm.weight");
const float* w_hnorm = f32("nextn.hnorm.weight");
const float* w_shn = f32("nextn.shared_head_norm.weight");
const float* w_an = f32("attn_norm.weight");
const float* w_pn = f32("post_attention_norm.weight");
const float* w_qn = f32("attn_q_norm.weight");
const float* w_kn = f32("attn_k_norm.weight");
const uint16_t* w_router = bf16("ffn_gate_inp.weight");
const uint16_t* w_sgate = bf16("ffn_gate_inp_shexp.weight");
int t_eh = -1, t_q = -1, t_k = -1, t_v = -1, t_o = -1;
const void* w_eh = tensor_native("nextn.eh_proj.weight", &t_eh);
const void* w_q = tensor_native("attn_q.weight", &t_q);
const void* w_k = tensor_native("attn_k.weight", &t_k);
const void* w_v = tensor_native("attn_v.weight", &t_v);
const void* w_o = tensor_native("attn_output.weight", &t_o);
NativeSharedWeights nsw;
nsw.gate_data = tensor_native("ffn_gate_shexp.weight", &nsw.gate_type);
nsw.up_data = tensor_native("ffn_up_shexp.weight", &nsw.up_type);
nsw.down_data = tensor_native("ffn_down_shexp.weight", &nsw.down_type);
nsw.q8_1 = xq_;
if (!w_enorm || !w_hnorm || !w_shn || !w_an || !w_pn || !w_qn || !w_kn || !w_router || !w_sgate || !w_eh || !w_q ||
!w_k || !w_v || !w_o || !nsw.gate_data || !nsw.up_data || !nsw.down_data) {
err = "mtp: a tensor of the Qwen3.6 draft pack is missing (check_qwen36_pack should have refused it)";
return false;
}
if (wt_ == nullptr) { err = "mtp: bind() before the forward"; return false; }
const WeightRef* wo_norm = wt_->find("output_norm.weight");
if (wo_norm == nullptr || wo_norm->data == nullptr) { err = "mtp: output_norm.weight is missing from the trunk's pack"; return false; }
if (wo_norm->kind != WeightKind::F32 || wo_norm->elements != N) {
err = "mtp: output_norm.weight is engine form " + std::to_string((int) wo_norm->kind) + " of " +
std::to_string(wo_norm->elements) + " elements; the drafter reads F32 x " + std::to_string(N);
return false;
}
try {
// ---- the two inputs: the token's embedding, and the trunk's final residual through the trunk's output norm
// (llama.cpp's h_nextn: the drafter's input is the OUTPUT-NORMED hidden state, then hnorm on top of it)
const WeightRef* we = wt_->find("token_embd.weight");
if (!we) { err = "mtp: token_embd.weight is missing"; return false; }
if (const NativeEmbed* ne = native_embed()) {
ne->gather_dev(tok_, T, emb_, cs);
} else {
if (we->data == nullptr) { err = "mtp: token_embd.weight has no canonical bytes and no native table is set"; return false; }
const auto* codes = (const uint8_t*) we->data;
const auto* scales = (const float*) (codes + we->codes_bytes);
const auto* offsets = we->has_offset ? (const float*) (codes + we->codes_bytes + we->scales_bytes) : nullptr;
embedding_gather_dev(codes, scales, offsets, tok_, T, we->ne0, we->code_bits, we->code_bias, we->group_elems,
(uint64_t) (we->ne0 / (8 / we->code_bits)), (uint64_t) (we->ne0 / we->group_elems), emb_, cs);
}
emit("mtp_tok_embd", emb_, T * N);
native_qsa_rms_norm_weighted(emb_, w_enorm, en_, (int) N, T, eps, cs);
emit("mtp_enorm", en_, T * N);
native_qsa_rms_norm_weighted(Rin_, (const float*) wo_norm->data, hn_, (int) N, T, eps, cs);
if (dbg != nullptr && dbg->skip_hnorm) { // the harness's rival: hnorm left out
if (cudaMemcpyAsync(h2_, hn_, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { err = "mtp: copy"; return false; }
} else {
native_qsa_rms_norm_weighted(hn_, w_hnorm, h2_, (int) N, T, eps, cs);
}
emit("mtp_hnorm", h2_, T * N);
// ---- concat(enorm, hnorm): the embedding first (ggml_concat(e_norm, h_norm, dim 0))
const float* first = en_;
const float* second = h2_;
if (dbg != nullptr && dbg->hidden_first) std::swap(first, second); // the harness's rival: the wrong order
if (cudaMemcpy2DAsync(cat_, (size_t) 2 * N * 4, first, (size_t) N * 4, (size_t) N * 4, (size_t) T, cudaMemcpyDeviceToDevice, cs) != cudaSuccess ||
cudaMemcpy2DAsync(cat_ + N, (size_t) 2 * N * 4, second, (size_t) N * 4, (size_t) N * 4, (size_t) T, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) {
err = "mtp: the concat copy failed";
return false;
}
emit("mtp_concat", cat_, T * 2 * N);
native_quantize_q8_1(cat_, xq_, (int) (2 * N), T, cs);
native_mmvq(t_eh, w_eh, xq_, R_, (int) (2 * N), (int) N, T, cs); // R_: the block's residual stream
emit("mtp_eh_proj", R_, T * N);
// ---- the attention half: x = rms_norm(R) * attn_norm; K/V into the drafter's own cache
native_qsa_rms_norm_weighted(R_, w_an, mixed_, (int) N, T, eps, cs);
emit("mtp_attn_norm", mixed_, T * N);
native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
native_mmvq(t_k, w_k, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);
native_mmvq(t_v, w_v, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);
emit("mtp_Vcur", vcur_, T * NKV * HD);
for (int t = 0; t < T; ++t)
native_qsa_rms_norm_weighted(kcur_ + t * NKV * HD, w_kn, kcur_ + t * NKV * HD, (int) HD, (int) NKV, eps, cs);
emit("mtp_Kcur_normed", kcur_, T * NKV * HD);
auto rope_rows = [&](float* data, int rows, const int32_t* p) {
if (native_rope_enabled()) native_rope_apply(data, data, rows, (int) HD, (int) s.n_rot, rope_scaling(), p, cs);
else rope_neox_apply(data, data, rows, (int) HD, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);
};
for (int t = 0; t < T; ++t) {
rope_rows(kcur_ + t * NKV * HD, (int) NKV, pos + t * NH);
if (st_.kv_rot) {
fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs);
fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs);
}
if (st_.kv_q4)
kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
vcur_ + t * NKV * HD, s, cs, &st_.host);
else if (st_.kv_int8)
kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,
kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);
else
kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
vcur_ + t * NKV * HD, s, cs, &st_.host);
}
if (!full) return true;
// ---- the query (q | gate per head), q norm, RoPE, dense attention over the cache, the sigmoid gate
native_mmvq(t_q, w_q, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);
emit("mtp_Qcur_full", qfull_, T * NH * 2 * HD);
for (int t = 0; t < T; ++t) {
float* qc = qcur_ + t * NH * HD;
if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, (size_t) HD * 4,
(size_t) NH, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) {
err = "mtp: q split failed";
return false;
}
native_qsa_rms_norm_weighted(qc, w_qn, qc, (int) HD, (int) NH, eps, cs);
}
emit("mtp_Qcur_normed", qcur_, T * NH * HD);
for (int t = 0; t < T; ++t) {
rope_rows(qcur_ + t * NH * HD, (int) NH, pos + t * NH);
if (st_.kv_rot) fwht256_inplace_cuda(qcur_ + t * NH * HD, NH, cs);
}
const QsaAttnPools pools = qsa_attn_pools(st_);
if (window_ > 0) window_ids(const_cast<int32_t*>(step), T, (int) window_, ident_, cap_, cs);
qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs);
if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);
emit("mtp_attn_pregate", attn_, T * NH * HD);
for (int t = 0; t < T; ++t)
native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs);
native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);
native_mmvq(t_o, w_o, xq_, bo_, (int) (NH * HD), (int) N, T, cs);
emit("mtp_attn_out", bo_, T * N);
add_inplace(R_, bo_, (int64_t) T * N, cs);
emit("mtp_attn_residual", R_, T * N);
// ---- the MoE half: x = rms_norm(R) * post_attention_norm; the router (BF16 weight, F32 activation), top-k
// renormalised, the routed experts through the native kernels on the resident blobs, the gated shared expert
native_qsa_rms_norm_weighted(R_, w_pn, mixed_, (int) N, T, eps, cs);
emit("mtp_attn_post_norm", mixed_, T * N);
for (int t = 0; t < T; ++t)
bf16_gemv_fp32_mmvf(mixed_ + t * N, w_router, logits_ + t * NE, (int) N, (int) NE, cs);
emit("ffn_moe_logits", logits_, T * NE);
router_top10(logits_, T, (int) NE, (int) K, ids_, w_, cs);
emit("ffn_moe_topk", (const float*) ids_, T * K);
emit("ffn_moe_weights_norm", w_, T * K);
moe_group_resident(ids_, (int) (T * K), (int) K, experts_, exp_blob_, grp_ptr_, grp_start_, grp_counts_, hit_dst_,
hit_slot_, cs);
native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
const NativeExpertLayout L = native_expert_layout(exp_gu_type_, exp_d_type_, N, g.n_ff);
native_expert_grouped(L, grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K,
xq_, hit_scratch_, parts_, cs);
const SForm none{};
const bool need_bf16_x = !shared_expert_native_bf16_enabled();
for (int t = 0; t < T; ++t) {
if (need_bf16_x) f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, cs);
shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr, none,
nullptr, nullptr, nullptr, w_sgate, sh_scratch_, shared_ + t * N, N, g.n_ff_shexp, 32, cs,
mixed_ + t * N, &nsw);
}
emit("mtp_ffn_shexp_gated", shared_, T * N);
for (int t = 0; t < T; ++t) {
if (native_moe_combine_enabled())
native_moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);
else
moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);
}
emit("mtp_ffn_out", y_, T * N);
add_inplace(R_, y_, (int64_t) T * N, cs);
emit("mtp_post_ffn", R_, T * N);
// ---- shared_head_norm and the main model's head (the draft subset when one is bound)
native_qsa_rms_norm_weighted(R_, w_shn, sample_, (int) N, T, eps, cs);
emit("mtp_shared_head_norm", sample_, T * N);
native_quantize_q8_1(sample_, xq_, (int) N, T, cs);
const bool sub = dhead_ != nullptr;
const int64_t nv = sub ? n_dvocab_ : n_vocab_;
native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs);
emit("result_output", head_logits_, T * nv);
if (coupled_rec_) {
coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs,
draft_br_);
return true;
}
SamplerParams sp;
sp.greedy = true;
sp.temperature = 0.0f;
sample_tokens(head_logits_, T, (int) nv, nullptr, 0, sp, out_ids_, cs);
row_top_prob(head_logits_, T, (int) nv, out_ids_, probs_, cs);
if (sub) map_ids(out_ids_, dvocab_, T, cs);
} catch (const std::exception& e) {
err = std::string("mtp: ") + e.what();
return false;
}
return true;
}
bool MtpDrafter::debug_row(const float* R_row, int32_t token, int64_t cell, int32_t pos, const DebugOpts& o,
const SeamFn& seam, int32_t* top1, std::string& err) {
const OnDevice on_device(device_);
if (!qwen36()) { err = "mtp: debug_row is the Qwen3.6 drafter's forward"; return false; }
if (head_ == nullptr || wt_ == nullptr) { err = "mtp: bind() before debug_row"; return false; }
if (cell < 0 || cell >= cap_) { err = "mtp: debug_row cell " + std::to_string(cell) + " is outside the K/V (" + std::to_string(cap_) + " cells)"; return false; }
const int32_t st[4] = {(int32_t) cell, (int32_t) (cell + 1), (int32_t) ((cell + 1) / 4), (int32_t) (cell + 1)};
std::vector<int32_t> ps((size_t) g_->n_head, pos);
if (cudaStreamSynchronize(cs_) != cudaSuccess ||
cudaMemcpy(tok_, &token, sizeof token, cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(step_, st, sizeof st, cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(pos_, ps.data(), ps.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(Rin_, R_row, (size_t) g_->n_embd * sizeof(float), cudaMemcpyDeviceToDevice) != cudaSuccess) {
err = std::string("mtp: debug_row staging: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
dbg_ = &o;
seam_ = seam ? &seam : nullptr;
const bool ok = record_forward_qwen36(1, 0, cs_, err);
dbg_ = nullptr;
seam_ = nullptr;
if (!ok) return false;
if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("mtp: debug_row: ") + cudaGetErrorString(cudaGetLastError()); return false; }
if (top1 != nullptr && cudaMemcpy(top1, out_ids_, sizeof(int32_t), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: debug_row: the draft readback failed"; return false; }
return true;
}
namespace {
bool finish_capture(cudaStream_t cs, bool ok, cudaGraphExec_t& exec, const char* what, std::string& err) {
cudaGraph_t graph = nullptr;
+11 -8
View File
@@ -1,5 +1,4 @@
// src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer.
#include "strata/core/qsa_shapes.hpp"
#include "strata/core/session.hpp"
#include "strata/kernels/mrope.hpp"
#include "strata/core/progress.hpp"
@@ -48,9 +47,8 @@ uint64_t gdn_state_floats(const ModelGeometry& g) {
/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the
/// session arena. The table and the weights are model-level and the caller owns them.
static uint64_t ple_hist_bytes(const ModelGeometry& g) {
// a model without a PLE (Qwen3.6, `has_ple` false) carves none of it (Qwen3.6 port, step 2; inventory row 29)
return g.has_ple ? (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float) : 0;
static uint64_t ple_hist_bytes() {
return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float);
}
uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) {
@@ -70,7 +68,7 @@ uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int
n += qsa_buffers_bytes(g, max_cells);
n += moe_buffers_bytes(g, k);
n += block_buffers_bytes(g);
n += ple_hist_bytes(g); // the PLE's NG_HIST normalized history rows (0 without a PLE)
n += ple_hist_bytes(); // the PLE's NG_HIST normalized history rows
return align_up(n, SESSION_STATE_ALIGN) + 4096;
}
@@ -125,7 +123,7 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void
block_buffers_init(g, s.block_arena, s.block);
// THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest. Sequence state, carved here and zeroed by
// `session_zero`; it survives every token, which is the whole point of a conv history.
s.ple_hist = ple_hist_bytes(g) ? (float*) take(ple_hist_bytes(g)) : nullptr;
s.ple_hist = (float*) take(ple_hist_bytes());
s.R = s.block.R;
return used;
}
@@ -158,7 +156,7 @@ void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init,
// so a stale one is a real contribution and not a zero. The token window resets to `NG_HIST`-many nulls
// for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence
// boundary IS.
if (s.ple_hist != nullptr) cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(g), cs);
cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(), cs);
s.ple_prev[0] = -1;
s.ple_prev[1] = -1;
s.ple_token = -1;
@@ -177,7 +175,12 @@ void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) {
/// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs
/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed.
void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) {
const strata::kernels::QsaShapes sh = qsa_shapes(g); // the one builder (qsa_shapes.hpp): dense width = n_kv
strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes();
sh.n_head = g.n_head;
sh.n_head_kv = g.n_head_kv;
sh.head_dim = g.head_dim;
sh.idx_n_head = g.idx_q_heads;
sh.idx_dim = g.idx_key_dim;
for (int64_t j = 0; j < s.qsa_alloc; ++j) {
QsaState& q = s.qsa_states[s.qsa_ord0 + j];
qsa_step_fill(q.host_step, pos, sh);
+44 -154
View File
@@ -1,5 +1,4 @@
// src/core/verify.cpp - see include/strata/core/verify.hpp.
#include "strata/core/qsa_shapes.hpp"
#include "strata/core/verify.hpp"
#include "strata/core/remote_expert_opt.hpp"
#if defined(_WIN32)
@@ -99,8 +98,15 @@ bool mapped(size_t bytes, void** h, void** d) {
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
}
// the one builder (strata/core/qsa_shapes.hpp): a dense geometry has its three indexer widths zero together
strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return strata::core::qsa_shapes(g); }
strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) {
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head;
s.n_head_kv = g.n_head_kv;
s.head_dim = g.head_dim;
s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
return s;
}
const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) {
const WeightRef* r = v.get(suffix);
@@ -119,30 +125,6 @@ bool native_of(const WeightRef* w, const std::string& name, std::string& err) {
} // namespace
bool verify_geometry_supported(const ModelGeometry& g, int64_t k, std::string& why) {
if (g.hc > 1 && !strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr)) {
why = "the fused hyper-connection read is built for n_embd 2560, hc 4, hc_lr 320, not " +
std::to_string(g.n_embd) + " / " + std::to_string(g.hc) + " / " + std::to_string(g.hc_lr);
return false;
}
if (k != g.n_expert_used) {
why = "the session routes top-" + std::to_string(k) + " but the file routes top-" +
std::to_string(g.n_expert_used) + " of " + std::to_string(g.n_expert) +
" experts (expert_used_count); the window reproduces the file's k";
return false;
}
if (k < 1 || k > g.n_expert) {
why = "k " + std::to_string(k) + " is outside 1.." + std::to_string(g.n_expert) + " experts";
return false;
}
if (g.ssm_state_size != 128 || g.ssm_d_conv != 4) {
why = "the T-token GDN kernels are built for state 128 and conv 4, not " + std::to_string(g.ssm_state_size) +
" / " + std::to_string(g.ssm_d_conv);
return false;
}
return true;
}
namespace {
std::atomic<const Verifier*> g_diag_verifier{nullptr};
void diag_active_verifier(std::FILE* f) {
@@ -347,12 +329,13 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
return false;
}
std::string why;
if (!layer_verify_compatible(g, why)) {
if (!layer_verify_compatible(why)) {
err = "verify: " + why + " (the verify window reproduces the default native decode path)";
return false;
}
if (!verify_geometry_supported(g, ss.k, why)) {
err = "verify: " + why;
if (!strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr) || ss.k != 10 || g.ssm_state_size != 128 ||
g.ssm_d_conv != 4) {
err = "verify: geometry differs from the artifact's";
return false;
}
if (le_ < 0) le_ = g.n_layers;
@@ -366,9 +349,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
n_vocab_ = wo->ne1;
const strata::kernels::QsaShapes s = shapes_of(g);
cap_ = strata::kernels::qsa_selection_cap(ss.qsa_states[ss.qsa_primary()].max_cells, s); // dense: max_cells
cap_ = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
const bool dense = strata::kernels::qsa_dense(s); // Qwen3.6: no indexer, no selection buffers (3.3)
attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s);
const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k;
@@ -435,7 +417,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
qfull_ = b.take<float>(T * NH * 2 * HD); qcur_ = b.take<float>(T * NH * HD);
kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD);
idx_raw_L_ = b.take<float>(nQ * T * ID); qidx_ = b.take<float>(T * IQ * ID);
if (!dense) { scores_ = b.take<float>(T * (uint64_t) max_blocks_); sel_ = b.take<int32_t>(T * (uint64_t) cap_); }
scores_ = b.take<float>(T * (uint64_t) max_blocks_); sel_ = b.take<int32_t>(T * (uint64_t) cap_);
attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD);
attn_scratch_ = b.take<float>(T * (uint64_t) attn_scratch_floats_);
tail_snap_ = b.take<float>(nQ * TS);
@@ -575,23 +557,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
const int64_t TS = (s.idx_block - 1) * ID;
const bool ple_on = ss.ple.ready() && ple_stage();
if (HC == 1 && ple_on) {
err = "verify: the plain block (hc = 1) has no per-layer embedding, but the session's PLE is wired";
return false;
}
const float eps = (float) g.rms_eps;
auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; // at hc = 1 the rows are contiguous: Rt(tb) spans n rows
// hc = 1: the plain block's F32 norm weights (layer.hpp, "the plain block"), checked as layer.cpp checks them
auto plain_w = [&](const LayerView& v, const char* suffix) -> const float* {
const WeightRef* w = need(v, suffix, err);
if (w == nullptr) return nullptr;
if (w->kind != WeightKind::F32 || w->elements != N || w->data == nullptr) {
err = v.name(suffix) + " is engine form " + std::to_string((int) w->kind) + " of " +
std::to_string(w->elements) + " elements; the plain block reads F32 x " + std::to_string(N);
return nullptr;
}
return (const float*) w->data;
};
auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one group
static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
auto stamp = [&](int64_t l, int i, int grp) {
@@ -656,14 +622,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
stamp(l, 0, grp);
const LayerView v(wt, l);
const char* pfx[2] = {"hc_attn_", "hc_ffn_"};
const WeightRef *wn[2] = {}, *wd[2] = {}, *wu[2] = {}, *wi[2] = {};
const float *w_attn = nullptr, *w_post = nullptr; // hc = 1: the plain block's two norms
if (HC == 1) {
w_attn = plain_w(v, "attn_norm.weight");
if (w_attn == nullptr) return false;
w_post = plain_w(v, "post_attention_norm.weight");
if (w_post == nullptr) return false;
} else
const WeightRef *wn[2], *wd[2], *wu[2], *wi[2];
for (int h = 0; h < 2; ++h) {
wn[h] = need(v, (std::string(pfx[h]) + "norm.weight").c_str(), err);
wd[h] = need(v, (std::string(pfx[h]) + "down.weight").c_str(), err);
@@ -672,8 +631,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false;
}
// the previous layer's FFN write, folded into this layer's first read (a control vector after it has
// already applied it); the plain block has no pending write (its residual adds are applied in place)
bool pending = HC > 1 && l > 0 && !cvec().covers(l - 1);
// already applied it)
bool pending = l > 0 && !cvec().covers(l - 1);
if (l == 1 && ple_on) {
if (grp == 0) {
if (all_resident_) wait_flag_ge(m_flag_, 1, cs);
@@ -734,16 +693,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,
(int) (l * kProfPer + (half == 0 ? 27 : 30)));
};
float* xm = mixed_ + tb * N;
try {
// x = rms_norm(R) * attn_norm over the group's n rows (`attn_norm-N`), or the GR read
if (HC == 1) plain_norm_rows(Rt(tb), w_attn, xm, N, eps, n, cs);
else gr_read_group(0, pending, inj2_, inj_);
} catch (const std::exception& e) {
err = "verify layer " + std::to_string(l) + " attn_norm: " + e.what();
return false;
}
gr_read_group(0, pending, inj2_, inj_);
stamp(l, 1, grp);
float* xm = mixed_ + tb * N;
try {
if (!is_qsa_layer(g, l)) {
// ======================= GDN =======================
@@ -789,12 +741,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
SessionState& sx = slot_ss(t);
float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
gdn_step_norm_multi(stx, hb + (size_t) t * C, (int) C, gate + (size_t) t * HV, beta + (size_t) t * HV,
z_ + (size_t) t * ZV, (const float*) wnm->data, EPS, g.gdn_gate(),
y_ + (size_t) t * ZV, (int) HK, (int) HV, 1, nullptr, cs, 0);
z_ + (size_t) t * ZV, (const float*) wnm->data, EPS, y_ + (size_t) t * ZV,
(int) HK, (int) HV, 1, nullptr, cs, 0);
}
} else
gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, g.gdn_gate(), y_,
(int) HK, (int) HV, te, nullptr, cs, tb);
gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
(int) HV, te, nullptr, cs, tb);
stamp(l, 6, grp);
native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs);
native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs);
@@ -802,18 +754,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// ======================= QSA =======================
const int64_t qi = qsa_idx[(size_t) l];
const QsaState& st = ss.qsa_states[qi];
// Qwen3.6 (3.3): dense attention - no indexer tensors, no raw key, no scores, no top-k; the split-K
// kernel reads every cell (a null ids is the identity) with the width n_kv from each row's step
const bool has_idx = g.has_indexer();
const WeightRef *wq = need(v, "attn_q.weight", err),
const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err),
*wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err),
*wo = need(v, "attn_output.weight", err),
*wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err);
const WeightRef *wik = has_idx ? need(v, "indexer.k_proj.weight", err) : nullptr,
*wiq = has_idx ? need(v, "indexer.q_proj.weight", err) : nullptr,
*wiqn = has_idx ? need(v, "indexer.q_norm.weight", err) : nullptr,
*wikn = has_idx ? need(v, "indexer.k_norm.weight", err) : nullptr;
if (!wq || !wk || !wv || !wo || !wqn || !wkn || (has_idx && (!wik || !wiq || !wiqn || !wikn))) return false;
*wo = need(v, "attn_output.weight", err), *wiq = need(v, "indexer.q_proj.weight", err),
*wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
*wiqn = need(v, "indexer.q_norm.weight", err), *wikn = need(v, "indexer.k_norm.weight", err);
if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
if (!native_of(wq, v.name("attn_q.weight"), err) || !native_of(wk, v.name("attn_k.weight"), err) ||
!native_of(wv, v.name("attn_v.weight"), err) || !native_of(wo, v.name("attn_output.weight"), err))
return false;
@@ -828,8 +774,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token)
const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4;
native_quantize_q8_1(xm, xq_, (int) N, n, cs);
if (!has_idx) {}
else if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs);
if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs);
else for (int t = tb; t < te; ++t)
bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs);
stamp(l, 7, grp);
@@ -844,8 +789,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
}
stamp(l, 8, grp);
if (!has_idx) {}
else if (batch_rec_) { // every slot's indexer tail, restored by its commit
if (batch_rec_) { // every slot's indexer tail, restored by its commit
for (int t = tb; t < te; ++t)
copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, slot_ss(t).qsa_states[qi].idx_tail,
TS, cs);
@@ -869,7 +813,6 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD,
vcur_ + t * NKV * HD, s, cs, &st.host);
}
if (has_idx)
for (int t = tb; t < te; ++t) {
const QsaState& sx = slot_ss(t).qsa_states[qi];
const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos};
@@ -888,11 +831,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH);
if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // <Hq, Hk> = <q, k>
if (has_idx) {
bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID,
N, IQ * ID, n, cs);
norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ);
}
} else {
for (int t = tb; t < te; ++t) {
float* qc = qcur_ + t * NH * HD;
@@ -904,7 +845,6 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH);
if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // <Hq, Hk> = <q, k>
}
if (has_idx)
for (int t = tb; t < te; ++t) {
float* qx = qidx_ + t * IQ * ID;
bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), cs);
@@ -912,20 +852,6 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
}
stamp(l, 10, grp);
if (!has_idx && batch_rec_) { // dense, each row over its own slot's K/V: every cell, no ids
for (int t = tb; t < te; ++t) {
const QsaState& sx = slot_ss(t).qsa_states[qi];
const QsaAttnPools px = qsa_attn_pools(sx);
qsa_decode_attn_batch(qcur_ + t * NH * HD, px, nullptr, step_ + t * kStepCount, cap_, s,
attn_scratch_ + (size_t) t * attn_scratch_floats_, attn_ + t * NH * HD, 1, cs);
}
} else if (!has_idx) { // dense: the n rows over every cell of the shared state, no ids
stamp(l, 11, grp);
stamp(l, 12, grp);
const QsaAttnPools pools = qsa_attn_pools(st);
qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, nullptr, step_ + tb * kStepCount, cap_, s,
attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, 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];
@@ -973,15 +899,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
return false;
}
stamp(l, 16, grp);
try {
if (HC == 1) { // R += mixer out (`attn_residual-N`), then x = rms_norm(R) * post_attention_norm
plain_residual_rows(Rt(tb), bo_ + tb * N, N, n, cs);
plain_norm_rows(Rt(tb), w_post, xm, N, eps, n, cs);
} else gr_read_group(1, true, inj_, inj2_);
} catch (const std::exception& e) {
err = "verify layer " + std::to_string(l) + " post_attention_norm: " + e.what();
return false;
}
gr_read_group(1, true, inj_, inj2_);
static const bool sh_stream_env = [] {
const char* e = std::getenv("STRATA_SH_STREAM");
return !e || e[0] != '0';
@@ -1080,7 +998,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
const char* e = std::getenv("STRATA_FUSE_HEAD_GR");
return e && e[0] == '1';
}();
const bool fuse_head_gr = fuse_head_gr_env && HC > 1 && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
const bool fuse_head_gr = fuse_head_gr_env && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
!cvec().covers(g.n_layers - 1);
auto post = [&](int64_t l, int grp) -> bool {
const int tb = tb_[grp], te = te_[grp], n = te - tb;
@@ -1173,15 +1091,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n,
device_plan_ ? skip_ + grp : nullptr, ring, cs);
stamp(l, 24, grp);
if (HC == 1) { // R += ffn out (`l_out-N`): in place, every layer; then a control vector if one covers it
try {
plain_residual_rows(Rt(tb), bo_ + tb * N, N, n, cs);
if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, N, nullptr, 0, nullptr, 0, false, cs);
} catch (const std::exception& e) {
err = "verify layer " + std::to_string(l) + " residual: " + e.what();
return false;
}
} else if (l == g.n_layers - 1) {
if (l == g.n_layers - 1) {
if (!fuse_head_gr) {
for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);
@@ -1210,24 +1120,10 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// ---- the head, T columns, and the argmax of each
stamp(g.n_layers, 0, 0);
{
const WeightRef *hn = nullptr, *hd = nullptr, *hu = nullptr;
if (HC > 1) {
hn = wt.find("output_hc_norm.weight"); hd = wt.find("output_hc_down.weight"); hu = wt.find("output_hc_up.weight");
if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; }
}
if (HC == 1 && head_ != nullptr && head_->loaded()) {
// the plain head: `result_norm = rms_norm(R) * output_norm` for the T rows in one launch (row t is the
// single-token `lm_head_mix`); the canonical head below goes through `lm_head`, which branches the same way
const WeightRef* wn = wt.find("output_norm.weight");
if (wn == nullptr) { err = "verify: output_norm.weight is missing (the plain block's head norm)"; return false; }
if (wn->kind != WeightKind::F32 || wn->elements != N || wn->data == nullptr) {
err = "verify: output_norm.weight is engine form " + std::to_string((int) wn->kind) + " of " +
std::to_string(wn->elements) + " elements; the plain head reads F32 x " + std::to_string(N);
return false;
}
try { plain_norm_rows(R_, (const float*) wn->data, head_mixed_, N, eps, T, cs); }
catch (const std::exception& e) { err = std::string("verify output_norm: ") + e.what(); return false; }
} else if (fuse_head_gr) {
const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"),
*hu = wt.find("output_hc_up.weight");
if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; }
if (fuse_head_gr) {
FusedGrArgs fa[kFusedGrMaxT];
for (int t = 0; t < T; ++t) {
FusedGrArgs& a = fa[t];
@@ -1396,13 +1292,9 @@ bool Verifier::capture_commit(std::string& err) {
const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C;
gdn_conv_commit(conv, qkv, (int) C, commit_, cs_);
gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV,
beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, g.gdn_gate(),
y_dummy_, (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, (int) MT);
beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_,
(int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, (int) MT);
++gdn_index;
} else if (!g.has_indexer()) {
// dense attention (Qwen3.6): no indexer key tail to restore; the K/V cells past the accepted prefix
// are overwritten when those positions are processed again (the header's STATE paragraph)
++qsa_index;
} else {
const QsaState& st = ss.qsa_states[qsa_index];
const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
@@ -1659,7 +1551,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
if (head_sampling_ && (sampled || hist_d_ != nullptr)) {
SamplerParams sp = sampling_;
sp.counter = (uint64_t) pos0;
sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_, br_);
sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
if (cudaStreamSynchronize(cs_) != cudaSuccess) { // m_out_ is the mapped h_out_: synced, it is readable
err = "verify: the head sampling failed";
return false;
@@ -1953,12 +1845,10 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri
gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) t * C, (int) C,
gate_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV,
beta_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV, z_ + (size_t) t * ZV,
(const float*) wnm->data, EPS, g.gdn_gate(), y_dummy_ + (size_t) t * ZV,
(int) g.ssm_k_heads, (int) HV, 1, keep, cs_);
(const float*) wnm->data, EPS, y_dummy_ + (size_t) t * ZV, (int) g.ssm_k_heads,
(int) HV, 1, keep, cs_);
}
++gdn_index;
} else if (!g.has_indexer()) {
++qsa_index; // dense attention: no indexer tail (as in capture_commit)
} else {
const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
if (!wikn) { ok = false; break; }
+3 -11
View File
@@ -230,19 +230,12 @@ void native_gu_rows(const NativeFmt&, const uint8_t*, const void* const*, int, f
void native_down_rows(const NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int) { std::abort(); }
#endif
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff,
std::string& err) {
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) {
ExpertLayout L;
L.n_layers = n_layers;
L.n_expert = n_expert;
std::ifstream in(pack_dir + "/native_experts.txt");
if (!in) {
if (n_embd != H || n_ff != FF) {
err = "the pack has no native_experts.txt, so its experts.bin is in the canonical Q2_0 form, which bakes " +
std::to_string(H) + " x " + std::to_string(FF) + " (strata/kernels/cpu/expert.hpp); the model is " +
std::to_string(n_embd) + " x " + std::to_string(n_ff) + ": pack it with tools/iq_pack.py (native experts)";
return false;
}
L.total = (uint64_t) n_layers * (uint64_t) n_expert * (uint64_t) BLOB;
g_layout = L;
return true;
@@ -288,11 +281,10 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n
return false;
}
NativeFmt f;
if (!native_fmt((int) gt, (int) dt, n_embd, n_ff, f, err)) return false;
if (!native_fmt((int) gt, (int) dt, H, FF, f, err)) return false;
if (f.bytes != blob) {
err = "native_experts.txt: layer " + std::to_string(l) + " blob is " + std::to_string(blob) +
" B but its formats make " + std::to_string(f.bytes) + " at n_embd " + std::to_string(n_embd) +
" x n_ff " + std::to_string(n_ff) + " (the model file's geometry): the pack is of another model";
" B but its formats make " + std::to_string(f.bytes);
return false;
}
if (ss >> go >> uo >> dox) { // v2 lines: the GGUF offsets
-5
View File
@@ -43,11 +43,6 @@ bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt
err = "native experts: ggml-cpu cannot quantize an activation for this layer";
return false;
}
if (n_embd <= 0 || n_ff <= 0 || n_embd > H || n_ff > FF) { // the pool's SplitBufMulti rows are FF / H wide
err = "native experts: expert geometry " + std::to_string(n_embd) + " x " + std::to_string(n_ff) +
" exceeds the pool's buffers (" + std::to_string(H) + " x " + std::to_string(FF) + ")";
return false;
}
if (n_embd % ggml_blck_size((ggml_type) gu_type) || n_ff % ggml_blck_size((ggml_type) d_type) ||
n_embd % ggml_blck_size(tg->vec_dot_type) || n_ff % ggml_blck_size(td->vec_dot_type)) {
err = "native experts: expert geometry is not whole blocks";
+5 -9
View File
@@ -559,12 +559,8 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
const int r0 = H * part / parts_b_, r1 = H * (part + 1) / parts_b_;
s2_expert_down_rows(jobs_[e].blob, split_[(size_t) e].a2, jobs_[e].out, r0, r1);
} else if (mode_ >= 5) {
// plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows. The widths are the layer's own
// (NativeFmt n_ff / n_embd: 512 / 2048 for Qwen3.6-35B-A3B), not the canonical pack's FF / H: with
// those, the down phase wrote H - n_embd rows past every output row and the gate/up phase read
// FF - n_ff rows past every expert's gate/up block, and every verify window with a CPU-computed
// expert miss decoded to token 0.
const int per = mode_ == 5 ? (int) nfmt_->n_ff : (int) nfmt_->n_embd;
// plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows
const int per = mode_ == 5 ? FF : H;
const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_;
for (int64_t r = g0; r < g1;) {
const int e = (int) (r / per), r0 = (int) (r % per);
@@ -700,16 +696,16 @@ void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs
nfmt_ = &f;
const int threads = n_ + (host_works_ ? 1 : 0);
mtasks_ = 3 * threads;
mrows_ = (int64_t) nb * f.n_ff; // the layer's widths (see run_phase mode 5 / 6), not FF / H
mrows_ = (int64_t) nb * FF;
const auto a = std::chrono::steady_clock::now();
run_phase(5, mtasks_);
const auto b = std::chrono::steady_clock::now();
for (int e = 0; e < nb; ++e)
for (int t = 0; t < mjobs_[e].nt; ++t)
if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], (int) f.n_ff, split_multi_[(size_t) e].a2[t]);
if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]);
else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]);
const auto c = std::chrono::steady_clock::now();
mrows_ = (int64_t) nb * f.n_embd;
mrows_ = (int64_t) nb * H;
run_phase(6, mtasks_);
const auto d = std::chrono::steady_clock::now();
ms_multi_gu += std::chrono::duration<double, std::milli>(b - a).count();
+5 -8
View File
@@ -19,7 +19,7 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict
const float* __restrict__ beta,
const float* __restrict__ z,
const float* __restrict__ gamma, float eps,
float* __restrict__ y, int h_k, int h_v, int silu) {
float* __restrict__ y, int h_k, int h_v) {
__shared__ float sk[S], sq[S];
__shared__ float red[RG][S];
__shared__ float wsum[S * RG / 32];
@@ -66,9 +66,7 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float scale = rsqrtf(ss / (float) S + eps);
const float zz = z[head * S + col];
// the gate: sigmoid(z) for Flash-Next (unchanged arithmetic), SiLU(z) = z / (1 + exp(-z)) for Qwen3.6
const float act = silu ? zz / (1.0f + __expf(-zz)) : (1.0f / (1.0f + __expf(-zz)));
y[head * S + col] = oc * scale * gamma[col] * act;
y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
}
}
@@ -150,15 +148,14 @@ void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet
}
void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate,
const float* beta, const float* z, const float* gamma, float eps, GdnGate act, float* y,
int h_k, int h_v, void* stream) {
const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v,
void* stream) {
if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) {
std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n");
std::exit(1);
}
gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, z,
gamma, eps, y, h_k, h_v,
act == GdnGate::Silu ? 1 : 0);
gamma, eps, y, h_k, h_v);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e));
+6 -11
View File
@@ -129,11 +129,10 @@ __global__ void gdn_l2_kernel(float* __restrict__ x, int cols, float eps) {
for (int i = threadIdx.x; i < cols; i += blockDim.x) p[i] *= inv;
}
/// y = rms_norm(o, eps) * ssm_norm * act(z), one warp per head, norm over that head's S values. `silu` 0 is
/// sigmoid(z) (Flash-Next), 1 is SiLU(z) = z * sigmoid(z) (Qwen3.6, ggml's `op_silu`: x / (1 + exp(-x))).
/// y = rms_norm(o, eps) * ssm_norm * sigmoid(z), one warp per head, norm over that head's S values.
__global__ void gdn_out_norm_kernel(const float* __restrict__ o, const float* __restrict__ z,
const float* __restrict__ ssm_norm, float* __restrict__ y, int S,
float eps, int silu) {
float eps) {
const int h = blockIdx.x;
const float* po = o + (size_t) h * S;
const float* pz = z + (size_t) h * S;
@@ -145,11 +144,8 @@ __global__ void gdn_out_norm_kernel(const float* __restrict__ o, const float* __
if (threadIdx.x == 0) ssum = acc;
__syncthreads();
const float inv = (float) (1.0 / sqrt(ssum / (double) S + (double) eps));
for (int i = threadIdx.x; i < S; i += blockDim.x) {
const float zz = pz[i];
const float act = silu ? zz / (1.0f + expf(-zz)) : sigmoid_f(zz);
py[i] = po[i] * inv * ssm_norm[i] * act;
}
for (int i = threadIdx.x; i < S; i += blockDim.x)
py[i] = po[i] * inv * ssm_norm[i] * sigmoid_f(pz[i]);
}
} // namespace
@@ -237,10 +233,9 @@ void gdn_beta_gate(float* beta, int64_t h_v, void* stream) {
}
void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S,
float eps, GdnGate act, void* stream) {
float eps, void* stream) {
if (h_v <= 0 || S <= 0) return;
gdn_out_norm_kernel<<<(unsigned) h_v, 32, 0, (cudaStream_t) stream>>>(o, z, ssm_norm, y, (int) S, eps,
act == GdnGate::Silu ? 1 : 0);
gdn_out_norm_kernel<<<(unsigned) h_v, 32, 0, (cudaStream_t) stream>>>(o, z, ssm_norm, y, (int) S, eps);
if (stream == nullptr) {
const cudaError_t e = cudaDeviceSynchronize();
if (e != cudaSuccess) {
+8 -67
View File
@@ -309,9 +309,8 @@ __device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vb
// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts
// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the
// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,
// gopinath87607), which agree with llama.cpp and with each other. Q6_K (Qwen3.6's UD-Q4_K_XL down projections on
// layers 34, 38, 39, and its layer 39 gate/up is Q5_K) is llama.cpp's vec_dot_q6_K_q8_1 (VDR 1), transcribed.
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2, VDR_Q6_K = 1;
// gopinath87607), which agree with llama.cpp and with each other.
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2;
__device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u,
const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m,
@@ -416,40 +415,6 @@ __device__ __forceinline__ float vec_dot_q5_K_q8_1(const void* __restrict__ vbq,
}
return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8);
}
// Q6_K: 16 int8 sub-scales per 256-value block, the 6-bit values as a 4-bit low part (ql) and a 2-bit high part (qh),
// centred by 32; no min term, so the q8_1 sum is not used (llama.cpp's vec_dot_q6_K_q8_1 / _impl_mmvq, unchanged).
__device__ __forceinline__ float vec_dot_q6_K_q8_1_impl_mmvq(const int& vl, const int& vh, const int* __restrict__ u,
const int8_t* __restrict__ scales, const float& d,
const float* __restrict__ d8) {
float sumf = 0.0f;
#pragma unroll
for (int i = 0; i < QR6_K; ++i) {
const int sc = scales[4 * i];
const int vil = (vl >> (4 * i)) & 0x0F0F0F0F;
const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
const int vi = __vsubss4((vil | vih), 0x20202020); // vi = (vil | vih) - 32
sumf += d8[i] * (ggml_cuda_dp4a(vi, u[i], 0) * sc);
}
return d * sumf;
}
__device__ __forceinline__ float vec_dot_q6_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
const int& kbx, const int& iqs) {
const block_q6_K* bq6_K = (const block_q6_K*) vbq + kbx;
const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 4);
const int scale_offset = (QI6_K / 4) * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 8);
const int vh_shift = 2 * ((iqs % (QI6_K / 2)) / (QI6_K / 4));
const int vl = get_int_b2(bq6_K->ql, iqs);
const int vh = get_int_b2(bq6_K->qh, (QI6_K / 4) * (iqs / (QI6_K / 2)) + iqs % (QI6_K / 4)) >> vh_shift;
const int8_t* scales = bq6_K->scales + scale_offset;
int u[QR6_K];
float d8[QR6_K];
#pragma unroll
for (int i = 0; i < QR6_K; ++i) {
u[i] = get_int_b4(bq8_1[bq8_offset + 2 * i].qs, iqs % QI8_1);
d8[i] = __low2float(bq8_1[bq8_offset + 2 * i].ds);
}
return vec_dot_q6_K_q8_1_impl_mmvq(vl, vh, u, scales, __half2float(bq6_K->d), d8);
}
// Q5_1: llama.cpp's integer chain, but the min term multiplies the sum of the QUANTIZED activations (dp4a with
// 0x01010101, times d8) instead of the q8_1 block's `ds.y`, which our quantizer (like llama.cpp's) fills with the sum
// of the ORIGINAL activations. That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant
@@ -548,8 +513,6 @@ template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<14> { static constexpr int qk = 256, ipb = QI6_K / VDR_Q6_K, step = VDR_Q6_K;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q6_K_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0;
@@ -558,13 +521,10 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0,
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } };
// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every
// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. The down
// kernels are generic in Fmt<T>; a 256-value type on the down list needs n_ff % 256 == 0 (native_expert_supported
// refuses the pair otherwise: Flash-Next's n_ff 640 cannot take them, Qwen3.6's 512 can). IQ3_XXS, Q5_K and Q6_K
// are Qwen3.6's down projections (UD-IQ3_XXS: IQ3_XXS on 37 layers; UD-Q4_K_XL: Q5_K on 37, Q6_K on 34, 38, 39).
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(8)
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8) X(18) X(13) X(14)
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(7) X(6) X(8)
// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8)
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8)
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8)
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
@@ -608,7 +568,7 @@ __global__ void __launch_bounds__(128) mmvq_kernel(const uint8_t* __restrict__ w
// order on the same values, so a column of the kernels below is BITWISE equal to the same column of mmvq_kernel /
// native_gu_kernel / native_down_kernel (iq_multi_parity checks it; STRATA_OLD_IQ_MMVQ=1 keeps the old kernels).
template<int TY> struct Split;
// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q6_K, Q5_1, Q8_0: UD-Q4_K_XL) the
// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q5_1, Q8_0: UD-Q4_K_XL) the
// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile
// time, so the multi kernels are never instantiated for a type without a Split).
template<int TY> inline constexpr bool kSplit = false;
@@ -1628,23 +1588,6 @@ __device__ void dq_q5_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
y[33] = cvt<dst_t>(d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2);
}
}
// Q6_K: llama.cpp's dequantize_q6_K (64 threads), its two halves (ip) taken by each of the 32 threads in turn
template<typename dst_t>
__device__ void dq_q6_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
const block_q6_K* x = (const block_q6_K*) vx;
const float d = __half2float(x[ibs].d);
for (int tt = tid; tt < 64; tt += 32) {
const int ip = tt / 32, il = tt - 32 * ip, is = 8 * ip + il / 16;
dst_t* y = yy + 128 * ip + il;
const uint8_t* ql = x[ibs].ql + 64 * ip + il;
const uint8_t qh = x[ibs].qh[32 * ip + il];
const int8_t* sc = x[ibs].scales + is;
y[0] = cvt<dst_t>(d * sc[0] * ((int8_t) ((ql[0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32));
y[32] = cvt<dst_t>(d * sc[2] * ((int8_t) ((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32));
y[64] = cvt<dst_t>(d * sc[4] * ((int8_t) ((ql[0] >> 4) | (((qh >> 4) & 3) << 4)) - 32));
y[96] = cvt<dst_t>(d * sc[6] * ((int8_t) ((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32));
}
}
template<typename dst_t>
__device__ void dq_q5_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
// symmetric: one delta (no min), the high bit folded in then centered by the format's fixed -16 offset
@@ -1711,7 +1654,6 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,
case 42: dq_q2_0(vx, ibs, y, tid); break;
case 12: dq_q4_k(vx, ibs, y, tid); break;
case 13: dq_q5_k(vx, ibs, y, tid); break;
case 14: dq_q6_k(vx, ibs, y, tid); break;
case 7: dq_q5_1(vx, ibs, y, tid); break;
case 6: dq_q5_0(vx, ibs, y, tid); break;
case 8: dq_q8_0(vx, ibs, y, tid); break;
@@ -1738,7 +1680,7 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v
// the types dq_dispatch dequantizes
bool is_iq(int t) {
return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 8;
t == 12 || t == 13 || t == 7 || t == 6 || t == 8;
}
// values per block of the types the grouped expert kernels take (0 = none)
int gu_qk(int t) {
@@ -1849,7 +1791,6 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {
case 42: return (size_t) (n / 64) * sizeof(block_q2_0);
case 12: return (size_t) (n / 256) * sizeof(block_q4_K);
case 13: return (size_t) (n / 256) * sizeof(block_q5_K);
case 14: return (size_t) (n / 256) * sizeof(block_q6_K);
case 7: return (size_t) (n / 32) * sizeof(block_q5_1);
case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
+5 -8
View File
@@ -97,7 +97,7 @@ __global__ void gate_softplus(const float* __restrict__ alpha, const float* __re
}
__global__ void out_norm(const float* __restrict__ input, const float* __restrict__ z,
const float* __restrict__ gamma, float* __restrict__ output, float epsilon, int silu) {
const float* __restrict__ gamma, float* __restrict__ output, float epsilon) {
const int col = threadIdx.x;
const size_t offset = size_t(blockIdx.x) * S;
const float value = col < S ? input[offset + col] : 0.0f;
@@ -107,11 +107,9 @@ __global__ void out_norm(const float* __restrict__ input, const float* __restric
partial = norm_sum(partial, sums);
const float scale = rsqrtf(partial / S + epsilon);
if (col < S) {
// RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul (qwen4exp) or silu*mul (qwen35moe,
// ggml-cuda unary.cu op_silu: x / (1 + expf(-x))).
// RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul.
const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]);
const float zz = z[offset + col];
output[offset + col] = weighted * (silu ? zz / (1.0f + expf(-zz)) : sigmoid(zz));
output[offset + col] = weighted * sigmoid(z[offset + col]);
}
}
@@ -186,7 +184,7 @@ void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a,
}
void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
float* destination, int64_t heads, int64_t cols,
float epsilon, GdnGate act, void* stream) {
float epsilon, void* stream) {
norm_geometry(heads, cols, epsilon, stream);
const size_t bytes = size_t(heads) * S * sizeof(float);
const Span writable{destination, bytes};
@@ -195,8 +193,7 @@ void native_gdn_out_norm(const float* output, const float* z, const float* gamma
valid(input);
disjoint(writable, input);
}
out_norm<<<unsigned(heads), 256, 0, static_cast<cudaStream_t>(stream)>>>(output, z, gamma, destination, epsilon,
act == GdnGate::Silu ? 1 : 0);
out_norm<<<unsigned(heads), 256, 0, static_cast<cudaStream_t>(stream)>>>(output, z, gamma, destination, epsilon);
check_launch();
}
} // namespace strata::kernels
+26 -46
View File
@@ -88,17 +88,29 @@ void check_sync(const char* what) {
/// Geometry validation. A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently
/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused.
void validate(const QsaShapes& s, const char* who) {
char why[256];
if (!qsa_shapes_valid(s, why, sizeof why)) {
std::fprintf(stderr, "qsa: %s: %s\n", who, why);
if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 ||
s.idx_block < 2 || s.page_size < 1) {
std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who);
std::exit(1);
}
}
/// The indexer's own entry points: a dense shape (no indexer) has nothing for them to read.
void validate_indexer(const QsaShapes& s, const char* who) {
validate(s, who);
if (qsa_dense(s)) {
std::fprintf(stderr, "qsa: %s: the geometry has no indexer (dense attention); nothing to score or select\n", who);
if (s.n_head % s.n_head_kv != 0) {
std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who,
(long long) s.n_head, (long long) s.n_head_kv);
std::exit(1);
}
if (s.head_dim % 4 != 0) {
std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who,
(long long) s.head_dim);
std::exit(1);
}
if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) {
std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who,
(long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim);
std::exit(1);
}
if (s.idx_n_head > 32) {
std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who,
(long long) s.idx_n_head);
std::exit(1);
}
}
@@ -595,7 +607,7 @@ void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_tabl
void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s,
const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) {
validate_indexer(s, "qsa_index");
validate(s, "qsa_index");
if (step == nullptr) fail("qsa_index: step is null");
if (max_blocks <= 0) fail("qsa_index: max_blocks must be positive");
// THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`. The kernel returns for
@@ -609,7 +621,7 @@ void qsa_index_step(const float* pooled, const float* q_idx, const float* bias,
void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step,
int32_t* ids, void* stream) {
validate_indexer(s, "topk_512");
validate(s, "topk_512");
if (step == nullptr) fail("topk_512: step is null");
// `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this
// token's is a device value. The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and
@@ -684,38 +696,6 @@ void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t*
// ================= host entry points =================
bool qsa_shapes_valid(const QsaShapes& s, char* why, size_t why_len) {
auto no = [&](const char* msg) { if (why && why_len) std::snprintf(why, why_len, "%s", msg); return false; };
// dense attention (Qwen3.6, qsa_dense): the three indexer widths are zero TOGETHER; the KV, gather, attend and
// gate kernels do not read them. Some of them zero is a half-set-up geometry (a builder that copied the
// geometry's two zeros and kept the sparse budget), refused rather than run as either model.
const bool dense = qsa_dense(s);
if (!dense && (s.idx_n_head == 0 || s.idx_dim == 0 || s.idx_top_k == 0)) {
if (why && why_len)
std::snprintf(why, why_len, "geometry is half set up: idx_n_head %lld, idx_dim %lld, idx_top_k %lld must be "
"all zero (dense attention) or all set (the indexer)", (long long) s.idx_n_head,
(long long) s.idx_dim, (long long) s.idx_top_k);
return false;
}
if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_block < 2 || s.page_size < 1)
return no("geometry is not set up");
if (s.n_head % s.n_head_kv != 0) {
if (why && why_len)
std::snprintf(why, why_len, "n_head %lld is not a multiple of n_head_kv %lld", (long long) s.n_head,
(long long) s.n_head_kv);
return false;
}
if (s.head_dim % 4 != 0) return no("head_dim must be a multiple of 4 (the gather copies uint2)");
if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || (!dense && s.n_rot > s.idx_dim)) {
if (why && why_len)
std::snprintf(why, why_len, "n_rot %lld must be even and <= head_dim %lld and idx_dim %lld",
(long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim);
return false;
}
if (s.idx_n_head > 32) return no("idx_n_head > 32 (one warp per indexer head)");
return true;
}
void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s) {
if (host_step == nullptr) return;
if (pos < 0) fail("qsa_step_fill: pos < 0");
@@ -742,7 +722,7 @@ void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, in
void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm,
float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab,
const float* sin_tab, void* stream) {
validate_indexer(s, "indexer_key_append");
validate(s, "indexer_key_append");
if (pos_dev == nullptr) fail("indexer_key_append: pos_dev is null");
if (b.tail == nullptr || b.dead == nullptr || b.pooled == nullptr || b.block_pos == nullptr)
fail("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)");
@@ -760,7 +740,7 @@ void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_ba
void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s,
int64_t n_kv, float* cell_scores, void* stream) {
validate_indexer(s, "qsa_index");
validate(s, "qsa_index");
if (n_bid < 0 || n_kv <= 0) fail("qsa_index: n_bid < 0 or n_kv <= 0");
// `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments
// disagree rather than launching a kernel that would score the wrong number of blocks.
@@ -776,7 +756,7 @@ void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const flo
void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids,
void* stream) {
validate_indexer(s, "topk_512");
validate(s, "topk_512");
if (n_kv <= 0) return;
if (n_kv > kTopkMaxCells) {
std::fprintf(stderr, "qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n",
+150 -406
View File
@@ -9,35 +9,15 @@
#include <cfloat>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
namespace strata::kernels {
namespace {
constexpr int HD = 256; // head_dim
constexpr int CHUNK = 64; // cells per SUB-CHUNK: the unit of the score / softmax / value phases below
constexpr int G = 12; // query heads per KV head (24 / 2)
constexpr int CHUNK = 64; // cells per block
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
// `G`, the query heads per KV head, is a template parameter of every kernel: 12 for Flash-Next (24 / 2), 8 for
// Qwen3.6 (16 / 2), 2 for the synthetic fixtures (4 / 2); `qsa_attn_group` picks it from the geometry.
// THE SPLIT-K BOUND (docs/QWEN36-35B-A3B.md 3.3 item 5). A block used to own exactly one 64-cell chunk, so the
// partials grew with the capacity: 64.5 MiB per query row at 262,144 cells and 16 heads. Now the grid has at
// most kMaxChunks blocks per KV head and a block walks its SPAN of the selection in 64-cell sub-chunks with the
// usual running (m, l, acc) rescale, so the partials are bounded (kMaxChunks x n_head x 258 floats: 2.0 MiB per
// row at 16 heads) whatever the capacity. The span is computed ON THE DEVICE from this token's width, not from
// the capacity: a short selection in a long state still spreads over one chunk per 64 cells (kMaxChunks x 64 =
// 8,192 cells before any block takes a second sub-chunk), so decode at a short depth keeps its parallelism, and a
// capacity up to 8,192 is the old kernel exactly - one sub-chunk per block, the same grid, the same arithmetic.
constexpr int kMaxChunks = 128;
// The bound applies to DENSE shapes only. A sparse (Flash-Next) shape keeps one block per 64 cells at any
// capacity - its states cap at 2,051, but the MTP drafter's ring runs this kernel at its --mtp-window (32,768 by
// default, 512 blocks) and must keep its previous grid, scratch and summation order bit for bit.
__host__ __device__ __forceinline__ int chunks_for(long long cap, bool dense) {
const long long c = (cap + CHUNK - 1) / CHUNK;
return (int) (dense && c > kMaxChunks ? kMaxChunks : c);
}
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
@@ -100,7 +80,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo
} else load8_q4(p, value, row, d0, out);
}
template <int KV_MODE, int G>
template <int KV_MODE>
__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,
@@ -109,111 +89,94 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
int n_chunks, int cap = 0, long long scratch_stride = 0) {
// 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;
if (ids != nullptr) ids += (size_t) blockIdx.z * (size_t) cap; // null: the identity (dense attention)
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[G][HD]; // 12 KB at G 12: this KV head's query heads
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads
__shared__ float sp[G][CHUNK]; // scores, then probabilities
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
__shared__ float srun_m[G], srun_l[G], sfac[G]; // the running max / sum per head, and this sub-chunk's rescale
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
// this block's span: the selection in ceil(n_ids / 64) sub-chunks, spread over the n_chunks blocks
const int span = ((((n_ids + CHUNK - 1) / CHUNK) + n_chunks - 1) / n_chunks) * CHUNK;
const int begin = chunk * span;
const int end = min(begin + span, n_ids);
const int c0 = chunk * CHUNK;
const int n_here = min(CHUNK, n_ids - c0);
const int slot = kvh * n_chunks + chunk;
if (begin >= end) {
if (n_here <= 0) {
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
if (t < G) { srun_m[t] = -FLT_MAX; srun_l[t] = 0.0f; }
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
for (int c0 = begin; c0 < end; c0 += CHUNK) {
const int n_here = min(CHUNK, end - c0);
__syncthreads(); // the previous sub-chunk's value loop is done with sp and srow
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t;
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
__syncthreads();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
for (int c = warp; c < CHUNK; c += WARPS) {
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum(s);
if (lane == 0) sp[h][c] = s * scale;
}
srow[t] = r;
}
__syncthreads();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
for (int c = warp; c < CHUNK; c += WARPS) {
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
__syncthreads();
// per-head sub-chunk max and exp-sum, folded into the running pair: warp w handles heads w and w+8.
// On the first sub-chunk the running max is -FLT_MAX, the rescale is 0 and the probabilities are
// exp(s - m_chunk): the single-chunk kernel's arithmetic, bit for bit.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float mc = warp_max(fmaxf(a, b));
const float mr = srun_m[h];
const float m = fmaxf(mr, mc);
const float f = mr == -FLT_MAX ? 0.0f : __expf(mr - m);
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { srun_m[h] = m; srun_l[h] = fmaf(srun_l[h], f, l); sfac[h] = f; }
}
__syncthreads();
// values: thread t owns dimension t for all G heads.
float k8[8];
load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] *= sfac[h];
for (int c = 0; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
float v;
if constexpr (KV_MODE == 0) {
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
} else if constexpr (KV_MODE == 1) {
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
v = (float) p.v_q[srow[c] * HD + t] * sc;
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = t / QK4_0;
const int rem = t % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = rem < 16 ? rem : (rem - 16);
const uint8_t byte = blk->qs[j];
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
v = (float) nibble * d;
}
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum(s);
if (lane == 0) sp[h][c] = s * scale;
}
}
__syncthreads();
if (t < G) { part_m[slot * G + t] = srun_m[t]; part_l[slot * G + t] = srun_l[t]; }
// per-head chunk max and exp-sum: warp w handles heads w and w+8.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float m = warp_max(fmaxf(a, b));
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
}
__syncthreads();
// values: thread t owns dimension t for all 12 heads.
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
for (int c = 0; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
float v;
if constexpr (KV_MODE == 0) {
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
} else if constexpr (KV_MODE == 1) {
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
v = (float) p.v_q[srow[c] * HD + t] * sc;
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = t / QK4_0;
const int rem = t % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = rem < 16 ? rem : (rem - 16);
const uint8_t byte = blk->qs[j];
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
v = (float) nibble * d;
}
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
}
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
}
@@ -274,199 +237,21 @@ __device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, i
}
}
template <int KV_MODE, int G>
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(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) {
static_assert(G <= 16, "reduce12 folds 16 lanes' sums");
// 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;
if (ids != nullptr) ids += (size_t) blockIdx.z * (size_t) cap; // null: the identity (dense attention)
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[G][HD]; // 12 KB at G 12: this KV head's query heads
__shared__ float sp[G][CHUNK]; // scores
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
// probabilities, cell-major: the value loop reads one cell's G as float4s. They used to alias `sq` (dead once
// the scores were done); a block that walks several sub-chunks reads `sq` again, so they have their own 3-4 KB.
__shared__ __align__(16) float spt[CHUNK][G];
__shared__ float srun_m[G], srun_l[G], sfac[G];
static_assert(G % 4 == 0 || G == 2, "the value loop reads the weights as float4 (or one float2 at G 2)");
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int span = ((((n_ids + CHUNK - 1) / CHUNK) + n_chunks - 1) / n_chunks) * CHUNK;
const int begin = chunk * span;
const int end = min(begin + span, n_ids);
const int slot = kvh * n_chunks + chunk;
if (begin >= end) {
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
if (t < G) { srun_m[t] = -FLT_MAX; srun_l[t] = 0.0f; }
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
const int hd = head_of_lane(lane);
for (int c0 = begin; c0 < end; c0 += CHUNK) {
const int n_here = min(CHUNK, end - c0);
__syncthreads(); // the previous sub-chunk's value loop is done with spt and srow
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t;
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
}
__syncthreads();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. NC cells per
// step (warp + 8 * (i + j)): a lane's q slice comes out of shared memory once for all of them, which cuts
// the traffic that bounds this phase (G x 16 B per lane per cell, against the FMAs) by NC; every dot
// product is the same expression as for a single cell, so the scores are unchanged.
constexpr int NC = 2; // 4 measured slower on a V100 (the registers cost occupancy)
for (int i = 0; i < CHUNK / WARPS; i += NC) {
int cc[NC];
bool all_ok = true;
#pragma unroll
for (int j = 0; j < NC; ++j) {
cc[j] = warp + WARPS * (i + j);
all_ok = all_ok && cc[j] < n_here && srow[cc[j]] >= 0;
}
if (all_ok) {
float kk[NC][8];
#pragma unroll
for (int j = 0; j < NC; ++j) load8<KV_MODE>(p, false, srow[cc[j]], lane * 8, kk[j]);
float pp[NC][16];
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
#pragma unroll
for (int j = 0; j < NC; ++j)
pp[j][h] = kk[j][0] * qa.x + kk[j][1] * qa.y + kk[j][2] * qa.z + kk[j][3] * qa.w +
kk[j][4] * qb.x + kk[j][5] * qb.y + kk[j][6] * qb.z + kk[j][7] * qb.w;
}
#pragma unroll
for (int j = 0; j < NC; ++j) {
#pragma unroll
for (int h = G; h < 16; ++h) pp[j][h] = 0.0f;
const float sj = reduce12(pp[j], lane);
if ((lane & 1) == 0 && hd < G) sp[hd][cc[j]] = sj * scale;
}
} else {
for (int k = 0; k < NC; ++k) { // a masked or out-of-range cell in the group: one cell at a time
const int c = cc[k];
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
float part[16];
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
part[h] = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
}
#pragma unroll
for (int h = G; h < 16; ++h) part[h] = 0.0f;
const float s = reduce12(part, lane);
if ((lane & 1) == 0 && hd < G) sp[hd][c] = s * scale;
}
}
}
__syncthreads();
// per-head sub-chunk max and exp-sum into the running pair (see attn_chunk_kernel): warp w, heads w, w+8.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float mc = warp_max(fmaxf(a, b));
const float mr = srun_m[h];
const float m = fmaxf(mr, mc);
const float f = mr == -FLT_MAX ? 0.0f : __expf(mr - m);
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
spt[lane][h] = ea;
spt[lane + 32][h] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { srun_m[h] = m; srun_l[h] = fmaf(srun_l[h], f, l); sfac[h] = f; }
}
__syncthreads();
// values: thread t owns dimension t for all G heads.
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] *= sfac[h];
// One cell's G weights (broadcast float4 loads) into the G accumulators; the cells are folded in
// ascending order, so the sums are the plain loop's, bit for bit.
const auto fold = [&](int c, float v) {
if constexpr (G == 2) {
const float2 w = *reinterpret_cast<const float2*>(spt[c]);
acc[0] = fmaf(w.x, v, acc[0]); acc[1] = fmaf(w.y, v, acc[1]);
} else {
const float4* w4 = reinterpret_cast<const float4*>(spt[c]);
#pragma unroll
for (int g4 = 0; g4 < G / 4; ++g4) {
const float4 w = w4[g4];
acc[4 * g4] = fmaf(w.x, v, acc[4 * g4]); acc[4 * g4 + 1] = fmaf(w.y, v, acc[4 * g4 + 1]);
acc[4 * g4 + 2] = fmaf(w.z, v, acc[4 * g4 + 2]); acc[4 * g4 + 3] = fmaf(w.w, v, acc[4 * g4 + 3]);
}
}
};
int c = 0;
// four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);
// a group holding a masked cell (page -1, rare) leaves this loop and the scalar one below finishes the chunk.
for (; c + 4 <= n_here; c += 4) {
const long long r0 = srow[c], r1 = srow[c + 1], r2 = srow[c + 2], r3 = srow[c + 3];
if ((r0 | r1 | r2 | r3) < 0) break;
const float v0 = load_v1<KV_MODE>(p, r0, t), v1 = load_v1<KV_MODE>(p, r1, t);
const float v2 = load_v1<KV_MODE>(p, r2, t), v3 = load_v1<KV_MODE>(p, r3, t);
fold(c, v0);
fold(c + 1, v1);
fold(c + 2, v2);
fold(c + 3, v3);
}
for (; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
fold(c, load_v1<KV_MODE>(p, srow[c], t));
}
}
__syncthreads();
if (t < G) { part_m[slot * G + t] = srun_m[t]; part_l[slot * G + t] = srun_l[t]; }
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
}
// The single-chunk form of the kernel above: PR #540's body as it was, with G and the null-ids identity. Every
// sparse (Flash-Next) shape runs THIS one at any capacity, and a dense state of at most kMaxChunks x 64 = 8,192
// cells too, so Flash-Next's Pascal path - the QSA layers at cap 2,051 and the MTP drafter's ring at its window -
// is the old kernel to the instruction (the looped form costs 16-28 registers on sm_61 and 15% on the Q4_0 pool at
// 2,051 cells; capping the registers spilled and cost more). The looped form above runs only for the dense model's
// states past 8,192 cells.
template <int KV_MODE, int G>
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75_single(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) {
// 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;
if (ids != nullptr) ids += (size_t) blockIdx.z * (size_t) cap; // null: the identity (dense attention)
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
static_assert(G == 2 || G % 4 == 0, "the value loop reads the weights as float4 (one float2 at G 2)");
__shared__ __align__(16) float sq[G][HD]; // 12 KB at G 12: this KV head's query heads (dead once the scores are done)
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads (dead once the scores are done)
__shared__ float sp[G][CHUNK]; // scores
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
// probabilities, cell-major: the value loop reads one cell's 12 as three float4. They are first written after the
@@ -488,7 +273,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75_single(const
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t;
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
@@ -569,25 +354,21 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75_single(const
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
}
__syncthreads();
// values: thread t owns dimension t for all G heads.
// values: thread t owns dimension t for all 12 heads.
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
// One cell's G weights (broadcast float4 loads) into the G accumulators; the cells are folded in
// One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in
// ascending order, so the sums are the plain loop's, bit for bit.
const auto fold = [&](int c, float v) {
if constexpr (G == 2) {
const float2 w = *reinterpret_cast<const float2*>(spt[c]);
acc[0] = fmaf(w.x, v, acc[0]); acc[1] = fmaf(w.y, v, acc[1]);
} else {
const float4* w4 = reinterpret_cast<const float4*>(spt[c]);
#pragma unroll
for (int g4 = 0; g4 < G / 4; ++g4) {
const float4 w = w4[g4];
acc[4 * g4] = fmaf(w.x, v, acc[4 * g4]); acc[4 * g4 + 1] = fmaf(w.y, v, acc[4 * g4 + 1]);
acc[4 * g4 + 2] = fmaf(w.z, v, acc[4 * g4 + 2]); acc[4 * g4 + 3] = fmaf(w.w, v, acc[4 * g4 + 3]);
}
}
const float4* w4 = reinterpret_cast<const float4*>(spt[c]);
const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2];
acc[0] = fmaf(w0.x, v, acc[0]); acc[1] = fmaf(w0.y, v, acc[1]);
acc[2] = fmaf(w0.z, v, acc[2]); acc[3] = fmaf(w0.w, v, acc[3]);
acc[4] = fmaf(w1.x, v, acc[4]); acc[5] = fmaf(w1.y, v, acc[5]);
acc[6] = fmaf(w1.z, v, acc[6]); acc[7] = fmaf(w1.w, v, acc[7]);
acc[8] = fmaf(w2.x, v, acc[8]); acc[9] = fmaf(w2.y, v, acc[9]);
acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]);
};
int c = 0;
// four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);
@@ -609,10 +390,8 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75_single(const
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
}
#endif // STRATA_EXPERIMENTAL_SM60
template <int G>
__global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict__ part_acc,
const float* __restrict__ part_m,
const float* __restrict__ part_l, int n_chunks,
@@ -661,21 +440,24 @@ bool pre75_attn() {
}
return cc[dev] < 75;
}
#define STRATA_ATTN_CHUNK(M, G) (pre75_attn() ? (!dense || n_chunks < kMaxChunks ? attn_chunk_kernel_pre75_single<M, G> : attn_chunk_kernel_pre75<M, G>) : attn_chunk_kernel<M, G>)
#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)
#else
#define STRATA_ATTN_CHUNK(M, G) attn_chunk_kernel<M, G>
#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
#endif
int kv_mode_of(const QsaAttnPools& pools) {
return pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 : (pools.k_q != nullptr ? 1 : 0));
}
} // namespace
template <int G>
void launch_group(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, cudaStream_t st) {
const int kv_mode = kv_mode_of(pools);
const bool dense = qsa_dense(s);
const int n_chunks = chunks_for(cap, dense);
void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
if (n_q <= 0) return;
if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps ||
!pools.page_table || n_q > 65535) {
std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n");
std::exit(1);
}
const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
: (pools.k_q != nullptr ? 1 : 0));
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
// per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride
const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
float* part_acc = scratch;
@@ -683,109 +465,71 @@ void launch_group(const float* q, const QsaAttnPools& pools, const int32_t* ids,
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);
if (kv_mode == 3)
STRATA_ATTN_CHUNK(3, G)<<<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);
else if (kv_mode == 2)
STRATA_ATTN_CHUNK(2, G)<<<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);
else if (kv_mode == 1)
STRATA_ATTN_CHUNK(1, G)<<<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);
else
STRATA_ATTN_CHUNK(0, G)<<<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);
attn_merge_kernel<G><<<dim3((unsigned) s.n_head, (unsigned) n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks,
attn, stride);
}
void refuse(const char* who, const char* why) {
std::fprintf(stderr, "%s: %s\n", who, why);
std::exit(1);
}
void run(const char* who, 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) {
char why[256];
const int G = qsa_attn_group(s, why, sizeof why);
if (G == 0) refuse(who, why);
if (s.head_dim != HD || cap <= 0 || !scratch || !steps || !pools.page_table || n_q > 65535)
refuse(who, "unsupported geometry or missing buffers (head_dim 256, cap > 0, scratch, steps, page_table, n_q <= 65535)");
const int kv_mode = kv_mode_of(pools);
if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4)
: (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale)
: (!pools.k_pool || !pools.v_pool))))
refuse(who, "incomplete KV pools");
cudaStream_t st = (cudaStream_t) stream;
if (G == 12) launch_group<12>(q, pools, ids, steps, cap, s, scratch, attn, n_q, st);
else if (G == 8) launch_group<8>(q, pools, ids, steps, cap, s, scratch, attn, n_q, st);
else launch_group<2>(q, pools, ids, steps, cap, s, scratch, attn, n_q, st);
if (kv_mode == 3)
STRATA_ATTN_CHUNK(3)<<<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);
else if (kv_mode == 2)
STRATA_ATTN_CHUNK(2)<<<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);
else if (kv_mode == 1)
STRATA_ATTN_CHUNK(1)<<<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);
else
STRATA_ATTN_CHUNK(0)<<<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);
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) refuse(who, cudaGetErrorString(e));
}
__global__ void identity_ids_kernel(int32_t* __restrict__ ids, const int32_t* __restrict__ steps, long long cap) {
const int q = blockIdx.y;
const int width = __ldg(steps + (size_t) q * kStepCount + kStepWidth);
for (long long j = (long long) blockIdx.x * blockDim.x + threadIdx.x; j < width; j += (long long) gridDim.x * blockDim.x)
ids[(size_t) q * cap + j] = (int32_t) j;
}
} // namespace
int qsa_attn_group(const QsaShapes& s, char* why, size_t why_len) {
const int64_t G = s.n_head_kv > 0 ? s.n_head / s.n_head_kv : 0;
if (s.n_head_kv > 0 && G * s.n_head_kv == s.n_head && (G == 2 || G == 8 || G == 12)) return (int) G;
if (why && why_len)
std::snprintf(why, why_len, "n_head %lld over n_head_kv %lld is %lld query heads per KV head; the decode "
"attention is built for 2, 8 (Qwen3.6: 16 / 2) and 12 (Flash-Next: 24 / 2)",
(long long) s.n_head, (long long) s.n_head_kv, (long long) G);
return 0;
}
bool qsa_attn_group_check(const QsaShapes& s, int G, char* why, size_t why_len) {
if (G != 2 && G != 8 && G != 12) {
if (why && why_len) std::snprintf(why, why_len, "G = %d: the decode attention is built for 2, 8 and 12", G);
return false;
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_decode_attn_batch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (s.n_head != (int64_t) G * s.n_head_kv) {
if (why && why_len)
std::snprintf(why, why_len, "G = %d refused: n_head %lld is not %d x n_head_kv %lld (that would be %lld "
"query heads per KV head)", G, (long long) s.n_head, G, (long long) s.n_head_kv,
s.n_head_kv > 0 ? (long long) (s.n_head / s.n_head_kv) : 0ll);
return false;
}
return true;
}
int64_t qsa_decode_attn_chunks(int64_t cap, const QsaShapes& s) { return chunks_for(cap, qsa_dense(s)); }
uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
return (uint64_t) chunks_for(cap, qsa_dense(s)) * (uint64_t) s.n_head * (HD + 2) + 64;
}
void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
if (n_q <= 0) return;
run("qsa_decode_attn_batch", q, pools, ids, steps, cap, s, scratch, attn, n_q, stream);
const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
}
void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step,
int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) {
run("qsa_decode_attn", q, pools, ids, step, cap, s, scratch, attn, 1, stream);
}
void qsa_identity_ids(int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, void* stream) {
if (n_q <= 0 || cap <= 0) return;
if (!ids || !steps || n_q > 65535) {
std::fprintf(stderr, "qsa_identity_ids: missing buffers or n_q > 65535\n");
if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step ||
!pools.page_table) {
std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n");
std::exit(1);
}
const unsigned bx = (unsigned) std::min<int64_t>((cap + 255) / 256, 64);
identity_ids_kernel<<<dim3(bx, (unsigned) n_q), 256, 0, (cudaStream_t) stream>>>(ids, steps, (long long) cap);
const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
: (pools.k_q != nullptr ? 1 : 0));
if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4)
: (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale)
: (!pools.k_pool || !pools.v_pool)))) {
std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n");
std::exit(1);
}
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
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);
cudaStream_t st = (cudaStream_t) stream;
if (kv_mode == 3)
STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
else if (kv_mode == 2)
STRATA_ATTN_CHUNK(2)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
else if (kv_mode == 1)
STRATA_ATTN_CHUNK(1)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
else
STRATA_ATTN_CHUNK(0)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_identity_ids: %s\n", cudaGetErrorString(e));
std::fprintf(stderr, "qsa_decode_attn: %s\n", cudaGetErrorString(e));
std::exit(1);
}
}
+66 -86
View File
@@ -19,8 +19,7 @@ namespace strata::kernels {
namespace {
constexpr int HD = 256; // head_dim
// `G`, the query heads per KV head, is a template parameter of every kernel below (2, 8, 12: qsa_attn_group); the
// MMA tiles are 16 query rows, so every G <= 16 pads with zero rows exactly as 12 did.
constexpr int G = 12; // query heads per KV head
#ifndef D1_CH
#define D1_CH 32
#endif
@@ -103,7 +102,7 @@ struct Smem {
long long row[CH];
};
template <int KV_MODE, int G>
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
@@ -115,7 +114,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
if (ids != nullptr) ids += (size_t) qi * cap;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int gid = lane >> 2, tig = lane & 3;
@@ -150,7 +149,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
if (t < CH) {
long long r = -1;
if (t < nh) {
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t; // null ids: the identity (dense)
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
@@ -416,8 +415,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int d = warp * 64 + j * 8 + 2 * tig;
if (gid < G) // G < 8 (the fixtures' 4 / 2): rows past G belong to the next KV head's output
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
if (gid + 8 < G)
*reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
}
@@ -462,7 +460,6 @@ __device__ __forceinline__ void cp_async_wait1() {
#endif
}
template <int G>
__global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
@@ -474,7 +471,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
if (ids != nullptr) ids += (size_t) qi * cap;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int gid = lane >> 2, tig = lane & 3;
@@ -512,7 +509,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
// the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead
const int n_chunks = (n + CH2 - 1) / CH2;
auto cell_of = [&](int c) -> int { return c < n ? (ids != nullptr ? __ldg(ids + c) : c) : -1; }; // null ids: identity
auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; };
auto row_of = [&](int cell) -> long long {
if (cell < 0) return -1;
const long long page = (long long) __ldg(p.page_table + cell / page_size);
@@ -672,14 +669,12 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int d = dim0 + j * 8 + 2 * tig;
if (gid < G) // G < 8 (the fixtures' 4 / 2): rows past G belong to the next KV head's output
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
if (gid + 8 < G)
*reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
}
}
template <int G>
bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs this on several)
@@ -688,7 +683,7 @@ bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, co
const int bytes = (int) sizeof(Smem2);
if (dev < 0 || dev >= 64) return false;
if (!attr[dev]) {
if (cudaFuncSetAttribute(prompt_attn_i8_kernel<G>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
cudaSuccess) {
cudaGetLastError();
return false;
@@ -698,8 +693,8 @@ bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, co
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_i8_kernel<G><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids != nullptr ? ids + q0 * cap : nullptr, steps + q0 * kStepCount, (int) s.n_head_kv,
prompt_attn_i8_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
@@ -710,7 +705,7 @@ bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, co
return true;
}
template <int KV_MODE, int G>
template <int KV_MODE>
bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
static bool attr[64] = {}; // per device, as above
@@ -719,7 +714,7 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const
const int bytes = (int) sizeof(Smem<KV_MODE>);
if (dev < 0 || dev >= 64) return false;
if (!attr[dev]) {
if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE, G>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
cudaSuccess) {
cudaGetLastError();
return false;
@@ -729,8 +724,8 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_kernel<KV_MODE, G><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids != nullptr ? ids + q0 * cap : nullptr, steps + q0 * kStepCount, (int) s.n_head_kv,
prompt_attn_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
@@ -794,7 +789,7 @@ struct Smem70 {
long long row[CH];
};
template <int KV_MODE, int G>
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
@@ -806,7 +801,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
if (ids != nullptr) ids += (size_t) qi * cap;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int qp = (lane >> 2) & 3, jj = (lane & 3) + 4 * (lane >> 4); // quad-pair, thread within it
@@ -847,7 +842,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
if (t < CH) {
long long r = -1;
if (t < nh) {
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t; // null ids: the identity (dense)
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
@@ -1088,7 +1083,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
}
}
template <int KV_MODE, int G>
template <int KV_MODE>
bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
static bool attr[64] = {};
@@ -1097,7 +1092,7 @@ bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, con
const int bytes = (int) sizeof(Smem70<KV_MODE>);
if (dev < 0 || dev >= 64) return false;
if (!attr[dev]) {
if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE, G>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
cudaSuccess) {
cudaGetLastError();
return false;
@@ -1107,8 +1102,8 @@ bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, con
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_v70_kernel<KV_MODE, G><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids != nullptr ? ids + q0 * cap : nullptr, steps + q0 * kStepCount, (int) s.n_head_kv,
prompt_attn_v70_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
@@ -1119,7 +1114,7 @@ bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, con
return true;
}
#else // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one)
template <int KV_MODE, int G>
template <int KV_MODE>
bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*,
int64_t, cudaStream_t) {
return false;
@@ -1174,7 +1169,6 @@ __device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128
return h;
}
template <int G>
__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
@@ -1186,7 +1180,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
if (ids != nullptr) ids += (size_t) qi * cap;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int col = lane & 15, half = lane >> 4; // fragment column / k half
@@ -1236,7 +1230,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*
// KV streaming left non-resident: masked as in the decode kernel)
long long myrow = -1;
if (c0 + lane < n) {
const int cell = ids != nullptr ? __ldg(ids + c0 + lane) : c0 + lane; // null ids: the identity
const int cell = __ldg(ids + c0 + lane);
const long long page = (long long) __ldg(p.page_table + cell / page_size);
if (page >= 0) myrow = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
@@ -1390,14 +1384,13 @@ bool hip_wmma_usable() {
return arch[dev] == 1;
}
template <int G>
bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_wmma_kernel<G><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(
q + q0 * s.n_head * HD, pools, ids != nullptr ? ids + q0 * cap : nullptr, steps + q0 * kStepCount, (int) s.n_head_kv,
prompt_attn_wmma_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
@@ -1409,51 +1402,6 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,
}
#endif
template <int G>
bool dispatch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, void* stream, bool volta, bool turing) {
#if defined(__HIPCC__)
// the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
// matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
(void) turing; (void) volta;
if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
cap > 0 && steps && pools.page_table && hip_wmma_usable())
return launch_wmma<G>(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
return false;
#endif
if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !steps || !pools.page_table)
return false;
cudaStream_t st = (cudaStream_t) stream;
if (pools.k_q4 != nullptr) { // Q4_0 K and V (--kv q4_0): mode 4. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B)
static const bool q4_off = [] {
const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4");
return v != nullptr && v[0] == '0';
}();
// sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet
if (q4_off || turing || pools.v_q4 == nullptr) return false;
return launch<4, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V
if (!pools.k_scale) return false;
if (volta) return launch70<3, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch<3, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (pools.k_q != nullptr) {
if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;
// STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control
// for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not
// exist before sm_80.
static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
if (volta) return launch70<1, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
if (v1 || turing) return launch<1, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch_i8<G>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (!pools.k_pool || !pools.v_pool) return false;
if (volta) return launch70<0, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch<0, G>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
} // namespace
bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
@@ -1486,14 +1434,46 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
volta = cc[dev] < 75; // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one
turing = cc[dev] < 80;
}
// Qwen3.6: the query heads per KV head from the geometry (2, 8, 12); any other ratio falls back to the decode
// kernel, which refuses it by name.
char why[256];
const int G = qsa_attn_group(s, why, sizeof why);
if (G == 12) return dispatch<12>(q, pools, ids, steps, cap, s, attn, n_q, stream, volta, turing);
if (G == 8) return dispatch<8>(q, pools, ids, steps, cap, s, attn, n_q, stream, volta, turing);
if (G == 2) return dispatch<2>(q, pools, ids, steps, cap, s, attn, n_q, stream, volta, turing);
#if defined(__HIPCC__)
// the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
// matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
(void) turing; (void) volta;
if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())
return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
return false;
#endif
if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table)
return false;
cudaStream_t st = (cudaStream_t) stream;
if (pools.k_q4 != nullptr) { // Q4_0 K and V (--kv q4_0): mode 4. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B)
static const bool q4_off = [] {
const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4");
return v != nullptr && v[0] == '0';
}();
// sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet
if (q4_off || turing || pools.v_q4 == nullptr) return false;
return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V
if (!pools.k_scale) return false;
if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (pools.k_q != nullptr) {
if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;
// STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control
// for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not
// exist before sm_80.
static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (!pools.k_pool || !pools.v_pool) return false;
if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
} // namespace strata::kernels
+70 -239
View File
@@ -80,113 +80,6 @@ __device__ __forceinline__ float apply_penalties(float logit, int count, const S
return logit;
}
// ---- DRY (llama.cpp's `dry` sampler): a token that would EXTEND a repeat longer than `dry_allowed_length`
// loses `dry_multiplier * dry_base^(repeat - allowed_length)`. `dry_build` is `llama_sampler_dry_apply`'s
// steps 1-3 (the restart-sequence scan, the reverse Z-algorithm, and the per-token maximum repeat), run once per
// row on ONE thread into shared memory; `apply_dry` is step 4, consulted per candidate.
//
// The window is the last `p.dry_penalty_last_n` tokens of the row, the SAME row the penalties count, with the
// `-1` padding `penalty_rows` writes in front dropped (`rat(0)` is then the most recent real token, as in
// llama.cpp's `last_tokens.rat`). `br` is `dry_processed_breakers`: sequence k is flat[off[k] .. off[k+1]).
struct DryShared {
int n; // tokens in `tok`/`len`
int drep[kDryWindowCap]; // step 2: the repeat length at each reversed position
int tok[kDryWindowCap]; // step 3: a token that would extend a repeat ...
int len[kDryWindowCap]; // ... and its longest such repeat length (the max over positions)
};
// The trailing window of the padded history row: `dlen` real tokens ending at the row's end, `drow` their base.
__device__ __forceinline__ void dry_window(const int* base, int history_len, int dry_last_n, const int*& drow,
int& dlen) {
int d = dry_last_n < history_len ? dry_last_n : history_len;
if (d > kDryWindowCap) d = kDryWindowCap;
if (d < 0) d = 0;
drow = base + history_len - d;
while (d > 0 && drow[0] == -1) { ++drow; --d; } // drop the -1 padding (a real id is never negative)
dlen = d;
}
__device__ void dry_build(DryShared& d, const int* hrow, int hlen, int dlen, const SamplerParams& p,
const DryBreakers& br) {
d.n = 0;
if (!dry_enabled(p) || dlen <= p.dry_allowed_length) return;
const int nb = br.n;
const int* bf = br.flat;
const int* bo = br.off;
auto rat = [&](int x) -> int { return hrow[hlen - 1 - x]; };
// Step 1: the nearest restart sequence (a head token with its tail tokens closer to the end) bounds the
// longest repeat we care about.
int rep_limit = dlen;
for (int i = 0; i < dlen; ++i) {
const int token = rat(i);
int longest = -1;
for (int b = 0; b < nb; ++b) {
if (bf[bo[b]] != token) continue;
const int sl = bo[b + 1] - bo[b] - 1;
if (sl > longest && sl <= i) {
bool match = true;
for (int off = 0; off < sl; ++off)
if (bf[bo[b] + 1 + off] != rat(i - off - 1)) { match = false; break; }
if (match) longest = sl;
}
}
if (longest >= 0) { rep_limit = i - longest; break; }
}
if (rep_limit < p.dry_allowed_length) return;
// Step 2: the reverse Z-algorithm, suffix length capped at `rep_limit`.
const int last = dlen - 1;
int rt = 0, lt = 0;
for (int k = 1; k < dlen; ++k) {
if (k > rt) {
int n = 0;
while (n + k < dlen && rat(n) == rat(n + k)) ++n;
d.drep[last - k] = n < rep_limit ? n : rep_limit;
if (n > 0) { lt = k; rt = k + n - 1; }
} else {
const int pp = k - lt, rpl = rt - k + 1;
if (d.drep[last - pp] < rpl) {
d.drep[last - k] = d.drep[last - pp] < rep_limit ? d.drep[last - pp] : rep_limit;
} else {
int i = rt + 1;
while (i < dlen && rat(i) == rat(i - k)) ++i;
const int n = (i - k) < rep_limit ? (i - k) : rep_limit;
d.drep[last - k] = n;
lt = k;
rt = i - 1;
}
}
}
// Step 3: each position whose repeat is long enough names the next token, which would extend it.
for (int i = 0; i < dlen - 1; ++i) {
const int repeat_len = d.drep[i];
if (repeat_len < p.dry_allowed_length) continue;
const int token = rat(dlen - 2 - i);
int j = 0;
for (; j < d.n; ++j) if (d.tok[j] == token) break;
if (j == d.n) { d.tok[d.n] = token; d.len[d.n] = repeat_len; ++d.n; }
else if (d.len[j] < repeat_len) d.len[j] = repeat_len;
}
}
__device__ __forceinline__ float apply_dry(float s, int v, const SamplerParams& p, const DryShared& d,
const DryBreakers& br) {
if (d.n <= 0) return s;
int rep = -1;
for (int j = 0; j < d.n; ++j) if (d.tok[j] == v) { rep = d.len[j]; break; }
if (rep < 0) return s;
// A single-token restart sequence (an empty tail) is never penalised.
for (int b = 0; b < br.n; ++b)
if (br.flat[br.off[b]] == v && br.off[b + 1] - br.off[b] == 1) return s;
int exp = rep - p.dry_allowed_length;
int max_exp = 0;
if (p.dry_base > 1.000001f) max_exp = (int) (88.7228391f / logf(p.dry_base)); // overflow guard
if (max_exp > 0 && exp > max_exp) exp = max_exp;
return s - p.dry_multiplier * powf(p.dry_base, (float) exp);
}
/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.**
///
/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.** `sampler_kernel` is launched as a grid over TOKENS
@@ -208,57 +101,47 @@ __device__ __forceinline__ float apply_dry(float s, int v, const SamplerParams&
/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change.
__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab,
const int* __restrict__ history, int history_len, const SamplerParams p,
int pmin, int plen, int* __restrict__ out, const DryBreakers br) {
int pmin, int plen, int* __restrict__ out) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
(void) pmin;
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hbase) {
if (hrow) {
hlen = plen < history_len ? plen : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the penalty window is the TAIL
hrow += history_len - hlen; // the window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
// PENALTY MEMBERSHIP AS A BITMAP. The history touches at most `hlen` tokens of a quarter-million
// vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen)
// integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload).
// A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan;
// the counts - and therefore every sampled value - are exactly what the per-candidate scan produced.
// The bitmap spans the WIDEST of the penalty and DRY windows, so it also gates the DRY lookup.
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
// The gate needs a NON-EMPTY WINDOW (`wlen > 0`): the launch sizes the shared bitmap only when penalties or
// DRY are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
const bool use_bits = wrow != nullptr && bits_words > 0;
// The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties
// are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < wlen; i += blockDim.x)
if (wrow[i] >= 0 && wrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[wrow[i] >> 5], 1u << (wrow[i] & 31));
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
// `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no
// elements contributes nothing rather than contributing a bogus zero.
float bv = __int_as_float(0xff800000); // -inf
int best = n_vocab;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
float s = l[v];
if (use_bits && (penal_bits[v >> 5] & (1u << (v & 31)))) {
s = apply_penalties(s, history_count(hrow, hlen, v), p);
s = apply_dry(s, v, p, g_dry, br);
}
const float s = apply_penalties(l[v], hit_count(v), p);
if (s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
@@ -395,7 +278,7 @@ __global__ void __launch_bounds__(kAmThreads) sampler_greedy_cluster_kernel(cons
/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order.
__global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens,
const int* __restrict__ history, int history_len, const SamplerParams p,
int* __restrict__ out, const DryBreakers br) {
int* __restrict__ out) {
const int t = blockIdx.x;
if (t >= n_tokens) return;
const float* l = logits + (size_t) t * n_vocab;
@@ -406,38 +289,32 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
// The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this
// launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer).
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hbase) {
if (hrow) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the penalty window is the TAIL
hrow += history_len - hlen; // the window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
// the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there. The gate needs an
// NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties or DRY are on, so a caller that hands
// over a stale history buffer with `penalty_last_n == 0` must not touch it. The bitmap spans the widest of
// the penalty and DRY windows, so it gates the DRY lookup too.
// NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over
// a stale history buffer with `penalty_last_n == 0` must not touch it.
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
const bool use_bits = wrow != nullptr && bits_words > 0;
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < wlen; i += blockDim.x)
if (wrow[i] >= 0 && wrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[wrow[i] >> 5], 1u << (wrow[i] & 31));
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
// top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel
// keeps, 64. Every row writes out[t]: a verify window reads all of them.
@@ -461,11 +338,7 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
bool taken = false;
for (int j = 0; j < i; ++j) if (sel_ids[j] == v) { taken = true; break; }
if (taken) continue;
float s = l[v];
if (use_bits && (penal_bits[v >> 5] & (1u << (v & 31)))) {
s = apply_penalties(s, history_count(hrow, hlen, v), p);
s = apply_dry(s, v, p, g_dry, br);
}
const float s = apply_penalties(l[v], hit_count(v), p);
if (s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
@@ -651,38 +524,33 @@ __device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, in
/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run.
__global__ void __launch_bounds__(1024)
sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const SamplerParams p, int* __restrict__ out, const DryBreakers br) {
int history_len, const SamplerParams p, int* __restrict__ out) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
// the penalty window and its membership bitmap, exactly as in `sampler_kernel`
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hbase) {
if (hrow) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the penalty window is the TAIL
hrow += history_len - hlen; // the window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
const bool use_bits = wrow != nullptr && bits_words > 0;
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < wlen; i += blockDim.x)
if (wrow[i] >= 0 && wrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[wrow[i] >> 5], 1u << (wrow[i] & 31));
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
const int k = sampled_k(p.top_k, n_vocab);
__shared__ int sel_ids[kSelMax];
@@ -697,11 +565,7 @@ sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const in
float bv = __int_as_float(0xff800000); // -inf
int best = n_vocab;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
float s = l[v];
if (use_bits && (penal_bits[v >> 5] & (1u << (v & 31)))) {
s = apply_penalties(s, history_count(hrow, hlen, v), p);
s = apply_dry(s, v, p, g_dry, br);
}
const float s = apply_penalties(l[v], hit_count(v), p);
if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
@@ -795,44 +659,33 @@ __device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int
/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)).
__global__ void __launch_bounds__(kSplitWarps * 32)
sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand,
const DryBreakers br) {
int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) {
const int t = blockIdx.y;
const float* l = logits + (size_t) t * n_vocab;
const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
const int blo = (int) blockIdx.x * kSplitBlockSpan;
const int* hbase = history ? history + (size_t) t * history_len : nullptr;
const int* hrow = hbase;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hbase) {
if (hrow) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the penalty window is the TAIL
hrow += history_len - hlen; // the window is the TAIL
}
const int* drow = nullptr;
int dlen = 0;
if (hbase) dry_window(hbase, history_len, p.dry_penalty_last_n, drow, dlen);
const int wlen = hlen > dlen ? hlen : dlen;
const int* wrow = (hbase && wlen > 0) ? hbase + history_len - wlen : nullptr;
// The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test,
// and a hit pays the same exact count over the whole window. It spans the widest of the penalty and DRY
// windows, so it also gates the DRY lookup.
// and a hit pays the same exact count over the whole window.
__shared__ unsigned int bits[kSplitBlockSpan / 32];
const bool use_bits = wrow != nullptr;
const bool use_bits = hrow != nullptr && hlen > 0;
if (use_bits) {
for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < wlen; i += blockDim.x) {
const int h = wrow[i];
for (int i = threadIdx.x; i < hlen; i += blockDim.x) {
const int h = hrow[i];
if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan)
atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31));
}
__syncthreads();
}
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
__syncthreads();
// This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the
// bitmap's hits go through it. Past the vocabulary: -inf, which no round picks.
@@ -847,10 +700,8 @@ sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const i
#pragma unroll
for (int j = 0; j < kSplitPerLane; ++j) {
const int v = lo + 32 * j + lane, b = v - blo;
if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31)))) {
if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31))))
s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p);
s[j] = apply_dry(s[j], v, p, g_dry, br);
}
}
}
@@ -932,34 +783,23 @@ __global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const
/// subset has no logit here. Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it.
__global__ void coupled_penalize_kernel(float* __restrict__ logits, int nv, const int* __restrict__ id_to_sub,
int id_vocab, const SamplerParams* __restrict__ dp, const int* __restrict__ ring,
int cap, int j, const DryBreakers br) {
int cap, int j) {
const SamplerParams p = *dp;
const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap);
const int hd = strata::core::coupled_hist_len(p.dry_penalty_last_n, cap);
const int wlen = h > hd ? h : hd;
const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h); // the penalty sub-window
const int* drow = ring + cap + j - hd; // the DRY sub-window (dropping -1 padding)
int dlen = hd;
while (dlen > 0 && drow[0] == -1) { ++drow; --dlen; }
__shared__ DryShared g_dry;
if (threadIdx.x == 0) dry_build(g_dry, drow, dlen, dlen, p, br);
if (wlen <= 0) { __syncthreads(); return; }
const int* wrow = ring + cap + j - wlen; // the union: both lookups are gated by it
if (h <= 0) return;
const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h);
extern __shared__ unsigned int seen[];
const int words = (nv + 31) / 32;
for (int w = threadIdx.x; w < words; w += blockDim.x) seen[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < wlen; i += blockDim.x) {
const int v = wrow[i];
for (int i = threadIdx.x; i < h; i += blockDim.x) {
const int v = hrow[i];
if (v < 0 || v >= id_vocab) continue;
const int s = id_to_sub != nullptr ? id_to_sub[v] : v;
if (s < 0 || s >= nv) continue;
const unsigned bit = 1u << (s & 31);
if (atomicOr(&seen[s >> 5], bit) & bit) continue;
float x = logits[s];
x = apply_penalties(x, history_count(hrow, h, v), p);
x = apply_dry(x, v, p, g_dry, br);
logits[s] = x;
logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p);
}
}
@@ -1135,22 +975,14 @@ bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int*
}
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream, const DryBreakers& breakers) {
const SamplerParams& p, int* out, void* stream) {
if (n_tokens <= 0 || n_vocab <= 0) return;
const bool has_hist = history != nullptr && history_len > 0;
if (p.penalty_last_n > 0 && !has_hist) {
if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
p.penalty_last_n, (const void*) history, history_len);
std::exit(1);
}
if (dry_enabled(p) && !has_hist) {
std::fprintf(stderr, "sample_tokens: dry_penalty_last_n %d needs a history (got %p, len %d)\n",
p.dry_penalty_last_n, (const void*) history, history_len);
std::exit(1);
}
// The bitmap spans the widest of the penalty and DRY windows, so it is sized (and the cluster kernel, which
// needs shmem == 0, is disabled) when EITHER is on.
const unsigned shmem = (has_hist && (p.penalty_last_n > 0 || dry_enabled(p)))
const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0)
? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned) // the penalty bitmap
: 0;
if (p.greedy || p.temperature <= 0.0f) {
@@ -1164,12 +996,12 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
const int gthreads = 1024;
if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream)))
sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out, breakers);
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
} else if (sampled_path() == SampledPath::Old) {
// The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See
// `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, n_tokens, history, history_len, p, out, breakers);
logits, n_vocab, n_tokens, history, history_len, p, out);
} else {
// The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per
// row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge
@@ -1185,12 +1017,12 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
if (scratch != nullptr) {
sampler_split_part_kernel<<<dim3((unsigned) n_blocks, (unsigned) n_tokens), kSplitWarps * 32, 0,
(cudaStream_t) stream>>>(logits, n_vocab, history, history_len, p, k,
n_blocks, scratch, breakers);
n_blocks, scratch);
sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>(
scratch, n_blocks, n_vocab, p, k, out);
} else {
sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, out, breakers);
logits, n_vocab, history, history_len, p, out);
}
}
const cudaError_t e = cudaGetLastError();
@@ -1226,21 +1058,20 @@ void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapp
void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
void* scratch, int32_t* out_id, float* out_prob, void* stream, const DryBreakers& breakers) {
void* scratch, int32_t* out_id, float* out_prob, void* stream) {
const cudaStream_t s = (cudaStream_t) stream;
const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
std::exit(1);
}
coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(
logits, nv, id_to_sub, id_vocab, params, ring, cap, j, breakers);
coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub,
id_vocab, params, ring, cap, j);
coupled_check("coupled_penalize");
// the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list,
// since the request's top_k is only known on the device), penalties and DRY already applied above (the null
// history here keeps the split kernel from applying them a second time)
// since the request's top_k is only known on the device), penalties already applied above
sampler_split_part_kernel<<<dim3((unsigned) n_blocks, 1u), kSplitWarps * 32, 0, s>>>(
logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch, DryBreakers{});
logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch);
coupled_check("coupled_draft split part");
coupled_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id, ring,
cap, j, out_id, out_prob);
+4 -7
View File
@@ -164,8 +164,7 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re
const float* __restrict__ z,
const float* __restrict__ gamma, float eps,
float* __restrict__ y, int h_k, int h_v, int T,
const int32_t* __restrict__ n_keep, int t_out_begin,
int silu) {
const int32_t* __restrict__ n_keep, int t_out_begin) {
__shared__ float sk[S], sq[S];
__shared__ float red[RG][S];
__shared__ float wsum[S * RG / 32];
@@ -225,8 +224,7 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float scale = rsqrtf(ss / (float) S + eps);
const float zz = z[(size_t) t * value_dim + head * S + col];
const float act = silu ? zz / (1.0f + __expf(-zz)) : (1.0f / (1.0f + __expf(-zz))); // bitwise fused_gdn_step_norm
y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * act;
y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
}
}
if (n_keep != nullptr && n > 0) {
@@ -473,7 +471,7 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet
}
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, GdnGate act, float* y, int h_k, int h_v, int n_tok,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
const int32_t* n_keep, void* stream, int t_out_begin) {
if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 ||
n_tok > kVerifyMaxT) {
@@ -489,8 +487,7 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const
state, h, conv_channels, gate, beta, h_k, h_v, n_keep);
} else {
gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(
state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin,
act == GdnGate::Silu ? 1 : 0);
state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin);
}
check("gdn_step_norm_multi");
}
+195 -330
View File
@@ -1,5 +1,4 @@
// src/kernels/gdn_parity.cpp - P2.S2's test for the GDN recurrence, the conv and the two norms; Qwen3.6 step 3
// re-pins it at 32 value heads with the SiLU output gate.
// src/kernels/gdn_parity.cpp - P2.S2's test for the GDN recurrence, the conv and the two norms.
//
// `ref/gdn.py` carries eleven PROPERTY checks, several of which exist because a rival reading of the SOURCE
// produces well-formed output. The four that the kernels here can be wrong about are re-pinned below, each
@@ -16,30 +15,10 @@
// differs by sqrt(S) = 11.3x at S = 128. `ref/gdn.py` PROPERTY 1 instruments the derivation, so it is
// not taken on trust there either.
//
// and the fifth, the one numerical difference between the two models this engine serves (docs/QWEN36-35B-A3B.md
// 3.2, geometry-inventory.md row 39):
//
// 5. THE OUTPUT GATE. Flash-Next (`qwen4exp`, 16 k-heads / 48 v-heads) closes the layer with
// `rms_norm(o) * ssm_norm * sigmoid(z)`; Qwen3.6 (`qwen35moe`, 16 / 32) with `... * SiLU(z)`. Both are
// well-formed and the same size; the oracle's negative control puts them 1.07 relative L1 apart at
// `final_output-0`. Every output kernel takes the choice as `GdnGate`; here each geometry is run with ITS
// gate against a reference of its gate, and then the kernel is run with the OTHER gate and required to
// differ from that reference by more than 5% - the wrong reading fails through the kernel itself, not
// only on the host.
//
// It also checks the STATE LAYOUT, which is the one place these kernels intentionally differ from the
// reference: (S, h_v, S) with j fastest instead of (S, S, h_v). A layout mix-up is silent, so the state is
// filled with a value that encodes its own coordinates.
//
// Geometries: the recurrence and the output kernels run at BOTH head counts, 16/48 (VPK 3) and 16/32 (VPK 2),
// through all four implementations - the legacy `gdn_step` + `gdn_out_norm`, the pinned `native_gdn_step` +
// `native_gdn_out_norm`, the fused `fused_gdn_step_norm`, and the verify window's `gdn_step_norm_multi` (which
// must be bitwise the fused kernel per token).
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/gdn.hpp"
#include "strata/kernels/native_gdn.hpp"
#include "strata/kernels/native_gdn_preprocess.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include <cuda_runtime.h>
@@ -53,8 +32,6 @@
namespace {
using strata::kernels::GdnGate;
void check(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
@@ -63,17 +40,11 @@ void check(cudaError_t e, const char* what) {
}
float sigmoid_f(float x) { return 1.0f / (1.0f + std::exp(-x)); }
float silu_f(float x) { return x / (1.0f + std::exp(-x)); }
float gate_act(GdnGate g, float x) { return g == GdnGate::Silu ? silu_f(x) : sigmoid_f(x); }
const char* gate_name(GdnGate g) { return strata::kernels::gdn_gate_name(g); }
GdnGate other(GdnGate g) { return g == GdnGate::Silu ? GdnGate::Sigmoid : GdnGate::Silu; }
/// The reference's `gdn_step`, with switches for the rival readings.
///
/// `state` is passed in the REFERENCE layout (S, S, h_v) - i.e. (i, j, h) - so that this function is a
/// transcription of `ref/gdn.py` and not of the kernel. `q` is taken AS GIVEN: the legacy kernel wants it
/// pre-scaled by 1/sqrt(S), the native and fused kernels scale the readout themselves, so the caller passes the
/// scaled q here and the unscaled q to those kernels.
/// transcription of `ref/gdn.py` and not of the kernel.
void ref_step(std::vector<double>& state, const std::vector<float>& q, const std::vector<float>& k,
const std::vector<float>& v, const std::vector<float>& gate, const std::vector<float>& beta,
int S, int h_k, int h_v, std::vector<float>& o, bool modulo_heads, bool decay_first) {
@@ -98,19 +69,6 @@ void ref_step(std::vector<double>& state, const std::vector<float>& q, const std
o = oo;
}
/// `y = rms_norm(o, eps) * ssm_norm * act(z)`, one RMS per head (row), as `ref/gdn.py` / `ref/qwen36.py` write it.
void ref_out_norm(const std::vector<float>& o, const std::vector<float>& z, const std::vector<float>& sn, int h_v,
int S, float eps, GdnGate act, std::vector<float>& y) {
y.assign((size_t) h_v * S, 0.0f);
for (int h = 0; h < h_v; ++h) {
double acc = 0;
for (int i = 0; i < S; ++i) acc += (double) o[(size_t) (h * S + i)] * (double) o[(size_t) (h * S + i)];
const float inv = (float) (1.0 / std::sqrt(acc / S + (double) eps));
for (int i = 0; i < S; ++i)
y[(size_t) (h * S + i)] = o[(size_t) (h * S + i)] * inv * sn[(size_t) i] * gate_act(act, z[(size_t) (h * S + i)]);
}
}
/// `ref/gdn.py::conv_step` in its own (d_conv, C) row-major orientation.
void ref_conv(std::vector<float>& cs, const std::vector<float>& x, const std::vector<float>& kern, int C,
int dc, std::vector<float>& out) {
@@ -134,241 +92,6 @@ double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
return d / (m > 1e-30 ? m : 1e-30);
}
/// The device state (S, h_v, S), j fastest, read back into the reference layout and compared.
double state_rel(const std::vector<double>& want, const std::vector<float>& got_dev, int S, int h_v) {
double d = 0, m = 0;
for (int i = 0; i < S; ++i)
for (int j = 0; j < S; ++j)
for (int h = 0; h < h_v; ++h) {
const double w = want[(size_t) (i * S + j) * h_v + h];
d += std::fabs(w - (double) got_dev[(size_t) (i * h_v + h) * S + j]);
m += std::fabs(w);
}
return d / (m > 1e-30 ? m : 1e-30);
}
template <class T>
T* dev(const std::vector<T>& h, const char* what) {
T* p = nullptr;
check(cudaMalloc(&p, h.size() * sizeof(T) + 16), what);
check(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), what);
return p;
}
template <class T>
std::vector<T> host(const T* d, size_t n, const char* what) {
std::vector<T> h(n);
check(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), what);
return h;
}
int g_bad = 0;
void observable(const char* what, double rel) {
std::printf(" %-58s %-4s (%.2f%% apart)\n", what, rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
if (!(rel > 0.05)) ++g_bad;
}
void within(const char* what, double rel, double tol) {
std::printf(" %-58s rel %.3e%s\n", what, rel, rel <= tol ? "" : " *** over tolerance ***");
if (!(rel <= tol)) ++g_bad;
}
/// Sections 1 and 5 for one geometry: the recurrence through every implementation, the state layout, the output
/// gate with its negative case. `model_gate` is the gate the model with this head count uses.
void recurrence_and_gate(int S, int h_k, int h_v, GdnGate model_gate, std::mt19937& rng, cudaStream_t stream) {
std::normal_distribution<float> gauss(0.0f, 1.0f);
std::printf("\n== geometry S %d, h_k %d, h_v %d (VPK %d), model gate %s\n", S, h_k, h_v, h_v / h_k,
gate_name(model_gate));
// The state encodes its own coordinates, so a layout mix-up cannot pass: reading (i,j,h) where the
// buffer holds (i,h,j) gives a DIFFERENT number, not a wrong-but-plausible one.
std::vector<double> st_ref((size_t) S * S * h_v);
std::vector<float> st_dev((size_t) S * h_v * S);
for (int i = 0; i < S; ++i)
for (int j = 0; j < S; ++j)
for (int h = 0; h < h_v; ++h) {
const float val = (float) (0.001 * (i + 2 * j + 3 * h) - 1.0);
st_ref[(size_t) (i * S + j) * h_v + h] = val;
st_dev[(size_t) (i * h_v + h) * S + j] = val; // (S, h_v, S), j fastest
}
std::vector<float> q((size_t) h_k * S), k((size_t) h_k * S), v((size_t) h_v * S), gate((size_t) h_v),
beta((size_t) h_v), z((size_t) h_v * S), sn((size_t) S);
for (auto& x : q) x = gauss(rng) * 0.1f;
for (auto& x : k) x = gauss(rng) * 0.1f;
for (auto& x : v) x = gauss(rng);
for (auto& x : gate) x = -(2.0f + 4.0f * (float) (rng() % 100) / 100.0f); // dec in (0.0025, 0.135]
for (auto& x : beta) x = (float) (rng() % 100) / 100.0f;
for (auto& x : z) x = gauss(rng);
for (auto& x : sn) x = 1.0f + 0.1f * gauss(rng);
const float eps = 1e-6f;
const float rs = 1.0f / std::sqrt((float) S);
std::vector<float> q_scaled = q; // the legacy kernel's contract: q pre-scaled
for (auto& x : q_scaled) x *= rs;
std::vector<float> want_o; // o = (S q) / sqrt(S) - what every implementation emits
std::vector<double> st_mod = st_ref;
ref_step(st_mod, q_scaled, k, v, gate, beta, S, h_k, h_v, want_o, true, true);
std::vector<float> want_y, want_y_wrong;
ref_out_norm(want_o, z, sn, h_v, S, eps, model_gate, want_y);
ref_out_norm(want_o, z, sn, h_v, S, eps, other(model_gate), want_y_wrong);
// ---- the traps, observable before any kernel is judged
{
std::vector<double> a = st_ref;
std::vector<float> oo;
ref_step(a, q_scaled, k, v, gate, beta, S, h_k, h_v, oo, false, true);
observable("modulo vs interleave head pairing", rel_l1(want_o, oo));
}
{
std::vector<double> a = st_ref;
std::vector<float> oo;
ref_step(a, q_scaled, k, v, gate, beta, S, h_k, h_v, oo, true, false);
// The two readings differ by exactly `k (x) (beta * v * (1 - dec))`, so the fixture is only able
// to see the trap when `dec` is far from 1 and `beta` is far from 0. The first version used
// gate in [-0.99, 0] - dec in [0.37, 1] - and managed 3.25%, which is a threshold the wrong
// reading nearly clears. Deep decay is also the realistic regime: `ssm_a = -exp(A_log) < 0` and
// softplus is positive, so gate is comfortably negative in the real model.
observable("decay before vs after the update", rel_l1(want_o, oo));
}
{
char what[96];
std::snprintf(what, sizeof what, "%s vs %s on the output gate (host)", gate_name(model_gate),
gate_name(other(model_gate)));
observable(what, rel_l1(want_y, want_y_wrong));
}
// ---- device buffers
float* d_st = dev(st_dev, "st");
float* d_q = dev(q, "q");
float* d_qs = dev(q_scaled, "qs");
float* d_k = dev(k, "k");
float* d_v = dev(v, "v");
float* d_g = dev(gate, "g");
float* d_b = dev(beta, "b");
float* d_z = dev(z, "z");
float* d_sn = dev(sn, "sn");
float *d_o = nullptr, *d_y = nullptr;
check(cudaMalloc(&d_o, (size_t) h_v * S * 4), "o");
check(cudaMalloc(&d_y, (size_t) h_v * S * 4), "y");
const strata::kernels::GdnShapes sh{S, h_k, h_v};
auto reset_state = [&] { check(cudaMemcpy(d_st, st_dev.data(), st_dev.size() * 4, cudaMemcpyHostToDevice), "rst"); };
// The kernel accumulates in f32 and the reference in f64, and the state is a RECURRENCE over 128 terms,
// so 1e-5 is the arithmetic's floor here and not a structural allowance.
const double tol = 1e-5;
// ---- 1. legacy: gdn_step, then gdn_out_norm
{
reset_state();
strata::kernels::gdn_step(d_st, d_qs, d_k, d_v, d_g, d_b, d_o, sh, nullptr);
within("legacy gdn_step: o vs reference", rel_l1(want_o, host(d_o, want_o.size(), "o")), tol);
within("legacy gdn_step: state (read via (S,h_v,S)) vs reference",
state_rel(st_mod, host(d_st, st_dev.size(), "st"), S, h_v), tol);
strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, h_v, S, eps, model_gate, nullptr);
within("legacy gdn_out_norm: y vs reference", rel_l1(want_y, host(d_y, want_y.size(), "y")), tol);
strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, h_v, S, eps, other(model_gate), nullptr);
observable("legacy gdn_out_norm with the WRONG gate differs (negative)",
rel_l1(want_y, host(d_y, want_y.size(), "y")));
}
// ---- 2. pinned native: native_gdn_step (q unscaled, readout scaled), then native_gdn_out_norm
if (S == 128) {
reset_state();
strata::kernels::native_gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, stream);
check(cudaStreamSynchronize(stream), "native step");
within("native_gdn_step: o vs reference", rel_l1(want_o, host(d_o, want_o.size(), "o")), tol);
within("native_gdn_step: state vs reference", state_rel(st_mod, host(d_st, st_dev.size(), "st"), S, h_v), tol);
strata::kernels::native_gdn_out_norm(d_o, d_z, d_sn, d_y, h_v, S, eps, model_gate, stream);
check(cudaStreamSynchronize(stream), "native norm");
within("native_gdn_out_norm: y vs reference", rel_l1(want_y, host(d_y, want_y.size(), "y")), tol);
strata::kernels::native_gdn_out_norm(d_o, d_z, d_sn, d_y, h_v, S, eps, other(model_gate), stream);
check(cudaStreamSynchronize(stream), "native norm wrong");
observable("native_gdn_out_norm with the WRONG gate differs (negative)",
rel_l1(want_y, host(d_y, want_y.size(), "y")));
}
// ---- 3. fused: step + norm in one kernel (the default native decode path)
std::vector<float> fused_state, fused_y;
if (S == 128) {
reset_state();
strata::kernels::fused_gdn_step_norm(d_st, d_q, d_k, d_v, d_g, d_b, d_z, d_sn, eps, model_gate, d_y, h_k, h_v,
stream);
check(cudaStreamSynchronize(stream), "fused");
fused_state = host(d_st, st_dev.size(), "st");
fused_y = host(d_y, want_y.size(), "y");
within("fused_gdn_step_norm: state vs reference", state_rel(st_mod, fused_state, S, h_v), tol);
within("fused_gdn_step_norm: y vs reference", rel_l1(want_y, fused_y), tol);
reset_state();
strata::kernels::fused_gdn_step_norm(d_st, d_q, d_k, d_v, d_g, d_b, d_z, d_sn, eps, other(model_gate), d_y, h_k,
h_v, stream);
check(cudaStreamSynchronize(stream), "fused wrong");
observable("fused_gdn_step_norm with the WRONG gate differs (negative)",
rel_l1(want_y, host(d_y, want_y.size(), "y")));
}
// ---- 4. the verify window's kernel, one token: verify (state untouched) then commit (state written), and
// both bitwise the fused kernel
if (S == 128) {
const int C = 2 * h_k * S + h_v * S;
std::vector<float> hbuf((size_t) C);
std::memcpy(hbuf.data(), q.data(), q.size() * 4);
std::memcpy(hbuf.data() + q.size(), k.data(), k.size() * 4);
std::memcpy(hbuf.data() + 2 * q.size(), v.data(), v.size() * 4);
float* d_h = dev(hbuf, "h");
const std::vector<int32_t> keep1{1};
int32_t* d_keep = dev(keep1, "keep");
reset_state();
strata::kernels::gdn_step_norm_multi(d_st, d_h, C, d_g, d_b, d_z, d_sn, eps, model_gate, d_y, h_k, h_v, 1,
nullptr, stream, 0);
check(cudaStreamSynchronize(stream), "multi verify");
const std::vector<float> vy = host(d_y, want_y.size(), "y");
const std::vector<float> vst = host(d_st, st_dev.size(), "st");
within("gdn_step_norm_multi (verify): y vs reference", rel_l1(want_y, vy), tol);
const bool untouched = std::memcmp(vst.data(), st_dev.data(), st_dev.size() * 4) == 0;
std::printf(" %-58s %s\n", "gdn_step_norm_multi (verify) leaves the state untouched", untouched ? "yes" : "*** NO ***");
if (!untouched) ++g_bad;
const bool bit_y = std::memcmp(vy.data(), fused_y.data(), vy.size() * 4) == 0;
std::printf(" %-58s %s\n", "gdn_step_norm_multi y is BITWISE fused_gdn_step_norm", bit_y ? "yes" : "*** NO ***");
if (!bit_y) ++g_bad;
strata::kernels::gdn_step_norm_multi(d_st, d_h, C, d_g, d_b, d_z, d_sn, eps, model_gate, d_y, h_k, h_v, 1,
d_keep, stream, 0);
check(cudaStreamSynchronize(stream), "multi commit");
const std::vector<float> cst = host(d_st, st_dev.size(), "st");
const bool bit_st = std::memcmp(cst.data(), fused_state.data(), cst.size() * 4) == 0;
std::printf(" %-58s %s\n", "gdn_step_norm_multi (commit) state is BITWISE the fused state", bit_st ? "yes" : "*** NO ***");
if (!bit_st) ++g_bad;
// the split commit kernel (t_out_begin >= n_tok, no outputs): the same state, bitwise
reset_state();
strata::kernels::gdn_step_norm_multi(d_st, d_h, C, d_g, d_b, d_z, d_sn, eps, model_gate, d_y, h_k, h_v, 1,
d_keep, stream, 1);
check(cudaStreamSynchronize(stream), "multi commit split");
const std::vector<float> sst = host(d_st, st_dev.size(), "st");
const bool bit_split = std::memcmp(sst.data(), fused_state.data(), sst.size() * 4) == 0;
std::printf(" %-58s %s\n", "gdn_step_norm_multi (split commit) state is BITWISE the fused state", bit_split ? "yes" : "*** NO ***");
if (!bit_split) ++g_bad;
reset_state();
strata::kernels::gdn_step_norm_multi(d_st, d_h, C, d_g, d_b, d_z, d_sn, eps, other(model_gate), d_y, h_k, h_v, 1,
nullptr, stream, 0);
check(cudaStreamSynchronize(stream), "multi wrong");
observable("gdn_step_norm_multi with the WRONG gate differs (negative)",
rel_l1(want_y, host(d_y, want_y.size(), "y")));
cudaFree(d_h); cudaFree(d_keep);
}
// a zero state stays zero, and a zero gate/beta leaves the state untouched (the reference's
// PROPERTY 4 setup) - a cheap independent invariant that no layout can fake
{
std::vector<float> zero(st_dev.size(), 0.0f), zg((size_t) h_v, 0.0f), zb((size_t) h_v, 0.0f);
check(cudaMemcpy(d_st, zero.data(), zero.size() * 4, cudaMemcpyHostToDevice), "z0");
check(cudaMemcpy(d_g, zg.data(), zg.size() * 4, cudaMemcpyHostToDevice), "z1");
check(cudaMemcpy(d_b, zb.data(), zb.size() * 4, cudaMemcpyHostToDevice), "z2");
strata::kernels::gdn_step(d_st, d_qs, d_k, d_v, d_g, d_b, d_o, sh, nullptr);
double nz = 0;
for (float x : host(d_st, zero.size(), "z3")) nz += std::fabs(x);
const bool ok = nz == 0.0;
std::printf(" %-58s %s\n", "gate=beta=0 from a zero state is a no-op", ok ? "yes" : "*** NO ***");
if (!ok) ++g_bad;
}
cudaFree(d_st); cudaFree(d_q); cudaFree(d_qs); cudaFree(d_k); cudaFree(d_v); cudaFree(d_g); cudaFree(d_b);
cudaFree(d_z); cudaFree(d_sn); cudaFree(d_o); cudaFree(d_y);
}
} // namespace
int main(int argc, char** argv) {
@@ -378,19 +101,125 @@ int main(int argc, char** argv) {
else { std::fprintf(stderr, "usage: gdn_parity [--selftest]\n"); return 2; }
}
const int S = 128, h_k = 16, h_v = 48; // the artifact's real geometry
std::mt19937 rng(2024);
std::normal_distribution<float> gauss(0.0f, 1.0f);
cudaStream_t stream = nullptr;
// A BLOCKING stream, deliberately: the fixtures are reset with pageable `cudaMemcpy`, which may return before the
// DMA lands, and a non-blocking stream does not order after the legacy stream - the first version of this test
// raced its own resets and reported the native kernels 7.5x off at one geometry and exact at the other.
check(cudaStreamCreate(&stream), "stream");
int bad = 0;
// ================= 1 + 5. the recurrence and the output gate, at both models' geometries =================
// Flash-Next: 16 k-heads / 48 v-heads, sigmoid. Qwen3.6-35B-A3B: 16 / 32, SiLU (the sigmoid run is its negative).
recurrence_and_gate(128, 16, 48, GdnGate::Sigmoid, rng, stream);
recurrence_and_gate(128, 16, 32, GdnGate::Silu, rng, stream);
int bad = g_bad;
// ================= 1. the recurrence =================
{
// The state encodes its own coordinates, so a layout mix-up cannot pass: reading (i,j,h) where the
// buffer holds (i,h,j) gives a DIFFERENT number, not a wrong-but-plausible one.
std::vector<double> st_ref((size_t) S * S * h_v);
std::vector<float> st_dev((size_t) S * h_v * S);
for (int i = 0; i < S; ++i)
for (int j = 0; j < S; ++j)
for (int h = 0; h < h_v; ++h) {
const float val = (float) (0.001 * (i + 2 * j + 3 * h) - 1.0);
st_ref[(size_t) (i * S + j) * h_v + h] = val;
st_dev[(size_t) (i * h_v + h) * S + j] = val; // (S, h_v, S), j fastest
}
std::vector<float> q((size_t) h_k * S), k((size_t) h_k * S), v((size_t) h_v * S), gate((size_t) h_v),
beta((size_t) h_v);
for (auto& x : q) x = gauss(rng) * 0.1f;
for (auto& x : k) x = gauss(rng) * 0.1f;
for (auto& x : v) x = gauss(rng);
for (auto& x : gate) x = -(2.0f + 4.0f * (float) (rng() % 100) / 100.0f); // dec in (0.0025, 0.135]
for (auto& x : beta) x = (float) (rng() % 100) / 100.0f;
std::vector<float> want_o;
std::vector<double> st_mod = st_ref;
ref_step(st_mod, q, k, v, gate, beta, S, h_k, h_v, want_o, true, true);
// the traps
{
std::vector<double> a = st_ref;
std::vector<float> oo;
ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, false, true);
const double rel = rel_l1(want_o, oo);
std::printf(" %-42s %-4s (%.2f%% apart)\n", "modulo vs interleave head pairing",
rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
if (!(rel > 0.05)) ++bad;
}
{
std::vector<double> a = st_ref;
std::vector<float> oo;
ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, true, false);
const double rel = rel_l1(want_o, oo);
std::printf(" %-42s %-4s (%.2f%% apart)\n", "decay before vs after the update",
rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
// The two readings differ by exactly `k (x) (beta * v * (1 - dec))`, so the fixture is only able
// to see the trap when `dec` is far from 1 and `beta` is far from 0. The first version used
// gate in [-0.99, 0] - dec in [0.37, 1] - and managed 3.25%, which is a threshold the wrong
// reading nearly clears. Deep decay is also the realistic regime: `ssm_a = -exp(A_log) < 0` and
// softplus is positive, so gate is comfortably negative in the real model.
if (!(rel > 0.05)) ++bad;
}
// the kernel
float *d_st = nullptr, *d_q = nullptr, *d_k = nullptr, *d_v = nullptr, *d_g = nullptr, *d_b = nullptr,
*d_o = nullptr;
check(cudaMalloc(&d_st, st_dev.size() * 4), "st");
check(cudaMalloc(&d_q, q.size() * 4), "q");
check(cudaMalloc(&d_k, k.size() * 4), "k");
check(cudaMalloc(&d_v, v.size() * 4), "v");
check(cudaMalloc(&d_g, gate.size() * 4), "g");
check(cudaMalloc(&d_b, beta.size() * 4), "b");
check(cudaMalloc(&d_o, (size_t) h_v * S * 4), "o");
check(cudaMemcpy(d_st, st_dev.data(), st_dev.size() * 4, cudaMemcpyHostToDevice), "cst");
check(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "cq");
check(cudaMemcpy(d_k, k.data(), k.size() * 4, cudaMemcpyHostToDevice), "ck");
check(cudaMemcpy(d_v, v.data(), v.size() * 4, cudaMemcpyHostToDevice), "cv");
check(cudaMemcpy(d_g, gate.data(), gate.size() * 4, cudaMemcpyHostToDevice), "cg");
check(cudaMemcpy(d_b, beta.data(), beta.size() * 4, cudaMemcpyHostToDevice), "cb");
strata::kernels::GdnShapes sh{S, h_k, h_v};
strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr);
std::vector<float> got_o((size_t) h_v * S), got_st(st_dev.size());
check(cudaMemcpy(got_o.data(), d_o, got_o.size() * 4, cudaMemcpyDeviceToHost), "cgo");
check(cudaMemcpy(got_st.data(), d_st, got_st.size() * 4, cudaMemcpyDeviceToHost), "cgst");
// o, and the STATE read back through the declared layout
const double rel_o = rel_l1(want_o, got_o);
double rel_st = 0, mag_st = 0;
for (int i = 0; i < S; ++i)
for (int j = 0; j < S; ++j)
for (int h = 0; h < h_v; ++h) {
const size_t dev = (size_t) (i * h_v + h) * S + j;
const double w = st_mod[(size_t) (i * S + j) * h_v + h];
rel_st += std::fabs(w - (double) got_st[dev]);
mag_st += std::fabs(w);
}
rel_st /= (mag_st > 1e-30 ? mag_st : 1e-30);
std::printf("\n %-42s rel %.3e\n", "o vs reference", rel_o);
std::printf(" %-42s rel %.3e\n", "state (read via (S,h_v,S)) vs reference", rel_st);
// The kernel accumulates in f32 and the reference in f64, and the state is a RECURRENCE over 128
// terms, so 1e-5 is the arithmetic's floor here and not a structural allowance.
if (!(rel_o <= 1e-5)) { std::printf(" *** o over 1e-5 ***\n"); ++bad; }
if (!(rel_st <= 1e-5)) { std::printf(" *** state over 1e-5 ***\n"); ++bad; }
// a zero state stays zero, and a zero gate/beta leaves the state untouched (the reference's
// PROPERTY 4 setup) - a cheap independent invariant that no layout can fake
{
std::vector<float> zero(st_dev.size(), 0.0f), zg((size_t) h_v, 0.0f), zb((size_t) h_v, 0.0f);
check(cudaMemcpy(d_st, zero.data(), zero.size() * 4, cudaMemcpyHostToDevice), "z0");
check(cudaMemcpy(d_g, zg.data(), zg.size() * 4, cudaMemcpyHostToDevice), "z1");
check(cudaMemcpy(d_b, zb.data(), zb.size() * 4, cudaMemcpyHostToDevice), "z2");
strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr);
std::vector<float> zz(zero.size());
check(cudaMemcpy(zz.data(), d_st, zz.size() * 4, cudaMemcpyDeviceToHost), "z3");
double nz = 0;
for (float x : zz) nz += std::fabs(x);
const bool ok = nz == 0.0;
std::printf(" %-42s %s\n", "gate=beta=0 from a zero state is a no-op", ok ? "yes" : "*** NO ***");
if (!ok) ++bad;
}
// ephemeral state: unchanged when the state is untouched but beta=1 — the delta rule writing k*d
cudaFree(d_st); cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_g); cudaFree(d_b); cudaFree(d_o);
}
// ================= 2. the conv =================
{
@@ -412,6 +241,12 @@ int main(int argc, char** argv) {
for (int c = 0; c < C; ++c) d[(size_t) (c * (dc - 1) + i)] = r[(size_t) (i * C + c)];
return d;
};
auto to_ref_layout = [&](const std::vector<float>& d) {
std::vector<float> r(d.size());
for (int i = 0; i < dc - 1; ++i)
for (int c = 0; c < C; ++c) r[(size_t) (i * C + c)] = d[(size_t) (c * (dc - 1) + i)];
return r;
};
std::vector<float> cs = to_dev_layout(cs_ref);
std::vector<float> want;
@@ -438,18 +273,29 @@ int main(int argc, char** argv) {
a += (double) x[(size_t) c] * (double) kW_wrong[(size_t) (c * dc + dc - 1)];
out_bad[(size_t) c] = (float) a;
}
std::printf("\n== the conv\n");
observable("conv weight layout is observable", rel_l1(want, out_bad));
const double rel = rel_l1(want, out_bad);
std::printf("\n %-42s %-4s (%.1f%% apart)\n", "conv weight layout is observable",
rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
if (!(rel > 0.05)) ++bad;
}
float* d_cs = dev(cs, "cs");
float* d_x = dev(x, "cx");
float* d_w = dev(kW, "cw");
float* d_o = nullptr;
float *d_cs = nullptr, *d_x = nullptr, *d_w = nullptr, *d_o = nullptr;
check(cudaMalloc(&d_cs, cs.size() * 4), "cs");
check(cudaMalloc(&d_x, x.size() * 4), "cx");
check(cudaMalloc(&d_w, kW.size() * 4), "cw");
check(cudaMalloc(&d_o, (size_t) C * 4), "co");
check(cudaMemcpy(d_cs, cs.data(), cs.size() * 4, cudaMemcpyHostToDevice), "ccs");
check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "ccx");
check(cudaMemcpy(d_w, kW.data(), kW.size() * 4, cudaMemcpyHostToDevice), "ccw");
strata::kernels::gdn_conv_step(d_cs, d_x, d_w, d_o, C, dc, nullptr);
within("conv out vs reference", rel_l1(want, host(d_o, (size_t) C, "cgo")), 1e-6);
within("conv state slide (mapped) vs reference", rel_l1(cs_want, host(d_cs, cs.size(), "cgs")), 1e-6);
std::vector<float> got((size_t) C), got_cs(cs.size());
check(cudaMemcpy(got.data(), d_o, got.size() * 4, cudaMemcpyDeviceToHost), "cgo");
check(cudaMemcpy(got_cs.data(), d_cs, got_cs.size() * 4, cudaMemcpyDeviceToHost), "cgs");
const double rel_out = rel_l1(want, got), rel_cs = rel_l1(cs_want, got_cs);
std::printf(" %-42s rel %.3e\n", "conv out vs reference", rel_out);
std::printf(" %-42s rel %.3e\n", "conv state slide (mapped) vs reference", rel_cs);
if (!(rel_out <= 1e-6)) { std::printf(" *** conv out ***\n"); ++bad; }
if (!(rel_cs <= 1e-6)) { std::printf(" *** conv state ***\n"); ++bad; }
cudaFree(d_cs); cudaFree(d_x); cudaFree(d_w); cudaFree(d_o);
}
@@ -477,55 +323,74 @@ int main(int argc, char** argv) {
const float inv = (float) (1.0 / std::sqrt(acc / cols + (double) eps));
for (int i = 0; i < cols; ++i) x_mean[(size_t) (r * cols + i)] *= inv;
}
std::printf("\n== l2_norm\n");
observable("eps on sum vs on mean is observable", rel_l1(x_ref, x_mean));
const double rel_trap = rel_l1(x_ref, x_mean);
std::printf("\n %-42s %-4s (%.1f%% apart)\n", "eps on sum vs on mean is observable",
rel_trap > 0.05 ? "yes" : "*** NO ***", rel_trap * 100);
if (!(rel_trap > 0.05)) ++bad;
float* d_x = dev(x, "lx");
float* d_x = nullptr;
check(cudaMalloc(&d_x, x.size() * 4), "lx");
check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "lcx");
strata::kernels::gdn_l2_norm(d_x, rows, cols, eps, nullptr);
within("l2_norm vs reference", rel_l1(x_ref, host(d_x, x.size(), "lcg")), 1e-6);
std::vector<float> got(x.size());
check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "lcg");
const double rel = rel_l1(x_ref, got);
std::printf(" %-42s rel %.3e\n", "l2_norm vs reference", rel);
if (!(rel <= 1e-6)) ++bad;
cudaFree(d_x);
}
// ================= 4. the closing norm on its own, both gates through both single-purpose kernels =================
// ================= 4. the closing norm =================
{
const int S2 = 128, hv2 = 8;
std::vector<float> o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) S2);
std::vector<float> o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) S2), y_ref((size_t) hv2 * S2);
for (auto& val : o) val = gauss(rng);
for (auto& val : z) val = gauss(rng);
for (auto& val : sn) val = 1.0f + 0.1f * gauss(rng);
const float eps = 1e-6f;
std::vector<float> y_sig, y_silu;
ref_out_norm(o, z, sn, hv2, S2, eps, GdnGate::Sigmoid, y_sig);
ref_out_norm(o, z, sn, hv2, S2, eps, GdnGate::Silu, y_silu);
std::printf("\n== the closing norm, both gates\n");
observable("sigmoid vs SiLU on the gate is observable", rel_l1(y_sig, y_silu));
float* d_o = dev(o, "no");
float* d_z = dev(z, "nz");
float* d_sn = dev(sn, "ns");
float* d_y = nullptr;
check(cudaMalloc(&d_y, y_sig.size() * 4), "ny");
for (GdnGate gt : {GdnGate::Sigmoid, GdnGate::Silu}) {
const std::vector<float>& want = gt == GdnGate::Silu ? y_silu : y_sig;
const std::vector<float>& wrong = gt == GdnGate::Silu ? y_sig : y_silu;
char what[96];
strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, hv2, S2, eps, gt, nullptr);
std::vector<float> got = host(d_y, want.size(), "ncy");
std::snprintf(what, sizeof what, "gdn_out_norm(%s) vs reference", gate_name(gt));
within(what, rel_l1(want, got), 1e-6);
std::snprintf(what, sizeof what, "gdn_out_norm(%s) vs the other gate's reference", gate_name(gt));
observable(what, rel_l1(wrong, got));
strata::kernels::native_gdn_out_norm(d_o, d_z, d_sn, d_y, hv2, S2, eps, gt, stream);
check(cudaStreamSynchronize(stream), "nn");
got = host(d_y, want.size(), "nny");
std::snprintf(what, sizeof what, "native_gdn_out_norm(%s) vs reference", gate_name(gt));
within(what, rel_l1(want, got), 1e-5);
for (int h = 0; h < hv2; ++h) {
double acc = 0;
for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)];
const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps));
for (int i = 0; i < S2; ++i)
y_ref[(size_t) (h * S2 + i)] = o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] *
sigmoid_f(z[(size_t) (h * S2 + i)]);
}
float *d_o = nullptr, *d_z = nullptr, *d_sn = nullptr, *d_y = nullptr;
check(cudaMalloc(&d_o, o.size() * 4), "no");
check(cudaMalloc(&d_z, z.size() * 4), "nz");
check(cudaMalloc(&d_sn, sn.size() * 4), "ns");
check(cudaMalloc(&d_y, y_ref.size() * 4), "ny");
check(cudaMemcpy(d_o, o.data(), o.size() * 4, cudaMemcpyHostToDevice), "nco");
check(cudaMemcpy(d_z, z.data(), z.size() * 4, cudaMemcpyHostToDevice), "ncz");
check(cudaMemcpy(d_sn, sn.data(), sn.size() * 4, cudaMemcpyHostToDevice), "ncs");
strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, hv2, S2, eps, nullptr);
std::vector<float> got(y_ref.size());
check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "ncy");
const double rel = rel_l1(y_ref, got);
std::printf("\n %-42s rel %.3e\n", "out norm (rms * ssm_norm * sigmoid z)", rel);
if (!(rel <= 1e-6)) ++bad;
// SiLU instead of sigmoid is the qwen3.5 reading; `ref/gdn.py` says this artifact does NOT use it
std::vector<float> y_silu(y_ref.size());
for (int h = 0; h < hv2; ++h) {
double acc = 0;
for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)];
const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps));
for (int i = 0; i < S2; ++i) {
const float zz = z[(size_t) (h * S2 + i)];
y_silu[(size_t) (h * S2 + i)] =
o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] * (zz / (1.0f + std::exp(-zz)));
}
}
const double rel_silu = rel_l1(y_ref, y_silu);
std::printf(" %-42s %-4s (%.2f%% apart)\n", "sigmoid vs SiLU on the gate is observable",
rel_silu > 0.05 ? "yes" : "*** NO ***", rel_silu * 100);
if (!(rel_silu > 0.05)) ++bad;
cudaFree(d_o); cudaFree(d_z); cudaFree(d_sn); cudaFree(d_y);
}
bad = g_bad;
std::printf("\ngdn: %d failures\n", bad);
cudaStreamDestroy(stream);
if (bad) return 1;
if (selftest) std::printf("gdn_parity OK\n");
return 0;
-1
View File
@@ -405,7 +405,6 @@ int main(int argc, char** argv) {
for (int gu : {16, 17, 18, 21, 22, 23, 29, 42}) {
for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng); // the model's shape
check_grouped(gu, 23, 1024, 512, s, rng); // IQ4_XS down needs n_ff % 256 == 0
check_grouped(gu, 18, 1024, 512, s, rng); // IQ3_XXS down (Qwen3.6 UD-IQ3_XXS)
}
check_q8_1_finite(s, rng);
if (do_bench) bench(s, rng);
+2 -12
View File
@@ -333,18 +333,8 @@ int main() {
// AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs
std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");
#else
// below sm_70 the host refuses by design (no mma.sync) and prefill takes the batched decode kernel,
// which case [4/4] above holds to the same reference: the engine's own fallback, not a failure
int dev = 0, major = 0;
ck(cudaGetDevice(&dev), "device");
ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc");
if (major < 7) {
std::printf("[5/5] qsa_prompt_attn mode 3: SKIP (sm_%d has no tensor-core prompt kernel; prefill runs the "
"batched decode kernel of [4/4] there)\n", major);
} else {
std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
g_fail = 1;
}
std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
g_fail = 1;
#endif
} else {
k::fwht256_inplace_cuda(d_at4, QH, nullptr);
+14 -85
View File
@@ -1,23 +1,14 @@
// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways.
//
// build/native_expert_parity [--geom HxFF] <shard.gguf> [layer ...] real rows (a split model's shards are
// found by name); expert 7 of each layer
// build/native_expert_parity [--geom HxFF] --synthetic GU/DOWN ... random weights quantized by ggml
// (e.g. q4_K/q5_1, iq2_s/iq3_xxs)
// build/native_expert_parity <shard.gguf> [layer ...] real rows (a split model's shards are found by name)
// build/native_expert_parity --synthetic GU/DOWN ... random weights quantized by ggml (e.g. q4_K/q5_1)
// build/native_expert_parity --q5_1-min the Q5_1 min term on crafted activations
//
// --geom gives n_embd x n_ff (default 2560x640, Flash-Next's; Qwen3.6-35B-A3B is 2048x512).
//
// (a) float reference: ggml's own dequantizer (`to_float`) and a float SwiGLU expert, (b) the CPU path
// (ggml-cpu vec_dot with its quantized activations), (c) the GPU path (`native_expert_grouped`, q8_1
// activations). (b) and (c) each differ from (a) by their activation rounding only (a few 1e-3 relative). (c) runs
// twice, with the kernels that decode a weight part once for all entries and with the per-entry ones: bitwise equal.
// (d) the GPU dequantizers of the prompt path and the embedding against `to_float` (Q8_0: bit for bit).
// (e) the negative control: the high byte of one block's fp16 scale flipped (its sign) in one down row must move
// that row's GPU output by more than 1e-2 relative for a 256-value block of a 512-wide row (Qwen3.6's down types),
// the gate scaled by the block's share of the row for the others (a 32-value block of Flash-Next's 640: 1e-3; the
// sign flip of one of 20 blocks measured 8e-3 to 1.4e-2), and no other row by any bit; the same in one gate row must
// move the output at all (more than 1e-4 relative over every row: one of n_ff SwiGLU terms changes).
// The synthetic mode and (d) follow eddoursul/Strata 8029fa9.
#include "strata/artifact/gguf_reader.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
@@ -35,7 +26,6 @@
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <chrono>
#include <cmath>
#include <cstdio>
@@ -56,26 +46,7 @@ static double rel(const std::vector<float>& a, const std::vector<float>& b) {
namespace {
constexpr int NT = 3, E = 7;
int64_t H = 2560, FF = 640; // --geom
// byte offset of the block's fp16 scale `d` inside a block of this type (the negative control flips its high byte)
size_t scale_byte(int type) {
switch (type) {
case 14: return ggml_type_size(GGML_TYPE_Q6_K) - sizeof(ggml_fp16_t); // block_q6_K: ql, qh, scales, then d
case 29: return 55; // IQ1_M: the top nibble of the last scale word
default: return 0; // every other format starts with d (or dm: d is its low half)
}
}
// the GPU path on one blob, one group of the NT entries (the activations already in `dxq`)
void gpu_expert(const strata::kernels::NativeExpertLayout& L, const std::vector<uint8_t>& blob, void* dblob,
const void* dxq, void* dscr, float* dout, unsigned long long* dptr, const int32_t* dstart,
const int32_t* dn, const int32_t* ddst, const int32_t* dtok, std::vector<float>& got, cudaStream_t s) {
cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice);
strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s);
cudaStreamSynchronize(s);
cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost);
}
constexpr int64_t H = 2560, FF = 640;
// The three ways and the dequantizers for one expert blob; returns the number of failed checks.
int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int seed, const std::string& label,
@@ -332,36 +303,9 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice);
strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s);
gpu_expert(L, blob, dblob, dxq, dscr, dout, dptr, dstart, dn, ddst, dtok, got_g, s);
{ // (e) the negative control: a flipped scale byte in one down row, then in one gate row
const int64_t rd = 5 % H, rg = 3 % FF; // the corrupted rows
std::vector<uint8_t> bad = blob;
bad[f.down_off + (size_t) rd * f.d_row + scale_byte(f.d_type)] ^= 0x80;
std::vector<float> got_bad(got_g.size());
gpu_expert(L, bad, dblob, dxq, dscr, dout, dptr, dstart, dn, ddst, dtok, got_bad, s);
double num = 0, den = 0;
size_t other_rows_differ = 0;
for (int k = 0; k < NT; ++k)
for (int64_t r = 0; r < H; ++r) {
const float a = got_bad[(size_t) (k * H + r)], b = got_g[(size_t) (k * H + r)];
if (r == rd) { num += std::fabs((double) a - b); den += std::fabs((double) b); }
else other_rows_differ += std::memcmp(&a, &b, 4) != 0;
}
const double rel_down = num / (den + 1e-30);
bad = blob;
bad[(size_t) rg * f.gu_row + scale_byte(f.gu_type)] ^= 0x80;
gpu_expert(L, bad, dblob, dxq, dscr, dout, dptr, dstart, dn, ddst, dtok, got_bad, s);
const double rel_gate = rel(got_bad, got_g);
const double gate_down = 1e-2 * ((double) ggml_blck_size((ggml_type) f.d_type) / 256.0) * (512.0 / (double) FF);
const bool seen = rel_down > gate_down && other_rows_differ == 0 && rel_gate > 1e-4 &&
std::isfinite(rel_down) && std::isfinite(rel_gate);
std::printf(" negative control: down row %lld's scale byte flipped moves that row by rel %.2e "
"(> %.1e) and %zu other rows by any bit (0); gate row %lld's moves the output by rel %.2e "
"(> 1e-4): %s\n", (long long) rd, rel_down, gate_down, other_rows_differ, (long long) rg,
rel_gate, seen ? "yes" : "*** NO ***");
if (!seen) ++failures;
cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice); // the good blob back for (c2), (d)
}
strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s);
cudaStreamSynchronize(s);
cudaMemcpy(got_g.data(), dout, got_g.size() * 4, cudaMemcpyDeviceToHost);
{ // the kernels that decode a weight part once for the NT entries, bitwise vs the per-entry ones (#242;
// the formats without a decode-once split take the per-entry kernels either way)
std::vector<float> old_g(got_g.size());
@@ -423,16 +367,10 @@ int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int se
cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);
}
const double ec = rel(got_c, ref), eg = rel(got_g, ref), ecg = rel(got_c, got_g);
// GPU vs the float reference: the tolerance policy's bound for a Q8-activation path (oracle-crosscheck.md: the Q8
// oracle's ffn_moe_out max 5.3e-3 x 4), measured 9.7e-3 to 1.3e-2 on Qwen3.6's five pairs; 3e-2 for a pair with a
// Q5_0 role (32-value blocks with no min on a 640-wide row: q4_K/q5_0 measured 2.7e-2; see the CMake note). CPU
// vs the reference: ggml-cpu rounds the activations to Q8_K (256-value blocks, one scale per 256 values, against
// the GPU's q8_1 per 32), measured up to 2.2e-2, so 3e-2. CPU vs GPU: both roundings, measured up to 2.4e-2, 4e-2.
const double gpu_bound = (f.gu_type == 6 || f.d_type == 6) ? 3e-2 : 2e-2;
const bool ok = ec < 3e-2 && eg < gpu_bound && ecg < 4e-2 && std::isfinite(ec) && std::isfinite(eg) && std::isfinite(ecg);
std::printf("%-9s %-8s/%-7s blob %8zu cpu rel %.2e (< 3e-2) gpu rel %.2e (< %.0e) cpu-gpu %.2e (< 4e-2) %s\n",
label.c_str(), ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec,
eg, gpu_bound, ecg, ok ? "ok" : "FAIL");
const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg);
std::printf("%-9s %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n", label.c_str(),
ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, eg, ecg,
ok ? "ok" : "FAIL");
return failures + (ok ? 0 : 1);
}
@@ -607,22 +545,13 @@ int main(int argc, char** argv) {
int failures = 0;
cudaStream_t s;
cudaStreamCreate(&s);
int ai = 1;
if (std::string(argv[ai]) == "--geom") {
if (argc < 4 || std::sscanf(argv[ai + 1], "%lldx%lld", (long long*) &H, (long long*) &FF) != 2 || H <= 0 || FF <= 0) {
std::fprintf(stderr, "--geom takes HxFF, e.g. 2048x512\n");
return 2;
}
ai += 2;
}
const std::string mode = argv[ai];
std::printf("geometry n_embd %lld x n_ff %lld\n", (long long) H, (long long) FF);
const std::string mode = argv[1];
if (mode == "--q5_1-min") {
failures += check_q5_1_min(s);
} else if (mode == "--bf16-embd") {
failures += check_bf16_embd(s);
} else if (mode == "--synthetic") {
for (int i = ai + 1; i < argc; ++i) {
for (int i = 2; i < argc; ++i) {
const std::string arg = argv[i];
const size_t slash = arg.find('/');
const int gu = slash == std::string::npos ? -1 : type_of(arg.substr(0, slash));
@@ -638,9 +567,9 @@ int main(int argc, char** argv) {
failures += check_blob(f, synthetic_blob(f, i), i, "synthetic", s);
}
} else {
const strata::GgufModel model(strata::gguf_split_paths(argv[ai]));
const strata::GgufModel model(strata::gguf_split_paths(argv[1]));
std::vector<int> layers;
for (int i = ai + 1; i < argc; ++i) layers.push_back(std::atoi(argv[i]));
for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i]));
if (layers.empty()) layers = {0, 1, 2, 3, 20, 47};
for (int l : layers) {
const strata::TensorInfo* t[3] = {};
+8 -58
View File
@@ -2,10 +2,8 @@
// q8_1 pass, against the launches before them (native_grouped_set_v1: a block row per possible group, SwiGLU and the
// q8_1 quantization as two kernels over all cap_entries). Synthetic blobs, no model.
//
// build/native_grouped_parity the checks (a ctest; needs the GPU)
// build/native_grouped_parity --bench the checks, then v1/new timings of 48 calls in a graph (a window's layers)
// build/native_grouped_parity --bench-down the checks, then the down kernel alone per expert, each down type at
// Qwen3.6's 2048 x 512 (the step-5 budget: Q5_1 is the comparator)
// build/native_grouped_parity the checks (a ctest; needs the GPU)
// build/native_grouped_parity --bench the checks, then v1/new timings of 48 calls in a graph (a window's layers)
//
// Every gate/up format with every down format; calls of 0..cap groups of 1..T entries each (an empty call is what the
// verify window's PCIe call usually is), entries from 0 and from past 0 (the PCIe call's follow the VRAM call's),
@@ -62,7 +60,6 @@ const char* name_of(int t) {
case 42: return "Q2_0";
case 12: return "Q4_K";
case 13: return "Q5_K";
case 14: return "Q6_K";
case 7: return "Q5_1";
case 8: return "Q8_0";
default: return "?";
@@ -83,11 +80,10 @@ std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& r
const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
} else { // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6
// (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63; Q6_K: the same range,
// its int8 sub-scales up to 127, and its d is the block's LAST two bytes)
const int e = (t == 12 || t == 13 || t == 14) ? 1 + ex(rng) % 4 : ex(rng);
// (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63)
const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng);
const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));
std::memcpy(&w[o + (t == 14 ? bs - 2 : 0)], &h, 2);
std::memcpy(&w[o], &h, 2);
if (t == 12 || t == 13 || t == 7) { // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small
const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4;
const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng));
@@ -337,64 +333,18 @@ void bench(cudaStream_t s, std::mt19937& rng) {
cudaEventDestroy(e1);
}
// ------------------------------------------------------------------------------------------------ --bench-down
// The down kernel alone (native_expert_set_mode phase 2: the gate/up, SwiGLU and q8_1 passes skipped; the scratch's
// q8_1 h rows are zeros, which the integer kernels time the same as any value) at Qwen3.6-35B-A3B's 2048 x 512, for
// each down type the engine takes there: a window's 48 calls in a graph, each layer its own experts, as --bench.
// Rows: a decode window of 4 tokens x top-8 as the engine groups it - 32 groups of 1 entry (every token its own
// experts), 8 groups of 4 entries (every token the same experts). Microseconds per call and per expert (group).
void bench_down(cudaStream_t s, std::mt19937& rng) {
std::printf("\n--bench-down: the down kernel per expert at 2048 x 512 (phase 2, 48 calls in a graph, each layer its own\n"
"experts); medians of %d launches after %d warm-ups; idle GPU assumed\n", kPairs, kWarmPairs);
std::printf(" %-8s %-26s %10s %12s %10s\n", "down", "groups x entries", "us/call", "us/expert", "MB/expert");
cudaEvent_t e0, e1;
ck(cudaEventCreate(&e0), "event");
ck(cudaEventCreate(&e1), "event");
for (const int dt : {7, 8, 23, 18, 13, 14}) {
const int gu = (dt == 18 || dt == 23) ? 22 : 12; // the file's gate/up beside it (unused: phase 2)
Setup S(gu, dt, 2048, 512, 4, 8, 32, rng, s); // cap 32 entries, 32 distinct blobs
const struct { const char* what; std::vector<int> sizes; } rows[] = {
{"32 x 1 (4 tokens, own experts)", std::vector<int>(32, 1)},
{"8 x 4 (4 tokens, shared)", std::vector<int>(8, 4)},
};
for (const auto& r : rows) {
const int ng = S.plan_sizes(r.sizes, 0, rng);
const Layers Ls(S, ng);
k::native_expert_set_mode(-1, 2);
cudaGraphExec_t g = make_graph(s, S, Ls, false, 0);
std::vector<float> t;
for (int i = 0; i < kWarmPairs + kPairs; ++i) {
const float x = launch_us(s, g, e0, e1);
if (i >= kWarmPairs) t.push_back(x);
}
k::native_expert_set_mode(-1, 0);
ck(cudaGraphExecDestroy(g), "graph");
const float us = median(t);
std::printf(" %-8s %-26s %10.2f %12.3f %10.3f\n", name_of(dt), r.what, us, us / ng,
(double) (S.L.bytes - S.L.down_off) / 1e6);
}
}
cudaEventDestroy(e0);
cudaEventDestroy(e1);
}
} // namespace
int main(int argc, char** argv) {
const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench";
const bool do_bench_down = argc > 1 && std::string(argv[1]) == "--bench-down";
cudaStream_t s;
ck(cudaStreamCreate(&s), "stream");
std::mt19937 rng(316);
for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 14, 8}) // STRATA_GU_FMTS
for (int dt : {20, 23, 42, 7, 8, 18, 13, 14}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS (256-value
// down types: n_ff % 256)
check(21, 20, 2560, 640, s, rng); // Flash-Next's shapes
for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 8}) // STRATA_GU_FMTS
for (int dt : {20, 23, 42, 7, 8}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS; IQ4_XS: n_ff % 256
check(21, 20, 2560, 640, s, rng); // a model's shapes
check(21, 23, 2560, 768, s, rng);
for (const auto& pr : {std::pair<int, int>{22, 18}, {22, 23}, {12, 13}, {12, 14}, {13, 14}}) // Qwen3.6's
check(pr.first, pr.second, 2048, 512, s, rng);
if (do_bench) bench(s, rng);
if (do_bench_down) bench_down(s, rng);
std::printf("native_grouped_parity: %d failures\n", g_fail);
cudaStreamDestroy(s);
return g_fail ? 1 : 0;
-151
View File
@@ -1,151 +0,0 @@
// src/kernels/qsa_attn_bench.cpp - what the split-K decode attention costs per call (GPU, synthetic, no model).
//
// qsa_attn_bench [--heads N,KV] [--kv fp16|int8|q4_0] [--cells C1,C2,...] [--reps R]
//
// One query row over `cells` cells (the identity selection, width = cells) through `qsa_decode_attn_step` on random
// pools behind a shuffled page table; the time is the median of `reps` back-to-back calls bracketed by events.
// Uses only the entry points the kernel had before Qwen3.6 step 3 (explicit ids), so the same file builds against
// the old kernel and the new one: the before / after numbers of docs/qwen36-port/step3-attn.md come from it.
// Exit 77 without a device.
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e, const char* w) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(1); }
}
template <typename T> T* up(const std::vector<T>& h) {
T* d = nullptr;
ck(cudaMalloc(&d, h.size() * sizeof(T) + 256), "malloc");
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
return d;
}
uint16_t f2h(float f) { // round-to-nearest fp16 bits, host side
uint32_t u; std::memcpy(&u, &f, 4);
const uint32_t sign = (u >> 16) & 0x8000u;
int exp = (int) ((u >> 23) & 0xff) - 127 + 15;
uint32_t man = u & 0x7fffffu;
if (exp <= 0) return (uint16_t) sign;
if (exp >= 31) return (uint16_t) (sign | 0x7c00u);
uint32_t h = sign | ((uint32_t) exp << 10) | (man >> 13);
if ((man & 0x1fffu) > 0x1000u || ((man & 0x1fffu) == 0x1000u && (h & 1u))) ++h;
return (uint16_t) h;
}
} // namespace
int main(int argc, char** argv) {
int64_t n_head = 24, n_kv = 2;
std::string kv = "fp16";
std::vector<int64_t> cells = {2051};
int reps = 50;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> const char* { if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); } return argv[++i]; };
if (a == "--heads") { if (std::sscanf(next(), "%lld,%lld", (long long*) &n_head, (long long*) &n_kv) != 2) return 2; }
else if (a == "--kv") kv = next();
else if (a == "--reps") reps = std::atoi(next());
else if (a == "--cells") {
cells.clear();
std::string v = next();
for (size_t p = 0; p < v.size();) { size_t q = v.find(',', p); if (q == std::string::npos) q = v.size(); cells.push_back(std::atoll(v.substr(p, q - p).c_str())); p = q + 1; }
} else { std::fprintf(stderr, "usage: qsa_attn_bench [--heads N,KV] [--kv fp16|int8|q4_0] [--cells C,...] [--reps R]\n"); return 2; }
}
int ndev = 0;
if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { std::printf("SKIP: no CUDA device\n"); return 77; }
cudaDeviceProp prop{};
ck(cudaGetDeviceProperties(&prop, 0), "props");
k::QsaShapes s = k::qsa_real_shapes();
s.n_head = n_head; s.n_head_kv = n_kv;
const int64_t HD = s.head_dim, PS = s.page_size;
const int64_t max_cells = *std::max_element(cells.begin(), cells.end());
const int64_t pages = (max_cells + PS - 1) / PS, rows = pages * n_kv * PS;
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.f, 1.f);
k::QsaAttnPools pl;
uint64_t bytes_per_cell = 0;
if (kv == "fp16") {
std::vector<uint16_t> kh((size_t) rows * HD), vh((size_t) rows * HD);
for (auto& x : kh) x = f2h(nd(rng) * 0.5f);
for (auto& x : vh) x = f2h(nd(rng));
pl.k_pool = up(kh); pl.v_pool = up(vh);
bytes_per_cell = (uint64_t) n_kv * HD * 2 * 2;
} else if (kv == "int8") {
std::uniform_int_distribution<int> code(-127, 127);
std::vector<int8_t> kq((size_t) rows * HD), vq((size_t) rows * HD);
std::vector<uint16_t> ks((size_t) rows * (HD / k::KV_Q8_GROUP), f2h(0.01f)), vs = ks;
for (auto& x : kq) x = (int8_t) code(rng);
for (auto& x : vq) x = (int8_t) code(rng);
pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs);
bytes_per_cell = k::kv_q8_bytes_per_cell(s);
} else if (kv == "q4_0") {
std::uniform_int_distribution<int> byte(0, 255);
const uint64_t ROW = k::kv_q4_bytes_per_head((int) HD);
std::vector<uint8_t> k4((size_t) rows * ROW), v4((size_t) rows * ROW);
for (auto* pool : {&k4, &v4})
for (int64_t b = 0; b < rows * (HD / k::QK4_0); ++b) {
const uint16_t d = f2h(0.05f);
std::memcpy(pool->data() + b * sizeof(k::block_q4_0), &d, 2);
for (int j = 0; j < 16; ++j) (*pool)[b * sizeof(k::block_q4_0) + 2 + j] = (uint8_t) byte(rng);
}
pl.k_q4 = up(k4); pl.v_q4 = up(v4);
bytes_per_cell = k::kv_q4_bytes_per_cell(s);
} else { std::fprintf(stderr, "--kv must be fp16, int8 or q4_0\n"); return 2; }
std::vector<int32_t> table((size_t) pages);
for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
std::shuffle(table.begin(), table.end(), rng);
pl.page_table = up(table);
std::vector<int32_t> ids((size_t) max_cells);
for (int64_t i = 0; i < max_cells; ++i) ids[i] = (int32_t) i;
const int32_t* d_ids = up(ids);
std::vector<float> q((size_t) n_head * HD);
for (auto& x : q) x = nd(rng);
const float* d_q = up(q);
float* d_attn = nullptr;
ck(cudaMalloc(&d_attn, (size_t) n_head * HD * 4), "malloc");
int32_t* d_step = nullptr;
ck(cudaMalloc(&d_step, 64), "malloc");
cudaEvent_t e0, e1;
ck(cudaEventCreate(&e0), "event"); ck(cudaEventCreate(&e1), "event");
std::printf("qsa_attn_bench on %s (sm_%d%d): %lld heads / %lld KV heads, %s KV, page_size %lld, %d reps\n",
prop.name, prop.major, prop.minor, (long long) n_head, (long long) n_kv, kv.c_str(), (long long) PS, reps);
std::printf(" %10s %12s %12s %12s\n", "cells", "us/call", "scratch MiB", "KV GB/s");
for (const int64_t c : cells) {
const int64_t cap = c;
const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s);
float* d_scr = nullptr;
ck(cudaMalloc(&d_scr, scr * 4 + 256), "malloc scratch");
const int32_t step[4] = {(int32_t) (c - 1), (int32_t) c, (int32_t) (c / 4), (int32_t) c};
ck(cudaMemcpy(d_step, step, 16, cudaMemcpyHostToDevice), "step");
for (int i = 0; i < 3; ++i) k::qsa_decode_attn_step(d_q, pl, d_ids, d_step, cap, s, d_scr, d_attn, nullptr);
ck(cudaDeviceSynchronize(), "warm");
std::vector<float> us;
for (int r = 0; r < reps; ++r) {
ck(cudaEventRecord(e0), "rec");
k::qsa_decode_attn_step(d_q, pl, d_ids, d_step, cap, s, d_scr, d_attn, nullptr);
ck(cudaEventRecord(e1), "rec");
ck(cudaEventSynchronize(e1), "sync");
float ms = 0.f;
ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
us.push_back(ms * 1000.f);
}
std::sort(us.begin(), us.end());
const float med = us[us.size() / 2];
std::printf(" %10lld %12.1f %12.2f %12.1f\n", (long long) c, (double) med, (double) scr * 4 / 1048576.0,
(double) c * (double) bytes_per_cell / (med * 1e-6) / 1e9);
cudaFree(d_scr);
}
return 0;
}
-616
View File
@@ -1,616 +0,0 @@
// src/kernels/qsa_dense_parity.cpp - dense attention (Qwen3.6-35B-A3B, docs/QWEN36-35B-A3B.md 3.3) through the
// engine's split-K decode kernel and the tensor-core prompt kernel: the query-head group G as a template
// parameter (2, 8, 12), a null `ids` as the identity selection, the bounded split-K scratch, and the sparse
// selection width refused for the dense model. GPU, synthetic, plus the oracle's fixtures when given.
//
// qsa_dense_parity [--fixtures DIR] [--selftest]
//
// DIR is what cmake/qwen36_attn_fixtures.cmake writes: <name>.gguf and <name>-dump/ (ref/qwen36.py's seams on 40
// tokens) for g8 (16 / 2), g12 (24 / 2) and g2 (4 / 2) at head_dim 256. The dumped `Qcur_reshaped-3`, `Kcur-3`,
// `Vcur-3#2` and `Qcur_full-3` go through the engine's own RMS norm, RoPE table, fp16 KV append, decode attention
// and output gate, and are held to the oracle's `Qcur-3`, `Kcur-3#2`, `kq_soft_max-3`, `kqv-3`, `attn_gated-3`.
//
// The negative-test discipline (docs/qwen36-port/upstream-tooling.md section 3): each rival reading must differ by
// more than 5% relative L1 before the right one is judged - the gate skipped (the oracle's 1.03 at attn_gated-3),
// RoPE on adjacent pairs instead of NEOX halves (0.20 at kqv-3), the GQA map `h % n_kv` (0.74 at kqv-3), G = 12 on
// 16 heads (refused by name), and the sparse width 2,051 on a 3,000-cell context (every cell past 2,051 unread).
//
// Exit 0 pass, 1 fail, 77 skip (no CUDA device, or --fixtures given and the fixtures are missing).
#include "strata/artifact/gguf_reader.hpp"
#include "strata/core/model_geometry.hpp"
#include "strata/core/qsa_shapes.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/f16_bits.hpp"
#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_prompt_attn.hpp"
#include "strata/kernels/rope.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <random>
#include <string>
#include <vector>
namespace k = strata::kernels;
namespace fs = std::filesystem;
namespace {
int g_fail = 0;
void verdict(const std::string& name, bool ok, const std::string& detail = "") {
std::printf(" %-78s %s%s%s\n", name.c_str(), ok ? "ok" : "FAIL", detail.empty() ? "" : " ", detail.c_str());
if (!ok) ++g_fail;
}
std::string sci(double v) { char b[32]; std::snprintf(b, sizeof b, "%.2e", v); return b; }
void ck(cudaError_t e, const char* w) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(1); }
}
template <typename T> T* dalloc(size_t n) {
T* d = nullptr;
ck(cudaMalloc(&d, n * sizeof(T) + 256), "malloc");
ck(cudaMemset(d, 0, n * sizeof(T) + 256), "memset");
return d;
}
template <typename T> T* up(const std::vector<T>& h) {
T* d = dalloc<T>(h.size());
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
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), "download");
return h;
}
// ||a - b|| / ||b|| (L2) and sum|a - b| / sum|b| (L1), NaN-safe: a non-finite value is an infinite error
double rel_l2(const std::vector<float>& a, const std::vector<float>& b) {
double n = 0, d = 0;
for (size_t i = 0; i < a.size(); ++i) {
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) return INFINITY;
n += (double) (a[i] - b[i]) * (a[i] - b[i]);
d += (double) b[i] * b[i];
}
return d > 0 ? std::sqrt(n / d) : (n > 0 ? INFINITY : 0.0);
}
double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
double n = 0, d = 0;
for (size_t i = 0; i < a.size(); ++i) {
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) return INFINITY;
n += std::fabs((double) a[i] - b[i]);
d += std::fabs((double) b[i]);
}
return d > 0 ? n / d : (n > 0 ? INFINITY : 0.0);
}
bool bitwise(const std::vector<float>& a, const std::vector<float>& b) {
return a.size() == b.size() && std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
}
// ---- the host reference: causal-free attention of one query over `cells` dequantized K/V rows, in double.
// q [n_head][HD], K/V [cell][kv][HD]; the GQA map is grouped (h / G) unless `mod_map`; probabilities out if asked
constexpr int HD = 256;
void ref_attend(const std::vector<float>& q, const std::vector<double>& K, const std::vector<double>& V, int64_t cells,
int64_t width, int64_t n_head, int64_t n_kv, std::vector<float>& out, std::vector<double>* probs,
bool mod_map = false) {
const int64_t G = n_head / n_kv;
const double scale = 1.0 / std::sqrt((double) HD);
out.assign((size_t) n_head * HD, 0.f);
if (probs) probs->assign((size_t) n_head * cells, 0.0);
std::vector<double> sc((size_t) width);
for (int64_t h = 0; h < n_head; ++h) {
const int64_t kv = mod_map ? h % n_kv : h / G;
double m = -INFINITY;
for (int64_t j = 0; j < width; ++j) {
double s = 0;
const double* kr = K.data() + ((size_t) j * n_kv + kv) * HD;
for (int d = 0; d < HD; ++d) s += kr[d] * (double) q[(size_t) h * HD + d];
sc[j] = s * scale;
m = std::max(m, sc[j]);
}
double l = 0;
for (int64_t j = 0; j < width; ++j) { sc[j] = std::exp(sc[j] - m); l += sc[j]; }
std::vector<double> acc(HD, 0.0);
for (int64_t j = 0; j < width; ++j) {
const double p = sc[j] / l;
if (probs) (*probs)[(size_t) h * cells + j] = p;
const double* vr = V.data() + ((size_t) j * n_kv + kv) * HD;
for (int d = 0; d < HD; ++d) acc[d] += p * vr[d];
}
for (int d = 0; d < HD; ++d) out[(size_t) h * HD + d] = (float) acc[d];
}
}
// ---- NEOX RoPE on the host, first n_rot dims, pairs (i, i + n_rot/2) in float64 (the engine's table is float64 too),
// or the rival adjacent-pair reading (2i, 2i+1)
void host_rope(std::vector<float>& x, int64_t rows, int n_rot, double theta, const std::vector<int>& pos, bool adjacent) {
for (int64_t r = 0; r < rows; ++r) {
float* v = x.data() + (size_t) r * HD;
for (int i = 0; i < n_rot / 2; ++i) {
const double f = std::pow(theta, -2.0 * i / n_rot);
const double a = pos[(size_t) r] * f, c = std::cos(a), s = std::sin(a);
const int ia = adjacent ? 2 * i : i, ib = adjacent ? 2 * i + 1 : i + n_rot / 2;
const double x0 = v[ia], x1 = v[ib];
v[ia] = (float) (x0 * c - x1 * s);
v[ib] = (float) (x0 * s + x1 * c);
}
}
}
// ---- Walsh-Hadamard of a 256-row, orthonormal (scale 1/16), self-inverse: kv_q4.hpp's rotation
void fwht256_host(double* x) {
for (int len = 1; len < 256; len <<= 1)
for (int i = 0; i < 256; i += 2 * len)
for (int j = i; j < i + len; ++j) { const double a = x[j], b = x[j + len]; x[j] = a + b; x[j + len] = a - b; }
for (int i = 0; i < 256; ++i) x[i] *= 1.0 / 16.0;
}
// ---- a paged KV state of `cells` capacity in one of the four formats, filled through the engine's own append kernels
struct Pools {
int mode = 0; // 0 fp16, 1 int8, 2 q4_0, 3 k8v4
int64_t n_kv = 0, pages = 0, rows = 0;
std::vector<int32_t> table; // logical page -> physical (shuffled)
k::QsaAttnPools p;
uint16_t *k_pool = nullptr, *v_pool = nullptr, *k_scale = nullptr, *v_scale = nullptr;
int8_t *k_q = nullptr, *v_q = nullptr;
uint8_t *k_q4 = nullptr, *v_q4 = nullptr;
int32_t* d_table = nullptr;
bool rot_k = false, rot_v = false, rot_q = false; // what the format rotates (the kernel's output follows V)
std::vector<double> K, V; // dequantized, [cell][kv][HD], as the kernel will read them (rotated where the format does)
};
Pools make_pools(int mode, int64_t cells, const k::QsaShapes& s, std::mt19937& rng, const std::vector<float>& kcur,
const std::vector<float>& vcur) { // kcur/vcur [cell][kv][HD] f32, unrotated
Pools P;
P.mode = mode;
P.n_kv = s.n_head_kv;
P.pages = (cells + s.page_size - 1) / s.page_size;
P.rows = P.pages * s.n_head_kv * s.page_size;
P.table.resize((size_t) P.pages);
for (int64_t i = 0; i < P.pages; ++i) P.table[i] = (int32_t) i;
std::shuffle(P.table.begin(), P.table.end(), rng);
P.d_table = up(P.table);
P.p.page_table = P.d_table;
const uint64_t q4row = k::kv_q4_bytes_per_head(HD);
if (mode == 0) { P.k_pool = dalloc<uint16_t>(P.rows * HD); P.v_pool = dalloc<uint16_t>(P.rows * HD); P.p.k_pool = P.k_pool; P.p.v_pool = P.v_pool; }
else if (mode == 1) {
P.k_q = dalloc<int8_t>(P.rows * HD); P.v_q = dalloc<int8_t>(P.rows * HD);
P.k_scale = dalloc<uint16_t>(P.rows * (HD / k::KV_Q8_GROUP)); P.v_scale = dalloc<uint16_t>(P.rows * (HD / k::KV_Q8_GROUP));
P.p.k_q = P.k_q; P.p.v_q = P.v_q; P.p.k_scale = P.k_scale; P.p.v_scale = P.v_scale;
} else if (mode == 2) {
P.k_q4 = dalloc<uint8_t>(P.rows * q4row); P.v_q4 = dalloc<uint8_t>(P.rows * q4row);
P.p.k_q4 = P.k_q4; P.p.v_q4 = P.v_q4;
P.rot_k = P.rot_v = P.rot_q = true;
} else {
P.k_q = dalloc<int8_t>(P.rows * HD); P.k_scale = dalloc<uint16_t>(P.rows * (HD / k::KV_Q8_GROUP));
P.v_q4 = dalloc<uint8_t>(P.rows * q4row);
P.p.k_q = P.k_q; P.p.k_scale = P.k_scale; P.p.v_q4 = P.v_q4;
P.rot_v = true;
}
// the cells through the append kernels, one step buffer per cell, V (and K) rotated as the engine does first
std::vector<int32_t> steps((size_t) cells * k::kStepCount);
for (int64_t c = 0; c < cells; ++c) k::qsa_step_fill(steps.data() + c * k::kStepCount, c, s);
int32_t* d_steps = up(steps);
float* d_k = up(kcur);
float* d_v = up(vcur);
if (P.rot_k) k::fwht256_inplace_cuda(d_k, cells * s.n_head_kv, nullptr);
if (P.rot_v) k::fwht256_inplace_cuda(d_v, cells * s.n_head_kv, nullptr);
for (int64_t c = 0; c < cells; ++c) {
const int32_t* st = d_steps + c * k::kStepCount;
const float* kc = d_k + c * s.n_head_kv * HD;
const float* vc = d_v + c * s.n_head_kv * HD;
if (mode == 0) k::kv_append_step(P.k_pool, P.v_pool, P.d_table, st, kc, vc, s, nullptr);
else if (mode == 1) k::kv_append_q8_step(P.k_q, P.v_q, P.k_scale, P.v_scale, P.d_table, st, kc, vc, s, nullptr);
else if (mode == 2) k::kv_append_q4_step(P.k_q4, P.v_q4, P.d_table, st, kc, vc, s, nullptr);
else {
k::kv_append_q8_step(P.k_q, P.k_q, P.k_scale, P.k_scale, P.d_table, st, kc, kc, s, nullptr);
k::kv_append_q4_step(P.v_q4, P.v_q4, P.d_table, st, vc, vc, s, nullptr);
}
}
ck(cudaDeviceSynchronize(), "append");
// read the pools back and dequantize exactly as the kernel's loads do
auto row_of = [&](int64_t cell, int64_t kv) { return ((int64_t) P.table[(size_t) (cell / s.page_size)] * s.n_head_kv + kv) * s.page_size + cell % s.page_size; };
P.K.assign((size_t) cells * s.n_head_kv * HD, 0.0);
P.V.assign((size_t) cells * s.n_head_kv * HD, 0.0);
auto deq_f16 = [&](const uint16_t* pool, std::vector<double>& out) {
const auto h = down(pool, (size_t) P.rows * HD);
for (int64_t c = 0; c < cells; ++c) for (int64_t kv = 0; kv < s.n_head_kv; ++kv) for (int d = 0; d < HD; ++d)
out[((size_t) c * s.n_head_kv + kv) * HD + d] = k::f32_from_f16(h[(size_t) row_of(c, kv) * HD + d]);
};
auto deq_q8 = [&](const int8_t* codes, const uint16_t* scales, std::vector<double>& out) {
const auto hc = down(codes, (size_t) P.rows * HD);
const auto hs = down(scales, (size_t) P.rows * (HD / k::KV_Q8_GROUP));
for (int64_t c = 0; c < cells; ++c) for (int64_t kv = 0; kv < s.n_head_kv; ++kv) for (int d = 0; d < HD; ++d) {
const int64_t r = row_of(c, kv);
out[((size_t) c * s.n_head_kv + kv) * HD + d] = (double) hc[(size_t) r * HD + d] * k::f32_from_f16(hs[(size_t) r * (HD / k::KV_Q8_GROUP) + d / k::KV_Q8_GROUP]);
}
};
auto deq_q4 = [&](const uint8_t* pool, std::vector<double>& out) {
const auto h = down(pool, (size_t) P.rows * q4row);
for (int64_t c = 0; c < cells; ++c) for (int64_t kv = 0; kv < s.n_head_kv; ++kv) for (int d = 0; d < HD; ++d) {
const uint8_t* blk = h.data() + (size_t) row_of(c, kv) * q4row + (d / k::QK4_0) * sizeof(k::block_q4_0);
uint16_t sc; std::memcpy(&sc, blk, 2);
const int j = d % k::QK4_0;
const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4);
out[((size_t) c * s.n_head_kv + kv) * HD + d] = (double) (code - 8) * k::f32_from_f16(sc);
}
};
if (mode == 0) { deq_f16(P.k_pool, P.K); deq_f16(P.v_pool, P.V); }
else if (mode == 1) { deq_q8(P.k_q, P.k_scale, P.K); deq_q8(P.v_q, P.v_scale, P.V); }
else if (mode == 2) { deq_q4(P.k_q4, P.K); deq_q4(P.v_q4, P.V); }
else { deq_q8(P.k_q, P.k_scale, P.K); deq_q4(P.v_q4, P.V); }
cudaFree(d_steps); cudaFree(d_k); cudaFree(d_v);
return P;
}
void free_pools(Pools& P) {
for (void* p : {(void*) P.k_pool, (void*) P.v_pool, (void*) P.k_scale, (void*) P.v_scale, (void*) P.k_q, (void*) P.v_q,
(void*) P.k_q4, (void*) P.v_q4, (void*) P.d_table})
if (p) cudaFree(p);
}
const char* mode_name(int m) { return m == 0 ? "fp16" : m == 1 ? "int8" : m == 2 ? "q4_0" : "k8v4"; }
k::QsaShapes dense_shapes(int64_t n_head, int64_t n_kv) {
k::QsaShapes s = k::qsa_real_shapes();
s.n_head = n_head; s.n_head_kv = n_kv;
s.idx_n_head = 0; s.idx_dim = 0; s.idx_top_k = 0; // what layer.cpp's qsa_shapes() does for a no-indexer geometry
return s;
}
// ================= 1. the group, the width, the capacity, the scratch (host only) =================
void section_dispatch() {
std::printf("\n-- the query-head group, the dense width and capacity, the bounded scratch\n");
char why[256];
const k::QsaShapes s16 = dense_shapes(16, 2), s24 = dense_shapes(24, 2), s4 = dense_shapes(4, 2), s26 = dense_shapes(26, 2);
verdict("16 / 2 is group 8 (Qwen3.6)", k::qsa_attn_group(s16, why, sizeof why) == 8);
verdict("24 / 2 is group 12 (Flash-Next)", k::qsa_attn_group(s24, why, sizeof why) == 12);
verdict("4 / 2 is group 2 (the fixture)", k::qsa_attn_group(s4, why, sizeof why) == 2);
why[0] = 0;
const bool r26 = k::qsa_attn_group(s26, why, sizeof why) == 0;
verdict("26 / 2 (13 per KV head) is refused, naming the heads", r26 && std::strstr(why, "26") && std::strstr(why, "13"), why);
why[0] = 0;
const bool r12 = !k::qsa_attn_group_check(s16, 12, why, sizeof why);
verdict("NEGATIVE: G = 12 asked of 16 heads over 2 is refused by name, not run", r12 && std::strstr(why, "16") && std::strstr(why, "12"), why);
verdict("G = 8 on 16 / 2 and G = 12 on 24 / 2 pass the check", k::qsa_attn_group_check(s16, 8, why, sizeof why) && k::qsa_attn_group_check(s24, 12, why, sizeof why));
k::QsaShapes sparse = k::qsa_real_shapes();
verdict("sparse (Flash-Next) width at 3,000 cells is 2,051 and its cap 2,051",
k::qsa_selection_width(3000, sparse) == 2051 && k::qsa_selection_cap(262144, sparse) == 2051);
verdict("dense width at 3,000 cells is 3,000 and the cap is max_cells",
k::qsa_selection_width(3000, s16) == 3000 && k::qsa_selection_cap(262144, s16) == 262144 && k::qsa_dense(s16) && !k::qsa_dense(sparse));
int32_t st[k::kStepCount];
k::qsa_step_fill(st, 2999, s16);
verdict("qsa_step_fill writes width = n_kv for the dense shape", st[k::kStepWidth] == 3000 && st[k::kStepNKv] == 3000);
k::qsa_step_fill(st, 2999, sparse);
verdict("... and 2,051 for the sparse one", st[k::kStepWidth] == 2051);
verdict("dense chunks: 2,051 cells -> 33 blocks (the old grid), 8,192 -> 128, 262,144 -> 128",
k::qsa_decode_attn_chunks(2051, s16) == 33 && k::qsa_decode_attn_chunks(8192, s16) == 128 && k::qsa_decode_attn_chunks(262144, s16) == 128);
verdict("sparse chunks are the old grid at any capacity: 2,051 -> 33, 32,768 (the MTP drafter's window) -> 512",
k::qsa_decode_attn_chunks(2051, sparse) == 33 && k::qsa_decode_attn_chunks(32768, sparse) == 512 &&
k::qsa_decode_attn_scratch_floats(32768, sparse) == 512ull * 24 * 258 + 64);
// the one builder (strata/core/qsa_shapes.hpp) from a qwen35moe geometry, and the half-set shape it prevents
{
strata::core::ModelGeometry g;
g.arch = strata::core::ModelArch::Qwen35Moe; g.hc = 1; g.hc_lr = 0; g.has_ple = false;
g.n_head = 16; g.n_head_kv = 2; g.head_dim = 256; g.idx_q_heads = 0; g.idx_key_dim = 0;
g.ssm_v_heads = 32; g.n_expert = 256; g.n_expert_used = 8; g.n_ff = 512; g.n_layers = 40; g.derive();
const k::QsaShapes built = strata::core::qsa_shapes(g);
verdict("qsa_shapes(qwen35moe geometry) is dense: idx_n_head, idx_dim, idx_top_k all 0, n_rot 64, idx_block 4",
k::qsa_dense(built) && built.idx_top_k == 0 && built.n_rot == 64 && built.idx_block == 4 && built.n_head == 16);
why[0] = 0;
verdict("... and the kernels' guard accepts it", k::qsa_shapes_valid(built, why, sizeof why), why);
strata::core::ModelGeometry f; // Flash-Next's defaults: the sparse shape, unchanged
const k::QsaShapes fn = strata::core::qsa_shapes(f);
verdict("qsa_shapes(qwen4exp geometry) is the sparse real shape (24 / 2, idx 4 x 128, top-k 2048)",
!k::qsa_dense(fn) && fn.idx_n_head == 4 && fn.idx_dim == 128 && fn.idx_top_k == 2048 && k::qsa_shapes_valid(fn, why, sizeof why));
k::QsaShapes half = k::qsa_real_shapes(); // what a hand-written builder made: two zeros, the budget kept
half.n_head = 16; half.idx_n_head = 0; half.idx_dim = 0;
why[0] = 0;
const bool refused = !k::qsa_shapes_valid(half, why, sizeof why);
verdict("NEGATIVE: the half-set shape (idx_n_head 0, idx_dim 0, idx_top_k 2048) is neither dense nor valid",
!k::qsa_dense(half) && refused && std::strstr(why, "half set up"), why);
}
const uint64_t old2051 = 33ull * 24 * 258 + 64, new262k = 128ull * 16 * 258 + 64;
verdict("scratch at cap 2,051 x 24 heads is the old formula (33 x 24 x 258 + 64 floats)",
k::qsa_decode_attn_scratch_floats(2051, s24) == old2051);
verdict("scratch at cap 262,144 x 16 heads is 128 x 16 x 258 + 64 floats = 528,448 (2.02 MiB), not 64.5 MiB",
k::qsa_decode_attn_scratch_floats(262144, s16) == new262k && new262k == 528448,
std::to_string(new262k * 4 / 1024) + " KiB");
}
// ================= 2. the decode kernel against the host reference, every KV format, three widths =================
struct Timer { std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now(); double s() const { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); } };
void section_random(int64_t n_head, int64_t n_kv, int mode, int64_t width, std::mt19937& rng, bool prompt_too) {
const k::QsaShapes s = dense_shapes(n_head, n_kv);
const int64_t cells = width;
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> kcur((size_t) cells * n_kv * HD), vcur((size_t) cells * n_kv * HD);
for (auto& x : kcur) x = nd(rng) * 0.7f;
for (auto& x : vcur) x = nd(rng);
Pools P = make_pools(mode, cells, s, rng, kcur, vcur);
// three query rows at widths w, w-1, w-77 (each its own step), q rotated when the format rotates K
const int64_t n_q = 3;
const int64_t widths[3] = {width, width - 1, std::max<int64_t>(width - 77, 1)};
std::vector<float> q((size_t) n_q * n_head * HD);
for (auto& x : q) x = nd(rng) * 1.5f;
float* d_q = up(q);
if (P.rot_q) k::fwht256_inplace_cuda(d_q, n_q * n_head, nullptr);
const auto q_dev = down(d_q, q.size()); // the (possibly rotated) q the kernel reads, for the reference
std::vector<int32_t> steps((size_t) n_q * k::kStepCount);
for (int64_t i = 0; i < n_q; ++i) k::qsa_step_fill(steps.data() + i * k::kStepCount, widths[i] - 1, s);
int32_t* d_steps = up(steps);
const int64_t cap = cells;
const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s);
float* d_scr = dalloc<float>(scr * n_q);
float* d_attn = dalloc<float>((size_t) n_q * n_head * HD);
const std::string tag = std::to_string(n_head) + "/" + std::to_string(n_kv) + " " + mode_name(mode) + " w=" + std::to_string(width);
// the kernel with a NULL ids (the dense identity)
k::qsa_decode_attn_batch(d_q, P.p, nullptr, d_steps, cap, s, d_scr, d_attn, n_q, nullptr);
ck(cudaDeviceSynchronize(), "decode");
const auto out_null = down(d_attn, (size_t) n_q * n_head * HD);
// the same with the explicit identity ids
int32_t* d_ids = dalloc<int32_t>((size_t) n_q * cap);
k::qsa_identity_ids(d_ids, d_steps, n_q, cap, nullptr);
k::qsa_decode_attn_batch(d_q, P.p, d_ids, d_steps, cap, s, d_scr, d_attn, n_q, nullptr);
ck(cudaDeviceSynchronize(), "decode ids");
const auto out_ids = down(d_attn, (size_t) n_q * n_head * HD);
verdict(tag + ": null ids == explicit identity ids, bit for bit", bitwise(out_null, out_ids));
{
const auto ids_h = down(d_ids, (size_t) n_q * cap);
bool ok = true;
for (int64_t i = 0; i < n_q && ok; ++i) for (int64_t j = 0; j < widths[i] && ok; ++j) ok = ids_h[(size_t) i * cap + j] == j;
verdict(tag + ": qsa_identity_ids writes 0..width-1 per row", ok);
}
// the host reference per row
Timer tm;
double worst = 0;
std::vector<float> ref_row;
for (int64_t i = 0; i < n_q; ++i) {
std::vector<float> qi(q_dev.begin() + i * n_head * HD, q_dev.begin() + (i + 1) * n_head * HD);
ref_attend(qi, P.K, P.V, cells, widths[i], n_head, n_kv, ref_row, nullptr);
std::vector<float> got(out_null.begin() + i * n_head * HD, out_null.begin() + (i + 1) * n_head * HD);
worst = std::max(worst, rel_l2(got, ref_row));
if (i == 0 && width == 3000) {
// NEGATIVE: the sparse width (2,051) on this context reads 949 cells fewer - what the old
// qsa_selection_width would have handed the kernel for Qwen3.6
std::vector<int32_t> sp(steps.begin(), steps.begin() + k::kStepCount);
sp[k::kStepWidth] = 2051;
int32_t* d_sp = up(sp);
k::qsa_decode_attn_batch(d_q, P.p, nullptr, d_sp, cap, s, d_scr, d_attn, 1, nullptr);
ck(cudaDeviceSynchronize(), "sparse width");
const auto narrow = down(d_attn, (size_t) n_head * HD);
const double l1 = rel_l1(narrow, ref_row);
verdict(tag + ": NEGATIVE: the sparse width 2,051 differs from the dense 3,000 by > 5% rel L1", l1 > 0.05, sci(l1));
cudaFree(d_sp);
}
}
const double tol = 3e-5; // fp32 kernel with __expf against the double reference over the SAME dequantized rows
verdict(tag + ": decode kernel vs host reference over the dequantized pools, rel L2 <= " + sci(tol), worst <= tol,
sci(worst) + " (" + std::to_string((int) (tm.s() * 1000)) + " ms ref)");
// the prompt (tensor-core) kernel at the same rows: sm_70+ only, the host returns false below it
if (prompt_too) {
float* d_pa = dalloc<float>((size_t) n_q * n_head * HD);
if (k::qsa_prompt_attn_batch(d_q, P.p, nullptr, d_steps, cap, s, d_pa, n_q, nullptr)) {
ck(cudaDeviceSynchronize(), "prompt");
const auto pa = down(d_pa, (size_t) n_q * n_head * HD);
k::qsa_prompt_attn_batch(d_q, P.p, d_ids, d_steps, cap, s, d_pa, n_q, nullptr);
ck(cudaDeviceSynchronize(), "prompt ids");
const auto pa_ids = down(d_pa, (size_t) n_q * n_head * HD);
verdict(tag + ": prompt kernel: null ids == explicit identity ids, bit for bit", bitwise(pa, pa_ids));
double w2 = 0;
for (int64_t i = 0; i < n_q; ++i) {
std::vector<float> qi(q_dev.begin() + i * n_head * HD, q_dev.begin() + (i + 1) * n_head * HD);
ref_attend(qi, P.K, P.V, cells, widths[i], n_head, n_kv, ref_row, nullptr);
std::vector<float> got(pa.begin() + i * n_head * HD, pa.begin() + (i + 1) * n_head * HD);
w2 = std::max(w2, rel_l2(got, ref_row));
}
const double ptol = 2e-3; // fp16 hi/lo split operands with fp32 accumulation (qsa_prompt_attn.hpp)
verdict(tag + ": prompt kernel vs host reference, rel L2 <= " + sci(ptol), w2 <= ptol, sci(w2));
} else {
std::printf(" %-78s %s\n", (tag + ": prompt kernel").c_str(), "skipped (the host keeps the decode kernel on this card / format)");
}
cudaFree(d_pa);
}
cudaFree(d_q); cudaFree(d_steps); cudaFree(d_scr); cudaFree(d_attn); cudaFree(d_ids);
free_pools(P);
}
// ================= 3. the oracle's fixtures =================
std::vector<float> load_f32(const fs::path& p, size_t expect) {
std::vector<float> v;
FILE* f = std::fopen(p.string().c_str(), "rb");
if (!f) { std::fprintf(stderr, "cannot open %s\n", p.string().c_str()); std::exit(77); }
std::fseek(f, 0, SEEK_END);
const long n = std::ftell(f);
std::fseek(f, 0, SEEK_SET);
v.resize((size_t) n / 4);
if (std::fread(v.data(), 4, v.size(), f) != v.size()) { std::fprintf(stderr, "short read %s\n", p.string().c_str()); std::exit(1); }
std::fclose(f);
if (v.size() != expect) { std::fprintf(stderr, "%s holds %zu floats, expected %zu\n", p.string().c_str(), v.size(), expect); std::exit(1); }
return v;
}
void section_fixture(const fs::path& dir, const std::string& name) {
std::printf("\n-- fixture %s: the oracle's attention layer (blk.3) through the engine's norm, RoPE, fp16 KV, decode kernel, gate\n", name.c_str());
const fs::path gguf = dir / (name + ".gguf"), dump = dir / (name + "-dump");
strata::core::ModelGeometry g;
std::string err;
if (!strata::core::read_model_geometry(gguf.string(), g, err)) { std::fprintf(stderr, "%s: %s\n", gguf.string().c_str(), err.c_str()); std::exit(1); }
const int64_t NH = g.n_head, NKV = g.n_head_kv, T = 40, L = 3;
if (g.head_dim != HD) { std::fprintf(stderr, "%s: head_dim %lld, the kernel is 256\n", name.c_str(), (long long) g.head_dim); std::exit(1); }
k::QsaShapes s = dense_shapes(NH, NKV);
s.n_rot = g.n_rot;
verdict(name + ": geometry " + std::to_string(NH) + " / " + std::to_string(NKV) + " at head_dim 256, n_rot " + std::to_string(g.n_rot) + ", no indexer",
!g.has_indexer() && g.idx_q_heads == 0 && k::qsa_dense(s));
const strata::GgufModel model = strata::GgufModel::open(gguf.string());
auto tensor = [&](const std::string& nm, size_t n) {
size_t sh = 0;
const strata::TensorInfo* t = model.find(nm, &sh);
if (!t || t->elements() != n || t->type != 0) { std::fprintf(stderr, "%s: %s missing or not F32[%zu]\n", name.c_str(), nm.c_str(), n); std::exit(1); }
std::vector<float> v(n);
std::memcpy(v.data(), model.shard(sh).tensor_data(*t), n * 4);
return v;
};
const auto wqn = tensor("blk.3.attn_q_norm.weight", HD), wkn = tensor("blk.3.attn_k_norm.weight", HD);
// the oracle's file names: <name>-<layer>.f32, a repeated name numbered <name>-<layer>#2.f32 (oracle-crosscheck.md)
auto seam = [&](const std::string& nm, size_t n) {
const size_t hash = nm.find('#');
const std::string base = nm.substr(0, hash), rep = hash == std::string::npos ? "" : nm.substr(hash);
return load_f32(dump / (base + "-" + std::to_string(L) + rep + ".f32"), n);
};
const auto q_pre = seam("Qcur_reshaped", T * NH * HD); // [t][h][d], before the norm
const auto k_pre = seam("Kcur", T * NKV * HD); // [t][kv*HD + d], the projection
const auto v_in = seam("Vcur#2", T * NKV * HD); // [t][kv][d]
const auto q_full = seam("Qcur_full", T * NH * 2 * HD); // [t][h][q | gate]
const auto q_ref = seam("Qcur", T * NH * HD); // normed and roped
const auto k_ref = seam("Kcur#2", T * NKV * HD);
const auto p_ref = seam("kq_soft_max", NH * T * T); // [h][t][j]
const auto kqv_ref = seam("kqv", NH * T * HD); // [h][t][d]
const auto gated_ref = seam("attn_gated", T * NH * HD); // [t][h*HD + d]
const auto q_normed_ref = seam("Qcur_normed", T * NH * HD);
const auto k_normed_ref = seam("Kcur_normed", T * NKV * HD);
// ---- norm + RoPE on the device: the engine's rms_norm_weighted and its float64-built table
float* d_q = up(q_pre);
float* d_k = up(k_pre);
k::rms_norm_weighted(d_q, up(wqn), T * NH, HD, (float) g.rms_eps, nullptr);
k::rms_norm_weighted(d_k, up(wkn), T * NKV, HD, (float) g.rms_eps, nullptr);
std::vector<float> cos_t((size_t) T * (g.n_rot / 2)), sin_t(cos_t.size());
k::build_rope_table((int) g.n_rot, g.rope_base, (int) T, cos_t.data(), sin_t.data());
const float* d_cos = up(cos_t);
const float* d_sin = up(sin_t);
std::vector<int> pos_q((size_t) T * NH), pos_k((size_t) T * NKV);
for (int64_t t = 0; t < T; ++t) { for (int64_t h = 0; h < NH; ++h) pos_q[t * NH + h] = (int) t; for (int64_t h = 0; h < NKV; ++h) pos_k[t * NKV + h] = (int) t; }
k::rope_neox_apply(d_q, d_q, T * NH, HD, (int) g.n_rot, d_cos, d_sin, up(pos_q), nullptr);
k::rope_neox_apply(d_k, d_k, T * NKV, HD, (int) g.n_rot, d_cos, d_sin, up(pos_k), nullptr);
ck(cudaDeviceSynchronize(), "norm rope");
const auto q_eng = down(d_q, q_pre.size()), k_eng = down(d_k, k_pre.size());
const double tol_rope = 2e-6;
verdict(name + ": engine norm + NEOX RoPE of q == oracle Qcur-3, rel L2 <= " + sci(tol_rope), rel_l2(q_eng, q_ref) <= tol_rope, sci(rel_l2(q_eng, q_ref)));
verdict(name + ": engine norm + NEOX RoPE of k == oracle Kcur-3#2, rel L2 <= " + sci(tol_rope), rel_l2(k_eng, k_ref) <= tol_rope, sci(rel_l2(k_eng, k_ref)));
// ---- the fp16 KV through kv_append_step, the T queries through the batched decode kernel (null ids)
std::mt19937 rng(99);
std::vector<float> kc(k_eng), vc(v_in);
Pools P = make_pools(0, T, s, rng, kc, vc);
std::vector<int32_t> steps((size_t) T * k::kStepCount);
for (int64_t t = 0; t < T; ++t) k::qsa_step_fill(steps.data() + t * k::kStepCount, t, s);
int32_t* d_steps = up(steps);
const int64_t cap = T;
float* d_scr = dalloc<float>(k::qsa_decode_attn_scratch_floats(cap, s) * T);
float* d_attn = dalloc<float>((size_t) T * NH * HD);
k::qsa_decode_attn_batch(d_q, P.p, nullptr, d_steps, cap, s, d_scr, d_attn, T, nullptr);
ck(cudaDeviceSynchronize(), "decode");
const auto attn = down(d_attn, (size_t) T * NH * HD); // [t][h][d]
std::vector<float> kqv_t((size_t) NH * T * HD); // to the oracle's [h][t][d]
for (int64_t t = 0; t < T; ++t) for (int64_t h = 0; h < NH; ++h)
std::memcpy(kqv_t.data() + ((size_t) h * T + t) * HD, attn.data() + ((size_t) t * NH + h) * HD, HD * 4);
const double e_kqv = rel_l2(kqv_t, kqv_ref);
// the same attention in double over the engine's fp32 q/k/v (no fp16 rounding): how much of e_kqv is the KV format
std::vector<double> K32(k_eng.begin(), k_eng.end()), V32(v_in.begin(), v_in.end());
std::vector<float> kqv_f32((size_t) NH * T * HD), probs_f32((size_t) NH * T * T, 0.f), row;
std::vector<double> pr;
for (int64_t t = 0; t < T; ++t) {
std::vector<float> qi(q_eng.begin() + t * NH * HD, q_eng.begin() + (t + 1) * NH * HD);
ref_attend(qi, K32, V32, T, t + 1, NH, NKV, row, &pr);
for (int64_t h = 0; h < NH; ++h) {
std::memcpy(kqv_f32.data() + ((size_t) h * T + t) * HD, row.data() + (size_t) h * HD, HD * 4);
for (int64_t j = 0; j < T; ++j) probs_f32[((size_t) h * T + t) * T + j] = (float) pr[(size_t) h * T + j];
}
}
const double e_p = rel_l2(probs_f32, p_ref), e_f32 = rel_l2(kqv_f32, kqv_ref);
verdict(name + ": softmax over the engine's q/k (host, double) == oracle kq_soft_max-3, rel L2 <= 1e-5", e_p <= 1e-5, sci(e_p));
verdict(name + ": attention over the engine's fp32 q/k/v (host, double) == oracle kqv-3, rel L2 <= 1e-5", e_f32 <= 1e-5, sci(e_f32));
const double tol_kqv = 1.5e-3; // the fp16 KV pool: K and V rounded to 11 bits (the oracle's are F32)
verdict(name + ": decode kernel over the fp16 KV == oracle kqv-3, rel L2 <= " + sci(tol_kqv), e_kqv <= tol_kqv, sci(e_kqv));
// ---- the gate: attn * sigmoid(second half of each head's q_full), qsa_gate_apply_f32
float* d_qf = up(q_full);
float* d_gated = dalloc<float>((size_t) T * NH * HD);
for (int64_t t = 0; t < T; ++t)
k::qsa_gate_apply_f32(d_attn + t * NH * HD, d_qf + t * NH * 2 * HD, s, d_gated + t * NH * HD, nullptr);
ck(cudaDeviceSynchronize(), "gate");
const auto gated = down(d_gated, (size_t) T * NH * HD);
const double e_g = rel_l2(gated, gated_ref);
verdict(name + ": gated output == oracle attn_gated-3, rel L2 <= " + sci(tol_kqv), e_g <= tol_kqv, sci(e_g));
// ---- NEGATIVE: the gate skipped (the oracle's control: 1.03 relative L1)
const double n_gate = rel_l1(attn, gated_ref);
verdict(name + ": NEGATIVE: the gate skipped differs from attn_gated-3 by > 5% rel L1", n_gate > 0.05, sci(n_gate));
// ---- NEGATIVE: RoPE on adjacent pairs (2i, 2i+1), from the oracle's own normed q/k (control: 0.20 at kqv-3)
{
std::vector<float> qa(q_normed_ref), ka(k_normed_ref);
host_rope(qa, T * NH, (int) g.n_rot, g.rope_base, pos_q, true);
host_rope(ka, T * NKV, (int) g.n_rot, g.rope_base, pos_k, true);
std::vector<float> qn(q_normed_ref), kn(k_normed_ref); // the right reading on the host, as a control of the control
host_rope(qn, T * NH, (int) g.n_rot, g.rope_base, pos_q, false);
host_rope(kn, T * NKV, (int) g.n_rot, g.rope_base, pos_k, false);
verdict(name + ": host NEOX RoPE agrees with the oracle (the rival below is the only change), rel L2 <= 1e-5",
rel_l2(qn, q_ref) <= 1e-5 && rel_l2(kn, k_ref) <= 1e-5, sci(std::max(rel_l2(qn, q_ref), rel_l2(kn, k_ref))));
std::vector<double> Ka(ka.begin(), ka.end());
std::vector<float> kqv_a((size_t) NH * T * HD);
for (int64_t t = 0; t < T; ++t) {
std::vector<float> qi(qa.begin() + t * NH * HD, qa.begin() + (t + 1) * NH * HD);
ref_attend(qi, Ka, V32, T, t + 1, NH, NKV, row, nullptr);
for (int64_t h = 0; h < NH; ++h) std::memcpy(kqv_a.data() + ((size_t) h * T + t) * HD, row.data() + (size_t) h * HD, HD * 4);
}
const double n_rope = rel_l1(kqv_a, kqv_ref);
verdict(name + ": NEGATIVE: adjacent-pair RoPE differs from kqv-3 by > 5% rel L1", n_rope > 0.05, sci(n_rope));
}
// ---- NEGATIVE: the GQA map h % n_kv instead of h / G (visible only with more than one KV head; control 0.74)
if (NKV > 1 && NH / NKV > 1) {
std::vector<float> kqv_m((size_t) NH * T * HD);
for (int64_t t = 0; t < T; ++t) {
std::vector<float> qi(q_eng.begin() + t * NH * HD, q_eng.begin() + (t + 1) * NH * HD);
ref_attend(qi, K32, V32, T, t + 1, NH, NKV, row, nullptr, true);
for (int64_t h = 0; h < NH; ++h) std::memcpy(kqv_m.data() + ((size_t) h * T + t) * HD, row.data() + (size_t) h * HD, HD * 4);
}
const double n_map = rel_l1(kqv_m, kqv_ref);
verdict(name + ": NEGATIVE: the GQA map h % n_kv differs from kqv-3 by > 5% rel L1", n_map > 0.05, sci(n_map));
}
cudaFree(d_q); cudaFree(d_k); cudaFree(d_steps); cudaFree(d_scr); cudaFree(d_attn); cudaFree(d_qf); cudaFree(d_gated);
free_pools(P);
}
} // namespace
int main(int argc, char** argv) {
std::string fixtures;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--fixtures" && i + 1 < argc) fixtures = argv[++i];
else if (a == "--selftest") {}
else { std::fprintf(stderr, "usage: qsa_dense_parity [--fixtures DIR] [--selftest]\n"); return 2; }
}
std::printf("qsa_dense_parity: dense attention (Qwen3.6) through the split-K decode kernel and the prompt kernel\n");
section_dispatch();
int ndev = 0;
if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) { std::printf("SKIP: no CUDA device\n"); return 77; }
cudaDeviceProp prop{};
ck(cudaGetDeviceProperties(&prop, 0), "props");
std::printf("\n-- device: %s (sm_%d%d)\n", prop.name, prop.major, prop.minor);
std::mt19937 rng(2024);
std::printf("\n-- the decode kernel vs the host reference: G = 8 (16 / 2) and G = 12 (24 / 2), four KV formats, widths 300 / 3,000 / 20,000\n");
for (const int64_t heads : {16, 24})
for (const int mode : {0, 1, 2, 3})
for (const int64_t w : {300, 3000, 20000})
section_random(heads, 2, mode, w, rng, w == 3000);
std::printf("\n-- G = 2 (4 / 2), fp16, 3,000 cells\n");
section_random(4, 2, 0, 3000, rng, true);
if (!fixtures.empty()) {
const fs::path dir(fixtures);
if (fs::exists(dir / "SKIP") || !fs::exists(dir / "g8.gguf")) {
std::printf("SKIP: the fixtures in %s were not written (python3 with numpy and gguf-py)\n", fixtures.c_str());
return 77;
}
for (const char* n : {"g8", "g12", "g2"}) section_fixture(dir, n);
} else {
std::printf("\n(no --fixtures DIR: the oracle's seams were not checked)\n");
}
std::printf("\n%s: %d failure(s)\n", g_fail ? "FAIL" : "qsa_dense_parity OK", g_fail);
return g_fail ? 1 : 0;
}
-526
View File
@@ -1,526 +0,0 @@
// src/kernels/qwen36_seam_parity.cpp - Qwen3.6 step 3 (GDN, router, shared expert): the engine's DECODE kernels
// held to the numpy oracle's seams, by llama.cpp's cb() names, on the synthetic fixture.
//
// qwen36_seam_parity <dir> <dir> is what cmake/qwen36_oracle_dumps.cmake wrote: k.gguf, o_f32/, o_q8/
//
// The oracle (ref/qwen36.py) agrees with the pinned llama.cpp graph on every seam (docs/qwen36-port/
// oracle-crosscheck.md), so holding a kernel to its dumps is holding it to llama.cpp. The fixture is the toy
// geometry at the engine's pinned state size: hidden 64, GDN 2 k-heads / 4 v-heads of 128 (VPK 2, the real model's
// ratio), conv 4, 256 experts top-8 of 32, shared expert 512 wide in Q8_0, the BF16-read weights (ssm_alpha,
// ssm_beta, ffn_gate_inp, ffn_gate_inp_shexp) BF16-exact. 11 tokens, one at a time, the GDN state carried.
//
// Seams, per the study's step 3:
// GDN `conv_output_silu-0` (every token), `new_state-0` (after the 11th), `final_output-0` (every token),
// through every decode implementation: legacy (gdn.cu), pinned native (native_gdn*.cu), fused
// (fused_gdn.cu), and the verify window's multi-token kernels (verify_kernels.cu), which carry the
// state across two windows (8 + 3 tokens) the way verify.cpp does. The fused path also holds
// `fused_gdn_ab` to `gate-0` / `beta_sigmoid-0` and `fused_gdn_conv_l2` to `q_conv_predelta-0`.
// router `ffn_moe_topk-0` exact and `ffn_moe_weights_norm-0` from the oracle's own `ffn_moe_logits-0`,
// 256 experts, top-8, through `router_top10`.
// shexp `ffn_shexp_gated-0` through `shared_expert` on the native Q8_0 path (the 1-D BF16 scalar gate),
// against the Q8 oracle (the activation rounding the engine performs), and `shared_expert_multi`
// bitwise the per-token call.
//
// Negative cases, through the kernels, each required > 5% relative L1 before the right reading is judged: the
// sigmoid gate on `final_output-0` (the Flash-Next reading; the oracle's control says 1.07), the un-normalised
// router weights on `ffn_moe_weights_norm-0` (0.14), the shared expert's gate skipped on `ffn_shexp_gated-0`.
//
// Tolerances are relative L1 (|a-b| summed over |a| summed): the F32 oracle's per-seam classes of
// oracle-crosscheck.md ("Tolerance policy") where the kernel works in F32, the Q8 oracle with its 4x margin where
// the kernel rounds activations. Exit 77 when the fixture is absent (no python with numpy at configure time).
#include "strata/artifact/gguf_reader.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/gdn.hpp"
#include "strata/kernels/native_gdn.hpp"
#include "strata/kernels/native_gdn_preprocess.hpp"
#include "strata/kernels/native_mmvq.hpp"
#include "strata/kernels/router_top10.hpp"
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <string>
#include <vector>
namespace fs = std::filesystem;
using strata::kernels::GdnGate;
namespace {
void check(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
std::exit(1);
}
}
int g_bad = 0;
void within(const std::string& what, double rel, double tol) {
std::printf(" %-70s rel %.3e (tol %.0e)%s\n", what.c_str(), rel, tol, rel <= tol ? "" : " *** over tolerance ***");
if (!(rel <= tol)) ++g_bad;
}
void observable(const std::string& what, double rel) {
std::printf(" %-70s %-4s (%.2f%% apart)\n", what.c_str(), rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
if (!(rel > 0.05)) ++g_bad;
}
void yes(const std::string& what, bool ok) {
std::printf(" %-70s %s\n", what.c_str(), ok ? "yes" : "*** NO ***");
if (!ok) ++g_bad;
}
double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
double d = 0, m = 0;
for (size_t i = 0; i < a.size(); ++i) {
d += std::fabs((double) a[i] - (double) b[i]);
m += std::fabs((double) a[i]);
}
return d / (m > 1e-30 ? m : 1e-30);
}
double rel_l1(const float* a, const float* b, size_t n) {
return rel_l1(std::vector<float>(a, a + n), std::vector<float>(b, b + n));
}
std::vector<float> load_f32(const fs::path& dir, const std::string& stem, size_t want) {
const fs::path p = dir / (stem + ".f32");
FILE* f = std::fopen(p.string().c_str(), "rb");
if (!f) { std::fprintf(stderr, "cannot open %s\n", p.string().c_str()); std::exit(1); }
std::vector<float> v(want);
const size_t got = std::fread(v.data(), 4, want, f);
const bool more = std::fgetc(f) != EOF;
std::fclose(f);
if (got != want || more) {
std::fprintf(stderr, "%s: expected %zu floats, file has %s\n", p.string().c_str(), want, more ? "more" : "fewer");
std::exit(1);
}
return v;
}
template <class T>
T* dev(const std::vector<T>& h, const char* what) {
T* p = nullptr;
check(cudaMalloc(&p, h.size() * sizeof(T) + 64), what);
check(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), what);
return p;
}
template <class T>
T* dev_zero(size_t n, const char* what) {
T* p = nullptr;
check(cudaMalloc(&p, n * sizeof(T) + 64), what);
check(cudaMemset(p, 0, n * sizeof(T) + 64), what);
return p;
}
template <class T>
std::vector<T> host(const T* d, size_t n, const char* what) {
std::vector<T> h(n);
check(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), what);
return h;
}
/// A tensor of the fixture as raw bytes, with its GGUF `ne` and type checked.
struct Tensor {
std::vector<uint8_t> bytes;
std::vector<uint64_t> ne;
uint32_t type = 0;
const float* f32() const { return (const float*) bytes.data(); }
std::vector<float> floats() const { return std::vector<float>(f32(), f32() + bytes.size() / 4); }
};
Tensor tensor(const strata::GgufFile& g, const std::string& name, const std::vector<uint64_t>& ne, uint32_t type) {
const strata::TensorInfo* t = g.find(name);
if (!t) { std::fprintf(stderr, "%s: missing\n", name.c_str()); std::exit(1); }
if (t->shape != ne || t->type != type) {
std::fprintf(stderr, "%s: type %s ne", name.c_str(), t->type_name());
for (auto d : t->shape) std::fprintf(stderr, " %llu", (unsigned long long) d);
std::fprintf(stderr, " is not the fixture this test expects\n");
std::exit(1);
}
Tensor r;
r.ne = t->shape;
r.type = t->type;
r.bytes.assign(g.tensor_data(*t), g.tensor_data(*t) + strata::tensor_payload_bytes(*t));
return r;
}
std::vector<uint16_t> to_bf16(const std::vector<float>& f) {
std::vector<uint16_t> b(f.size());
for (size_t i = 0; i < f.size(); ++i) {
b[i] = strata::kernels::bf16_from_f32(f[i]);
if (strata::kernels::f32_from_bf16(b[i]) != f[i]) {
std::fprintf(stderr, "a BF16-read weight is not BF16-exact (the fixture was not written with --bf16-exact)\n");
std::exit(1);
}
}
return b;
}
// --------------------------------------------------------------------------------------------- geometry
constexpr int N = 64, HK = 2, HV = 4, S = 128, DC = 4;
constexpr int QK = HK * S, V = HV * S, C = 2 * QK + V;
constexpr int E = 256, K = 8, FF_SH = 512;
constexpr int T = 11;
constexpr float EPS = 1e-6f;
constexpr uint32_t GGML_F32 = 0, GGML_Q8_0 = 8;
/// The oracle's `new_state-0`: numpy (Hv, S_v = j, S_k = i) -> the engine's (i, h, j).
std::vector<float> oracle_state_to_engine(const std::vector<float>& o) {
std::vector<float> s((size_t) S * HV * S);
for (int h = 0; h < HV; ++h)
for (int j = 0; j < S; ++j)
for (int i = 0; i < S; ++i) s[((size_t) i * HV + h) * S + j] = o[((size_t) h * S + j) * S + i];
return s;
}
struct Fixture {
fs::path dir, o32, oq8;
// weights
std::vector<float> conv_w, ssm_norm, ssm_a, dt, alpha_w, beta_w;
std::vector<uint16_t> alpha_bf16, beta_bf16, ginp_bf16;
std::vector<uint8_t> sh_gate, sh_up, sh_down;
// oracle inputs and seams
std::vector<float> x_attn_norm, qkv, z, alpha_raw, beta_raw, gate_ref, beta_sig_ref, conv_silu_ref, q_pre_ref,
k_pre_ref, new_state_ref, final_ref, x_post_norm, logits, topk_ref, wnorm_ref, w_raw_ref, shexp_gated_q8,
shexp_gated_f32, shexp_ungated_q8;
};
Fixture load(const fs::path& dir) {
Fixture f;
f.dir = dir; f.o32 = dir / "o_f32"; f.oq8 = dir / "o_q8";
strata::GgufFile g((dir / "k.gguf").string());
f.conv_w = tensor(g, "blk.0.ssm_conv1d.weight", {DC, C}, GGML_F32).floats(); // ne0 = d_conv fastest: kW[c*4 + i]
f.ssm_norm = tensor(g, "blk.0.ssm_norm.weight", {S}, GGML_F32).floats();
f.ssm_a = tensor(g, "blk.0.ssm_a", {HV}, GGML_F32).floats();
f.dt = tensor(g, "blk.0.ssm_dt.bias", {HV}, GGML_F32).floats();
f.alpha_w = tensor(g, "blk.0.ssm_alpha.weight", {N, HV}, GGML_F32).floats(); // (HV, N) row-major
f.beta_w = tensor(g, "blk.0.ssm_beta.weight", {N, HV}, GGML_F32).floats();
f.alpha_bf16 = to_bf16(f.alpha_w);
f.beta_bf16 = to_bf16(f.beta_w);
f.ginp_bf16 = to_bf16(tensor(g, "blk.0.ffn_gate_inp_shexp.weight", {N}, GGML_F32).floats());
f.sh_gate = tensor(g, "blk.0.ffn_gate_shexp.weight", {N, FF_SH}, GGML_Q8_0).bytes; // FF_SH rows of N
f.sh_up = tensor(g, "blk.0.ffn_up_shexp.weight", {N, FF_SH}, GGML_Q8_0).bytes;
f.sh_down = tensor(g, "blk.0.ffn_down_shexp.weight", {FF_SH, N}, GGML_Q8_0).bytes; // N rows of FF_SH
f.x_attn_norm = load_f32(f.o32, "attn_norm-0", (size_t) T * N);
f.qkv = load_f32(f.o32, "linear_attn_qkv_mixed-0", (size_t) T * C);
f.z = load_f32(f.o32, "z-0", (size_t) T * V);
f.alpha_raw = load_f32(f.o32, "alpha-0", (size_t) T * HV);
f.beta_raw = load_f32(f.o32, "beta-0", (size_t) T * HV);
f.gate_ref = load_f32(f.o32, "gate-0", (size_t) T * HV);
f.beta_sig_ref = load_f32(f.o32, "beta_sigmoid-0", (size_t) T * HV);
f.conv_silu_ref = load_f32(f.o32, "conv_output_silu-0", (size_t) T * C);
f.q_pre_ref = load_f32(f.o32, "q_conv_predelta-0", (size_t) T * QK);
f.k_pre_ref = load_f32(f.o32, "k_conv_predelta-0", (size_t) T * QK);
f.new_state_ref = oracle_state_to_engine(load_f32(f.o32, "new_state-0", (size_t) HV * S * S));
f.final_ref = load_f32(f.o32, "final_output-0", (size_t) T * V);
f.x_post_norm = load_f32(f.o32, "attn_post_norm-0", (size_t) T * N);
f.logits = load_f32(f.o32, "ffn_moe_logits-0", (size_t) T * E);
f.topk_ref = load_f32(f.o32, "ffn_moe_topk-0", (size_t) T * K);
f.wnorm_ref = load_f32(f.o32, "ffn_moe_weights_norm-0", (size_t) T * K);
f.w_raw_ref = load_f32(f.o32, "ffn_moe_weights-0", (size_t) T * K);
f.shexp_gated_q8 = load_f32(f.oq8, "ffn_shexp_gated-0", (size_t) T * N);
f.shexp_gated_f32 = load_f32(f.o32, "ffn_shexp_gated-0", (size_t) T * N);
f.shexp_ungated_q8 = load_f32(f.oq8, "ffn_shexp-0", (size_t) T * N);
return f;
}
// --------------------------------------------------------------------------------------------- GDN
// The per-token scratch every path shares; the state and the conv history are reset per path.
struct GdnDev {
float *conv_hist, *state, *qkv_t, *conv_out, *h, *alpha, *beta, *gate, *o, *z_t, *y, *w, *norm, *a, *dt, *x_t;
uint16_t *alpha_bf16, *beta_bf16;
};
GdnDev gdn_dev(const Fixture& f) {
GdnDev d{};
d.conv_hist = dev_zero<float>((size_t) C * (DC - 1), "hist");
d.state = dev_zero<float>((size_t) S * HV * S, "state");
d.qkv_t = dev_zero<float>(C, "qkv");
d.conv_out = dev_zero<float>(C, "conv_out");
d.h = dev_zero<float>(C, "h");
d.alpha = dev_zero<float>(HV, "alpha");
d.beta = dev_zero<float>(HV, "beta");
d.gate = dev_zero<float>(HV, "gate");
d.o = dev_zero<float>(V, "o");
d.z_t = dev_zero<float>(V, "z");
d.y = dev_zero<float>(V, "y");
d.x_t = dev_zero<float>(N, "x");
d.w = dev(f.conv_w, "conv_w");
d.norm = dev(f.ssm_norm, "ssm_norm");
d.a = dev(f.ssm_a, "ssm_a");
d.dt = dev(f.dt, "dt");
d.alpha_bf16 = dev(f.alpha_bf16, "alpha_bf16");
d.beta_bf16 = dev(f.beta_bf16, "beta_bf16");
return d;
}
void gdn_reset(const GdnDev& d) {
check(cudaMemset(d.conv_hist, 0, (size_t) C * (DC - 1) * 4), "reset hist");
check(cudaMemset(d.state, 0, (size_t) S * HV * S * 4), "reset state");
check(cudaDeviceSynchronize(), "reset sync");
}
void token_inputs(const Fixture& f, const GdnDev& d, int t) {
check(cudaMemcpy(d.qkv_t, f.qkv.data() + (size_t) t * C, C * 4, cudaMemcpyHostToDevice), "qkv_t");
check(cudaMemcpy(d.z_t, f.z.data() + (size_t) t * V, V * 4, cudaMemcpyHostToDevice), "z_t");
check(cudaMemcpy(d.alpha, f.alpha_raw.data() + (size_t) t * HV, HV * 4, cudaMemcpyHostToDevice), "alpha_t");
check(cudaMemcpy(d.beta, f.beta_raw.data() + (size_t) t * HV, HV * 4, cudaMemcpyHostToDevice), "beta_t");
check(cudaMemcpy(d.x_t, f.x_attn_norm.data() + (size_t) t * N, N * 4, cudaMemcpyHostToDevice), "x_t");
check(cudaDeviceSynchronize(), "inputs sync");
}
/// One decode path over the 11 tokens. `path`: 0 legacy, 1 native, 2 fused. Returns the worst per-token relative
/// L1 at `conv_output_silu-0` and `final_output-0`, and the state's at the end; with `act` the gate used.
struct GdnResult { double conv = 0, final_out = 0, state = 0, gate = 0, beta = 0, qk_pre = 0; };
GdnResult run_gdn(const Fixture& f, const GdnDev& d, int path, GdnGate act, cudaStream_t cs) {
using namespace strata::kernels;
GdnResult r;
gdn_reset(d);
const strata::kernels::GdnShapes sh{S, HK, HV};
const float rs = 1.0f / std::sqrt((float) S);
for (int t = 0; t < T; ++t) {
token_inputs(f, d, t);
const float* conv_silu_t = f.conv_silu_ref.data() + (size_t) t * C;
if (path == 0) { // ---- legacy (gdn.cu + elementwise.cu)
gdn_conv_step(d.conv_hist, d.qkv_t, d.w, d.conv_out, C, DC, nullptr);
check(cudaMemcpy(d.h, d.conv_out, C * 4, cudaMemcpyDeviceToDevice), "h");
silu_inplace(d.h, C, nullptr);
check(cudaDeviceSynchronize(), "legacy conv");
r.conv = std::fmax(r.conv, rel_l1(conv_silu_t, host(d.h, C, "h").data(), C));
gdn_l2_norm(d.h, HK, S, EPS, nullptr);
gdn_l2_norm(d.h + QK, HK, S, EPS, nullptr);
scale_inplace(d.h, QK, rs, nullptr); // the legacy step wants q pre-scaled
gdn_beta_gate(d.beta, HV, nullptr);
gdn_gate(d.alpha, d.dt, d.a, d.gate, 1, HV, nullptr);
gdn_step(d.state, d.h, d.h + QK, d.h + 2 * QK, d.gate, d.beta, d.o, sh, nullptr);
gdn_out_norm(d.o, d.z_t, d.norm, d.y, HV, S, EPS, act, nullptr);
check(cudaDeviceSynchronize(), "legacy token");
} else if (path == 1) { // ---- pinned native, unfused
native_gdn_conv_silu(d.conv_hist, d.qkv_t, d.w, d.conv_out, d.h, C, DC, cs);
check(cudaStreamSynchronize(cs), "native conv");
r.conv = std::fmax(r.conv, rel_l1(conv_silu_t, host(d.h, C, "h").data(), C));
native_gdn_l2_norm(d.h, HK, S, EPS, cs);
native_gdn_l2_norm(d.h + QK, HK, S, EPS, cs);
native_gdn_beta_gate(d.beta, HV, cs);
native_gdn_gate(d.alpha, d.dt, d.a, d.gate, HV, cs);
native_gdn_step(d.state, d.h, d.h + QK, d.h + 2 * QK, d.gate, d.beta, d.o, sh, cs);
native_gdn_out_norm(d.o, d.z_t, d.norm, d.y, HV, S, EPS, act, cs);
check(cudaStreamSynchronize(cs), "native token");
} else { // ---- fused (the default native decode)
fused_gdn_conv_l2(d.conv_hist, d.qkv_t, d.w, d.h, C, 2 * HK, EPS, cs);
fused_gdn_ab(d.x_t, d.alpha_bf16, d.beta_bf16, d.dt, d.a, d.gate, d.beta, N, HV, cs);
check(cudaStreamSynchronize(cs), "fused pre");
const std::vector<float> h = host(d.h, C, "h");
// h is q|k L2-normalised (not pre-scaled) and v after SiLU: the v part is conv_output_silu's, the q/k
// parts are the oracle's q_conv_predelta / k_conv_predelta
r.conv = std::fmax(r.conv, rel_l1(conv_silu_t + 2 * QK, h.data() + 2 * QK, V));
r.qk_pre = std::fmax(r.qk_pre, rel_l1(f.q_pre_ref.data() + (size_t) t * QK, h.data(), QK));
r.qk_pre = std::fmax(r.qk_pre, rel_l1(f.k_pre_ref.data() + (size_t) t * QK, h.data() + QK, QK));
r.gate = std::fmax(r.gate, rel_l1(f.gate_ref.data() + (size_t) t * HV, host(d.gate, HV, "gate").data(), HV));
r.beta = std::fmax(r.beta, rel_l1(f.beta_sig_ref.data() + (size_t) t * HV, host(d.beta, HV, "beta").data(), HV));
fused_gdn_step_norm(d.state, d.h, d.h + QK, d.h + 2 * QK, d.gate, d.beta, d.z_t, d.norm, EPS, act, d.y, HK, HV, cs);
check(cudaStreamSynchronize(cs), "fused token");
}
r.final_out = std::fmax(r.final_out, rel_l1(f.final_ref.data() + (size_t) t * V, host(d.y, V, "y").data(), V));
}
r.state = rel_l1(f.new_state_ref, host(d.state, (size_t) S * HV * S, "state"));
return r;
}
/// The verify window's kernels: two windows (8 + 3 tokens) as verify.cpp runs them - the multi kernels over the
/// window from the untouched state, then the commit of every token (all accepted here).
GdnResult run_verify_window(const Fixture& f, const GdnDev& d, GdnGate act, cudaStream_t cs) {
using namespace strata::kernels;
GdnResult r;
gdn_reset(d);
float* qkv_all = dev(f.qkv, "qkv_all");
float* x_all = dev(f.x_attn_norm, "x_all");
float* z_all = dev(f.z, "z_all");
float* h_all = dev_zero<float>((size_t) T * C, "h_all");
float* gate_all = dev_zero<float>((size_t) T * HV, "gate_all");
float* beta_all = dev_zero<float>((size_t) T * HV, "beta_all");
float* y_all = dev_zero<float>((size_t) T * V, "y_all");
for (int t0 = 0; t0 < T; t0 += kVerifyMaxT) {
const int n = std::min(kVerifyMaxT, T - t0);
const std::vector<int32_t> keep{n};
int32_t* d_keep = dev(keep, "keep");
gdn_conv_l2_multi(d.conv_hist, qkv_all + (size_t) t0 * C, d.w, h_all + (size_t) t0 * C, C, 2 * HK, EPS, n, cs, 0);
gdn_ab_multi(x_all + (size_t) t0 * N, d.alpha_bf16, d.beta_bf16, d.dt, d.a, gate_all + (size_t) t0 * HV,
beta_all + (size_t) t0 * HV, N, HV, n, cs);
// verify: outputs for every token, the state untouched
gdn_step_norm_multi(d.state, h_all + (size_t) t0 * C, C, gate_all + (size_t) t0 * HV, beta_all + (size_t) t0 * HV,
z_all + (size_t) t0 * V, d.norm, EPS, act, y_all + (size_t) t0 * V, HK, HV, n, nullptr, cs, 0);
check(cudaStreamSynchronize(cs), "verify window");
for (int t = t0; t < t0 + n; ++t) {
const std::vector<float> h = host(h_all + (size_t) t * C, C, "h");
r.conv = std::fmax(r.conv, rel_l1(f.conv_silu_ref.data() + (size_t) t * C + 2 * QK, h.data() + 2 * QK, V));
r.qk_pre = std::fmax(r.qk_pre, rel_l1(f.q_pre_ref.data() + (size_t) t * QK, h.data(), QK));
r.qk_pre = std::fmax(r.qk_pre, rel_l1(f.k_pre_ref.data() + (size_t) t * QK, h.data() + QK, QK));
r.gate = std::fmax(r.gate, rel_l1(f.gate_ref.data() + (size_t) t * HV, host(gate_all + (size_t) t * HV, HV, "g").data(), HV));
r.beta = std::fmax(r.beta, rel_l1(f.beta_sig_ref.data() + (size_t) t * HV, host(beta_all + (size_t) t * HV, HV, "b").data(), HV));
r.final_out = std::fmax(r.final_out, rel_l1(f.final_ref.data() + (size_t) t * V, host(y_all + (size_t) t * V, V, "y").data(), V));
}
// commit: all n tokens accepted, conv history and state advance
gdn_conv_commit(d.conv_hist, qkv_all + (size_t) t0 * C, C, d_keep, cs);
gdn_step_norm_multi(d.state, h_all + (size_t) t0 * C, C, gate_all + (size_t) t0 * HV, beta_all + (size_t) t0 * HV,
z_all + (size_t) t0 * V, d.norm, EPS, act, d.y, HK, HV, n, d_keep, cs, n);
check(cudaStreamSynchronize(cs), "commit window");
cudaFree(d_keep);
}
r.state = rel_l1(f.new_state_ref, host(d.state, (size_t) S * HV * S, "state"));
cudaFree(qkv_all); cudaFree(x_all); cudaFree(z_all); cudaFree(h_all); cudaFree(gate_all); cudaFree(beta_all); cudaFree(y_all);
return r;
}
void gdn_section(const Fixture& f, cudaStream_t cs) {
std::printf("\n== GDN layer 0: %d k-heads / %d v-heads of %d (VPK %d), conv %d, %d tokens one at a time\n", HK, HV, S,
HV / HK, DC, T);
const GdnDev d = gdn_dev(f);
// tolerances: conv (one 4-tap f32 dot per channel) 1e-6; the oracle-crosscheck classes for the rest, F32 column
// with the 2x margin folded in: gate/beta (a 64-term dot against a BF16-exact weight) 1e-6, q/k L2 1e-6,
// final_output 8e-5 (the "gdn_out" class), the recurrent state after 11 tokens 2e-5.
const char* names[] = {"legacy (gdn.cu)", "native (native_gdn*.cu)", "fused (fused_gdn.cu)"};
for (int path = 0; path < 3; ++path) {
const GdnResult r = run_gdn(f, d, path, GdnGate::Silu, cs);
const std::string p = names[path];
within(p + ": conv_output_silu-0 (worst token)", r.conv, 1e-6);
if (path == 2) {
within(p + ": q_conv_predelta-0 / k_conv_predelta-0 (fused_gdn_conv_l2)", r.qk_pre, 1e-6);
within(p + ": gate-0 (fused_gdn_ab softplus epilogue)", r.gate, 1e-6);
within(p + ": beta_sigmoid-0 (fused_gdn_ab sigmoid epilogue)", r.beta, 1e-6);
}
within(p + ": final_output-0 (worst token, SiLU gate)", r.final_out, 8e-5);
within(p + ": new_state-0 after 11 tokens", r.state, 2e-5);
}
{
const GdnResult r = run_verify_window(f, d, GdnGate::Silu, cs);
const std::string p = "verify window (verify_kernels.cu, 8 + 3 tokens)";
within(p + ": conv_output_silu-0 v part / q,k predelta", std::fmax(r.conv, r.qk_pre), 1e-6);
within(p + ": gate-0 / beta_sigmoid-0 (gdn_ab_multi)", std::fmax(r.gate, r.beta), 1e-6);
within(p + ": final_output-0 (worst token, SiLU gate)", r.final_out, 8e-5);
within(p + ": new_state-0 after both commits", r.state, 2e-5);
}
// the negative: the Flash-Next gate through the kernels (the oracle's control: 1.07 at final_output-0)
{
const GdnResult r = run_gdn(f, d, 2, GdnGate::Sigmoid, cs);
observable("sigmoid gate (the qwen4exp reading) moves final_output-0 (negative)", r.final_out);
const GdnResult rv = run_verify_window(f, d, GdnGate::Sigmoid, cs);
observable("sigmoid gate through the verify window moves final_output-0 (negative)", rv.final_out);
}
}
// --------------------------------------------------------------------------------------------- router
void router_section(const Fixture& f) {
std::printf("\n== router layer 0: %d experts, top-%d, from the oracle's ffn_moe_logits-0 (%d tokens)\n", E, K, T);
float* d_l = dev(f.logits, "logits");
int* d_ids = dev_zero<int>((size_t) T * K, "ids");
float* d_w = dev_zero<float>((size_t) T * K, "w");
strata::kernels::router_top10(d_l, T, E, K, d_ids, d_w, nullptr);
const std::vector<int> ids = host(d_ids, (size_t) T * K, "ids");
const std::vector<float> w = host(d_w, (size_t) T * K, "w");
int id_bad = 0;
for (size_t i = 0; i < ids.size(); ++i) id_bad += ids[i] != (int) f.topk_ref[i];
yes("ffn_moe_topk-0: every (token, slot) identical (" + std::to_string(id_bad) + " differ)", id_bad == 0);
within("ffn_moe_weights_norm-0 (softmax, gather, renormalise)", rel_l1(f.wnorm_ref, w), 1e-5);
observable("un-normalised weights (ffn_moe_weights-0) differ from the normalised (negative)", rel_l1(f.wnorm_ref, f.w_raw_ref));
// every token's weights sum to 1 (the clamp at 2^-14 is unreachable: top-8 of 256 sums to at least 8/256)
double worst = 0;
for (int t = 0; t < T; ++t) {
double s = 0;
for (int i = 0; i < K; ++i) s += w[(size_t) t * K + i];
worst = std::fmax(worst, std::fabs(s - 1.0));
}
within("weights sum to 1 per token (|sum-1|)", worst, 1e-6);
cudaFree(d_l); cudaFree(d_ids); cudaFree(d_w);
}
// --------------------------------------------------------------------------------------------- shared expert
void shexp_section(const Fixture& f, cudaStream_t cs) {
using namespace strata::kernels;
std::printf("\n== shared expert layer 0: %d wide, Q8_0 weights on the native path, 1-D BF16 scalar gate (%d tokens)\n", FF_SH, T);
uint8_t* d_gate = dev(f.sh_gate, "sh_gate");
uint8_t* d_up = dev(f.sh_up, "sh_up");
uint8_t* d_down = dev(f.sh_down, "sh_down");
uint16_t* d_ginp = dev(f.ginp_bf16, "ginp");
float* d_x = dev(f.x_post_norm, "x_post_norm");
uint16_t* d_xb = dev_zero<uint16_t>((size_t) T * N, "x_bf16");
f32_to_bf16_bulk(d_x, d_xb, (int64_t) T * N, cs);
float* d_scratch = dev_zero<float>(shared_expert_scratch_bytes(FF_SH) / 4 + 16, "scratch");
const size_t q81 = native_q8_1_bytes(FF_SH > N ? FF_SH : N, kVerifyMaxT);
uint8_t* d_q81 = dev_zero<uint8_t>(q81, "q8_1");
float* d_out = dev_zero<float>((size_t) T * N, "out");
NativeSharedWeights nw;
nw.gate_type = (int) GGML_Q8_0; nw.gate_data = d_gate;
nw.up_type = (int) GGML_Q8_0; nw.up_data = d_up;
nw.down_type = (int) GGML_Q8_0; nw.down_data = d_down;
nw.q8_1 = d_q81;
const SForm dummy{2, -1, 64, Codebook::Affine, false, 0}; // unused: all three projections are native
shared_expert_set_native_bf16(true);
for (int t = 0; t < T; ++t)
shared_expert(nullptr, nullptr, d_xb + (size_t) t * N, dummy, nullptr, nullptr, nullptr, dummy, nullptr, nullptr,
nullptr, dummy, nullptr, nullptr, nullptr, d_ginp, d_scratch, d_out + (size_t) t * N, N, FF_SH, 32,
cs, d_x + (size_t) t * N, &nw);
check(cudaStreamSynchronize(cs), "shexp");
const std::vector<float> got = host(d_out, (size_t) T * N, "out");
// the Q8 oracle is the reference for a path that rounds activations to Q8_1; its class is ffn_out 2.1e-3 /
// 4.5e-3 on the real file where the EXPERT weights are IQ2/IQ3; here every weight is Q8_0 (exact integer
// products on both sides) so the only difference left is summation order
within("ffn_shexp_gated-0 vs the Q8 oracle (--act-quant q8)", rel_l1(f.shexp_gated_q8, got), 1e-5);
std::printf(" %-70s rel %.3e (the activation rounding itself; not a gate)\n", "ffn_shexp_gated-0 vs the F32 oracle",
rel_l1(f.shexp_gated_f32, got));
observable("the scalar gate skipped (ffn_shexp-0) differs from the gated (negative)", rel_l1(f.shexp_gated_q8, f.shexp_ungated_q8));
// the verify window's multi-token call: every token bitwise the per-token call
{
float* d_g = dev_zero<float>((size_t) kVerifyMaxT * FF_SH, "g");
float* d_u = dev_zero<float>((size_t) kVerifyMaxT * FF_SH, "u");
float* d_s = dev_zero<float>(kVerifyMaxT, "s");
float* d_out2 = dev_zero<float>((size_t) T * N, "out2");
for (int t0 = 0; t0 < T; t0 += kVerifyMaxT) {
const int n = std::min(kVerifyMaxT, T - t0);
shared_expert_multi(n, d_x + (size_t) t0 * N, d_xb + (size_t) t0 * N, nw, d_ginp, d_g, d_u, d_s,
d_out2 + (size_t) t0 * N, N, FF_SH, cs);
}
check(cudaStreamSynchronize(cs), "shexp multi");
const std::vector<float> got2 = host(d_out2, (size_t) T * N, "out2");
const double rel = rel_l1(got, got2);
const bool bitwise = std::memcmp(got.data(), got2.data(), got.size() * 4) == 0;
std::printf(" %-70s %s (rel %.3e)\n", "shared_expert_multi (8 + 3 tokens) vs per-token shared_expert", bitwise ? "bitwise" : "NOT bitwise", rel);
within("shared_expert_multi vs per-token (the multi-column MMVQ's own rounding)", rel, 1e-5);
cudaFree(d_g); cudaFree(d_u); cudaFree(d_s); cudaFree(d_out2);
}
shared_expert_set_native_bf16(false);
cudaFree(d_gate); cudaFree(d_up); cudaFree(d_down); cudaFree(d_ginp); cudaFree(d_x); cudaFree(d_xb);
cudaFree(d_scratch); cudaFree(d_q81); cudaFree(d_out);
}
} // namespace
int main(int argc, char** argv) {
if (argc != 2) {
std::fprintf(stderr, "usage: qwen36_seam_parity <dir with k.gguf, o_f32/, o_q8/ (cmake/qwen36_oracle_dumps.cmake)>\n");
return 2;
}
const fs::path dir = argv[1];
if (fs::exists(dir / "SKIP") || !fs::exists(dir / "k.gguf") || !fs::exists(dir / "o_f32" / "final_output-0.f32")) {
std::printf("qwen36_seam_parity: fixture not present in %s (no python3 with numpy and gguf-py?): skipped\n",
dir.string().c_str());
return 77;
}
int devices = 0;
if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
std::printf("qwen36_seam_parity: no CUDA device: skipped\n");
return 77;
}
const Fixture f = load(dir);
cudaStream_t cs = nullptr;
check(cudaStreamCreate(&cs), "stream"); // blocking: ordered after the synchronous memcpys that stage each token
gdn_section(f, cs);
router_section(f);
shexp_section(f, cs);
std::printf("\nqwen36_seam_parity: %d failures\n", g_bad);
cudaStreamDestroy(cs);
return g_bad ? 1 : 0;
}
+34 -53
View File
@@ -9,11 +9,6 @@
// logit distributions including ties (where the "smallest index wins" rule is the only thing that decides) and
// near-ties (where a float difference decides). It also asserts that the 2**-14 CLAMP CANNOT TRIGGER for this
// model's geometry - see below - so the absence of a clamp test is a proven fact rather than an omission.
//
// TWO GEOMETRIES: Flash-Next's 512 experts / top-10 and Qwen3.6-35B-A3B's 256 / top-8 (docs/QWEN36-35B-A3B.md 3.4).
// The kernel is generic in both (`router_top10.hpp`: n_expert <= 512, k <= 32), so this is the same five fixtures at
// the second shape, plus a tie of EXACTLY k experts (the whole top-k decided by index order and nothing else). The
// seams `ffn_moe_topk-N` / `ffn_moe_weights_norm-N` against the oracle at 256/8 are in qwen36_seam_parity.
#include "strata/kernels/router_top10.hpp"
#include <cuda_runtime.h>
@@ -121,65 +116,51 @@ int main(int argc, char** argv) {
else { std::fprintf(stderr, "usage: router_top10_parity [--selftest]\n"); return 2; }
}
const int NE = 512; // the real n_expert
const int K = 10; // the real top-k
const int NT = 64;
std::mt19937 rng(2024);
std::normal_distribution<float> gauss(0.0f, 1.0f);
int bad = 0;
// Flash-Next (qwen4exp): 512 experts, top-10. Qwen3.6-35B-A3B (qwen35moe): 256 experts, top-8.
const int geometries[2][2] = {{512, 10}, {256, 8}};
for (const auto& geo : geometries) {
const int NE = geo[0], K = geo[1];
std::printf("== %d experts, top-%d\n", NE, K);
// ---- random logits
std::vector<float> a((size_t) NT * NE);
for (auto& v : a) v = gauss(rng);
bad += run_case("random normal", a, NT, NE, K, 1e-5);
// ---- random logits
std::vector<float> a((size_t) NT * NE);
for (auto& v : a) v = gauss(rng);
bad += run_case("random normal", a, NT, NE, K, 1e-5);
// ---- ALL-EQUAL logits: every expert ties, so the "smallest index wins" rule is the ONLY thing deciding
// the ids. An unstable sort or a >= comparison in the maximum scan fails this and passes everything else.
std::vector<float> b((size_t) NT * NE, 0.5f);
bad += run_case("all equal (ties)", b, NT, NE, K, 1e-5);
// ---- ALL-EQUAL logits: every expert ties, so the "smallest index wins" rule is the ONLY thing deciding
// the ids. An unstable sort or a >= comparison in the maximum scan fails this and passes everything else.
std::vector<float> b((size_t) NT * NE, 0.5f);
bad += run_case("all equal (ties)", b, NT, NE, K, 1e-5);
// ---- a few exact ties among otherwise distinct values, WIDER than k: which k of the 12 is index order
std::vector<float> c((size_t) NT * NE);
for (int t = 0; t < NT; ++t) {
for (int e = 0; e < NE; ++e) c[(size_t) t * NE + e] = (e < 12) ? 2.0f : gauss(rng);
}
bad += run_case("12-way exact tie", c, NT, NE, K, 1e-5);
// ---- a few exact ties among otherwise distinct values
std::vector<float> c((size_t) NT * NE);
for (int t = 0; t < NT; ++t) {
for (int e = 0; e < NE; ++e) c[(size_t) t * NE + e] = (e < 12) ? 2.0f : gauss(rng);
}
bad += run_case("12-way exact tie", c, NT, NE, K, 1e-5);
// ---- a tie of EXACTLY k experts at the top, scattered through the index range (not the first k): the whole
// selection is the tie, in index order, and every weight is the same 1/k
std::vector<float> ck((size_t) NT * NE);
for (int t = 0; t < NT; ++t) {
for (int e = 0; e < NE; ++e) ck[(size_t) t * NE + e] = gauss(rng) - 4.0f;
for (int i = 0; i < K; ++i) ck[(size_t) t * NE + (size_t) ((t * 7 + i * (NE / K)) % NE)] = 3.0f;
}
char name[32];
std::snprintf(name, sizeof name, "%d-way (= k) exact tie", K);
bad += run_case(name, ck, NT, NE, K, 1e-5);
// ---- one dominant expert: the top-1 must be that expert and its weight must dominate
std::vector<float> d((size_t) NT * NE, 0.0f);
for (int t = 0; t < NT; ++t) d[(size_t) t * NE + (t % NE)] = 20.0f;
bad += run_case("dominant expert", d, NT, NE, K, 1e-5);
// ---- one dominant expert: the top-1 must be that expert and its weight must dominate
std::vector<float> d((size_t) NT * NE, 0.0f);
for (int t = 0; t < NT; ++t) d[(size_t) t * NE + (t % NE)] = 20.0f;
bad += run_case("dominant expert", d, NT, NE, K, 1e-5);
// ---- THE CLAMP CANNOT TRIGGER, and that is provable rather than untested.
// The sum of the top k of a probability vector over n outcomes is at least k/n (the minimum is the uniform
// distribution). At 512/10 k/n = 0.01953125, 320x the 2**-14 = 6.1035e-05 clamp; at 256/8 it is 0.03125,
// 512x. No input whatsoever can make either model's renormalisation clamp - not an extreme one, not an
// adversarial one. Asserting the bound is worth more than a test that cannot reach it.
const double min_possible = (double) K / (double) NE;
std::printf(" %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx %s\n", "clamp reachability",
K, min_possible, RENORM_CLAMP, min_possible / RENORM_CLAMP,
min_possible > RENORM_CLAMP ? "(CLAMP IS UNREACHABLE, asserted)" : "*** REACHABLE ***");
if (min_possible <= RENORM_CLAMP) {
std::fprintf(stderr, "the clamp CAN trigger, so it needs a test\n");
++bad;
}
// ---- THE CLAMP CANNOT TRIGGER, and that is provable rather than untested.
// The sum of the top k of a probability vector over n outcomes is at least k/n (the minimum is the uniform
// distribution). Here k/n = 10/512 = 0.01953125, which is 320x the 2**-14 = 6.1035e-05 clamp, so no input
// whatsoever can make this model's renormalisation clamp - not an extreme one, not an adversarial one.
// Asserting the bound is worth more than a test that cannot reach it.
const double min_possible = (double) K / (double) NE;
std::printf(" %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx %s\n", "clamp reachability",
K, min_possible, RENORM_CLAMP, min_possible / RENORM_CLAMP,
min_possible > RENORM_CLAMP ? "(CLAMP IS UNREACHABLE, asserted)" : "*** REACHABLE ***");
if (min_possible <= RENORM_CLAMP) {
std::fprintf(stderr, "the clamp CAN trigger, so it needs a test\n");
++bad;
}
std::printf("\nrouter_top10: %d failures over 5 distributions x %d tokens at 512/10 and 256/8\n", bad, NT);
std::printf("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n", bad, NT, NE,
K);
if (bad) return 1;
if (selftest) std::printf("router_top10_parity OK\n");
return 0;
+8 -156
View File
@@ -20,7 +20,6 @@
#include <limits>
#include <random>
#include <string>
#include <unordered_map>
#include <vector>
namespace {
@@ -32,65 +31,6 @@ void check(cudaError_t e, const char* what) {
}
}
// ---- DRY host reference, transcribed from llama.cpp's `llama_sampler_dry_apply` (Step 1 restart sequences,
// then a NAIVE repeat-length computation in place of the Z-algorithm: an independent check of the device's
// Z-array). `hist` is the row, oldest to newest; only its last `dry_penalty_last_n` entries are read. The
// result is token -> maximum repeat length, from which Step 4 subtracts `multiplier * base^(len - allowed)`.
std::unordered_map<int, int> host_dry_map(const std::vector<int>& hist, const strata::kernels::SamplerParams& p,
const std::vector<std::vector<int>>& breakers) {
std::unordered_map<int, int> out;
if (!strata::kernels::dry_enabled(p)) return out;
const int dlen = (int) std::min<size_t>((size_t) std::max(p.dry_penalty_last_n, 0), hist.size());
if (dlen <= p.dry_allowed_length) return out;
auto rat = [&](int x) { return hist[(size_t) (dlen - 1 - x)]; }; // rat(0) is the newest token
int rep_limit = dlen;
for (int i = 0; i < dlen; ++i) {
const int token = rat(i);
int longest = -1;
for (const auto& s : breakers) {
if (s.empty() || s[0] != token) continue;
const int sl = (int) s.size() - 1; // the tail length (head already matched)
if (sl > longest && sl <= i) {
bool match = true;
for (int off = 0; off < sl; ++off)
if (s[(size_t) (1 + off)] != rat(i - off - 1)) { match = false; break; }
if (match) longest = sl;
}
}
if (longest >= 0) { rep_limit = i - longest; break; }
}
if (rep_limit < p.dry_allowed_length) return out;
const int last = dlen - 1;
std::vector<int> drep((size_t) dlen, 0);
for (int k = 1; k < dlen; ++k) {
int n = 0;
while (n + k < dlen && rat(n) == rat(n + k)) ++n;
drep[(size_t) (last - k)] = std::min(n, rep_limit);
}
for (int i = 0; i < dlen - 1; ++i) {
const int repeat_len = drep[(size_t) i];
if (repeat_len >= p.dry_allowed_length) {
const int token = rat(dlen - 2 - i);
auto it = out.find(token);
if (it == out.end() || it->second < repeat_len) out[token] = repeat_len;
}
}
return out;
}
bool host_single_token_breaker(int id, const std::vector<std::vector<int>>& breakers) {
for (const auto& s : breakers) if (s.size() == 1 && s[0] == id) return true;
return false;
}
float host_dry_penalty(int repeat_len, const strata::kernels::SamplerParams& p) {
int max_exponent = 0;
if (p.dry_base > 1.000001f) max_exponent = (int) (88.7228391f / std::log(p.dry_base));
int e = repeat_len - p.dry_allowed_length;
if (max_exponent > 0 && e > max_exponent) e = max_exponent;
return p.dry_multiplier * std::pow(p.dry_base, (float) e);
}
// The host reference for the specified order: top_k -> top_p -> temperature -> argmax.
// `temp_first` swaps the first and last stages, which is the intuitive-but-wrong order.
int reference_pick(const std::vector<float>& l, const strata::kernels::SamplerParams& p, bool temp_first) {
@@ -162,8 +102,7 @@ int reference_cut(const std::vector<float>& l, const strata::kernels::SamplerPar
}
int run(const char* name, const std::vector<float>& logits, int n_tokens, const strata::kernels::SamplerParams& p,
const std::vector<int>& want, const std::vector<int>& hist = {}, int hist_len = 0,
const std::vector<std::vector<int>>* breakers = nullptr) {
const std::vector<int>& want, const std::vector<int>& hist = {}, int hist_len = 0) {
float* d_l = nullptr;
int* d_o = nullptr;
check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits");
@@ -177,27 +116,8 @@ int run(const char* name, const std::vector<float>& logits, int n_tokens, const
check(cudaMalloc(&d_h, hist.size() * sizeof(int)), "malloc hist");
check(cudaMemcpy(d_h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist");
}
// The DRY breakers as the device wants them: a flat id array plus `n + 1` offsets.
strata::kernels::DryBreakers br;
int* d_bf = nullptr;
int* d_bo = nullptr;
std::vector<int> flat, off;
if (breakers != nullptr && !breakers->empty()) {
off.push_back(0);
for (const auto& s : *breakers) {
for (int id : s) flat.push_back(id);
off.push_back((int) flat.size());
}
check(cudaMalloc(&d_bf, flat.size() * sizeof(int)), "malloc breakers flat");
check(cudaMemcpy(d_bf, flat.data(), flat.size() * sizeof(int), cudaMemcpyHostToDevice), "copy breakers flat");
check(cudaMalloc(&d_bo, off.size() * sizeof(int)), "malloc breakers off");
check(cudaMemcpy(d_bo, off.data(), off.size() * sizeof(int), cudaMemcpyHostToDevice), "copy breakers off");
br.flat = d_bf;
br.off = d_bo;
br.n = (int) breakers->size();
}
strata::kernels::sample_tokens(d_l, n_tokens, (int) (logits.size() / n_tokens), d_h, hist_len, p, d_o,
nullptr, br);
nullptr);
std::vector<int> got((size_t) n_tokens);
check(cudaMemcpy(got.data(), d_o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back");
int bad = 0;
@@ -208,8 +128,6 @@ int run(const char* name, const std::vector<float>& logits, int n_tokens, const
cudaFree(d_l);
cudaFree(d_o);
if (d_h) cudaFree(d_h);
if (d_bf) cudaFree(d_bf);
if (d_bo) cudaFree(d_bo);
return bad;
}
@@ -244,18 +162,11 @@ float host_philox_uniform(uint64_t seed, uint64_t counter) {
// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at
// (seed, counter + row). One penalties stage (issue #53: this reference used to repeat the kernel's second one).
int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
const strata::kernels::SamplerParams& p, int row,
const std::vector<std::vector<int>>* breakers = nullptr) {
const std::unordered_map<int, int> dry = breakers ? host_dry_map(hist, p, *breakers)
: std::unordered_map<int, int>{};
auto penal = [&](float logit, int count, int v) {
if (count > 0) {
if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
}
const auto it = dry.find(v);
if (it != dry.end() && !(breakers && host_single_token_breaker(v, *breakers)))
logit -= host_dry_penalty(it->second, p);
const strata::kernels::SamplerParams& p, int row) {
auto penal = [&](float logit, int count) {
if (count <= 0) return logit;
if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
return logit;
};
auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; };
@@ -269,7 +180,7 @@ int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
int best = -1; float bv = 0;
for (int v = 0; v < nv; ++v) {
if (taken[(size_t) v]) continue;
const float s = penal(l[(size_t) v], count(v), v);
const float s = penal(l[(size_t) v], count(v));
if (best < 0 || s > bv) { best = v; bv = s; }
}
taken[(size_t) best] = 1;
@@ -1085,65 +996,6 @@ int main(int argc, char** argv) {
bad += wrong;
}
// ---- fixture 19: DRY (llama.cpp's `dry` sampler). A window of the last `dry_penalty_last_n` tokens is
// scanned for repeats; a token that would EXTEND a repeat longer than `dry_allowed_length` loses
// `mult * base^(len - allowed)`. The window here is 7 9 7 9 7 9 (newest last): the longest repeat is 4 and
// the token that continues it is 7, so token 7 is penalised 1.0 * 1.75^2 = 3.0625 and loses to token 9.
// Two breaker cases pin Step 1: the single-token breaker [7] makes 7 a restart head and it is NOT penalised
// (llama.cpp's empty tail rule); the multi-token breaker [9, 7] caps `rep_limit` at 1 so DRY does nothing.
{
const int W = 6, NVd = 16;
const std::vector<int> win = {7, 9, 7, 9, 7, 9};
std::vector<float> row((size_t) NVd, -8.0f);
row[7] = 5.0f; row[9] = 4.5f; row[3] = 4.0f;
strata::kernels::SamplerParams p;
p.greedy = true; p.temperature = 0.0f; p.top_k = 0; p.top_p = 1.0f;
p.penalty_last_n = 0; // DRY only, so the reference's count scan cannot interfere
p.dry_multiplier = 1.0f; p.dry_base = 1.75f; p.dry_allowed_length = 2; p.dry_penalty_last_n = W;
const std::vector<std::vector<int>> none = {};
const std::vector<std::vector<int>> single = {{7}};
const std::vector<std::vector<int>> multi = {{9, 7}};
auto greedy_dry = [&](const std::vector<std::vector<int>>& br) {
const std::unordered_map<int, int> map = host_dry_map(win, p, br);
int best = 0; float bv = 0; bool first = true;
for (int v = 0; v < NVd; ++v) {
float s = row[(size_t) v];
const auto it = map.find(v);
if (it != map.end() && !host_single_token_breaker(v, br)) s -= host_dry_penalty(it->second, p);
if (first || s > bv) { bv = s; best = v; first = false; }
}
return best;
};
const int d_none = greedy_dry(none), d_single = greedy_dry(single), d_multi = greedy_dry(multi);
const bool observable = d_none == 9 && d_single == 7 && d_multi == 7;
std::printf(" %-34s %s (dry %d, single-token breaker %d, multi-token breaker %d)\n",
"DRY changes the pick", observable ? "yes" : "*** NO ***", d_none, d_single, d_multi);
if (!observable) ++bad;
else {
bad += run("DRY: no breakers (greedy)", row, 1, p, {d_none}, win, W, &none);
bad += run("DRY: single-token breaker", row, 1, p, {d_single}, win, W, &single);
bad += run("DRY: multi-token breaker", row, 1, p, {d_multi}, win, W, &multi);
}
// The sampled chain over the same window: the full chain with the host Philox must match draw for draw.
// Every row carries the same window, so the history buffer is 64 rows of it (the kernel reads one row
// per sampled row at a stride of `history_len`).
const int NTd = 64;
std::vector<float> l((size_t) NVd * NTd);
std::vector<int> hrows((size_t) NTd * W);
for (int t = 0; t < NTd; ++t) {
std::copy(row.begin(), row.end(), l.begin() + (size_t) t * NVd);
std::copy(win.begin(), win.end(), hrows.begin() + (size_t) t * W);
}
strata::kernels::SamplerParams sp = p;
sp.greedy = false; sp.temperature = 1.0f; sp.top_k = 4; sp.top_p = 1.0f; sp.seed = 19; sp.counter = 0;
std::vector<int> want((size_t) NTd);
for (int t = 0; t < NTd; ++t) want[(size_t) t] = sampled_reference(row, win, sp, t, &none);
bad += run("DRY: sampled chain", l, NTd, sp, want, hrows, W, &none);
}
// A continuous stream and individual decode calls consume the same draw counters.
{
constexpr int count = 32, vocab = 16;
-191
View File
@@ -15,13 +15,10 @@
// readings are a per-dimension elementwise gate and a per-expert gate. The elementwise reading is
// checked the same way - it is computed and required to differ.
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/f16_bits.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s_gemv.hpp"
#include "strata/kernels/native_mmvq.hpp"
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include <cuda_runtime.h>
@@ -405,194 +402,6 @@ int main(int argc, char** argv) {
cudaFree(d_witness);
}
// ================= Qwen3.6: the shared expert at 2048 x 512, Q8_0 on the native path, the 1-D BF16 gate =================
//
// Qwen3.6-35B-A3B's shared expert is 512 wide (docs/QWEN36-35B-A3B.md 3.4): `n_ff % 256 == 0`, so the Q8_K
// activation rule the 640-wide Flash-Next expert could not meet is met (geometry-inventory.md row 127), and the
// real file serves it through the NATIVE projections (ggml types, `native_mmvq`, Q8_1 activations) rather than the
// canonical S-forms above. Its scalar gate `ffn_gate_inp_shexp` is F32 in the file and the engine reads it as
// BF16 (the pack rounds it under --compat-bf16): the reference below dots the F32 activation with the
// BF16-rounded weight, as the native BF16 MMVF does, and REPORTS what the rounding moved against the unrounded
// F32 gate (a number for the step-4 --compat-bf16 decision, not an assertion).
//
// The host reference is written from the block layouts, not from the kernels: Q8_0 weights (gguf-py's
// quantizer: integers from the F32 scale amax/127, the scale stored as fp16), Q8_1 activations (ggml-cuda
// quantize_q8_1: integers from the F32 scale, fp16 scale in the dot), silu(gate) * up in F32, the intermediate
// re-quantized to Q8_1 for the down projection, times sigmoid(x . bf16(w)).
{
using namespace strata::kernels;
const int n_embd2 = 2048, n_ff2 = 512;
std::mt19937 rq(4242);
std::normal_distribution<float> gq(0.0f, 1.0f);
std::printf("\n== Qwen3.6 shared expert: %d x %d, Q8_0 native projections, BF16 scalar gate\n", n_embd2, n_ff2);
// ---- Q8_0 rows (34 B per 32 elements: fp16 d, 32 int8), from F32 values; returns the dequantized value too
auto q8_0_rows = [&](int rows, int cols, float gain, std::vector<uint8_t>& bytes, std::vector<float>& deq) {
bytes.assign((size_t) rows * (cols / 32) * 34, 0);
deq.assign((size_t) rows * cols, 0.0f);
for (int r = 0; r < rows; ++r)
for (int b = 0; b < cols / 32; ++b) {
float v[32], amax = 0.0f;
for (int i = 0; i < 32; ++i) { v[i] = gq(rq) * gain; amax = std::fmax(amax, std::fabs(v[i])); }
const float d = amax / 127.0f;
const float id = d != 0.0f ? 1.0f / d : 0.0f;
const uint16_t d16 = f16_from_f32(d);
uint8_t* blk = bytes.data() + ((size_t) r * (cols / 32) + b) * 34;
std::memcpy(blk, &d16, 2);
for (int i = 0; i < 32; ++i) {
const int q = (int) std::nearbyint(v[i] * id);
((int8_t*) (blk + 2))[i] = (int8_t) q;
deq[(size_t) r * cols + b * 32 + i] = (float) q * f32_from_f16(d16);
}
}
};
std::vector<uint8_t> gb, ub, db;
std::vector<float> gw, uw, dw;
q8_0_rows(n_ff2, n_embd2, 1.0f / std::sqrt((float) n_embd2) * 2.0f, gb, gw);
q8_0_rows(n_ff2, n_embd2, 1.0f / std::sqrt((float) n_embd2) * 2.0f, ub, uw);
q8_0_rows(n_embd2, n_ff2, 1.0f / std::sqrt((float) n_ff2), db, dw);
std::vector<float> x2((size_t) n_embd2);
for (auto& v : x2) v = gq(rq);
// the gate weight: F32, drawn so the dot sits around -1 (sigmoid 0.27), where skipping the gate is loud
std::vector<float> ginp32((size_t) n_embd2);
for (auto& v : ginp32) v = gq(rq) * 0.03f;
{
double dot = 0, xx = 0;
for (int i = 0; i < n_embd2; ++i) { dot += (double) x2[(size_t) i] * ginp32[(size_t) i]; xx += (double) x2[(size_t) i] * x2[(size_t) i]; }
const float shift = (float) ((-1.0 - dot) / xx); // w += shift * x moves the dot to -1
for (int i = 0; i < n_embd2; ++i) ginp32[(size_t) i] += shift * x2[(size_t) i];
}
std::vector<uint16_t> ginp_bf((size_t) n_embd2);
for (int i = 0; i < n_embd2; ++i) ginp_bf[(size_t) i] = bf16_from_f32(ginp32[(size_t) i]);
// ---- the Q8_1 image of an F32 row (values only: integers from the F32 scale, the fp16 scale in the product)
auto q8_1_values = [](const std::vector<float>& x) {
std::vector<float> out(x.size());
for (size_t b = 0; b < x.size() / 32; ++b) {
float amax = 0.0f;
for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(x[b * 32 + i]));
const float d = amax / 127.0f;
const float d16 = f32_from_f16(f16_from_f32(d));
for (int i = 0; i < 32; ++i) {
const int q = amax == 0.0f ? 0 : (int) std::nearbyint(x[b * 32 + i] / d);
out[b * 32 + i] = (float) q * d16;
}
}
return out;
};
auto reference2 = [&](bool silu_on_up, bool gate_skipped, bool gate_f32) {
const std::vector<float> xq = q8_1_values(x2);
std::vector<float> gp((size_t) n_ff2), up((size_t) n_ff2), h((size_t) n_ff2);
for (int r = 0; r < n_ff2; ++r) {
double a = 0, b = 0;
for (int i = 0; i < n_embd2; ++i) {
a += (double) xq[(size_t) i] * gw[(size_t) r * n_embd2 + i];
b += (double) xq[(size_t) i] * uw[(size_t) r * n_embd2 + i];
}
gp[(size_t) r] = (float) a; up[(size_t) r] = (float) b;
}
for (int r = 0; r < n_ff2; ++r) {
const float g = silu_on_up ? up[(size_t) r] : gp[(size_t) r];
const float o = silu_on_up ? gp[(size_t) r] : up[(size_t) r];
h[(size_t) r] = (g / (1.0f + std::exp(-g))) * o;
}
const std::vector<float> hq = q8_1_values(h);
std::vector<float> out((size_t) n_embd2);
double dot = 0;
for (int i = 0; i < n_embd2; ++i)
dot += (double) x2[(size_t) i] * (gate_f32 ? (double) ginp32[(size_t) i] : (double) f32_from_bf16(ginp_bf[(size_t) i]));
const double sg = gate_skipped ? 1.0 : 1.0 / (1.0 + std::exp(-dot));
for (int o = 0; o < n_embd2; ++o) {
double a = 0;
for (int r = 0; r < n_ff2; ++r) a += (double) hq[(size_t) r] * dw[(size_t) o * n_ff2 + r];
out[(size_t) o] = (float) (a * sg);
}
return out;
};
const std::vector<float> want2 = reference2(false, false, false);
{
const double r_silu = rel_l1(want2, reference2(true, false, false));
const double r_gate = rel_l1(want2, reference2(false, true, false));
std::printf(" %-56s %-4s (%.2f%% apart)\n", "silu-on-gate vs silu-on-up is observable at 512",
r_silu > 0.05 ? "yes" : "*** NO ***", r_silu * 100);
if (!(r_silu > 0.05)) ++bad;
std::printf(" %-56s %-4s (%.2f%% apart)\n", "the scalar gate skipped is observable",
r_gate > 0.05 ? "yes" : "*** NO ***", r_gate * 100);
if (!(r_gate > 0.05)) ++bad;
const double r_bf16 = rel_l1(reference2(false, false, true), want2);
std::printf(" %-56s rel %.3e (measured, not asserted: the --compat-bf16 rounding of the gate)\n",
"F32 gate weight vs its BF16 rounding, on the output", r_bf16);
}
// ---- the kernel: all three projections native, the native BF16 gate, per the layer's call in moe_shared
uint8_t *d_gb = nullptr, *d_ub = nullptr, *d_db = nullptr, *d_q81 = nullptr;
float *d_x2 = nullptr, *d_out2 = nullptr, *d_scr2 = nullptr;
uint16_t *d_ginp2 = nullptr, *d_xb2 = nullptr;
check(cudaMalloc(&d_gb, gb.size()), "gb"); check(cudaMemcpy(d_gb, gb.data(), gb.size(), cudaMemcpyHostToDevice), "gb");
check(cudaMalloc(&d_ub, ub.size()), "ub"); check(cudaMemcpy(d_ub, ub.data(), ub.size(), cudaMemcpyHostToDevice), "ub");
check(cudaMalloc(&d_db, db.size()), "db"); check(cudaMemcpy(d_db, db.data(), db.size(), cudaMemcpyHostToDevice), "db");
check(cudaMalloc(&d_x2, x2.size() * 4), "x2"); check(cudaMemcpy(d_x2, x2.data(), x2.size() * 4, cudaMemcpyHostToDevice), "x2");
check(cudaMalloc(&d_ginp2, ginp_bf.size() * 2), "ginp2");
check(cudaMemcpy(d_ginp2, ginp_bf.data(), ginp_bf.size() * 2, cudaMemcpyHostToDevice), "ginp2");
check(cudaMalloc(&d_xb2, (size_t) n_embd2 * 2), "xb2");
check(cudaMalloc(&d_out2, (size_t) n_embd2 * 4), "out2");
check(cudaMalloc(&d_scr2, shared_expert_scratch_bytes(n_ff2)), "scr2");
check(cudaMalloc(&d_q81, native_q8_1_bytes(n_embd2, kVerifyMaxT)), "q81");
cudaStream_t cs2 = nullptr;
check(cudaStreamCreate(&cs2), "cs2");
f32_to_bf16_bulk(d_x2, d_xb2, n_embd2, cs2);
NativeSharedWeights nw2;
nw2.gate_type = 8; nw2.gate_data = d_gb; // GGML_TYPE_Q8_0 = 8
nw2.up_type = 8; nw2.up_data = d_ub;
nw2.down_type = 8; nw2.down_data = d_db;
nw2.q8_1 = d_q81;
shared_expert_set_native_bf16(true);
shared_expert(nullptr, nullptr, d_xb2, f, nullptr, nullptr, nullptr, f, nullptr, nullptr, nullptr, f, nullptr, nullptr,
nullptr, d_ginp2, d_scr2, d_out2, n_embd2, n_ff2, tpr, cs2, d_x2, &nw2);
check(cudaStreamSynchronize(cs2), "shexp 512");
std::vector<float> got2((size_t) n_embd2);
check(cudaMemcpy(got2.data(), d_out2, got2.size() * 4, cudaMemcpyDeviceToHost), "got2");
long long nonfinite2 = 0;
for (float v : got2) nonfinite2 += !std::isfinite(v);
const double rel2 = rel_l1(want2, got2);
std::printf(" %-56s rel %.3e over %d outputs%s\n", "shared_expert (native Q8_0, BF16 gate) vs reference", rel2,
n_embd2, nonfinite2 ? " *** NON-FINITE ***" : "");
// Q8_0 x Q8_1 products are exact integers on both sides; what remains is the fp16 scale products' summation
// order over 64 blocks and a Q8_1 integer that may round differently in f32 and double at a .5 boundary
if (!(rel2 <= 1e-4) || nonfinite2) ++bad;
// the verify window's call, 1 and 8 tokens of the same x: bitwise the per-token call per column
{
float *d_g8 = nullptr, *d_u8 = nullptr, *d_s8 = nullptr, *d_o8 = nullptr, *d_x8 = nullptr;
uint16_t* d_xb8 = nullptr;
check(cudaMalloc(&d_g8, (size_t) kVerifyMaxT * n_ff2 * 4), "g8");
check(cudaMalloc(&d_u8, (size_t) kVerifyMaxT * n_ff2 * 4), "u8");
check(cudaMalloc(&d_s8, (size_t) kVerifyMaxT * 4), "s8");
check(cudaMalloc(&d_o8, (size_t) kVerifyMaxT * n_embd2 * 4), "o8");
check(cudaMalloc(&d_x8, (size_t) kVerifyMaxT * n_embd2 * 4), "x8");
check(cudaMalloc(&d_xb8, (size_t) kVerifyMaxT * n_embd2 * 2), "xb8");
for (int t = 0; t < kVerifyMaxT; ++t) {
check(cudaMemcpy(d_x8 + (size_t) t * n_embd2, x2.data(), x2.size() * 4, cudaMemcpyHostToDevice), "x8");
}
f32_to_bf16_bulk(d_x8, d_xb8, (int64_t) kVerifyMaxT * n_embd2, cs2);
shared_expert_multi(kVerifyMaxT, d_x8, d_xb8, nw2, d_ginp2, d_g8, d_u8, d_s8, d_o8, n_embd2, n_ff2, cs2);
check(cudaStreamSynchronize(cs2), "multi 512");
std::vector<float> o8((size_t) kVerifyMaxT * n_embd2);
check(cudaMemcpy(o8.data(), d_o8, o8.size() * 4, cudaMemcpyDeviceToHost), "o8");
double worst8 = 0;
for (int t = 0; t < kVerifyMaxT; ++t)
worst8 = std::fmax(worst8, rel_l1(got2, std::vector<float>(o8.begin() + (size_t) t * n_embd2,
o8.begin() + (size_t) (t + 1) * n_embd2)));
std::printf(" %-56s worst rel %.3e over %d tokens\n", "shared_expert_multi vs per-token shared_expert", worst8,
kVerifyMaxT);
if (!(worst8 <= 1e-5)) ++bad;
cudaFree(d_g8); cudaFree(d_u8); cudaFree(d_s8); cudaFree(d_o8); cudaFree(d_x8); cudaFree(d_xb8);
}
shared_expert_set_native_bf16(false);
cudaStreamDestroy(cs2);
cudaFree(d_gb); cudaFree(d_ub); cudaFree(d_db); cudaFree(d_q81); cudaFree(d_x2); cudaFree(d_out2); cudaFree(d_scr2);
cudaFree(d_ginp2); cudaFree(d_xb2);
}
// ================= moe_combine: the two readings it exists to pin =================
//
// `ref/moe.py` L156 is `routed + shared_expert(...)`, and the routed half is `out[t] += w[t,i] * g[0]`
+43 -251
View File
@@ -1,38 +1,23 @@
// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit, against a reference, and timed.
// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit and timed.
//
// src/prefill/kernels.cu runs gdn_rec_kh_kernel (the value heads that share a key head in one thread, the inputs
// staged in blocks of 8 tokens) on CUDA sm_80+ cards that hold all 64 of its blocks at once, and
// src/prefill/kernels.cu runs gdn_rec_kh_kernel (the three value heads that share a key head in one thread, the
// inputs staged in blocks of 8 tokens) on CUDA sm_80+ cards that hold all 64 of its blocks at once, and
// gdn_rec_cols_pipe_kernel elsewhere and with STRATA_GDN_KEYHEAD=0. Both are copied below verbatim, with the output
// norm (gdn_out_norm_kernel) and the norm as it was before, which also stored the normalized value in FP32 although
// nothing reads it. The two recurrences do the same arithmetic in the same order per value head and column, so the
// output, the state after it and the FP16 output must be the same bits.
//
// Qwen3.6 port (step 3): the kernels are templates on the head geometry, <HV, HK, C> = <48, 16, 10240> (Flash-Next,
// 3 value heads per key head, the sigmoid(z) output gate) and <32, 16, 8192> (Qwen3.6, 2 per key head, SiLU(z)), and
// the engine's own launches (gdn_conv, gdn_recurrence through their GdnGeom) are held to a double-precision host
// transcription of the recurrence (docs/qwen36-port/oracle-crosscheck.md, "Gated DeltaNet": decay before the rank-1
// update, v-head h paired with k-head h % HK, the gated RMS-normed output). Negative controls, in the repo's
// discipline (gdn_parity.cpp): each rival reading is computed with the same reference and must sit more than 5 %
// relative L1 from the right one before the kernel is judged - the sigmoid gate on the SiLU model, the interleaved
// head pairing (h // VPK) - and a geometry the kernels are not built for (a third value head per key head on 32 heads,
// i.e. Flash-Next's 48-head channel layout on Qwen3.6's heads) is refused by gdn_geometry_supported, not mis-indexed.
//
// Synthetic inputs of the model's shape (q/k L2-normalized per key head as gdn_l2_kernel leaves them), no model.
// gdn_rec_parity the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk), both
// geometries; the reference checks and the negative controls
// gdn_rec_parity --bench and the timings at T = 8192 and 32768 (one layer, all value heads, both geometries);
// the two variants' launches alternate, since a card under load steps its clock down
// after a fraction of a second (see native_grouped_parity); then (Flash-Next) both at 1
// to 6 blocks per SM, as on cards with more or fewer SMs (scale), and both with the
// engine's grids on 32 to all of this card's SMs, the others held by a sleeping kernel
// (fewer_sms)
#include "strata/prefill/kernels.hpp"
// gdn_rec_parity the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk)
// gdn_rec_parity --bench and the timings at T = 8192 and 32768 (one layer, all 48 value heads); the two
// variants' launches alternate, since a card under load steps its clock down after a
// fraction of a second (see native_grouped_parity); then both at 1 to 6 blocks per
// SM, as on cards with more or fewer SMs (scale), and both with the engine's grids on
// 32 to all of this card's SMs, the others held by a sleeping kernel (fewer_sms)
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
@@ -42,11 +27,9 @@
namespace {
constexpr int S = 128; // as kernels.cu: the head size (both models)
constexpr int S = 128, HK = 16, HV = 48, C = 10240; // as kernels.cu: head size, key heads, value heads, q|k|v width
constexpr int RG = 4, RPG = S / RG;
constexpr int CB = 32, NCB = S / CB;
// the Flash-Next geometry the timing sections below keep (the engine's 192- and 64-block grids they describe)
constexpr int FN_HV = 48, FN_HK = 16, FN_C = 10240;
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
@@ -67,7 +50,6 @@ __device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__floa
// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split.
// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
template <int HV, int HK, int C>
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
@@ -164,13 +146,11 @@ __device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the ne
asm volatile("cp.async.wait_group 1;\n" ::);
#endif
}
constexpr int GDN_TB = 8; // tokens per staged block
template <int HV, int HK, int C>
constexpr int GDN_TB = 8, VPK = HV / HK; // tokens per staged block, value heads per key head
__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
float* __restrict__ oc_out, int64_t T) {
constexpr int VPK = HV / HK; // value heads per key head
constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4, VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v
__shared__ __align__(16) float sq[2][TB][S];
__shared__ __align__(16) float sk[2][TB][S];
@@ -260,10 +240,8 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__
for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];
}
}
template <bool SILU> __device__ __forceinline__ float gdn_gate(float z) { return SILU ? z * sigm(z) : sigm(z); }
// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the
// norm stays in its scratch buffer)
template <int HV, bool SILU>
__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
float eps, const float* __restrict__ y,
uint16_t* __restrict__ y16) {
@@ -276,12 +254,11 @@ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict
if ((col & 31) == 0) wsum[col >> 5] = sp;
__syncthreads();
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate<SILU>(z[t * HV * S + head * S + col]);
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
y16[at] = hf(v);
}
// ------------------------------------------------------------------ the output norm before (0.1.31)
template <int HV, bool SILU>
__global__ void __launch_bounds__(S) gdn_out_norm_old_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
float eps, float* __restrict__ y,
uint16_t* __restrict__ y16) {
@@ -294,7 +271,7 @@ __global__ void __launch_bounds__(S) gdn_out_norm_old_kernel(const float* __rest
if ((col & 31) == 0) wsum[col >> 5] = sp;
__syncthreads();
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate<SILU>(z[t * HV * S + head * S + col]);
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
y[at] = v;
y16[at] = hf(v);
}
@@ -314,7 +291,6 @@ __global__ void fill_gauss(float* x, int64_t n, float scale, uint64_t seed, floa
x[i] = offset + scale * gauss(seed * 0x9E3779B97F4A7C15ULL + (uint64_t) i);
}
// the q and k rows L2-normalized per key head, as gdn_l2_kernel leaves them for the recurrence
template <int C>
__global__ void l2_rows(float* h, float eps) {
float* x = h + (int64_t) blockIdx.y * C + (int64_t) blockIdx.x * S;
const float v = x[threadIdx.x];
@@ -412,7 +388,6 @@ unsigned long long diff_words(const void* a, const void* b, size_t bytes) {
return h;
}
template <int HV, int HK, int C>
struct Inputs {
int64_t T = 0;
float *h = nullptr, *gate = nullptr, *beta = nullptr, *z = nullptr, *gamma = nullptr, *state0 = nullptr;
@@ -424,7 +399,7 @@ struct Inputs {
gamma = dalloc<float>(S);
state0 = dalloc<float>((size_t) S * HV * S);
fill_gauss<<<4096, 256>>>(h, T * C, 1.0f, seed);
l2_rows<C><<<dim3(2 * HK, (unsigned) T), S>>>(h, 1e-6f);
l2_rows<<<dim3(2 * HK, (unsigned) T), S>>>(h, 1e-6f);
fill_gates<<<1024, 256>>>(gate, beta, T * HV, seed + 1);
fill_gauss<<<4096, 256>>>(z, T * HV * S, 1.0f, seed + 2);
fill_gauss<<<1, 128>>>(gamma, S, 0.1f, seed + 3, 1.0f);
@@ -437,17 +412,15 @@ struct Inputs {
};
enum Rec { kBefore, kKeyHead, kRecCount };
template <int HV, int HK, int C>
void run_rec(Rec v, float* state, const Inputs<HV, HK, C>& in, float* oc, cudaStream_t s = 0) {
void run_rec(Rec v, float* state, const Inputs& in, float* oc, cudaStream_t s = 0) {
if (v == kBefore)
gdn_rec_cols_pipe_kernel<HV, HK, C><<<HV * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
else
gdn_rec_kh_kernel<HV, HK, C><<<HK * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
}
template <int HV, int HK, int C>
int check_bits(int64_t T, uint64_t seed) {
Inputs<HV, HK, C> in(T, seed);
Inputs in(T, seed);
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
float* state[kRecCount];
float* oc[kRecCount];
@@ -455,7 +428,7 @@ int check_bits(int64_t T, uint64_t seed) {
state[v] = dalloc<float>(st);
oc[v] = dalloc<float>(oc_n);
ck(cudaMemcpy(state[v], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy");
run_rec<HV, HK, C>((Rec) v, state[v], in, oc[v]);
run_rec((Rec) v, state[v], in, oc[v]);
}
ck(cudaDeviceSynchronize(), "recurrence");
int fails = 0;
@@ -471,16 +444,15 @@ int check_bits(int64_t T, uint64_t seed) {
uint16_t* y16b = dalloc<uint16_t>(oc_n);
float* yb = dalloc<float>(oc_n);
ck(cudaMemcpy(yb, oc[kBefore], oc_n * 4, cudaMemcpyDeviceToDevice), "y copy");
constexpr bool SILU = HV == 32; // the Qwen3.6 geometry gates with SiLU
gdn_out_norm_kernel<HV, SILU><<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, yb, y16b);
gdn_out_norm_old_kernel<HV, SILU><<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc[kBefore], y16a);
gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, yb, y16b);
gdn_out_norm_old_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc[kBefore], y16a);
ck(cudaDeviceSynchronize(), "norm");
const unsigned long long d16 = diff_words(y16a, y16b, oc_n * 2);
if (d16) {
std::printf("FAIL T=%lld output norm: %llu of %zu FP16 pairs differ\n", (long long) T, d16, oc_n / 2);
++fails;
}
std::printf("%d/%d/%d T=%-6lld %s\n", HV, HK, C, (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)");
std::printf("T=%-6lld %s\n", (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)");
for (int v = 0; v < kRecCount; ++v) { cudaFree(state[v]); cudaFree(oc[v]); }
cudaFree(y16a); cudaFree(y16b); cudaFree(yb);
return fails;
@@ -491,10 +463,8 @@ float median(std::vector<float> v) {
return v.empty() ? 0.0f : v[v.size() / 2];
}
template <int HV, int HK, int C>
void bench(int64_t T) {
constexpr bool SILU = HV == 32;
Inputs<HV, HK, C> in(T, 0xB3);
Inputs in(T, 0xB3);
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
float* state = dalloc<float>(st);
float* oc = dalloc<float>(oc_n);
@@ -517,7 +487,7 @@ void bench(int64_t T) {
for (int i = 0; i < warm + rounds; ++i) {
for (int j = 0; j < kRecCount; ++j) {
const Rec v = (Rec) ((i + j) % kRecCount); // a different variant first in each round
const float ms = timed([&] { run_rec<HV, HK, C>(v, state, in, oc); });
const float ms = timed([&] { run_rec(v, state, in, oc); });
if (i >= warm) t_rec[v].push_back(ms);
}
}
@@ -525,23 +495,22 @@ void bench(int64_t T) {
for (int j = 0; j < 2; ++j) {
const int v = (i + j) % 2;
const float ms = timed([&] {
if (v == 0) gdn_out_norm_old_kernel<HV, SILU><<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
else gdn_out_norm_kernel<HV, SILU><<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
if (v == 0) gdn_out_norm_old_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
else gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
});
if (i >= warm) t_norm[v].push_back(ms);
}
}
const float r0 = median(t_rec[kBefore]), r1 = median(t_rec[kKeyHead]), n0 = median(t_norm[0]), n1 = median(t_norm[1]);
std::printf(" T = %lld tokens, one layer (%d value heads / %d key heads), medians of %d alternating runs:\n", (long long) T, HV, HK, rounds);
std::printf(" T = %lld tokens, one layer (48 value heads), medians of %d alternating runs:\n", (long long) T, rounds);
std::printf(" recurrence, before (gdn_rec_cols_pipe_kernel) %8.2f ms (%.3f us per token)\n", r0,
1000.0f * r0 / (float) T);
std::printf(" recurrence, gdn_rec_kh_kernel %8.2f ms (%.3f us per token) %.2fx\n", r1,
1000.0f * r1 / (float) T, r0 / r1);
std::printf(" output norm, before (FP32 and FP16 store) %8.2f ms\n", n0);
std::printf(" output norm, FP16 store only %8.2f ms %.2fx\n", n1, n0 / n1);
const float nl = HV == 32 ? 30.0f : 36.0f; // the model's DeltaNet layers (Qwen3.6: 30 of 40; Flash-Next: 36 of 48)
std::printf(" %.0f DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n",
nl, (long long) T, nl * (r0 + n0), nl * (r1 + n1), nl * (r0 + n0 - r1 - n1));
std::printf(" 36 DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n",
(long long) T, 36.0f * (r0 + n0), 36.0f * (r1 + n1), 36.0f * (r0 + n0 - r1 - n1));
cudaEventDestroy(e0);
cudaEventDestroy(e1);
cudaFree(state); cudaFree(oc); cudaFree(y16);
@@ -554,16 +523,15 @@ void bench(int64_t T) {
// its own state and output, all started together, so the block scheduler puts one block of each round on every SM.
// The kernels are the ones above, unchanged.
void scale(int64_t T) {
constexpr int HV = FN_HV, HK = FN_HK, C = FN_C;
int dev = 0, sms = 0, per_sm[kRecCount] = {};
ck(cudaGetDevice(&dev), "device");
ck(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev), "SMs");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel<HV, HK, C>, CB * RG, 0), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel<HV, HK, C>, CB * RG, 0), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel, CB * RG, 0), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "occupancy");
constexpr int kMaxB = 6, kMaxLaunches = 6;
const int full[kRecCount] = {HV * NCB, HK * NCB}; // the grids as the engine launches them
auto parts = [&](int v) { return (sms + full[v] - 1) / full[v]; }; // launches per round
Inputs<HV, HK, C> in(T, 0xC7);
Inputs in(T, 0xC7);
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
float* state[kMaxLaunches];
float* oc[kMaxLaunches];
@@ -591,9 +559,9 @@ void scale(int64_t T) {
const int k = c % np, grid = sms / np + (k < sms % np ? 1 : 0); // round c / np, part k
if (c > 0) cudaStreamWaitEvent(stream[c], e0, 0);
if (cs.v == kBefore)
gdn_rec_cols_pipe_kernel<HV, HK, C><<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
gdn_rec_cols_pipe_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
else
gdn_rec_kh_kernel<HV, HK, C><<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
gdn_rec_kh_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
cudaEventRecord(done[c], stream[c]);
}
for (int c = 1; c < n; ++c) cudaStreamWaitEvent(stream[0], done[c], 0);
@@ -660,7 +628,6 @@ void scale(int64_t T) {
// shows for every N where the two grids land: none on a held SM, and how many blocks share the busiest SM. The
// recurrences are the ones above, unchanged; L2, memory and clock stay this card's.
void fewer_sms(int64_t T) {
constexpr int HV = FN_HV, HK = FN_HK, C = FN_C;
int dev = 0, sms = 0, optin = 0, smem_sm = 0, reserved = 0, hold_per_sm = 0, per_sm[kRecCount] = {};
ck(cudaGetDevice(&dev), "device");
ck(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev), "SMs");
@@ -675,13 +642,13 @@ void fewer_sms(int64_t T) {
// Loaded now rather than at a first launch: with lazy loading (CUDA 12's default) a kernel's first launch may wait
// until the device is idle, and so for hold_sm, which waits for release_sms.
cudaFuncAttributes fa[kRecCount], fx;
ck(cudaFuncGetAttributes(&fa[kBefore], gdn_rec_cols_pipe_kernel<HV, HK, C>), "attributes");
ck(cudaFuncGetAttributes(&fa[kKeyHead], gdn_rec_kh_kernel<HV, HK, C>), "attributes");
ck(cudaFuncGetAttributes(&fa[kBefore], gdn_rec_cols_pipe_kernel), "attributes");
ck(cudaFuncGetAttributes(&fa[kKeyHead], gdn_rec_kh_kernel), "attributes");
for (const void* f : {(const void*) hold_sm, (const void*) wait_sitting, (const void*) release_sms, (const void*) land})
ck(cudaFuncGetAttributes(&fx, f), "attributes");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&hold_per_sm, hold_sm, 1, optin), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel<HV, HK, C>, CB * RG, 0), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel<HV, HK, C>, CB * RG, 0), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel, CB * RG, 0), "occupancy");
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "occupancy");
const int grid[kRecCount] = {HV * NCB, HK * NCB}; // as the engine launches them
std::printf(" the engine's grids on N of this card's %d SMs (%lld tokens; the other SMs held by a sleeping kernel, see "
"fewer_sms):\n", sms, (long long) T);
@@ -712,7 +679,7 @@ void fewer_sms(int64_t T) {
if (n < sms && (int64_t) n * per_sm[kBefore] >= grid[kBefore] && (int64_t) n * per_sm[kKeyHead] >= grid[kKeyHead])
ns.push_back(n);
Inputs<HV, HK, C> in(T, 0xD5);
Inputs in(T, 0xD5);
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
float* state = dalloc<float>(st);
float* oc = dalloc<float>(oc_n);
@@ -816,7 +783,7 @@ void fewer_sms(int64_t T) {
ck(cudaMemcpyAsync(state, in.state0, st * 4, cudaMemcpyDeviceToDevice, s_run), "state");
hold(n);
ck(cudaEventRecord(e0, s_run), "event");
run_rec<HV, HK, C>(cs.v, state, in, oc, s_run);
run_rec(cs.v, state, in, oc, s_run);
ck(cudaEventRecord(e1, s_run), "event");
let_go(n);
settle("fewer SMs");
@@ -894,165 +861,6 @@ void fewer_sms(int64_t T) {
done();
}
// ------------------------------------------------------------------ the reference (a host transcription, double)
// docs/qwen36-port/oracle-crosscheck.md, "Gated DeltaNet": per value head hv with key head qh = hv % HK (tiled; the
// rival pairs hv with hv / VPK), per token: S *= exp(g); d = (v - S^T k) * beta; S += k (x) d; o = S^T q / sqrt(S);
// y = rms_norm(o) * gamma * gate(z) with gate SiLU (Qwen3.6) or sigmoid (Flash-Next). The state is [k][hv][v].
struct RefOpts { bool silu = true, tiled = true; };
struct HostIn {
int64_t T, HV, HK, C;
std::vector<float> h, gate, beta, z, gamma, state0;
template <int HV_, int HK_, int C_> explicit HostIn(const Inputs<HV_, HK_, C_>& in)
: T(in.T), HV(HV_), HK(HK_), C(C_), h((size_t) in.T * C_), gate((size_t) in.T * HV_), beta((size_t) in.T * HV_),
z((size_t) in.T * HV_ * S), gamma(S), state0((size_t) S * HV_ * S) {
ck(cudaMemcpy(h.data(), in.h, h.size() * 4, cudaMemcpyDeviceToHost), "h");
ck(cudaMemcpy(gate.data(), in.gate, gate.size() * 4, cudaMemcpyDeviceToHost), "gate");
ck(cudaMemcpy(beta.data(), in.beta, beta.size() * 4, cudaMemcpyDeviceToHost), "beta");
ck(cudaMemcpy(z.data(), in.z, z.size() * 4, cudaMemcpyDeviceToHost), "z");
ck(cudaMemcpy(gamma.data(), in.gamma, gamma.size() * 4, cudaMemcpyDeviceToHost), "gamma");
ck(cudaMemcpy(state0.data(), in.state0, state0.size() * 4, cudaMemcpyDeviceToHost), "state0");
}
};
// y [T][HV][S] (the gated, normed output) and the state after the chunk
void ref_rec(const HostIn& in, const RefOpts& o, std::vector<double>& y, std::vector<double>& state) {
const int64_t T = in.T, HV = in.HV, HK = in.HK, C = in.C, VPK = HV / HK;
state.assign(in.state0.begin(), in.state0.end());
y.assign((size_t) T * HV * S, 0.0);
std::vector<double> Sh((size_t) S * S), kv(S), d(S), oc(S);
for (int64_t hv = 0; hv < HV; ++hv) {
const int64_t qh = o.tiled ? hv % HK : hv / VPK;
for (int i = 0; i < S; ++i) for (int j = 0; j < S; ++j) Sh[(size_t) i * S + j] = state[((size_t) i * HV + hv) * S + j];
for (int64_t t = 0; t < T; ++t) {
const float* ht = in.h.data() + t * C;
const float *q = ht + qh * S, *k = ht + HK * S + qh * S, *v = ht + 2 * HK * S + hv * S;
const double g = std::exp((double) in.gate[(size_t) t * HV + hv]), b = in.beta[(size_t) t * HV + hv];
for (int j = 0; j < S; ++j) { kv[j] = 0.0; for (int i = 0; i < S; ++i) kv[j] += Sh[(size_t) i * S + j] * g * k[i]; }
for (int j = 0; j < S; ++j) d[j] = (v[j] - kv[j]) * b;
double ss = 0.0;
for (int j = 0; j < S; ++j) {
double acc = 0.0;
for (int i = 0; i < S; ++i) {
Sh[(size_t) i * S + j] = g * Sh[(size_t) i * S + j] + k[i] * d[j];
acc += Sh[(size_t) i * S + j] * q[i];
}
oc[j] = acc / std::sqrt((double) S);
ss += oc[j] * oc[j];
}
const double rs = 1.0 / std::sqrt(ss / S + 1e-6);
for (int j = 0; j < S; ++j) {
const double zz = in.z[((size_t) t * HV + hv) * S + j], sg = 1.0 / (1.0 + std::exp(-zz));
y[((size_t) t * HV + hv) * S + j] = oc[j] * rs * in.gamma[j] * (o.silu ? zz * sg : sg);
}
}
for (int i = 0; i < S; ++i) for (int j = 0; j < S; ++j) state[((size_t) i * HV + hv) * S + j] = Sh[(size_t) i * S + j];
}
}
double rel_l1(const std::vector<double>& a, const std::vector<double>& b) { // ||a - b||_1 / ||b||_1, NaN-safe (NaN -> inf)
double num = 0.0, den = 0.0;
for (size_t i = 0; i < a.size(); ++i) {
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) return INFINITY;
num += std::fabs(a[i] - b[i]);
den += std::fabs(b[i]);
}
return den > 0.0 ? num / den : (num > 0.0 ? INFINITY : 0.0);
}
float h2f(uint16_t h) { return __half2float(__ushort_as_half(h)); }
// The engine's own launches (gdn_recurrence through its GdnGeom: the kh kernel where the card takes it, the pipe
// kernel otherwise, then the output norm) against the reference, with the negative controls. Tolerances: the FP16
// output 2e-3 relative L1 (the FP16 store is 2^-11), the FP32 state 1e-4; a negative must sit above 5 %.
template <int HV, int HK, int C>
int check_reference(int64_t T, uint64_t seed) {
constexpr bool SILU = HV == 32;
Inputs<HV, HK, C> in(T, seed);
const HostIn hin(in);
const size_t st = (size_t) S * HV * S, n = (size_t) T * HV * S;
float* state = dalloc<float>(st);
float* y = dalloc<float>(n);
uint16_t* y16 = dalloc<uint16_t>(n);
ck(cudaMemcpy(state, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state");
const strata::prefill::GdnGeom geom{HV, HK, C, SILU ? strata::kernels::GdnGate::Silu : strata::kernels::GdnGate::Sigmoid};
strata::prefill::gdn_recurrence(state, in.h, in.gate, in.beta, in.z, in.gamma, 1e-6f, y, y16, T, geom, nullptr);
ck(cudaDeviceSynchronize(), "gdn_recurrence");
std::vector<uint16_t> hy16(n);
std::vector<float> hstate(st);
ck(cudaMemcpy(hy16.data(), y16, n * 2, cudaMemcpyDeviceToHost), "y16");
ck(cudaMemcpy(hstate.data(), state, st * 4, cudaMemcpyDeviceToHost), "state");
std::vector<double> ey(n), es(hstate.begin(), hstate.end());
for (size_t i = 0; i < n; ++i) ey[i] = h2f(hy16[i]);
std::vector<double> ry, rs;
ref_rec(hin, RefOpts{SILU, true}, ry, rs);
const double ey_err = rel_l1(ey, ry), es_err = rel_l1(es, rs);
int fails = 0;
const bool ok = ey_err <= 2e-3 && es_err <= 1e-4;
std::printf("%d/%d/%d T=%-6lld engine vs reference (%s gate): y16 %.2e, state %.2e %s\n", HV, HK, C, (long long) T,
SILU ? "SiLU" : "sigmoid", ey_err, es_err, ok ? "ok" : "*** FAIL ***");
fails += !ok;
// the negative controls: the rival readings, computed by the same reference, must be visibly wrong
struct Neg { const char* what; RefOpts o; };
const Neg negs[] = {{SILU ? "sigmoid(z) gate (the Flash-Next reading)" : "SiLU(z) gate (the Qwen3.6 reading)", RefOpts{!SILU, true}},
{"interleaved head pairing (h // VPK instead of h % HK)", RefOpts{SILU, false}}};
for (const Neg& ng : negs) {
std::vector<double> ny, ns;
ref_rec(hin, ng.o, ny, ns);
const double dy = rel_l1(ny, ry), de = rel_l1(ey, ny); // rival vs right; the engine vs the rival
const bool seen = dy > 0.05 && de > 0.05;
std::printf(" rival: %-58s %.3f relative L1 from the right reading, the engine %.3f from it: %s\n", ng.what, dy, de,
seen ? "yes" : "*** NO ***");
fails += !seen;
}
cudaFree(state); cudaFree(y); cudaFree(y16);
return fails;
}
// gdn_conv (the 4-tap causal conv + SiLU, the conv history, the q/k L2 norm) against a host transcription, both geometries
template <int HV, int HK, int C>
int check_conv(int64_t T, uint64_t seed) {
float* qkv = dalloc<float>((size_t) T * C);
float* w = dalloc<float>((size_t) C * 4);
float* hist = dalloc<float>((size_t) C * 3);
float* h = dalloc<float>((size_t) T * C);
fill_gauss<<<4096, 256>>>(qkv, T * C, 1.0f, seed);
fill_gauss<<<256, 256>>>(w, (int64_t) C * 4, 0.5f, seed + 1);
fill_gauss<<<256, 256>>>(hist, (int64_t) C * 3, 1.0f, seed + 2);
ck(cudaDeviceSynchronize(), "conv inputs");
std::vector<float> hq((size_t) T * C), hw((size_t) C * 4), hh((size_t) C * 3);
ck(cudaMemcpy(hq.data(), qkv, hq.size() * 4, cudaMemcpyDeviceToHost), "qkv");
ck(cudaMemcpy(hw.data(), w, hw.size() * 4, cudaMemcpyDeviceToHost), "w");
ck(cudaMemcpy(hh.data(), hist, hh.size() * 4, cudaMemcpyDeviceToHost), "hist");
const strata::prefill::GdnGeom geom{HV, HK, C, HV == 32 ? strata::kernels::GdnGate::Silu : strata::kernels::GdnGate::Sigmoid};
strata::prefill::gdn_conv(hist, qkv, w, h, T, 1e-6f, geom, nullptr);
ck(cudaDeviceSynchronize(), "gdn_conv");
std::vector<float> eh((size_t) T * C), ehist((size_t) C * 3);
ck(cudaMemcpy(eh.data(), h, eh.size() * 4, cudaMemcpyDeviceToHost), "h");
ck(cudaMemcpy(ehist.data(), hist, ehist.size() * 4, cudaMemcpyDeviceToHost), "hist out");
// the reference: y[t][c] = sum_i w[c][i] * in[c][t - 3 + i] over [hist | qkv], then silu; q/k rows L2-normed per head
std::vector<double> ry((size_t) T * C), rh((size_t) C * 3);
for (int c = 0; c < C; ++c) {
auto at = [&](int64_t t) -> double { return t >= 0 ? hq[(size_t) t * C + c] : hh[(size_t) c * 3 + (t + 3)]; };
for (int64_t t = 0; t < T; ++t) {
double v = 0.0;
for (int i = 0; i < 4; ++i) v += (double) hw[(size_t) c * 4 + i] * at(t - 3 + i);
ry[(size_t) t * C + c] = v / (1.0 + std::exp(-v));
}
for (int i = 0; i < 3; ++i) rh[(size_t) c * 3 + i] = at(T - 3 + i);
}
for (int64_t t = 0; t < T; ++t)
for (int hd = 0; hd < 2 * HK; ++hd) {
double ss = 0.0;
for (int j = 0; j < S; ++j) ss += ry[(size_t) t * C + hd * S + j] * ry[(size_t) t * C + hd * S + j];
const double rs = 1.0 / std::sqrt(ss + 1e-6);
for (int j = 0; j < S; ++j) ry[(size_t) t * C + hd * S + j] *= rs;
}
std::vector<double> ey(eh.begin(), eh.end()), ehd(ehist.begin(), ehist.end());
const double e1 = rel_l1(ey, ry), e2 = rel_l1(ehd, rh);
const bool ok = e1 <= 1e-5 && e2 <= 1e-6;
std::printf("%d/%d/%d T=%-6lld gdn_conv vs reference: h %.2e, history %.2e %s\n", HV, HK, C, (long long) T, e1, e2,
ok ? "ok" : "*** FAIL ***");
cudaFree(qkv); cudaFree(w); cudaFree(hist); cudaFree(h);
return !ok;
}
} // namespace
int main(int argc, char** argv) {
@@ -1063,29 +871,13 @@ int main(int argc, char** argv) {
ck(cudaGetDeviceProperties(&p, 0), "device");
std::printf("gdn_rec_parity on %s (sm_%d%d)\n", p.name, p.major, p.minor);
int fails = 0;
// the geometries: built for exactly these two; a third value head per key head on 32 heads (Flash-Next's 48-head
// channel layout, C 10240, on Qwen3.6's heads) and 4 per key head are refused by name
const bool g1 = strata::prefill::gdn_geometry_supported(48, 16, 10240), g2 = strata::prefill::gdn_geometry_supported(32, 16, 8192);
const bool r1 = strata::prefill::gdn_geometry_supported(32, 16, 10240), r2 = strata::prefill::gdn_geometry_supported(32, 8, 8192),
r3 = strata::prefill::gdn_geometry_supported(48, 16, 8192);
std::printf("geometries: 48/16/10240 %s, 32/16/8192 %s; refused: 32 heads with the 48-head channel layout (32/16/10240) %s, "
"4 value heads per key head (32/8/8192) %s, 48/16/8192 %s\n", g1 ? "built" : "*** MISSING ***",
g2 ? "built" : "*** MISSING ***", r1 ? "*** NO ***" : "yes", r2 ? "*** NO ***" : "yes", r3 ? "*** NO ***" : "yes");
fails += !g1 + !g2 + r1 + r2 + r3;
const int64_t Ts[] = {1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257, 1000, 4099};
uint64_t seed = 11;
for (const int64_t T : Ts) fails += check_bits<48, 16, 10240>(T, seed++);
for (const int64_t T : Ts) fails += check_bits<32, 16, 8192>(T, seed++);
const int64_t Tr[] = {1, 7, 33, 257};
for (const int64_t T : Tr) fails += check_reference<48, 16, 10240>(T, seed++);
for (const int64_t T : Tr) fails += check_reference<32, 16, 8192>(T, seed++);
for (const int64_t T : {1, 2, 5, 70, 257}) fails += check_conv<48, 16, 10240>(T, seed++) + check_conv<32, 16, 8192>(T, seed++);
for (const int64_t T : Ts) fails += check_bits(T, seed++);
if (do_bench) {
std::printf("--bench: the prompt path's DeltaNet recurrence\n");
bench<48, 16, 10240>(8192);
bench<48, 16, 10240>(32768);
bench<32, 16, 8192>(8192);
bench<32, 16, 8192>(32768);
bench(8192);
bench(32768);
scale(8192);
fewer_sms(8192);
}
+65 -171
View File
@@ -15,13 +15,8 @@
namespace strata::prefill {
namespace {
// The hyper-connection kernels are Flash-Next's alone (n_embd 2560, hc 4, hc_lr 320): Qwen3.6 has hc = 1 and takes the
// plain-block kernels below (rms_norm_images, residual_add). The GDN kernels are templates on the head geometry
// <HV, HK, C> (Flash-Next 48 / 16 / 10240, Qwen3.6 32 / 16 / 8192) and on the output gate (sigmoid(z) for Flash-Next,
// SiLU(z) for Qwen3.6): their shared-memory staging is sized from the heads, so they are forked per geometry rather
// than made runtime (docs/QWEN36-35B-A3B.md section 3.6). The head size S is 128 in both.
constexpr int N = 2560, HC = 4, D = N * HC, LR = 320;
constexpr int S = 128;
constexpr int S = 128, HK = 16, HV = 48, C = 10240;
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
@@ -209,11 +204,6 @@ __global__ void gr_broadcast_kernel(const float* __restrict__ e, float* __restri
}
// ---------------------------------------------------------------- GDN
// the output gate: Flash-Next multiplies the normed output by sigmoid(z), Qwen3.6 by SiLU(z) = z * sigmoid(z)
// (qwen35moe.cpp:267-276; the oracle's negative control puts the two 1.07 relative L1 apart at final_output-0)
template <bool SILU> __device__ __forceinline__ float gdn_gate(float z) { return SILU ? z * sigm(z) : sigm(z); }
template <int HV>
__global__ void gdn_gates_kernel(const float* __restrict__ ab, const float* __restrict__ dt,
const float* __restrict__ ssm_a, float* __restrict__ gate, float* __restrict__ beta,
int64_t T) {
@@ -225,7 +215,6 @@ __global__ void gdn_gates_kernel(const float* __restrict__ ab, const float* __re
beta[i] = sigm(ab[t * 2 * HV + HV + h]);
}
// one thread per channel, walks the chunk; then a second kernel normalises
template <int C>
__global__ void gdn_conv_kernel(float* __restrict__ hist, const float* __restrict__ qkv, const float* __restrict__ w,
float* __restrict__ h, int64_t T) {
const int c = blockIdx.x * blockDim.x + threadIdx.x;
@@ -244,7 +233,6 @@ __global__ void gdn_conv_kernel(float* __restrict__ hist, const float* __restric
// chunk (or the history before it) instead of carrying them - the conv reads inputs, not its own outputs, so the
// tiles are independent. The same expression per element (so the same bits); the history is written afterwards.
constexpr int CONV_TILE = 64;
template <int C>
__global__ void gdn_conv_tiled_kernel(const float* __restrict__ hist, const float* __restrict__ qkv,
const float* __restrict__ w, float* __restrict__ h, int64_t T) {
const int c = blockIdx.x * blockDim.x + threadIdx.x;
@@ -263,7 +251,6 @@ __global__ void gdn_conv_tiled_kernel(const float* __restrict__ hist, const floa
}
}
// the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3)
template <int C>
__global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int64_t T) {
const int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= C) return;
@@ -274,9 +261,8 @@ __global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __re
}
hist[c * 3] = v[0]; hist[c * 3 + 1] = v[1]; hist[c * 3 + 2] = v[2];
}
template <int C>
__global__ void gdn_l2_kernel(float* __restrict__ h, float eps) {
// block (t, head) over the 2 * HK q/k heads, 128 threads
// block (t, head) over the 32 q/k heads, 128 threads
const int64_t t = blockIdx.y;
const int head = blockIdx.x;
float* x = h + t * C + head * S;
@@ -289,7 +275,6 @@ __global__ void gdn_l2_kernel(float* __restrict__ h, float eps) {
x[threadIdx.x] = v * rsqrtf(ss + eps);
}
constexpr int RG = 4, RPG = S / RG;
template <int HV, int HK, int C, bool SILU>
__global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta, const float* __restrict__ z,
@@ -336,7 +321,7 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta
__syncthreads();
if (rg == 0) {
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * gdn_gate<SILU>(z[t * HV * S + head * S + col]);
const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(z[t * HV * S + head * S + col]);
y[t * HV * S + head * S + col] = v;
y16[t * HV * S + head * S + col] = hf(v);
}
@@ -350,7 +335,6 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta
// in its own kernel. Per column the same arithmetic in the same order (the 4 row-group partial sums added as
// red[0] + red[1] + red[2] + red[3]; the norm's warp sums over the same 32-column warps): the same bits.
constexpr int CB = 32, NCB = S / CB;
template <int HV, int HK, int C>
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
@@ -394,7 +378,6 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict
// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split.
// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
template <int HV, int HK, int C>
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
@@ -492,14 +475,11 @@ __device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the ne
asm volatile("cp.async.wait_group 1;\n" ::);
#endif
}
constexpr int GDN_TB = 8; // tokens per staged block
template <int HV, int HK, int C>
constexpr int GDN_TB = 8, VPK = HV / HK; // tokens per staged block, value heads per key head
__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
float* __restrict__ oc_out, int64_t T) {
constexpr int VPK = HV / HK; // value heads per key head: 3 (Flash-Next), 2 (Qwen3.6)
static_assert(HV % HK == 0 && VPK <= RG, "a row group writes one value head's output");
constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4, VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v
__shared__ __align__(16) float sq[2][TB][S];
__shared__ __align__(16) float sk[2][TB][S];
@@ -595,8 +575,7 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__
// With the engine's grids on fewer SMs (gdn_rec_parity --bench), on a 4080 SUPER / a 3090: 1.40-1.42x / 1.28-1.29x at
// 64 SMs and more, 1.02-1.04x / 1.03-1.06x at 48 to 63 (two blocks against four: a draw, slower on neither),
// 1.28-1.31x / 1.28-1.30x at 39 to 47, 1.53-1.57x / 1.54-1.55x at 32 to 38. Per call, from the current device (a
// layer split can mix cards). Per geometry: the grid is HK * NCB blocks either way (64 at 16 key heads).
template <int HV, int HK, int C>
// layer split can mix cards).
bool gdn_keyhead_ok() {
static const bool off = [] { const char* v = std::getenv("STRATA_GDN_KEYHEAD"); return v != nullptr && std::atoi(v) == 0; }();
if (off) return false;
@@ -607,7 +586,7 @@ bool gdn_keyhead_ok() {
int major = 0, sms = 0, per_sm = 0;
const bool yes = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && major >= 8 &&
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, gdn_rec_kh_kernel<HV, HK, C>, CB * RG, 0) ==
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, gdn_rec_kh_kernel, CB * RG, 0) ==
cudaSuccess &&
(int64_t) per_sm * sms >= (int64_t) HK * NCB;
if (!yes) cudaGetLastError();
@@ -618,7 +597,6 @@ bool gdn_keyhead_ok() {
#endif
// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the
// norm stays in its scratch buffer)
template <int HV, bool SILU>
__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
float eps, const float* __restrict__ y,
uint16_t* __restrict__ y16) {
@@ -631,59 +609,14 @@ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict
if ((col & 31) == 0) wsum[col >> 5] = sp;
__syncthreads();
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate<SILU>(z[t * HV * S + head * S + col]);
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
y16[at] = hf(v);
}
// The two geometries the GDN kernels are built for. `f` is called with a std::integral_constant triple (HV, HK, C);
// anything else stops the process, as the kernels' own unsupported-geometry convention does (Prefill::init refuses
// first, with an error string, through gdn_geometry_supported).
template <int HV_, int HK_, int C_> struct GdnTag { static constexpr int HV = HV_, HK = HK_, C = C_; };
template <typename F> void gdn_dispatch(const GdnGeom& g, const char* what, F&& f) {
if (g.hv == 48 && g.hk == 16 && g.c == 10240) f(GdnTag<48, 16, 10240>{});
else if (g.hv == 32 && g.hk == 16 && g.c == 8192) f(GdnTag<32, 16, 8192>{});
else {
std::fprintf(stderr, "prefill %s: no GDN kernels for %d value heads / %d key heads / %d conv channels (built for "
"48/16/10240 and 32/16/8192)\n", what, g.hv, g.hk, g.c);
std::exit(1);
}
}
// ---------------------------------------------------------------- the plain residual block (hc = 1)
// mixed[t, :] = R[t, :] * rsqrt(mean R[t, :]^2 + eps) * w, and its BF16 and FP16 images: gr_norm_kernel's arithmetic
// on one stream (block_sum over 256 threads, r * rs * w), the mixing of the four streams gone with them
__global__ void rms_norm_images_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, int64_t n,
float* __restrict__ mixed, uint16_t* __restrict__ mixed16,
uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) {
__shared__ float sh[32];
const int64_t row = blockIdx.x;
const float* r = R + row * n;
float ss = 0.0f;
for (int64_t d = threadIdx.x; d < n; d += blockDim.x) ss += r[d] * r[d];
const float rs = rsqrtf(block_sum(ss, sh) / (float) n + eps);
for (int64_t d = threadIdx.x; d < n; d += blockDim.x) {
const float v = r[d] * rs * w[d];
const int64_t i = row * n + d;
if (mixed) mixed[i] = v;
if (mixed16) {
const uint16_t h = bf(v);
mixed16[i] = h;
if (mixed16_lo) mixed16_lo[i] = bf_lo(v, h);
}
if (mixed_h) mixed_h[i] = hf(v);
}
}
__global__ void residual_add_kernel(float* __restrict__ R, const float* __restrict__ bo, int64_t n) {
for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
R[i] += bo[i];
}
// ---------------------------------------------------------------- MoE
// softmax over REG * 32 experts, the top k (<= 32) by rank with ties to the lower id, the k weights renormalised with
// the 2^-14 clamp: the native router's semantics (router_top10.hpp), k a parameter (10 for Flash-Next, 8 for Qwen3.6)
template <int REG>
__global__ void route_kernel(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ wout,
int64_t T, int k) {
int64_t T) {
const int64_t t = (int64_t) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
if (t >= T) return;
const int lane = threadIdx.x & 31;
@@ -702,7 +635,7 @@ __global__ void route_kernel(const float* __restrict__ logits, int32_t* __restri
#pragma unroll
for (int i = 0; i < REG; ++i) { v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX; }
float selected = 0.0f, selected_sum = 0.0f;
for (int rank = 0; rank < k; ++rank) {
for (int rank = 0; rank < 10; ++rank) {
float best = v[0];
int ex = lane;
#pragma unroll
@@ -714,11 +647,11 @@ __global__ void route_kernel(const float* __restrict__ logits, int32_t* __restri
if (ob > best || (ob == best && oi < ex)) { best = ob; ex = oi; }
}
if ((ex & 31) == lane) { v[ex / 32] = -INFINITY; selected_sum += best; }
if (lane == 0) ids[t * k + rank] = ex;
if (lane == 0) ids[t * 10 + rank] = ex;
if (rank == lane) selected = best;
}
selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f);
if (lane < k) wout[t * k + lane] = selected / selected_sum;
if (lane < 10) wout[t * 10 + lane] = selected / selected_sum;
}
// Strata blob: gate/up codes [1280][640 B], down codes [2560][160 B], gate/up scales [1280][40] f16, down scales [2560][10] f16
template <bool HALF>
@@ -746,17 +679,17 @@ __global__ void blob_dequant_kernel(const uint8_t* __restrict__ blob, uint16_t*
for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); }
}
}
__global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t n, int64_t n_ff) {
__global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n * n_ff) return;
const int64_t r = i / n_ff, k = i % n_ff;
const float g = gu[r * 2 * n_ff + 2 * k], u = gu[r * 2 * n_ff + 2 * k + 1];
if (i >= n * 640) return;
const int64_t r = i / 640, k = i % 640;
const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1];
h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u);
}
__global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16,
int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
if (i >= n * 640) return;
const float a = g[i];
h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]);
}
@@ -768,15 +701,15 @@ __global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32
const int64_t r = i / per, j = i % per;
reinterpret_cast<uint4*>(dst)[r * per + j] = reinterpret_cast<const uint4*>(x)[(int64_t) src[r] * per + j];
}
// the routed sum in rank order (as the decode combine and llama.cpp's sum over the top-k), plus the gated shared expert
__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot,
const float* __restrict__ w, const float* __restrict__ shared,
const float* __restrict__ sg, float* __restrict__ bo, int64_t T, int64_t n, int k) {
const float* __restrict__ sg, float* __restrict__ bo, int64_t T) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * n) return;
const int64_t t = i / n, d = i % n;
if (i >= T * N) return;
const int64_t t = i / N, d = i % N;
float s = 0.0f;
for (int j = 0; j < k; ++j) s = fmaf(w[t * k + j], Dm[(int64_t) slot[t * k + j] * n + d], s);
#pragma unroll
for (int k = 0; k < 10; ++k) s = fmaf(w[t * 10 + k], Dm[(int64_t) slot[t * 10 + k] * N + d], s);
bo[i] = s + shared[i] * sigm(sg[t]);
}
@@ -814,19 +747,18 @@ __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, i
p[pair] = a * c - b * s;
p[pair + 32] = a * s + b * c;
}
// attn_q is [n_head, 2, 256] per token: the query is the first 256 of each head's 512, the gate the second (both models)
__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T, int64_t n_head) {
__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * n_head * 256) return;
const int64_t t = i / (n_head * 256), h = (i / 256) % n_head, d = i % 256;
q[i] = qf[t * n_head * 512 + h * 512 + d];
if (i >= T * 24 * 256) return;
const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256;
q[i] = qf[t * 24 * 512 + h * 512 + d];
}
__global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16,
int64_t T, int64_t n_head) {
int64_t T) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= T * n_head * 256) return;
const int64_t t = i / (n_head * 256), h = (i / 256) % n_head, d = i % 256;
o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * n_head * 512 + h * 512 + 256 + d]))));
if (i >= T * 24 * 256) return;
const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256;
o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d]))));
}
// one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is
@@ -957,88 +889,51 @@ void gr_broadcast(const float* e, float* R, int64_t T, void* stream) {
gr_broadcast_kernel<<<blocks_for(T * D), 256, 0, (cudaStream_t) stream>>>(e, R, T);
check("gr_broadcast");
}
bool gdn_geometry_supported(int hv, int hk, int c) {
return (hv == 48 && hk == 16 && c == 10240) || (hv == 32 && hk == 16 && c == 8192);
}
void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, const GdnGeom& g,
void* stream) {
gdn_dispatch(g, "gdn_gates", [&](auto tag) {
constexpr int HV = decltype(tag)::HV;
gdn_gates_kernel<HV><<<blocks_for(T * HV), 256, 0, (cudaStream_t) stream>>>(ab, dt, ssm_a, gate, beta, T);
});
void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream) {
gdn_gates_kernel<<<blocks_for(T * HV), 256, 0, (cudaStream_t) stream>>>(ab, dt, ssm_a, gate, beta, T);
check("gdn_gates");
}
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, const GdnGeom& g,
void* stream) {
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream) {
static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr; // the old walk (A/B)
gdn_dispatch(g, "gdn_conv", [&](auto tag) {
constexpr int HK = decltype(tag)::HK, C = decltype(tag)::C;
if (serial || T <= CONV_TILE) {
gdn_conv_kernel<C><<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, conv_w, h, T);
} else {
gdn_conv_tiled_kernel<C><<<dim3(C / 128, (unsigned) ((T + CONV_TILE - 1) / CONV_TILE)), 128, 0,
(cudaStream_t) stream>>>(history, qkv, conv_w, h, T);
gdn_conv_hist_kernel<C><<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, T);
}
gdn_l2_kernel<C><<<dim3(2 * HK, (unsigned) T), S, 0, (cudaStream_t) stream>>>(h, eps);
});
if (serial || T <= CONV_TILE) {
gdn_conv_kernel<<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, conv_w, h, T);
} else {
gdn_conv_tiled_kernel<<<dim3(C / 128, (unsigned) ((T + CONV_TILE - 1) / CONV_TILE)), 128, 0,
(cudaStream_t) stream>>>(history, qkv, conv_w, h, T);
gdn_conv_hist_kernel<<<C / 128, 128, 0, (cudaStream_t) stream>>>(history, qkv, T);
}
gdn_l2_kernel<<<dim3(2 * HK, (unsigned) T), S, 0, (cudaStream_t) stream>>>(h, eps);
check("gdn_conv");
}
void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, const GdnGeom& g, void* stream) {
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) {
static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B)
static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();
const cudaStream_t cs = (cudaStream_t) stream;
gdn_dispatch(g, "gdn_recurrence", [&](auto tag) {
constexpr int HV = decltype(tag)::HV, HK = decltype(tag)::HK, C = decltype(tag)::C;
const bool silu = g.gate == strata::kernels::GdnGate::Silu;
if (serial || T <= 0) {
if (silu)
gdn_rec_kernel<HV, HK, C, true><<<HV, dim3(S, RG), 0, cs>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);
else
gdn_rec_kernel<HV, HK, C, false><<<HV, dim3(S, RG), 0, cs>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);
return;
}
if (serial || T <= 0) {
gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);
} else {
static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();
#if !defined(__HIPCC__)
if (pipe && gdn_keyhead_ok<HV, HK, C>()) // the value heads of a key head in one thread (same bits)
gdn_rec_kh_kernel<HV, HK, C><<<HK * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits)
gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
else
#endif
if (pipe) // the software-pipelined loads (same bits)
gdn_rec_cols_pipe_kernel<HV, HK, C><<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
else
gdn_rec_cols_kernel<HV, HK, C><<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
if (silu) gdn_out_norm_kernel<HV, true><<<dim3((unsigned) T, HV), S, 0, cs>>>(z, gamma, eps, y, y16);
else gdn_out_norm_kernel<HV, false><<<dim3((unsigned) T, HV), S, 0, cs>>>(z, gamma, eps, y, y16);
});
gdn_rec_cols_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16);
}
check("gdn_recurrence");
}
void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, int64_t k, void* stream) {
if (k < 1 || k > 32 || k > n_expert) { // Prefill::init refuses this first, with an error string
std::fprintf(stderr, "prefill route: top-%lld of %lld experts (k must be 1..32 and at most n_expert)\n",
(long long) k, (long long) n_expert);
std::exit(1);
}
void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {
if (n_expert == 512)
route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T, (int) k);
route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);
else if (n_expert == 256)
route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T, (int) k);
route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);
else
strata::kernels::router_top10(logits, (int) T, (int) n_expert, (int) k, ids, weights, stream);
strata::kernels::router_top10(logits, (int) T, (int) n_expert, 10, ids, weights, stream);
check("route");
}
void rms_norm_images(const float* R, const float* w, float eps, float* mixed, uint16_t* mixed16, uint16_t* mixed_h,
int64_t T, int64_t n, void* stream, uint16_t* mixed16_lo) {
if (T <= 0) return;
rms_norm_images_kernel<<<(unsigned) T, 256, 0, (cudaStream_t) stream>>>(R, w, eps, n, mixed, mixed16, mixed_h, mixed16_lo);
check("rms_norm_images");
}
void residual_add(float* R, const float* bo, int64_t n, void* stream) {
if (n <= 0) return;
residual_add_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(R, bo, n);
check("residual_add");
}
void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) {
blob_dequant_kernel<false><<<blocks_for(1280LL * 640 + 2560LL * 160), 256, 0, (cudaStream_t) stream>>>(blob, gu16, down16);
check("blob_dequant");
@@ -1047,14 +942,13 @@ void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, voi
blob_dequant_kernel<true><<<blocks_for(1280LL * 640 + 2560LL * 160), 256, 0, (cudaStream_t) stream>>>(blob, gu16, down16);
check("blob_dequant_f16");
}
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, int64_t n_ff, void* stream) {
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream) {
if (n <= 0) return;
swiglu_il_kernel<<<blocks_for(n * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h16, n, n_ff);
swiglu_il_kernel<<<blocks_for(n * 640), 256, 0, (cudaStream_t) stream>>>(gu, h16, n);
check("swiglu_interleaved");
}
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, int64_t n_ff, void* stream) {
if (n <= 0) return;
swiglu_pair_kernel<<<blocks_for(n * n_ff), 256, 0, (cudaStream_t) stream>>>(g, u, h16, n * n_ff);
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) {
swiglu_pair_kernel<<<blocks_for(n * 640), 256, 0, (cudaStream_t) stream>>>(g, u, h16, n);
check("swiglu_pair");
}
namespace {
@@ -1088,8 +982,8 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int
check("gather_rows16");
}
void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
int64_t T, int64_t n, int64_t k, void* stream) {
moe_combine_kernel<<<blocks_for(T * n), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T, n, (int) k);
int64_t T, void* stream) {
moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T);
check("moe_combine");
}
void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) {
@@ -1118,12 +1012,12 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p
strata::kernels::mrope_table(), rt);
check("rope");
}
void split_q(const float* q_full, float* q, int64_t T, int64_t n_head, void* stream) {
split_q_kernel<<<blocks_for(T * n_head * 256), 256, 0, (cudaStream_t) stream>>>(q_full, q, T, n_head);
void split_q(const float* q_full, float* q, int64_t T, void* stream) {
split_q_kernel<<<blocks_for(T * 24 * 256), 256, 0, (cudaStream_t) stream>>>(q_full, q, T);
check("split_q");
}
void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, int64_t n_head, void* stream) {
gate_attn_kernel<<<blocks_for(T * n_head * 256), 256, 0, (cudaStream_t) stream>>>(attn, q_full, out16, T, n_head);
void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream) {
gate_attn_kernel<<<blocks_for(T * 24 * 256), 256, 0, (cudaStream_t) stream>>>(attn, q_full, out16, T);
check("gate_attn");
}
+9 -17
View File
@@ -56,8 +56,7 @@ constexpr int WLD = 80; // bytes per decoded weight row of a sta
__host__ __device__ constexpr int tile_rows(int ww) { return 256 / ww; }
__host__ __device__ constexpr int weight_rows(int ww) { return 64 * ww; }
constexpr int ASTAGES = 4; // cp.async depth of the activations (64 values of K a stage)
// K of gate/up (n_embd) and of down (n_ff) are the layer's (NativeGeom): 2560 / 640 for Flash-Next, 2048 / 512 for
// Qwen3.6. They set the stage count and the weight-row blocks per tile, loop bounds rather than unrolled constants.
constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and of down (n_ff)
// the formats (ggml type ids)
constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S,
@@ -295,11 +294,9 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
constexpr int TR = tile_rows(WW), WR = weight_rows(WW);
constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB;
const int n_embd = (int) geo.n_embd, n_ff = (int) geo.n_ff;
const int NS = (GU ? n_embd : n_ff) / 64; // 64-value stages along K
const int NFB = (GU ? 2 * n_ff : n_embd) / WR; // weight-row blocks per tile
const int ACT_LD = NS * AB; // bytes per activation row: n_embd / 64 * 80 (a token), n_ff / 64 * 80 (a row's H)
const int H_BLOCKS = n_ff / 64; // 64-value blocks of a row's H
constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K
constexpr int NFB = (GU ? 1280 : 2560) / WR; // weight-row blocks per tile
constexpr int ACT_LD = NS * AB; // bytes per activation row: 3200 (a token), 800 (a row's H)
constexpr int BS = block_bytes(WT);
constexpr bool K16 = per16(WT);
extern __shared__ __align__(16) uint8_t smem[];
@@ -352,7 +349,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
// slice at once (180 or 360 bytes a row)
constexpr int PF = 2;
auto prefetch_sb = [&](int sb) {
if (dec && sb < n_embd / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));
if (dec && sb < GU_ROWS_K / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));
};
if (GU) {
#pragma unroll
@@ -484,7 +481,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
const float inv = am > 0.0f ? 127.0f / am : 0.0f;
const int r = nb0 + 8 * n + 2 * tig + c;
if (r < nrows) {
uint8_t* o = out + (size_t) (row0 + r) * (H_BLOCKS * AB) + (blk >> 1) * AB;
uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;
const int hh = blk & 1;
#pragma unroll
for (int i = 0; i < 4; ++i) o[32 * hh + 8 * i + g] = (uint8_t) (int8_t) __float2int_rn(h[i] * inv);
@@ -501,7 +498,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
#pragma unroll
for (int q = 0; q < 4; ++q) {
const int r = nb0 + 8 * n + 2 * tig + (q & 1);
if (r < nrows) dm[(size_t) (row0 + r) * n_embd + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q];
if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q];
}
}
}
@@ -623,13 +620,8 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n
// the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the
// ones inside a larger item end at once
const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
if (g.n_embd % 256 != 0 || g.n_ff % 64 != 0 || (2 * g.n_ff) % weight_rows(ww) != 0 || g.n_embd % weight_rows(ww) != 0) {
std::fprintf(stderr, "prefill fused experts (native): n_embd %lld / n_ff %lld do not tile (n_embd a multiple of 256, "
"2 n_ff and n_embd multiples of %d)\n", (long long) g.n_embd, (long long) g.n_ff, weight_rows(ww));
std::exit(1);
}
const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (2 * g.n_ff / weight_rows(ww)), (int64_t) d.sms * d.occ);
const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (g.n_embd / weight_rows(ww)), (int64_t) d.sms * d.occ);
const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / weight_rows(ww)), (int64_t) d.sms * d.occ);
const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / weight_rows(ww)), (int64_t) d.sms * d.occ);
switch (g.gu_type) {
case T_IQ2_XXS: launch<T_IQ2_XXS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
case T_IQ2_XS: launch<T_IQ2_XS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
-2
View File
@@ -116,7 +116,6 @@ bool supported(int t) {
case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9)
#ifdef STRATA_MMQ_KQUANTS
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: // Unsloth's UD-Q4_K_XL experts (CUDA)
case GGML_TYPE_Q6_K: // Qwen3.6-35B-A3B UD-Q4_K_XL's down projections on layers 34, 38, 39
#endif
return true;
default:
@@ -202,7 +201,6 @@ void Context::run(const Product& p, void* stream) {
case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
#endif
default:
std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t);
+138 -413
View File
@@ -1,5 +1,4 @@
// src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp.
#include "strata/core/qsa_shapes.hpp"
#include "strata/prefill/prefill.hpp"
#include "strata/core/mtp.hpp"
#include "strata/core/progress.hpp"
@@ -88,35 +87,8 @@ namespace {
using Clock = std::chrono::steady_clock;
constexpr float EPS = 1e-6f;
// The model's geometry as this path uses it, from ModelGeometry (Qwen3.6 port, step 3: the file-wide constants N 2560,
// HC 4, LR 320, K 10, NE 512, C 10240, ZV 6144, HV 48 became these members; docs/QWEN36-35B-A3B.md section 3.6).
// Every function below takes it from Impl (or builds it from the ModelGeometry it was given) and names the members
// as the constants were named, so the arithmetic reads as before.
struct Geom {
int64_t n = 2560; ///< n_embd
int64_t hc = 4, d = 10240, lr = 320; ///< hyper-connection streams, hc * n_embd, the bottleneck (hc 1: no GR)
int64_t k = 10, ne = 512, ff = 640; ///< experts per token, experts, expert width
int64_t ff2 = 1280, ffs = 640; ///< 2 * n_ff (gate | up rows), the shared expert's width
int64_t c = 10240, zv = 6144, hv = 48, hk = 16; ///< GDN: conv channels, value dim, value heads, key heads
int64_t nh = 24, nkv = 2, hd = 256; ///< attention heads, KV heads, head dim
int64_t qf = 24 * 512, av = 6144, kvw = 512; ///< attn_q's width (q | gate per head), n_head * 256, n_head_kv * 256
bool indexer = true; ///< the QSA indexer (Flash-Next); Qwen3.6's attention is dense
strata::kernels::GdnGate gate = strata::kernels::GdnGate::Sigmoid; ///< the GDN output gate (ModelGeometry::gdn_gate)
static Geom of(const core::ModelGeometry& g) {
Geom o;
o.n = g.n_embd; o.hc = g.hc; o.d = g.hc * g.n_embd; o.lr = g.hc_lr;
o.k = g.n_expert_used; o.ne = g.n_expert; o.ff = g.n_ff; o.ff2 = 2 * g.n_ff; o.ffs = g.n_ff_shexp;
o.c = g.ssm_conv_channels; o.zv = g.ssm_value_dim; o.hv = g.ssm_v_heads; o.hk = g.ssm_k_heads;
o.nh = g.n_head; o.nkv = g.n_head_kv; o.hd = g.head_dim;
o.qf = g.n_head * 2 * g.head_dim; o.av = g.n_head * g.head_dim; o.kvw = g.n_head_kv * g.head_dim;
o.indexer = g.has_indexer();
o.gate = g.gdn_gate();
return o;
}
GdnGeom gdn() const { return GdnGeom{(int) hv, (int) hk, (int) c, gate}; }
};
// The largest expert count any pack has (the peer path's event ring and host bounds are sized once from it).
constexpr int64_t NE_MAX = 512;
constexpr int64_t N = 2560, HC = 4, D = N * HC, LR = 320, K = 10, NE = 512;
constexpr int64_t C = 10240, ZV = 6144, HV = 48;
// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer)
inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; }
constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min())
@@ -261,25 +233,13 @@ struct Alloc {
const uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull;
if (count_only) { used += bytes; return nullptr; }
if (base != nullptr) {
if (used + bytes > cap) {
if (std::getenv("STRATA_PREFILL_ALLOC_TRACE")) // which take overflowed its region (a count/carve mismatch)
std::fprintf(stderr, "prefill alloc: %llu bytes do not fit (%llu of %llu used)\n", (unsigned long long) bytes,
(unsigned long long) used, (unsigned long long) cap);
ok = false;
return nullptr;
}
if (used + bytes > cap) { ok = false; return nullptr; }
T* p = (T*) (base + used);
used += bytes;
return p;
}
void* p = nullptr;
if (const cudaError_t e = cudaMalloc(&p, bytes); e != cudaSuccess) {
if (std::getenv("STRATA_PREFILL_ALLOC_TRACE"))
std::fprintf(stderr, "prefill alloc: cudaMalloc of %llu bytes: %s\n", (unsigned long long) bytes, cudaGetErrorString(e));
cudaGetLastError();
ok = false;
return nullptr;
}
if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return nullptr; }
owned->push_back(p);
used += bytes;
return (T*) p;
@@ -434,7 +394,7 @@ struct PeerPrefill {
cudaEvent_t ev_done = nullptr; // on the peer: its rows have landed in the primary's Dm
// multi-GPU: the result rows go back group by group on a second stream while the next group computes
cudaStream_t s_out = nullptr;
static constexpr int kGrpEv = NE_MAX / 16 + 2; // sized for the largest pack; a smaller one uses fewer
static constexpr int kGrpEv = NE / 16 + 2;
cudaEvent_t ev_grp[kGrpEv] = {};
bool out_pending = false; // s_out may still read Dm (the next layer's products wait for it)
bool out_pipe = true;
@@ -483,7 +443,7 @@ struct PeerPrefill {
int32_t* host_src = nullptr; // the peer's rows' tokens (mapped, portable)
int32_t* host_bounds = nullptr; // its group bounds (mapped, portable)
size_t host_x_cap = 0, host_rows_cap = 0, host_src_cap = 0; // elements
static constexpr size_t kHostBounds = 2 * (NE_MAX + NE_MAX / 16 + 2) + 64;
static constexpr size_t kHostBounds = 2 * (NE + NE / 16 + 2) + 64;
int64_t back_at = 0, back_rows = 0;
std::vector<int32_t> bounds_host;
std::vector<void*> owned;
@@ -518,7 +478,6 @@ struct PeerPrefill {
struct Prefill::Impl {
const core::WeightTable* wt = nullptr;
const core::ModelGeometry* g = nullptr;
Geom geo; ///< the model's widths (Geom::of(*g))
core::SessionState* ss = nullptr;
core::ExpertSource* src = nullptr;
const core::ExpertCache* cache = nullptr;
@@ -613,7 +572,6 @@ namespace {
bool stage_own() { static const bool v = std::getenv("STRATA_KV_STAGE_OWN") != nullptr; return v; }
void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::kernels::QsaShapes& s,
strata::kernels::KvHostPools& st, bool& ok) {
if (ss.qsa_alloc <= 0) return; // a model with no attention layer (the harness's gdn3 fixture): no KV to stage
const core::QsaState& q0 = ss.qsa_states[ss.qsa_primary()];
if (q0.kv_mode != 1) return;
if (stage_own() && o_borrowed.count_only) return;
@@ -679,40 +637,22 @@ constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspace
// of the largest holds them all. That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk
// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token). The sizes are
// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap.
uint64_t gdn_set_bytes(size_t T, const Geom& G) {
const int64_t C = G.c, ZV = G.zv, HV = G.hv;
uint64_t gdn_set_bytes(size_t T) {
Alloc a; a.count_only = true; bool ok = true;
a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<float>(T * 2 * HV, ok); a.take<float>(T * HV, ok);
a.take<float>(T * HV, ok); a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<uint16_t>(T * ZV, ok);
return a.used;
}
// the indexer's two buffers (the raw key, the query) only with an indexer; the dense model carves none
uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch,
const strata::kernels::QsaShapes& s, const Geom& G) {
const strata::kernels::QsaShapes& s) {
Alloc a; a.count_only = true; bool ok = true;
a.take<float>(T * G.kvw, ok); a.take<float>(T * G.kvw, ok); a.take<float>(T * G.qf, ok); a.take<float>(T * G.av, ok);
if (G.indexer) { a.take<float>(T * s.idx_dim, ok); a.take<float>(T * s.idx_n_head * s.idx_dim, ok); }
a.take<float>(T * G.av, ok); a.take<uint16_t>(T * G.av, ok);
if (G.indexer) a.take<int32_t>(T * (size_t) cap, ok); // dense attention carries no ids (a null is the identity)
if (G.indexer) a.take<float>((size_t) sel_batch * (size_t) max_blocks, ok);
a.take<float>(T * 512, ok); a.take<float>(T * 512, ok); a.take<float>(T * 12288, ok); a.take<float>(T * ZV, ok);
a.take<float>(T * 128, ok); a.take<float>(T * 512, ok); a.take<float>(T * ZV, ok); a.take<uint16_t>(T * ZV, ok);
a.take<int32_t>(T * (size_t) cap, ok);
a.take<float>((size_t) sel_batch * (size_t) max_blocks, ok);
a.take<float>((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok);
return a.used;
}
// the primary attention state's cells (0 when the model has no attention layer at all: the harness's gdn3 fixture)
int64_t primary_cells(const core::SessionState& ss) {
return ss.qsa_alloc > 0 ? ss.qsa_states[ss.qsa_primary()].max_cells : 0;
}
// The attention shapes of this model. A model without an indexer (Qwen3.6) zeroes the three indexer widths together:
// that is the kernels' dense signal (qsa_dense; qsa.cu's guard refuses a shape with only some of them zero).
strata::kernels::QsaShapes shapes_of(const core::ModelGeometry& g) {
return strata::core::qsa_shapes(g); // the one builder (strata/core/qsa_shapes.hpp), as layer, verify, mtp, session
}
// The capacity of the per-query selection buffers: the sparse width (2,051) with an indexer, every cell of the
// context (the primary state's max_cells) for dense attention - qsa_selection_cap, as the attention branch defines
// it; the dense path carries no ids (a null is the identity) and the split-K scratch is bounded there.
int64_t selection_cap(const core::SessionState& ss, const strata::kernels::QsaShapes& s) {
return std::max<int64_t>(strata::kernels::qsa_selection_cap(primary_cells(ss), s), 1);
}
// Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob
// is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest
// gate/up and down matrices a group buffer slot holds. STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B).
@@ -737,15 +677,12 @@ const MmqPlan& mmq_plan() {
p.fallback = !on || layers <= 0;
for (int64_t l = 0; on && l < layers; ++l) {
const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
// the layer's widths: the native pack's own (2048 / 512 for Qwen3.6), the canonical Q2_0 pack's 2560 / 640
const int64_t n_embd = lay.native ? lay.fmt[(size_t) l].n_embd : 2560;
const int64_t n_ff = lay.native ? lay.fmt[(size_t) l].n_ff : 640;
// #420: a tile on every GPU for these shapes (gate+up: 2 n_ff rows, down: n_embd rows), else the FP16 path
if (!mmq::fits(gt, 2 * n_ff) || !mmq::fits(dt, n_embd)) { p.fallback = true; continue; }
// #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path
if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { p.fallback = true; continue; }
p.layer[(size_t) l] = 1;
p.any = true;
p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 2 * n_ff, n_embd));
p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, n_embd, n_ff));
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));
}
return p;
}();
@@ -763,27 +700,25 @@ bool fused_layout(size_t T, bool src) {
// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes. Without `fused` (the
// default): MMQ's, for T tokens.
struct MoeBufs { size_t gu, h, xq, hq; };
MoeBufs moe_bufs(size_t T, const Geom& G, bool fused) {
const int64_t K = G.k, N = G.n, FF = G.ff, FF2 = G.ff2;
if (!fused) return {T * K * FF2, T * K * FF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), FF)};
MoeBufs moe_bufs(size_t T, int64_t n_expert, bool fused) {
if (!fused) return {T * K * 1280, T * K * 640, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), 640)};
const size_t ts = (size_t) std::min<int64_t>((int64_t) T, stream_all_min() - 1); // MMQ's last small chunk
return {std::max(ts * K * FF2, (fused::group_bytes((int64_t) (T * K), (int) G.ne) + 3) / 4),
std::max(ts * K * FF, (fused::act_bytes((int64_t) (T * K), FF) + 3) / 4),
return {std::max(ts * K * 1280, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4),
std::max(ts * K * 640, (fused::act_bytes((int64_t) (T * K), 640) + 3) / 4),
std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)),
mmq::q8_bytes((int64_t) (ts * K), FF)};
mmq::q8_bytes((int64_t) (ts * K), 640)};
}
uint64_t moe_set_bytes(size_t T, const Geom& G, bool fused) {
const int64_t K = G.k, N = G.n, FF = G.ff, FFS = G.ffs;
uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
const MmqPlan& mp = mmq_plan();
const MoeBufs mb = moe_bufs(T, G, fused);
const MoeBufs mb = moe_bufs(T, n_expert, fused);
Alloc a; a.count_only = true; bool ok = true;
a.take<float>(T * G.ne, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
a.take<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
a.take<int32_t>(T * K, ok);
if (mp.fallback) a.take<uint16_t>(T * K * N, ok);
a.take<float>(mb.gu, ok);
if (mp.fallback) a.take<uint16_t>(T * K * FF, ok);
a.take<float>(T * K * N, ok); a.take<float>(T * FFS, ok);
a.take<float>(T * FFS, ok); a.take<uint16_t>(T * FFS, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
if (mp.fallback) a.take<uint16_t>(T * K * 640, ok);
a.take<float>(T * K * N, ok); a.take<float>(T * 640, ok);
a.take<float>(T * 640, ok); a.take<uint16_t>(T * 640, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
if (mp.any) {
a.take<uint8_t>(mb.xq, ok);
a.take<float>(mb.h, ok);
@@ -799,38 +734,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
Impl& m = *impl_;
m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res;
m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_;
m.geo = Geom::of(g);
const Geom& G = m.geo;
const int64_t D = G.d, K = G.k, N = G.n;
// The geometries this path is built for: Flash-Next's (the hyper-connection kernels at 2560 / 4 / 320, top-10) and
// Qwen3.6's (the plain block, hc 1, the GDN kernels forked at 32 / 16 / 8192, top-8 of 256). Everything else in
// the layer loop is runtime; what is not (the GDN head geometry, the head size, the KV layout) is refused here by
// name rather than mis-indexed below.
if (g.arch == core::ModelArch::Qwen4Exp) {
if (g.n_embd != 2560 || g.hc != 4 || g.hc_lr != 320 || ss.k != 10 || g.n_expert_used != 10) {
err = "prefill: geometry differs from the artifact's (Flash-Next: n_embd 2560, hc 4, hc_lr 320, top-10)";
return false;
}
} else if (g.hc != 1) {
err = "prefill: qwen35moe with hc " + std::to_string(g.hc) + " (the plain block has one residual stream)";
return false;
}
if (g.n_expert < 1 || ss.k != g.n_expert_used || ss.k < 1 || ss.k > 32 || ss.k > g.n_expert) {
err = "prefill: top-" + std::to_string(ss.k) + " routing over " + std::to_string(g.n_expert) +
" experts (the file says top-" + std::to_string(g.n_expert_used) + "; k must be 1..32 and at most n_expert)";
return false;
}
if (!gdn_geometry_supported((int) g.ssm_v_heads, (int) g.ssm_k_heads, (int) g.ssm_conv_channels) || g.ssm_state_size != 128 ||
g.ssm_d_conv != 4) {
err = "prefill: no GDN kernels for " + std::to_string(g.ssm_v_heads) + " value heads / " + std::to_string(g.ssm_k_heads) +
" key heads / " + std::to_string(g.ssm_conv_channels) + " conv channels (built for 48/16/10240 and 32/16/8192, "
"state 128, conv 4)";
return false;
}
if (g.head_dim != 256 || g.n_head_kv != 2 || g.n_rot != 64 || g.n_embd % 256 != 0 || g.n_ff % 64 != 0) {
err = "prefill: the attention and expert kernels take head_dim 256, 2 KV heads, n_rot 64, n_embd a multiple of 256 "
"and n_ff a multiple of 64";
return false;
if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) {
err = "prefill: geometry differs from the artifact's"; return false;
}
cudaGetDevice(&m.device);
if (stage_le_ < 0) stage_le_ = g.n_layers;
@@ -908,7 +813,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
ok = false;
m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS);
}
if (ss.qsa_alloc > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table
if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table
const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages;
std::vector<int32_t> ident((size_t) pages);
for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i;
@@ -943,30 +848,28 @@ bool Prefill::carve(size_t T, void* alloc) {
Alloc& o = *static_cast<Alloc*>(alloc);
const core::ModelGeometry& g = *m.g;
core::SessionState& ss = *m.ss;
const Geom& G = m.geo;
const int64_t N = G.n, HC = G.hc, D = G.d, LR = G.lr, K = G.k, C = G.c, ZV = G.zv, HV = G.hv;
const bool gr = HC > 1; // the hyper-connection's buffers; the plain block (hc 1) reads R and writes R directly
bool ok = true;
m.emb = o.take<float>(T * N, ok); m.R = o.take<float>(T * D, ok);
m.xn = gr && gr_unfused() ? o.take<float>(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R)
m.grs = gr ? o.take<float>(T * HC, ok) : nullptr;
m.xn16 = gr ? o.take<uint16_t>(T * D, ok) : nullptr;
m.lo = gr ? o.take<float>(T * LR, ok) : nullptr; m.lo16 = gr ? o.take<uint16_t>(T * LR, ok) : nullptr;
m.gated = gr ? o.take<float>(T * D, ok) : nullptr; m.inj = gr ? o.take<float>(T * HC, ok) : nullptr;
m.xn = gr_unfused() ? o.take<float>(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R)
m.grs = o.take<float>(T * HC, ok);
m.xn16 = o.take<uint16_t>(T * D, ok); m.lo = o.take<float>(T * LR, ok); m.lo16 = o.take<uint16_t>(T * LR, ok);
m.gated = o.take<float>(T * D, ok); m.inj = o.take<float>(T * HC, ok);
m.mixed = o.take<float>(T * N, ok); m.mixed_bf = o.take<uint16_t>(T * N, ok);
m.mixed_h = o.take<uint16_t>(T * N, ok); m.bo = o.take<float>(T * N, ok);
if (gr && bf16x2_hc()) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }
if (bf16x2_hc()) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }
if (bf16x2()) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);
m.steps_dev = o.take<int32_t>(T * strata::kernels::kStepCount, ok);
const strata::kernels::QsaShapes s = shapes_of(g);
m.cap = selection_cap(ss, s);
m.max_blocks = primary_cells(ss) / s.idx_block + 2;
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
{
// one region for the attention half's and the MoE half's scratch (see gdn_set_bytes)
const bool fz = fused_layout(T, m.src != nullptr);
const MoeBufs mb = moe_bufs(T, G, fz);
const uint64_t region = std::max({gdn_set_bytes(T, G), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
m.attn_batch, s, G), moe_set_bytes(T, G, fz)});
const MoeBufs mb = moe_bufs(T, m.g->n_expert, fz);
const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, fz)});
uint8_t* base = o.take<uint8_t>((size_t) region, ok);
m.region = base;
m.region_bytes = region;
@@ -977,24 +880,22 @@ bool Prefill::carve(size_t T, void* alloc) {
m.y = a.take<float>(T * ZV, ok); m.y_h = a.take<uint16_t>(T * ZV, ok);
Alloc b;
b.base = base; b.cap = region; b.owned = &m.owned;
m.Kc = b.take<float>(T * G.kvw, ok); m.Vc = b.take<float>(T * G.kvw, ok); m.Qf = b.take<float>(T * G.qf, ok);
m.q = b.take<float>(T * G.av, ok);
m.idx_raw = G.indexer ? b.take<float>(T * s.idx_dim, ok) : nullptr;
m.q_idx = G.indexer ? b.take<float>(T * s.idx_n_head * s.idx_dim, ok) : nullptr;
m.attn = b.take<float>(T * G.av, ok); m.attn_h = b.take<uint16_t>(T * G.av, ok);
m.sel_ids = G.indexer ? b.take<int32_t>(T * (size_t) m.cap, ok) : nullptr;
m.sel_scores = G.indexer ? b.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok) : nullptr;
m.Kc = b.take<float>(T * 512, ok); m.Vc = b.take<float>(T * 512, ok); m.Qf = b.take<float>(T * 12288, ok);
m.q = b.take<float>(T * ZV, ok); m.idx_raw = b.take<float>(T * 128, ok); m.q_idx = b.take<float>(T * 512, ok);
m.attn = b.take<float>(T * ZV, ok); m.attn_h = b.take<uint16_t>(T * ZV, ok);
m.sel_ids = b.take<int32_t>(T * (size_t) m.cap, ok);
m.sel_scores = b.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);
m.attn_scratch = b.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);
Alloc c;
c.base = base; c.cap = region; c.owned = &m.owned;
m.logits = c.take<float>(T * G.ne, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
m.logits = c.take<float>(T * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
m.slot_dev = c.take<int32_t>(T * K, ok); m.src_dev = c.take<int32_t>(T * K, ok);
const MmqPlan& mp = mmq_plan();
m.Xs = mp.fallback ? c.take<uint16_t>(T * K * N, ok) : nullptr;
m.GU = c.take<float>(mb.gu, ok);
m.Hh = mp.fallback ? c.take<uint16_t>(T * K * G.ff, ok) : nullptr;
m.Hh = mp.fallback ? c.take<uint16_t>(T * K * 640, ok) : nullptr;
m.Dm = c.take<float>(T * K * N, ok);
m.sgate = c.take<float>(T * G.ffs, ok); m.sup = c.take<float>(T * G.ffs, ok); m.sh_h = c.take<uint16_t>(T * G.ffs, ok);
m.sgate = c.take<float>(T * 640, ok); m.sup = c.take<float>(T * 640, ok); m.sh_h = c.take<uint16_t>(T * 640, ok);
m.shared = c.take<float>(T * N, ok); m.sg = c.take<float>(T, ok);
if (mp.any) {
m.Xq = c.take<uint8_t>(mb.xq, ok);
@@ -1003,11 +904,11 @@ bool Prefill::carve(size_t T, void* alloc) {
}
if (base == nullptr) ok = false;
}
for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take<uint16_t>((size_t) (G.ff2 * N), ok); m.dq_d[i] = o.take<uint16_t>((size_t) (N * G.ff), ok); }
for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take<uint16_t>(1280 * 2560, ok); m.dq_d[i] = o.take<uint16_t>(2560 * 640, ok); }
if (mmq_plan().any) {
const MmqPlan& mp = mmq_plan();
m.ids_identity = o.take<int32_t>(T * K, ok);
m.bounds_dev = o.take<int32_t>((size_t) (2 * (G.ne + G.ne / MMQ_GROUP + 2)), ok);
m.bounds_dev = o.take<int32_t>((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok);
m.grp_gu = o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);
m.grp_d = o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
// (written at every run's start, not here: when serving, these are live expert-cache slots until a request
@@ -1020,8 +921,8 @@ bool Prefill::carve(size_t T, void* alloc) {
m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for
m.used_of[i] = i;
}
m.ple_emb = g.has_ple ? o.take<float>(T * N, ok) : nullptr;
m.ple_norm = g.has_ple ? o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok) : nullptr;
m.ple_emb = o.take<float>(T * N, ok);
m.ple_norm = o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok);
take_stage(o, ss, s, m.stage, ok);
m.T = (int64_t) T;
return ok;
@@ -1064,140 +965,13 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
// drafter's own pass for a ring (the A/B).
static const bool ring_ok = [] { const char* v = std::getenv("STRATA_MTP_BATCH_RING"); return v == nullptr || v[0] != '0'; }();
core::QsaState& st = mtp.kv_state_rw();
if (off || n <= 0 || m.g == nullptr || m.region == nullptr ||
(st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) || st.kv_hybrid || mtp.device() != m.device)
if (off || n <= 0 || m.g == nullptr || m.region == nullptr || (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) ||
st.kv_hybrid || mtp.device() != m.device)
return false;
const auto t0 = Clock::now();
const core::ModelGeometry& g = *m.g;
const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim, HC = m.geo.hc, LR = m.geo.lr;
const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim;
constexpr int kQ8_0 = 8; // GGML_TYPE_Q8_0
static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes
// E-9: the drafter's Q8_0 matrices through Q8_1 x Q8_0 MMQ - its own pass's integer dot products (mmvq), so
// its K/V stay close to what the drafter computes itself; STRATA_MTP_BATCH_F16=1: FP16 GEMMs (the A/B)
static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v && v[0] == '1'; }();
if (g.arch == core::ModelArch::Qwen35Moe) {
// ---- QWEN3.6 (docs/qwen36-port/step4-drafter.md): the nextn block's K/V for the prompt's cells through this
// path's GEMMs, the drafter's own graph (core/mtp.cpp record_forward_qwen36) row for row:
// e = rms_norm(embed(next_token)) * enorm; h = rms_norm(rms_norm(R) * output_norm) * hnorm
// cur = eh_proj . concat(e, h); x = rms_norm(cur) * attn_norm; K = rope(k_norm(attn_k . x)), V = attn_v . x
// The projections are the pack's native types (Q8_0 in both shipped files); the embedding is the native table.
if (!mtp.qwen36()) return false;
const float* w_enorm = mtp.tensor_f32("nextn.enorm.weight");
const float* w_hnorm = mtp.tensor_f32("nextn.hnorm.weight");
const float* w_an = mtp.tensor_f32("attn_norm.weight");
const float* w_kn = mtp.tensor_f32("attn_k_norm.weight");
int t_eh = -1, t_k = -1, t_v = -1;
const void* w_eh = mtp.tensor_native("nextn.eh_proj.weight", &t_eh);
const void* w_k = mtp.tensor_native("attn_k.weight", &t_k);
const void* w_v = mtp.tensor_native("attn_v.weight", &t_v);
const core::WeightRef* wo_norm = m.wt->find("output_norm.weight");
const core::NativeEmbed* nemb = core::native_embed();
if (!w_enorm || !w_hnorm || !w_an || !w_kn || !w_eh || !w_k || !w_v || nemb == nullptr || wo_norm == nullptr ||
wo_norm->data == nullptr || wo_norm->kind != core::WeightKind::F32 || wo_norm->elements != Nn)
return false;
const float* w_on = (const float*) wo_norm->data;
const float eps = (float) g.rms_eps;
const int64_t r0 = std::max<int64_t>(0, mtp.first_needed() - cell0);
if (r0 >= n) return true;
const bool q8 = !f16_only && mmq::built() && mmq::supported(t_eh) && mmq::supported(t_k) && mmq::supported(t_v) &&
mmq::fits(t_eh, Nn) && mmq::fits(t_k, KV) && mmq::fits(t_v, KV);
// per row: emb (N) + its fp16 image, hn (N), cat (2N) + fp16, cur (N) + fp16, K and V (KV each), the token;
// with MMQ the q8 image of the widest input (2N) and the identity row
const uint64_t per_row = 4 * (Nn + Nn + 2 * Nn + Nn + 2 * KV + 1) + 2 * (Nn + 2 * Nn + Nn) + 64 +
(q8 ? (uint64_t) mmq::q8_bytes(1, 2 * Nn) + 4 : 0);
int64_t B = std::min<int64_t>(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63);
if (st.kv_mode == 2)
B = std::min<int64_t>(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63);
if (B < 64) return false;
uint8_t* q = m.region;
auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; };
float* emb = (float*) carve((size_t) B * Nn * 4);
uint16_t* emb16 = (uint16_t*) carve((size_t) B * Nn * 2);
float* hn = (float*) carve((size_t) B * Nn * 4);
float* cat = (float*) carve((size_t) B * 2 * Nn * 4);
uint16_t* cat16 = (uint16_t*) carve((size_t) B * 2 * Nn * 2);
float* cur = (float*) carve((size_t) B * Nn * 4);
uint16_t* cur16 = (uint16_t*) carve((size_t) B * Nn * 2);
float* Kc = (float*) carve((size_t) B * KV * 4);
float* Vc = (float*) carve((size_t) B * KV * 4);
int32_t* tok = (int32_t*) carve((size_t) B * 4);
void* xq = q8 ? carve(mmq::q8_bytes(B, 2 * Nn)) : nullptr;
int32_t* ident = q8 ? (int32_t*) carve((size_t) B * 4) : nullptr;
int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr;
(void) emb16;
if ((uint64_t) (q - m.region) > m.region_bytes) return false;
if (timing) cudaStreamSynchronize(m.cs);
const auto ti0 = Clock::now();
if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V
const double ms_idle = ms_since(ti0);
const auto tl0 = Clock::now();
const strata::kernels::QsaShapes s = shapes_of(g);
std::vector<int32_t> tk((size_t) B);
if (q8) {
if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
mmq::iota(ident, B, m.cs);
}
auto proj = [&](const float* x, uint16_t* x16, int type, const void* w, float* y, int64_t rows, int64_t n_out, int64_t k) {
if (!q8) { to_f16(x, x16, rows * k, m.cs); m.gemm.native(x16, type, w, y, rows, n_out, k); return; }
mmq::quantize(x, nullptr, xq, type, k, k, rows, m.cs);
mmq::Product p;
p.w = w; p.type = type; p.w_rows = n_out; p.w_cols = k; p.expert_bytes = mmq::matrix_bytes(type, n_out, k);
p.n = 1; p.xq = xq; p.bounds = bnd; p.ids = ident; p.total_rows = rows; p.max_rows = rows;
p.dst = y; p.ld_dst = n_out;
m.mmq_ctx->run(p, m.cs);
};
for (int64_t b0 = r0; b0 < n; b0 += B) {
const int64_t nb = std::min(B, n - b0), c0 = cell0 + b0;
for (int64_t i = 0; i < nb; ++i) tk[(size_t) i] = next_tokens[b0 + i];
const int32_t bh[4] = {0, (int32_t) nb, 0, (int32_t) nb};
if ((q8 && cudaMemcpyAsync(bnd, bh, sizeof bh, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) ||
cudaMemcpyAsync(tok, tk.data(), (size_t) nb * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) {
err = "prefill: the draft inputs' upload failed";
return false;
}
// e = rms_norm(embed(token)) * enorm; h = rms_norm(rms_norm(R) * output_norm) * hnorm; concat(e, h)
nemb->gather_dev(tok, nb, emb, m.cs);
rms_rows(emb, w_enorm, nb, Nn, Nn, eps, m.cs);
if (cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * Nn * 4, cudaMemcpyDeviceToDevice, m.cs) != cudaSuccess) {
err = "prefill: the draft residual copy failed";
return false;
}
rms_rows(hn, w_on, nb, Nn, Nn, eps, m.cs);
rms_rows(hn, w_hnorm, nb, Nn, Nn, eps, m.cs);
if (cudaMemcpy2DAsync(cat, (size_t) 2 * Nn * 4, emb, (size_t) Nn * 4, (size_t) Nn * 4, (size_t) nb, cudaMemcpyDeviceToDevice, m.cs) != cudaSuccess ||
cudaMemcpy2DAsync(cat + Nn, (size_t) 2 * Nn * 4, hn, (size_t) Nn * 4, (size_t) Nn * 4, (size_t) nb, cudaMemcpyDeviceToDevice, m.cs) != cudaSuccess) {
err = "prefill: the draft concat failed";
return false;
}
proj(cat, cat16, t_eh, w_eh, cur, nb, Nn, 2 * Nn);
// x = rms_norm(cur) * attn_norm; K and V into the drafter's cache, as the prompt path's attention layers
rms_rows(cur, w_an, nb, Nn, Nn, eps, m.cs);
proj(cur, cur16, t_k, w_k, Kc, nb, KV, Nn);
proj(cur, cur16, t_v, w_v, Vc, nb, KV, Nn);
rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, eps, m.cs);
rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs);
if (st.kv_rot) {
strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs);
strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs);
}
if (st.kv_q4) {
strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host);
} else {
kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, &st.host);
}
}
if (cudaStreamSynchronize(m.cs) != cudaSuccess) {
err = std::string("prefill: the draft layer's K/V: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
mtp.ms_prefill += ms_since(t0);
if (timing)
std::fprintf(stderr, "strata draft kv (qwen35moe): %lld cells from %lld (first needed %lld), batch %lld: drafter idle "
"%.1f ms, the batches %.1f ms, all %.1f ms\n", (long long) n, (long long) cell0, (long long) (cell0 + r0),
(long long) B, ms_idle, ms_since(tl0), ms_since(t0));
return true;
}
const float* w_ne = mtp.tensor_f32("pre_fc_norm_embedding.weight");
const void* w_fe = mtp.tensor_q8("fc_embedding.weight");
const float* w_nh = mtp.tensor_f32("pre_fc_norm_hidden.weight");
@@ -1219,6 +993,9 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
if (r0 >= n) return true;
// per row: emb/e2 (N), en16 (N half), hn/h2/Rm/gated (HCN), hn16/xn16 (HCN half), lo (LR) + lo16, grs, mixed (N) +
// mixed_h, K and V (KV each), the token id
// E-9: the drafter's Q8_0 matrices through Q8_1 x Q8_0 MMQ - its own pass's integer dot products (mmvq), so
// its K/V stay close to what the drafter computes itself; STRATA_MTP_BATCH_F16=1: FP16 GEMMs (the A/B)
static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v && v[0] == '1'; }();
const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV); // #420
const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 +
(q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 4 * g.hc : 0);
@@ -1249,12 +1026,15 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
int32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr;
int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr;
if ((uint64_t) (q - m.region) > m.region_bytes) return false;
static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes
if (timing) cudaStreamSynchronize(m.cs);
const auto ti0 = Clock::now();
if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V
const double ms_idle = ms_since(ti0);
const auto tl0 = Clock::now();
const strata::kernels::QsaShapes s = shapes_of(g);
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
std::vector<int32_t> tk((size_t) B);
if (q8) {
if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
@@ -1422,7 +1202,6 @@ bool Prefill::bind_stage_helper(int64_t T) {
h.grp_gu == nullptr || h.grp_d == nullptr || !h.mmq_ctx || h.ring <= STAGE)
return false;
PeerPrefill& P = *m.help_pp;
const int64_t K = m.geo.k, N = m.geo.n;
P.T_max = T;
P.cap_rows = T * K;
P.G = T; // one expert never has more rows than the chunk has tokens
@@ -1475,8 +1254,6 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e
if (!peer->p2p()) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; }
if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; }
auto pp = std::make_unique<PeerPrefill>();
const Geom& G = m.geo;
const int64_t K = G.k, N = G.n, NE = G.ne, FF = G.ff, FF2 = G.ff2;
pp->peer = peer;
pp->T_max = m.T_max;
pp->cap_rows = std::max<int64_t>(1, std::min<int64_t>(cap_rows, m.T_max * K));
@@ -1514,9 +1291,9 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e
pp->G = m.T_max; // one expert never has more rows than the chunk has tokens
const int64_t Gr = pp->G;
pp->Xq_g = take(mmq::q8_bytes(Gr, N));
pp->Hq_g = take(mmq::q8_bytes(Gr, FF));
pp->GU_g = (float*) take((size_t) Gr * FF2 * 4);
pp->H_g = (float*) take((size_t) Gr * FF * 4);
pp->Hq_g = take(mmq::q8_bytes(Gr, 640));
pp->GU_g = (float*) take((size_t) Gr * 1280 * 4);
pp->H_g = (float*) take((size_t) Gr * 640 * 4);
pp->Dm_b[0] = (float*) take((size_t) Gr * N * 4);
pp->Dm_b[1] = (float*) take((size_t) Gr * N * 4);
for (int b = 0; b < 2 && ok; ++b) ok = cudaEventCreateWithFlags(&pp->ev_dm[b], cudaEventDisableTiming) == cudaSuccess;
@@ -1540,9 +1317,9 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e
}
} else {
pp->Xq = take(mmq::q8_bytes(R, N));
pp->Hq = take(mmq::q8_bytes(R, FF));
pp->GU = (float*) take((size_t) R * FF2 * 4);
pp->H = (float*) take((size_t) R * FF * 4);
pp->Hq = take(mmq::q8_bytes(R, 640));
pp->GU = (float*) take((size_t) R * 1280 * 4);
pp->H = (float*) take((size_t) R * 640 * 4);
pp->Dm = (float*) take((size_t) R * N * 4);
}
const int64_t Rt = pp->cap_rows;
@@ -1581,9 +1358,6 @@ double Prefill::pinned_share() { return g_pinned_share; }
uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) {
// the same allocation sequence as `init`, counted
const size_t T = (size_t) chunk;
const Geom G = Geom::of(g);
const int64_t N = G.n, HC = G.hc, D = G.d, LR = G.lr, K = G.k;
const bool gr = HC > 1;
bool ok = true;
Alloc o;
o.count_only = true;
@@ -1595,25 +1369,26 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session
// `grs`. Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the
// prompt path was told it had less room than it did. Safe - the direction is over-estimating, and `take`
// still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller.
// The plain block (hc 1) has none of the hyper-connection's buffers.
if (ring_bytes_on() || !gr) {
if (ring_bytes_on()) {
f(T * N); f(T * D);
if (gr && gr_unfused()) f(T * D);
if (gr) f(T * HC);
if (gr_unfused()) f(T * D);
f(T * HC);
} else { // STRATA_RING_BYTES=0: 0.1.39's count
f(T * N); f(T * D); f(T * D);
}
if (gr) { o.take<uint16_t>(T * D, ok); f(T * LR); o.take<uint16_t>(T * LR, ok); f(T * D); f(T * HC); }
f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);
if (gr && bf16x2_hc()) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }
o.take<uint16_t>(T * D, ok); f(T * LR); o.take<uint16_t>(T * LR, ok);
f(T * D); f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);
if (bf16x2_hc()) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }
if (bf16x2()) o.take<uint16_t>(T * N, ok);
o.take<int32_t>(T * strata::kernels::kStepCount, ok);
const strata::kernels::QsaShapes s = shapes_of(g);
const int64_t cap = selection_cap(ss, s);
const int64_t max_blocks = primary_cells(ss) / s.idx_block + 2;
o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T, G), qsa_set_bytes(T, cap, max_blocks, 256, 32, s, G),
moe_set_bytes(T, G, fused_layout(T, true))}), ok);
for (int i = 0; i < DQ; ++i) { o.take<uint16_t>((size_t) (G.ff2 * N), ok); o.take<uint16_t>((size_t) (N * G.ff), ok); }
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s),
moe_set_bytes(T, g.n_expert, fused_layout(T, true))}), ok);
for (int i = 0; i < DQ; ++i) { o.take<uint16_t>(1280 * 2560, ok); o.take<uint16_t>(2560 * 640, ok); }
if (mmq_plan().any) {
const MmqPlan& mp = mmq_plan();
o.take<int32_t>(T * K, ok);
@@ -1622,10 +1397,8 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session
o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
}
for (int i = 0; i < ring_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
if (g.has_ple) {
f(T * N);
f((size_t) strata::kernels::NG_HC_DIM);
}
f(T * N);
f((size_t) strata::kernels::NG_HC_DIM);
strata::kernels::KvHostPools stage;
take_stage(o, ss, s, stage, ok);
return o.used + (8u << 20); // alignment slack
@@ -1775,16 +1548,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const core::OnDevice on_device(m.device);
const core::ModelGeometry& g = *m.g;
core::SessionState& ss = *m.ss;
const Geom& G = m.geo;
const int64_t N = G.n, HC = G.hc, D = G.d, K = G.k, HV = G.hv;
const bool plain = HC == 1; // the plain residual block (Qwen3.6): no hyper-connection read or write
const GdnGeom gdn_geom = G.gdn();
const auto t_start = Clock::now();
const int64_t LB = stage_lb_, LE = stage_le_;
// The direct successor's future lives on the Prefill object. Intermediate
// stages therefore do not drain the complete remaining GPU chain here.
double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share
const strata::kernels::QsaShapes s = shapes_of(g);
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
(uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
@@ -1905,10 +1676,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return false;
}
}
if (hand_in_ == nullptr) {
if (plain) cudaMemcpyAsync(m.R, m.emb, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, m.cs); // R = emb
else gr_broadcast(m.emb, m.R, T, m.cs);
}
if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs);
// ---- the PLE rows of the whole chunk, one batched SSD request on a thread (see ple_gather). A later chunk's
// were read ahead during the previous chunk; the first chunk's are read beside layer 0 - they are needed from
// layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt)
@@ -1948,7 +1716,6 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
};
for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; }
// ---- the QSA step records of every position in the chunk
// (dense attention: qsa_step_fill's width is n_kv itself, every cell up to the query's own)
for (int64_t t = 0; t < T; ++t) strata::kernels::qsa_step_fill(m.steps_host.data() + t * strata::kernels::kStepCount, p0 + t, s);
cudaMemcpyAsync(m.steps_dev, m.steps_host.data(), (size_t) T * strata::kernels::kStepCount * 4,
cudaMemcpyHostToDevice, m.cs);
@@ -2206,20 +1973,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
stats_.ms_ple += ms_since(tp);
}
if (on_seam) { // a test's view of the layer's input rows (and its chance to replace them: teacher forcing)
if (!on_seam("l_in", l, m.R, T, D, p0, err)) return false;
}
for (int half = 0; half < 2; ++half) {
if (plain) {
// ---- the plain block's read: x = rms_norm(R, attn_norm | post_attention_norm), its two images
// (the oracle's attn_norm-N / attn_post_norm-N)
const core::WeightRef* wn = need(v, half == 0 ? "attn_norm.weight" : "post_attention_norm.weight", err);
if (!wn) return false;
if (wn->kind != core::WeightKind::F32 || !wn->data) { err = "prefill: " + v.name(half == 0 ? "attn_norm.weight" : "post_attention_norm.weight") + " is not a resident F32 tensor"; return false; }
pt.mark(kPfHc, cs);
rms_norm_images(m.R, (const float*) wn->data, EPS, m.mixed, m.mixed_bf, m.mixed_h, T, N, m.cs, m.mixed_bf_lo);
if (on_seam && !on_seam(half == 0 ? "attn_norm" : "attn_post_norm", l, m.mixed, T, N, p0, err)) return false;
} else {
// ---- the hyper-connection read of this half
const char* pre = half == 0 ? "hc_attn_" : "hc_ffn_";
const std::string sn = std::string(pre) + "norm.weight", sd = std::string(pre) + "down.weight",
@@ -2238,7 +1992,6 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);
else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h,
m.mixed_bf_lo);
}
if (half == 0 && !core::is_qsa_layer(g, l)) {
// ======================= GDN =======================
@@ -2256,39 +2009,32 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines
gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, gdn_geom, m.cs);
gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, gdn_geom, m.cs);
gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs);
gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs);
pt.mark(kPfGdnRec, cs);
gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, gdn_geom, m.cs);
gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs);
pt.mark(kPfGdnOut, cs);
if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false;
++gdn_index;
} else if (half == 0) {
// ======================= QSA =======================
const core::QsaState& st = ss.qsa_states[qsa_index];
// the indexer's four tensors exist on Flash-Next only; Qwen3.6's attention is dense (no indexer)
const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err),
*wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err),
*wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err);
if (!wq || !wk || !wv || !wo || !wqn || !wkn) return false;
const core::WeightRef *wik = nullptr, *wiq = nullptr, *wiqn = nullptr, *wikn = nullptr;
if (G.indexer) {
wik = need(v, "indexer.k_proj.weight", err);
wiq = need(v, "indexer.q_proj.weight", err);
wiqn = need(v, "indexer.q_norm.weight", err);
wikn = need(v, "indexer.k_norm.weight", err);
if (!wik || !wiq || !wiqn || !wikn) return false;
}
*wik = need(v, "indexer.k_proj.weight", err),
*wiq = need(v, "indexer.q_proj.weight", err),
*wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
*wiqn = need(v, "indexer.q_norm.weight", err),
*wikn = need(v, "indexer.k_norm.weight", err);
if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
pt.mark(kPfQsa, cs);
if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
if (G.indexer) {
if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
}
rms_rows(m.Kc, (const float*) wkn->data, T * G.nkv, 256, 256, EPS, m.cs);
rope(m.Kc, T, G.nkv, 256, G.kvw, p0, strata::kernels::rope_scaling(), m.cs);
if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs);
rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs);
// KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the
// chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks
const bool staged = st.kv_mode == 1;
@@ -2337,18 +2083,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
(p0 + T + s.page_size - 1) / s.page_size, s, m.cs);
}
if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l);
split_q(m.Qf, m.q, T, G.nh, m.cs);
rms_rows(m.q, (const float*) wqn->data, T * G.nh, 256, 256, EPS, m.cs);
rope(m.q, T, G.nh, 256, G.av, p0, strata::kernels::rope_scaling(), m.cs);
if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * G.nh, m.cs);
// dense attention (no indexer): every cell up to the query's own - the width in the step records,
// a null ids as the identity selection (the attention branch's kernels, G templated at 2 / 8 / 12
// query heads per KV head; any other ratio is refused by name before a launch)
if (!G.indexer) {
char why[256] = {0};
if (strata::kernels::qsa_attn_group(s, why, sizeof why) == 0) { err = std::string("prefill: ") + why; return false; }
}
if (G.indexer) {
split_q(m.Qf, m.q, T, m.cs);
rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs);
rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs);
if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs);
rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs);
rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs);
// the indexer appends, token by token; then scores + selection for many queries at once:
@@ -2473,7 +2211,6 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
}
}
} // G.indexer
const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table)
: core::qsa_attn_pools(st);
pt.mark(kPfQsaAttn, cs);
@@ -2486,13 +2223,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
m.attn, T, m.cs))
for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) {
const int64_t nb = std::min(m.attn_batch, T - t0);
strata::kernels::qsa_decode_attn_batch(m.q + t0 * G.av, pools, m.sel_ids ? m.sel_ids + t0 * m.cap : nullptr,
strata::kernels::qsa_decode_attn_batch(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap,
m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,
s, m.attn_scratch, m.attn + t0 * G.av, nb, m.cs);
s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);
}
if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * G.nh, m.cs);
if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);
pt.mark(kPfQsa, cs);
gate_attn(m.attn, m.Qf, m.attn_h, T, G.nh, m.cs);
gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs);
if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false;
++qsa_index;
} else {
@@ -2505,12 +2242,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
pt.mark(kPfRouter, cs);
if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false;
route(m.logits, m.ids, m.w, T, m.g->n_expert, K, m.cs);
if (on_seam && !on_seam("ffn_moe_topk", l, (float*) m.ids, T, K, p0, err)) return false; // int32 ids as floats
route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);
// the shared expert and its scalar gate
if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;
swiglu_pair(m.sgate, m.sup, m.sh_h, T, G.ffs, m.cs);
swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs);
if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false;
if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
@@ -2576,8 +2312,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
pt.mark(kPfGemmGU, cs);
if (fused_nat) {
const auto& f = lay.fmt[(size_t) l];
const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off,
f.n_embd, f.n_ff};
const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off};
fused::experts_native(b, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H,
m.Dm, m.cs);
} else {
@@ -2673,8 +2408,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last:
if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most time
n_order = order.size();
const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, G.ff2, N) : 0;
const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, G.ff) : 0;
const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;
const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;
pt.mark(kPfGather, cs);
if (use_mmq) {
// step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
@@ -2797,16 +2532,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps);
mmq::quantize(P.mixed, P.src + r0, P.Xq_g, mmq_gt, N, N, nr, ps);
mmq::Product gu;
gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident;
gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = G.ff2;
gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = 1280;
P.run_ctx->run(gu, ps);
mmq::swiglu(P.GU_g, P.H_g, nr, G.ff, !lay.native, ps);
mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, G.ff, G.ff, nr, ps);
mmq::swiglu(P.GU_g, P.H_g, nr, 640, !lay.native, ps);
mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, 640, 640, nr, ps);
const int b = (int) (g2 & 1);
if (P.dm_live[b]) cudaStreamWaitEvent(ps, P.ev_dm[b], 0); // its last rows have left
mmq::Product dn;
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; dn.expert_bytes = mmq_db;
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
dn.n = ngx; dn.xq = P.Hq_g; dn.bounds = rel;
dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm_b[b];
dn.ld_dst = N;
@@ -2858,14 +2593,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
cudaMemsetAsync(P.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, ps);
cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps);
mmq::Product gu;
gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident;
gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = G.ff2;
gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = 1280;
P.run_ctx->run(gu, ps);
mmq::swiglu(P.GU + r0 * G.ff2, P.H + r0 * G.ff, nr, G.ff, !lay.native, ps);
mmq::quantize(P.H + r0 * G.ff, nullptr, P.Hq, mmq_dt, G.ff, G.ff, nr, ps);
mmq::swiglu(P.GU + r0 * 1280, P.H + r0 * 640, nr, 640, !lay.native, ps);
mmq::quantize(P.H + r0 * 640, nullptr, P.Hq, mmq_dt, 640, 640, nr, ps);
mmq::Product dn;
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; dn.expert_bytes = mmq_db;
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
dn.n = ngx; dn.xq = P.Hq; dn.bounds = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);
dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm + r0 * N;
dn.ld_dst = N;
@@ -3026,15 +2761,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs);
cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs);
mmq::Product gu;
gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
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 = G.ff2;
gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
m.mmq_ctx->run(gu, m.cs);
mmq::swiglu(m.GU + r0 * G.ff2, m.H + r0 * G.ff, nr, G.ff, !lay.native, m.cs);
mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
pt.mark(kPfGemmD, cs);
mmq::quantize(m.H + r0 * G.ff, nullptr, m.Hq, mmq_dt, G.ff, G.ff, nr, m.cs);
mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs);
mmq::Product dn;
dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; dn.expert_bytes = mmq_db;
dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
dn.ld_dst = N;
@@ -3054,10 +2789,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (slot >= 0) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
pt.mark(kPfGemmGU, cs);
m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * G.ff2, ne, G.ff2, N);
swiglu_interleaved(m.GU + o0 * G.ff2, m.Hh + o0 * G.ff, ne, G.ff, m.cs);
m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N);
swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs);
pt.mark(kPfGemmD, cs);
m.gemm.f16(m.Hh + o0 * G.ff, m.dq_d[q], m.Dm + o0 * N, ne, N, G.ff);
m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640);
return true;
};
if (!stream_all) {
@@ -3125,7 +2860,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (!m.pp->p2p)
copy_f32_wide(m.Dm + (size_t) m.pp->back_at * N, m.pp->host_rows, m.pp->back_rows * N, m.cs);
}
moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, N, K, m.cs);
moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);
// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values
if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {
cudaStreamSynchronize(m.cs);
@@ -3137,9 +2872,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return c;
};
// (fused: GU and H hold the grouping tables and int8 rows, not floats)
const int64_t bgu = fused_l ? 0 : bad(m.GU, T * K * G.ff2), bdm = bad(m.Dm, T * K * N),
const int64_t bgu = fused_l ? 0 : bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N),
bbo = bad(m.bo, T * N);
const int64_t bh = m.H && !fused_l ? bad(m.H, T * K * G.ff) : -1;
const int64_t bh = m.H && !fused_l ? bad(m.H, T * K * 640) : -1;
static int64_t reported = -1;
if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) {
reported = stats_.chunks;
@@ -3150,14 +2885,6 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
}
}
if (on_seam) { // the mixer's output before the residual (the oracle's linear_attn_out / attn_output / ffn_out)
const char* seam = half == 1 ? "ffn_out" : core::is_qsa_layer(g, l) ? "attn_output" : "linear_attn_out";
if (!on_seam(seam, l, m.bo, T, N, p0, err)) return false;
}
if (plain) {
// ---- the plain block's write: R += out (the oracle's attn_residual-N / l_out-N)
residual_add(m.R, m.bo, T * N, m.cs);
} else {
// ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else
// touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a
// control vector)
@@ -3177,10 +2904,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
} else {
gr_write(m.R, m.bo, m.inj, HC, T, m.cs);
}
}
if (half == 1 && strata::kernels::cvec().covers(l)) // --control-vector-scaled
strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
if (on_seam && half == 1 && !on_seam("l_out", l, m.R, T, D, p0, err)) return false;
}
}
if (!ple_land()) return false; // a stage that ends before layer 1: the rows land anyway, the next gather starts
+53 -598
View File
File diff suppressed because it is too large. Load diff
@@ -1,44 +0,0 @@
// #369: per-layer admission on a sized cache (open_sized, every native pack) - each layer admits into its own slot
// range, as on the uniform cache, so no two layers write the same slot. Needs a CUDA device (exits 77 without one).
#include "strata/core/expert_cache.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <string>
#include <vector>
int main() {
int n = 0;
if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) {
std::puts("no CUDA device: skipped");
return 77;
}
std::string err;
for (int sized = 0; sized < 2; ++sized) {
strata::core::ExpertCache cache;
const bool ok = sized ? cache.open_sized(std::vector<int64_t>(6, 1024), 3, 4, err)
: cache.open(6, 3, 4, 1024, err);
if (!ok) {
std::fprintf(stderr, "open: %s\n", err.c_str());
return 1;
}
cache.set_per_layer_admission(true);
for (int64_t layer = 0; layer < 3; ++layer) {
int64_t lo = 0, hi = 0;
cache.layer_slot_range(layer, lo, hi);
for (int64_t e = 0; e < 3; ++e) {
const int32_t slot = cache.admit(layer, e);
const bool want_room = lo + e < hi;
if (want_room ? slot != (int32_t) (lo + e) : slot != strata::core::kNotResident) {
std::fprintf(stderr, "%s cache: layer %lld expert %lld got slot %d (range %lld..%lld)\n",
sized ? "sized" : "uniform", (long long) layer, (long long) e, slot, (long long) lo,
(long long) hi - 1);
return 1;
}
}
}
}
std::puts("expert cache per-layer admission: uniform and sized caches passed");
return 0;
}
@@ -1,99 +0,0 @@
// #533: the segmented expert cache (--vram-elastic). A shrink gives the last segments' VRAM back to the driver and
// keeps every slot left exactly as it was (same address, same bytes); a grow maps them again at the same addresses.
// Uniform and sized slots. Needs a CUDA device with virtual memory management (exits 77 without one).
#include "strata/core/expert_cache.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <string>
#include <vector>
namespace {
int fail(const char* what, const std::string& err = "") {
std::fprintf(stderr, "FAIL %s %s\n", what, err.c_str());
return 1;
}
size_t free_vram() {
size_t f = 0, t = 0;
cudaMemGetInfo(&f, &t);
return f;
}
// slot i holds the byte (i * 7 + 1) everywhere
bool fill(strata::core::ExpertCache& c, int64_t from, int64_t to, int64_t blob) {
std::vector<uint8_t> b((size_t) blob);
for (int64_t i = from; i < to; ++i) {
std::fill(b.begin(), b.end(), (uint8_t) (i * 7 + 1));
if (cudaMemcpy(c.device_slot((int32_t) i), b.data(), (size_t) blob, cudaMemcpyHostToDevice) != cudaSuccess)
return false;
}
return true;
}
bool check(const strata::core::ExpertCache& c, int64_t to, int64_t blob) {
std::vector<uint8_t> b((size_t) blob);
for (int64_t i = 0; i < to; ++i) {
if (cudaMemcpy(b.data(), c.device_slot((int32_t) i), (size_t) blob, cudaMemcpyDeviceToHost) != cudaSuccess)
return false;
for (const uint8_t x : b)
if (x != (uint8_t) (i * 7 + 1)) return false;
}
return true;
}
} // namespace
int main() {
int n = 0;
if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) {
std::puts("no CUDA device: skipped");
return 77;
}
constexpr int64_t kBlob = 1 << 20, kSlots = 96, kSeg = 8ll << 20;
for (int sized = 0; sized < 2; ++sized) {
strata::core::ExpertCache c;
c.set_segment_bytes(kSeg);
std::string err;
const bool ok = sized ? c.open_sized(std::vector<int64_t>(kSlots, kBlob), 4, 64, err)
: c.open(kSlots, 4, 64, kBlob, err);
if (!ok) {
if (err.find("virtual memory management") != std::string::npos) {
std::printf("%s: skipped\n", err.c_str());
return 77;
}
return fail("open", err);
}
if (!c.segmented() || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) return fail("open sizes");
uint8_t* const first = c.device_slot(0);
if (!fill(c, 0, kSlots, kBlob)) return fail("fill");
const size_t before = free_vram();
// keep 30 MiB: rounded up to whole 8 MiB segments = 32 MiB = 32 slots
if (!c.shrink(30ll << 20, err)) return fail("shrink", err);
if (c.slots() != 32 || c.mapped_bytes() != 32ll << 20 || c.bytes() != 32ll << 20)
return fail("shrunk sizes");
if (c.full_slots() != kSlots || c.full_bytes() != kSlots * kBlob) return fail("full sizes");
const size_t freed = free_vram() - before;
if (freed + (8u << 20) < (size_t) (64ll << 20)) { // ~64 MiB back to the driver (WDDM rounds a little)
std::fprintf(stderr, "freed %zu bytes\n", freed);
return fail("VRAM not given back");
}
if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the shrink");
// grow to 70 MiB: whole segments only, 64 MiB = 64 slots
if (!c.grow(70ll << 20, err) || c.slots() != 64) return fail("grow part", err);
if (!c.grow(1ll << 40, err) || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob)
return fail("grow all", err);
if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the grow");
if (!fill(c, 32, kSlots, kBlob) || !check(c, kSlots, kBlob)) return fail("the grown slots");
if (c.slots_within(0) != 0 || c.slots_within(kBlob * 3 + 5) != 3 || c.bytes_of(5) != 5 * kBlob)
return fail("slots_within / bytes_of");
c.close();
if (c.valid() || c.slots() != 0) return fail("close");
}
// the default (no segment size): one allocation, shrink refused
strata::core::ExpertCache d;
std::string err;
if (!d.open(8, 2, 4, kBlob, err) || d.segmented() || d.shrink(0, err)) return fail("unsegmented", err);
std::puts("expert cache segments: shrink gives VRAM back and keeps the slots, grow maps them again");
return 0;
}
-412
View File
@@ -1,412 +0,0 @@
// tests/core/expert_layout_test.cpp - native_experts.txt (v2/v3/v4) and the expert arena filled from GGUF shards,
// without a model or a GPU.
//
// 1. Copies of the real packs' native_experts.txt (tests/data/native_experts: Q2_0, IQ2_XS, IQ3_XXS, IQ3_S,
// Coder IQ1_M, Swift IQ2_XS; v2 and v3 headers) parse to the layout the pre-v4 reader produced: the test
// parses each line again with that reader's rules (one shard name for all three roles) and compares every
// field, and the totals with the header's.
// 2. The v4 shard column `gate,up,down` (an empty field = the --native shard); v5, four names, two names and a
// trailing column are refused.
// 3. check_experts_gguf + load_experts_gguf on a synthetic arena at the real dimensions 2560/640 with Unsloth's
// format pairs (Q4_K/Q5_1, Q5_K/Q8_0): layer 1's gate/up in another file than its down. Every byte of the
// arena is compared with the source tensors. Then the refusals: an offset that is not the tensor's, a
// truncated file, a role named in the wrong file, a type or a shape the pack does not say, a missing file.
#include "gguf_fixture.hpp"
#include "strata/core/expert_source.hpp"
#include "strata/core/pinned.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
#include <algorithm>
#include <chrono>
#include <cstring>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
namespace fs = std::filesystem;
using strata::kernels::cpu::ExpertLayout;
namespace {
int g_fail = 0;
void check(bool ok, const std::string& what) {
std::printf(" %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL");
if (!ok) ++g_fail;
}
struct TempDir {
fs::path path;
TempDir() {
path = fs::temp_directory_path() /
("strata-expert-layout-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
fs::create_directories(path);
}
~TempDir() {
std::error_code ignored;
fs::remove_all(path, ignored);
}
};
void write_text(const fs::path& p, const std::string& s) { std::ofstream(p, std::ios::binary) << s; }
bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, int64_t n_embd, int64_t n_ff, std::string& err) {
err.clear();
return strata::kernels::cpu::expert_layout_load(dir.string(), n_layers, n_expert, n_embd, n_ff, err);
}
bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, std::string& err) {
return load(dir, n_layers, n_expert, 2560, 640, err);
}
// ---- 1. the real packs' files
void real_packs(const fs::path& data) {
for (const char* pack : {"q2_0", "iq2_xs", "iq3_xxs", "iq3_s", "coder-iq1_m", "swift-iq2_xs"}) {
TempDir d;
fs::copy_file(data / (std::string(pack) + ".txt"), d.path / "native_experts.txt");
std::string err;
const bool ok = load(d.path, 48, 512, err);
check(ok, std::string(pack) + ": loads" + (ok ? "" : ": " + err));
if (!ok) continue;
const ExpertLayout& L = strata::kernels::cpu::expert_layout();
// the pre-v4 reader's rules, applied to the same text
std::ifstream in(d.path / "native_experts.txt");
std::string line;
long long hdr_n = -1, hdr_total = -1;
bool same = L.native && L.n_layers == 48 && L.gguf_off.size() == 3 * 48;
uint64_t max_blob = 0;
while (std::getline(in, line)) {
if (line.empty()) continue;
if (line[0] == '#') {
if (line.find("(n_expert ") == std::string::npos) continue;
std::istringstream h(line.substr(line.find("(n_expert ") + 10));
char comma = 0;
std::string word;
h >> hdr_n >> comma >> word >> hdr_total; // "(n_expert N, total T; ..."
continue;
}
std::istringstream ss(line);
long long l = 0, gt = 0, dt = 0;
unsigned long long off = 0, blob = 0, o[3] = {0, 0, 0};
std::string file;
ss >> l >> gt >> dt >> off >> blob >> o[0] >> o[1] >> o[2];
ss >> file;
same = same && L.fmt[(size_t) l].gu_type == gt && L.fmt[(size_t) l].d_type == dt &&
L.offset[(size_t) l] == off && L.bytes[(size_t) l] == blob;
for (int r = 0; r < 3; ++r) {
same = same && L.gguf_off[(size_t) (3 * l + r)] == o[r];
const std::string got = L.gguf_file.empty() ? std::string() : L.gguf_file[(size_t) (3 * l + r)];
same = same && got == file;
}
if (blob > max_blob) max_blob = blob;
}
same = same && L.n_expert == hdr_n && (long long) L.total == hdr_total && L.max_blob == max_blob;
check(same, std::string(pack) + ": every field as the pre-v4 reader, totals as the header (v" +
std::to_string(L.version) + ", n_expert " + std::to_string(L.n_expert) + ")");
}
}
// ---- 1b. Qwen3.6-35B-A3B's two files (tools/iq_pack.py --layout-only over the real UD-IQ3_XXS and UD-Q4_K_XL files,
// 2026-10-11): 40 layers x 256 experts at 2048 x 512. Loaded with the model's geometry every layer's NativeFmt makes
// the pack's blob; loaded with Flash-Next's 2560 x 640 (what expert_layout_load passed until the Qwen3.6 port's
// step 2, geometry-inventory.md row 108) the same files are refused by their numbers. The per-layer types are
// the census of docs/QWEN36-35B-A3B.md section 1: IQ2_S gate/up with IQ3_XXS down on 37 layers and IQ4_XS on
// layers 34, 38, 39; Q4_K/Q5_K on 37 layers, Q4_K/Q6_K on 34 and 38, Q5_K/Q6_K on 39 (the largest blob).
void qwen36(const fs::path& data) {
struct Case { const char* file; int gu, d, d_odd; int64_t blob, blob_odd, blob_39; uint64_t total; };
const Case cases[] = {
{"qwen36-iq3_xxs.txt", 22, 18, 23, 1073152, 1228800, 1228800, 11108614144ull},
{"qwen36-q4_k_xl.txt", 12, 13, 14, 1900544, 2039808, 2301952, 19635634176ull},
};
for (const Case& c : cases) {
TempDir d;
fs::copy_file(data / c.file, d.path / "native_experts.txt");
std::string err;
const bool ok = load(d.path, 40, 256, 2048, 512, err);
check(ok, std::string(c.file) + ": loads at the model's 40 x 256 x 2048 x 512" + (ok ? "" : ": " + err));
if (ok) {
const ExpertLayout& L = strata::kernels::cpu::expert_layout();
bool types = L.native && L.n_layers == 40 && L.n_expert == 256 && L.total == c.total && L.max_blob == (uint64_t) c.blob_39;
for (int64_t l = 0; l < 40 && types; ++l) {
const auto& f = L.fmt[(size_t) l];
const bool odd = l == 34 || l == 38 || l == 39;
types = f.n_embd == 2048 && f.n_ff == 512 && f.bytes == L.bytes[(size_t) l] &&
f.gu_type == (l == 39 && c.gu == 12 ? 13 : c.gu) && f.d_type == (odd ? c.d_odd : c.d) &&
(int64_t) f.bytes == (l == 39 ? c.blob_39 : odd ? c.blob_odd : c.blob);
}
check(types, std::string(c.file) + ": per-layer formats and blobs (down " + std::to_string(c.d_odd) +
" on 34/38/39, " + std::to_string(c.blob_39) + " B at layer 39, total " +
std::to_string(c.total) + " B)");
const auto& f0 = L.fmt[0];
check(f0.up_off == f0.gu_row * 512 && f0.down_off == 2 * f0.up_off && f0.bytes == f0.down_off + f0.d_row * 2048,
std::string(c.file) + ": blob = gate rows | up rows | down rows at 512 and 2048");
}
// n_ff 640 is not whole 256-value blocks for IQ2_S / Q4_K rows, so native_fmt refuses before the blob is
// compared; a geometry that IS whole blocks (2048 x 512 for a 2560 x 640 pack) would reach the blob message.
const bool refused = !load(d.path, 40, 256, 2560, 640, err);
check(refused && (err.find("not whole blocks") != std::string::npos ||
(err.find("layer 0 blob is") != std::string::npos && err.find("2560 x n_ff 640") != std::string::npos)),
std::string(c.file) + ": at Flash-Next's 2560 x 640 refused: " + err.substr(0, 60));
}
// a pack with no native_experts.txt is the canonical Q2_0 form, which bakes 2560 x 640: refused for a 2048 x 512 model
TempDir d;
std::string err;
check(!load(d.path, 40, 256, 2048, 512, err) && err.find("canonical Q2_0") != std::string::npos,
"no native_experts.txt (canonical Q2_0 pack) refused for a 2048 x 512 model: " + err.substr(0, 50));
check(load(d.path, 48, 512, 2560, 640, err), "no native_experts.txt at the canonical 2560 x 640 still loads");
}
// ---- 2. the v4 column and the refusals
std::string manifest(int version, const std::string& col1, int64_t blob, int n_expert = 2) {
std::string s = "# strata native experts v" + std::to_string(version) +
": layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] "
"(n_expert " + std::to_string(n_expert) + ", total " + std::to_string(2 * blob * n_expert) + ")\n";
s += "0 12 7 0 " + std::to_string(blob) + " 100 200 300\n";
s += "1 12 7 " + std::to_string(blob * n_expert) + " " + std::to_string(blob) + " 400 500 600" +
(col1.empty() ? "" : " " + col1) + "\n";
return s;
}
void columns() {
strata::kernels::cpu::NativeFmt f;
std::string err;
if (!strata::kernels::cpu::native_fmt(12, 7, 2560, 640, f, err)) {
check(false, "Q4_K/Q5_1 native format: " + err);
return;
}
const int64_t blob = (int64_t) f.bytes;
TempDir d;
write_text(d.path / "native_experts.txt", manifest(4, "B.gguf,B.gguf,", blob));
bool ok = load(d.path, 2, 512, err);
const ExpertLayout& L = strata::kernels::cpu::expert_layout();
check(ok && L.version == 4 && L.gguf_file.size() == 6 && L.gguf_file[0].empty() && L.gguf_file[2].empty() &&
L.gguf_file[3] == "B.gguf" && L.gguf_file[4] == "B.gguf" && L.gguf_file[5].empty() &&
L.gguf_off[5] == 600,
"v4: `B.gguf,B.gguf,` = gate and up in B.gguf, down in the --native shard" + (ok ? "" : ": " + err));
write_text(d.path / "native_experts.txt", manifest(3, "A.gguf", blob));
ok = load(d.path, 2, 512, err);
check(ok && L.gguf_file[3] == "A.gguf" && L.gguf_file[4] == "A.gguf" && L.gguf_file[5] == "A.gguf",
"v3: one name covers the three roles");
write_text(d.path / "native_experts.txt", manifest(5, "", blob));
ok = load(d.path, 2, 512, err);
check(!ok && err.find("v5") != std::string::npos, "v5 is refused (\"" + err.substr(0, 40) + "...\")");
write_text(d.path / "native_experts.txt", manifest(4, "a,b,c,d", blob));
check(!load(d.path, 2, 512, err) && err.find("gate,up,down") != std::string::npos, "four names are refused");
write_text(d.path / "native_experts.txt", manifest(4, "a,b", blob));
check(!load(d.path, 2, 512, err), "two names are refused");
write_text(d.path / "native_experts.txt", manifest(4, "a extra", blob));
check(!load(d.path, 2, 512, err), "a column after the shard column is refused");
}
// ---- 3. the arena from synthetic shards
void arena() {
using fixture::Tensor;
constexpr int64_t H = 2560, FF = 640, NE = 2;
const uint32_t Q4_K = 12, Q5_1 = 7, Q5_K = 13, Q8_0 = 8, Q3_K = 11, IQ3_S = 21;
strata::kernels::cpu::NativeFmt f0, f1;
std::string err;
if (!strata::kernels::cpu::native_fmt(Q4_K, Q5_1, H, FF, f0, err) ||
!strata::kernels::cpu::native_fmt(Q5_K, Q8_0, H, FF, f1, err)) {
check(false, "Q4_K/Q5_1 and Q5_K/Q8_0 native formats: " + err);
return;
}
TempDir d;
const fs::path A = d.path / "M-00002-of-00003.gguf", B = d.path / "M-00003-of-00003.gguf";
// A: layer 0 (all roles) and layer 1's down; B: layer 1's gate and up
const std::vector<Tensor> ta = {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q4_K, 11},
{"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q4_K, 12},
{"blk.0.ffn_down_exps.weight", {FF, H, NE}, Q5_1, 13},
{"blk.1.ffn_down_exps.weight", {FF, H, NE}, Q8_0, 23}};
const std::vector<Tensor> tb = {{"blk.1.ffn_gate_exps.weight", {H, FF, NE}, Q5_K, 21},
{"blk.1.ffn_up_exps.weight", {H, FF, NE}, Q5_K, 22}};
const auto wa = fixture::write(A, {}, ta);
const auto wb = fixture::write(B, {}, tb);
auto at = [](const fixture::Written& w, size_t i) { return std::to_string(w.data_start + w.offsets[i]); };
const uint64_t total = (f0.bytes + f1.bytes) * NE;
auto text = [&](const std::string& down1, const std::string& col1) {
return "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off "
"[shard | gate,up,down] (n_expert 2, total " + std::to_string(total) + ")\n" +
"0 12 7 0 " + std::to_string(f0.bytes) + " " + at(wa, 0) + " " + at(wa, 1) + " " + at(wa, 2) + "\n" +
"1 13 8 " + std::to_string(f0.bytes * NE) + " " + std::to_string(f1.bytes) + " " + at(wb, 0) + " " +
at(wb, 1) + " " + down1 + " " + col1 + "\n";
};
const fs::path pack = d.path / "pack";
fs::create_directories(pack);
write_text(pack / "native_experts.txt", text(at(wa, 3), B.filename().string() + "," + B.filename().string() + ","));
bool ok = load(pack, 2, 512, err);
check(ok, "the v4 manifest of the split layer loads" + (ok ? "" : ": " + err));
if (!ok) return;
const ExpertLayout& L = strata::kernels::cpu::expert_layout();
ok = strata::core::check_experts_gguf(A.string(), L, err);
check(ok, "check_experts_gguf: every span is its tensor" + (ok ? "" : ": " + err));
std::vector<uint8_t> dst((size_t) L.total, 0xEE);
const strata::core::LoadStats st = strata::core::load_experts_gguf(A.string(), dst.data(), L, 3);
check(st.ok && st.bytes == L.total && L.total == total, "load_experts_gguf reads the whole arena (" +
std::to_string(L.total) + " B)");
// every byte: expert e's slice of role r comes from byte e * per[r] of that role's tensor
bool exact = true;
for (int64_t l = 0; l < 2 && exact; ++l) {
const auto& fm = L.fmt[(size_t) l];
const uint64_t per[3] = {fm.up_off, fm.up_off, fm.bytes - fm.down_off};
const uint64_t off[3] = {0, fm.up_off, fm.down_off};
const uint8_t seed[2][3] = {{11, 12, 13}, {21, 22, 23}};
for (int64_t e = 0; e < NE && exact; ++e)
for (int r = 0; r < 3 && exact; ++r) {
const uint8_t* got = dst.data() + L.blob_offset(l, e) + off[r];
for (uint64_t j = 0; j < per[r]; ++j)
if (got[j] != fixture::pattern(seed[l][r], (uint64_t) e * per[r] + j)) { exact = false; break; }
}
}
check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files");
{ // CS-T: the same blobs from FileExpertSource reading the shards in place (no experts.bin in the pack)
strata::core::FileExpertSource fs;
fs.set_gguf(A.string());
std::string e1;
const bool opened = fs.open(pack.string(), 2, NE, e1);
check(opened && fs.gguf_mode(), "FileExpertSource opens the GGUF in place" + (opened ? "" : ": " + e1));
if (opened) {
bool same = true, copies = true, transient = true;
std::vector<uint8_t> buf((size_t) std::max(f0.bytes, f1.bytes));
for (int64_t l = 0; l < 2; ++l)
for (int64_t e = 0; e < NE; ++e) {
fs.begin_layer(l, nullptr, 0);
const uint8_t* b = fs.blob(l, e);
const size_t n = (size_t) L.blob_bytes(l);
same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0;
copies = copies && fs.copy_blob(l, e, buf.data()) &&
std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0;
transient = transient && fs.transient(l, e);
}
check(same && copies && transient, "blob() and copy_blob() equal the loaded arena byte for byte (transient)");
// a blob asked again in the same layer is the same buffer; its bytes hold through two more layers
fs.begin_layer(0, nullptr, 0);
const uint8_t* p = fs.blob(0, 1);
const uint8_t* q = fs.blob(0, 1);
fs.begin_layer(1, nullptr, 0);
(void) fs.blob(1, 0);
(void) fs.blob(1, 1);
fs.begin_layer(0, nullptr, 0);
(void) fs.blob(0, 0);
check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0,
"an assembled blob stays put while it is in use");
check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")");
// prefetch: a layer's experts fetched together on several threads, then the same bytes from blob()
bool pre = true;
for (int round = 0; round < 3; ++round)
for (int64_t l = 0; l < 2; ++l) {
fs.begin_layer(l, nullptr, 0);
fs.begin_layer(l == 0 ? 1 : 0, nullptr, 0); // age the buffers so the prefetch refills them
fs.begin_layer(l, nullptr, 0);
const int64_t both[2] = {1, 0};
fs.set_fetch_threads(2);
fs.prefetch(l, both, 2);
for (int64_t e = 0; e < NE; ++e) {
const uint8_t* b = fs.blob(l, e);
pre = pre && b != nullptr &&
std::memcmp(b, dst.data() + L.blob_offset(l, e), (size_t) L.blob_bytes(l)) == 0;
}
}
check(pre && fs.file_blob_bytes() > 0 && fs.file_ms() >= 0.0,
"prefetch on 2 threads, then blob(): the same bytes");
}
fs.close();
// with experts.bin present, the pack's file is mapped as before, whatever set_gguf says
{
std::ofstream eb(pack / "experts.bin", std::ios::binary);
eb.write((const char*) dst.data(), (std::streamsize) dst.size());
}
strata::core::FileExpertSource fb;
fb.set_gguf(A.string());
std::string e2;
const bool ob = fb.open(pack.string(), 2, NE, e2);
const uint8_t* b11 = ob ? fb.blob(1, 1) : nullptr;
check(ob && !fb.gguf_mode() && !fb.transient(1, 1) && b11 != nullptr &&
std::memcmp(b11, dst.data() + L.blob_offset(1, 1), (size_t) L.blob_bytes(1)) == 0,
"with experts.bin the mapped file is used (unchanged behaviour)");
fb.close();
fs::remove(pack / "experts.bin");
}
auto refused = [&](const std::string& what, const std::string& needle) {
std::string e2;
const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(),
strata::kernels::cpu::expert_layout(), e2);
check(bad && e2.find(needle) != std::string::npos, what + " (\"..." + needle + "...\")");
};
const std::string both = B.filename().string() + "," + B.filename().string() + ",";
write_text(pack / "native_experts.txt", text(std::to_string(std::stoull(at(wa, 3)) + 32), both));
refused("an offset that is not the tensor's is refused", "starts at byte");
write_text(pack / "native_experts.txt", text(at(wa, 3), ""));
refused("layer 1's gate named in the file that does not hold it is refused", "is not in it");
write_text(pack / "native_experts.txt", text(at(wa, 3), both + ",x"));
std::string e3;
check(!load(pack, 2, 512, e3), "a malformed column is refused at load");
write_text(pack / "native_experts.txt", text(at(wa, 3), "missing.gguf,missing.gguf,"));
refused("a shard that is not there is refused", "cannot open");
fixture::write(B, {}, tb, /*cut=*/100);
write_text(pack / "native_experts.txt", text(at(wa, 3), both));
refused("a truncated shard is refused before anything is read", "past the end");
// a type and a shape the pack does not say: Q3_K and IQ3_S are both 110 B per 256, so only the type differs
TempDir d2;
const fs::path C = d2.path / "C.gguf";
const auto wc = fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, IQ3_S, 31},
{"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32},
{"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}});
strata::kernels::cpu::NativeFmt f2;
if (!strata::kernels::cpu::native_fmt(Q3_K, Q5_1, H, FF, f2, err)) {
check(false, "Q3_K/Q5_1 native format: " + err);
return;
}
fs::create_directories(d2.path / "pack");
write_text(d2.path / "pack" / "native_experts.txt",
"# strata native experts v3: (n_expert 2, total " + std::to_string(f2.bytes * NE) + ")\n0 11 7 0 " +
std::to_string(f2.bytes) + " " + std::to_string(wc.data_start + wc.offsets[0]) + " " +
std::to_string(wc.data_start + wc.offsets[1]) + " " + std::to_string(wc.data_start + wc.offsets[2]) + "\n");
ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(),
strata::kernels::cpu::expert_layout(), err);
check(ok && err.find("is IQ3_S") != std::string::npos, "a gate of another type than the pack's is refused");
// the same bytes with the pack's types, but a down tensor of three experts where the pack says two
fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q3_K, 31},
{"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32},
{"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}});
ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(),
strata::kernels::cpu::expert_layout(), err);
check(ok && err.find("is not [640, 2560, 2]") != std::string::npos, "a down tensor of another shape is refused");
}
} // namespace
int main(int argc, char** argv) {
// `expert_layout_test --real PACK_DIR NATIVE_SHARD`: a real pack's native_experts.txt against its model's files
// (headers only - check_experts_gguf reads no expert byte)
if ((argc == 4 || argc == 8) && std::string(argv[1]) == "--real") {
// optional: N_LAYERS N_EXPERT N_EMBD N_FF (default Flash-Next's 48 512 2560 640; Qwen3.6 is 40 256 2048 512)
std::string err;
const int64_t nl = argc == 8 ? std::atoll(argv[4]) : 48, ne = argc == 8 ? std::atoll(argv[5]) : 512;
const int64_t nd = argc == 8 ? std::atoll(argv[6]) : 2560, nf = argc == 8 ? std::atoll(argv[7]) : 640;
if (!load(argv[2], nl, ne, nd, nf, err)) { std::printf("layout refused: %s\n", err.c_str()); return 1; }
const ExpertLayout& L = strata::kernels::cpu::expert_layout();
const bool ok = strata::core::check_experts_gguf(argv[3], L, err);
size_t split = 0;
for (int64_t l = 0; l < L.n_layers && !L.gguf_file.empty(); ++l)
split += L.gguf_file[(size_t) (3 * l)] != L.gguf_file[(size_t) (3 * l + 2)];
std::printf("%s: v%d, %lld layers x %lld experts, %.2f GiB, %zu layer(s) split per role: %s%s\n", argv[2],
L.version, (long long) L.n_layers, (long long) L.n_expert, (double) L.total / (1u << 30), split,
ok ? "every span is its tensor" : "REFUSED: ", ok ? "" : err.c_str());
return ok ? 0 : 1;
}
std::printf("expert_layout_test\n");
if (argc < 2) {
std::printf("usage: expert_layout_test <tests/data/native_experts>\n");
return 2;
}
real_packs(argv[1]);
qwen36(argv[1]);
columns();
arena();
std::printf(g_fail ? "expert_layout_test: %d FAILED\n" : "expert_layout_test: all passed\n", g_fail);
return g_fail ? 1 : 0;
}
-92
View File
@@ -1,92 +0,0 @@
// #477: --expert-profile-save's profile - rank_learned_profile's order (resident first, then the counted routing, then
// the profile the engine started from) and write_expert_profile's file, byte for byte tools/make_profile.py's format,
// read back by read_expert_profile. CPU only: no device is touched.
#include "strata/core/expert_cache.hpp"
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <string>
#include <utility>
#include <vector>
namespace {
int fails = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: %s\n", what);
++fails;
}
}
} // namespace
int main() {
using Pair = std::pair<int32_t, int32_t>;
const int64_t L = 3, E = 4; // 12 pairs, index = layer * 4 + expert
std::vector<uint8_t> resident(12, 0);
resident[5] = 1; // (1, 1)
resident[2] = 1; // (0, 2)
std::vector<double> heat(12, 0.0);
heat[2] = 1.0;
heat[5] = 7.0;
heat[11] = 9.0; // (2, 3): the hottest, but not resident
heat[0] = 3.0;
const std::vector<Pair> prior = {{2, 0}, {1, 3}, {0, 1}}; // a profile that ranks three pairs
const std::vector<Pair> r = strata::core::rank_learned_profile(L, E, resident, heat, prior);
check(r.size() == 12, "every pair is ranked");
const std::vector<Pair> head = {{1, 1}, {0, 2}, {2, 3}, {0, 0}, {2, 0}, {1, 3}, {0, 1}, {0, 3}};
for (size_t i = 0; i < head.size() && i < r.size(); ++i)
check(r[i] == head[i], "resident by heat, then the rest by heat, then the prior, then the index");
// no counts at all: the resident ones, then the prior's order
const std::vector<Pair> r0 = strata::core::rank_learned_profile(L, E, resident, {}, prior);
check(r0.size() == 12 && r0[0] == Pair(0, 2) && r0[1] == Pair(1, 1) && r0[2] == Pair(2, 0) &&
r0[3] == Pair(1, 3) && r0[4] == Pair(0, 1) && r0[5] == Pair(0, 0), "without heat: resident, then prior");
const std::filesystem::path dir = std::filesystem::temp_directory_path() / "strata_profile_save_test";
std::filesystem::create_directories(dir);
const std::string path = (dir / "learned.bin").string();
std::string err;
check(strata::core::write_expert_profile(path, L, E, r, err), "written");
check(!std::filesystem::exists(path + ".tmp"), "no temporary file left");
// the bytes make_profile.write_profile would write for the same ranking
std::vector<uint8_t> want(4);
std::memcpy(want.data(), "STRP", 4);
auto u32 = [&](uint32_t v) { for (int b = 0; b < 4; ++b) want.push_back((uint8_t) (v >> (8 * b))); };
auto u16 = [&](uint32_t v) { want.push_back((uint8_t) v); want.push_back((uint8_t) (v >> 8)); };
for (uint32_t v : {1u, 3u, 4u, 12u, 12u}) u32(v);
for (const Pair& p : r) { u16((uint32_t) p.first); u16((uint32_t) p.second); }
std::vector<int32_t> table(12, -1);
for (size_t i = 0; i < r.size(); ++i) table[(size_t) (r[i].first * E + r[i].second)] = (int32_t) i;
for (int32_t v : table) u32((uint32_t) v);
std::vector<uint8_t> got(want.size() + 1);
if (std::FILE* f = std::fopen(path.c_str(), "rb")) {
got.resize(std::fread(got.data(), 1, got.size(), f));
std::fclose(f);
}
check(got == want, "the file is make_profile.py's format, byte for byte");
std::vector<Pair> back;
int64_t slots = 0;
check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r && slots == 12,
"read back by the loader");
// a second save replaces the first (the rename over an existing file)
check(strata::core::write_expert_profile(path, L, E, r0, err), "written again");
check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0, "replaced");
check(!strata::core::write_expert_profile(path, L, E, {{3, 0}}, err), "a pair out of range is refused");
check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0,
"a refused save keeps the file");
// a profile of another model is refused by its numbers: Flash-Next's 48 x 512 against Qwen3.6's 40 x 256
// (expert_cache.cpp's header check; the Qwen3.6 port's step 2 negative test)
{
const std::string other = (dir / "flash-next.bin").string();
check(strata::core::write_expert_profile(other, 48, 512, {{47, 511}, {0, 0}}, err), "a 48 x 512 profile written");
const bool refused = !strata::core::read_expert_profile(other, 40, 256, back, slots, err);
check(refused && err.find("48x512") != std::string::npos && err.find("40x256") != std::string::npos &&
err.find("different artifact") != std::string::npos,
"a 48 x 512 profile is refused for a 40 x 256 model, naming both");
check(strata::core::read_expert_profile(other, 48, 512, back, slots, err) && back.size() == 2,
"the same profile reads for the 48 x 512 model");
}
std::filesystem::remove_all(dir);
if (fails == 0) std::puts("expert_profile_save_test: OK");
return fails == 0 ? 0 : 1;
}
-360
View File
@@ -1,360 +0,0 @@
#include "strata/core/expert_source.hpp"
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#if defined(STRATA_NATIVE_EXPERTS)
#include "strata/kernels/cpu/native_expert.hpp"
#include "ggml.h"
#endif
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
namespace fs = std::filesystem;
namespace {
void require(bool ok, const std::string& message) {
if (!ok) throw std::runtime_error(message);
}
struct TempDirectory {
fs::path path;
TempDirectory() {
const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
path = fs::temp_directory_path() / ("strata-file-source-test-" + std::to_string(stamp));
fs::create_directories(path);
}
~TempDirectory() {
std::error_code ignored;
fs::remove_all(path, ignored);
}
};
void create_pack(const fs::path& dir, uint64_t bytes, const std::vector<std::pair<uint64_t, char>>& markers = {}) {
const fs::path file = dir / "experts.bin";
{
std::ofstream out(file, std::ios::binary | std::ios::trunc);
require((bool) out, "could not create synthetic experts.bin");
if (bytes > 0) {
out.seekp((std::streamoff) (bytes - 1));
out.put('\0');
}
require((bool) out, "could not size synthetic experts.bin");
}
for (const auto& [offset, marker] : markers) {
require(offset < bytes, "synthetic marker lies beyond experts.bin");
std::fstream file_out(file, std::ios::binary | std::ios::in | std::ios::out);
require((bool) file_out, "could not open synthetic experts.bin for markers");
file_out.seekp((std::streamoff) offset);
file_out.put(marker);
require((bool) file_out, "could not write synthetic expert marker");
}
}
void check_file_size_rejection(strata::core::FileExpertSource& source, const fs::path& dir, int64_t layers,
int64_t experts, uint64_t expected_bytes) {
std::string err;
source.close();
fs::resize_file(dir / "experts.bin", expected_bytes - 1);
require(!source.open(dir.string(), layers, experts, err), "a truncated expert file was accepted");
require(!source.mapped() && !err.empty(), "truncated-file rejection left the source mapped or unreported");
fs::resize_file(dir / "experts.bin", expected_bytes + 1);
err.clear();
require(!source.open(dir.string(), layers, experts, err), "an oversized expert file was accepted");
require(!source.mapped() && !err.empty(), "oversized-file rejection left the source mapped or unreported");
}
void test_canonical_layout() {
using namespace strata::core;
using namespace strata::kernels::cpu;
constexpr int64_t layers = 2;
constexpr int64_t experts = 3;
const uint64_t layer_bytes = (uint64_t) experts * BLOB;
const uint64_t total = (uint64_t) layers * layer_bytes;
TempDirectory dir;
std::string err;
const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, 2560, 640, err);
require(layout_ok, "could not load canonical layout: " + err);
create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) BLOB, 'b'}, {layer_bytes, 'c'},
{layer_bytes + (uint64_t) BLOB, 'd'}});
FileExpertSource source;
bool opened = source.open(dir.path.string(), layers, experts, err);
require(opened, "could not map canonical pack: " + err);
require(source.blobs() == layers * experts, "canonical blob count is wrong");
const uint8_t* first = source.blob(0, 0);
const uint8_t* second = source.blob(0, 1);
const uint8_t* next_layer = source.blob(1, 0);
require(first && second && next_layer, "valid canonical blob lookup failed");
require(second - first == (ptrdiff_t) BLOB && next_layer - first == (ptrdiff_t) layer_bytes,
"canonical expert or layer stride is wrong");
require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c',
"canonical blob lookup returned bytes from the wrong expert");
require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr &&
source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr,
"canonical bounds check accepted an invalid layer or expert");
require(source.reads() == 3, "invalid canonical lookups changed the read count");
check_file_size_rejection(source, dir.path, layers, experts, total);
create_pack(dir.path, total, {{layer_bytes, 'c'}});
err.clear();
opened = source.open(dir.path.string(), layers, experts, err);
require(opened, "source failed to reopen after size errors: " + err);
const uint8_t* reopened = source.blob(1, 0);
require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened canonical source kept stale state");
source.close();
}
#if defined(STRATA_NATIVE_EXPERTS)
void test_native_variable_layout() {
using namespace strata::core;
using namespace strata::kernels::cpu;
constexpr int64_t layers = 2;
constexpr int64_t experts = 3;
constexpr int64_t embedding = 2560;
constexpr int64_t feed_forward = 640;
TempDirectory dir;
NativeFmt first_fmt, second_fmt;
std::string err;
const bool first_ok = native_fmt(GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, embedding, feed_forward, first_fmt, err);
require(first_ok, "IQ3_XXS/IQ4_NL synthetic format is unavailable: " + err);
err.clear();
const bool second_ok = native_fmt(GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, embedding, feed_forward, second_fmt, err);
require(second_ok, "IQ2_XS/IQ4_NL synthetic format is unavailable: " + err);
require(first_fmt.bytes != second_fmt.bytes, "chosen native formats do not exercise variable layer sizes");
const uint64_t layer0_bytes = (uint64_t) first_fmt.bytes * experts;
const uint64_t total = layer0_bytes + (uint64_t) second_fmt.bytes * experts;
{
std::ofstream metadata(dir.path / "native_experts.txt");
require((bool) metadata, "could not create synthetic native_experts.txt");
metadata << "0 " << GGML_TYPE_IQ3_XXS << ' ' << GGML_TYPE_IQ4_NL << " 0 " << first_fmt.bytes << '\n';
metadata << "1 " << GGML_TYPE_IQ2_XS << ' ' << GGML_TYPE_IQ4_NL << ' ' << layer0_bytes << ' '
<< second_fmt.bytes << '\n';
require((bool) metadata, "could not write synthetic native_experts.txt");
}
create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) first_fmt.bytes, 'b'},
{layer0_bytes, 'c'}, {layer0_bytes + (uint64_t) second_fmt.bytes, 'd'}});
const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, 2560, 640, err);
require(layout_ok, "could not load synthetic native layout: " + err);
FileExpertSource source;
bool opened = source.open(dir.path.string(), layers, experts, err);
require(opened, "could not map native pack: " + err);
require(source.blobs() == layers * experts, "native blob count is wrong");
const uint8_t* first = source.blob(0, 0);
const uint8_t* second = source.blob(0, 1);
const uint8_t* next_layer = source.blob(1, 0);
const uint8_t* next_layer_second = source.blob(1, 1);
require(first && second && next_layer && next_layer_second, "valid native blob lookup failed");
require(second - first == (ptrdiff_t) first_fmt.bytes && next_layer - first == (ptrdiff_t) layer0_bytes &&
next_layer_second - next_layer == (ptrdiff_t) second_fmt.bytes,
"native per-layer expert stride is wrong");
require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c' && next_layer_second[0] == 'd',
"native blob lookup returned bytes from the wrong expert");
require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr &&
source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr,
"native bounds check accepted an invalid layer or expert");
require(source.reads() == 4, "invalid native lookups changed the read count");
check_file_size_rejection(source, dir.path, layers, experts, total);
create_pack(dir.path, total, {{layer0_bytes, 'c'}});
err.clear();
opened = source.open(dir.path.string(), layers, experts, err);
require(opened, "source failed to reopen after size errors: " + err);
const uint8_t* reopened = source.blob(1, 0);
require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened native source kept stale state");
source.close();
}
#endif
void test_complement_plan() {
using namespace strata::core::detail;
std::vector<uint64_t> offsets;
uint64_t bytes = 0;
std::string error;
require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error);
require(bytes == 16 && offsets == std::vector<uint64_t>{0, kNoCacheComplement, 3, 6, 11, kNoCacheComplement},
"wrong compact offsets for variable native layer sizes");
const uint8_t resident[16] = {}, mapped[5] = {};
require(cache_complement_blob_or_fallback(1, offsets, resident, mapped) == mapped,
"GPU-resident expert lost mmap fallback");
require(cache_complement_blob_or_fallback(4, offsets, resident, mapped) == resident + 11,
"CPU miss did not use resident complement");
require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {0, 1}}, {}, offsets, bytes, error)
&& offsets.empty() && bytes == 0, "duplicate pair accepted");
require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}}, {{0, 1}}, offsets, bytes, error),
"overlapping tiers accepted");
require(!make_cache_complement_plan(2, 3, {3, 5}, {{2, 0}}, {}, offsets, bytes, error),
"out-of-range pair accepted");
require(!make_cache_complement_plan(2, 3, {0, 5}, {}, {}, offsets, bytes, error), "zero-size layer accepted");
}
void test_resident_lend_region() {
using namespace strata::core::detail;
// four slots (sizes 5, 3, 3, 5); the experts no slot holds take 10 bytes
const std::vector<uint64_t> slots{5, 3, 3, 5};
require(choose_resident_keep_from(slots, 10, 9, 1) == -1, "a base larger than the budget was accepted");
require(choose_resident_keep_from(slots, 10, 10, 1) == 4, "no room: the lend region must stay on the file");
require(choose_resident_keep_from(slots, 10, 15, 1) == 3, "the last slot fits and must be kept first");
require(choose_resident_keep_from(slots, 10, 17, 1) == 3, "a slot that does not fit ends the lend region's walk");
require(choose_resident_keep_from(slots, 10, 18, 1) == 2, "two slots fit");
require(choose_resident_keep_from(slots, 10, 100, 1) == 1, "the walk must stop at the lend region's first slot");
require(choose_resident_keep_from(slots, 10, 100, -1) == 4, "no lend region kept slots in RAM");
require(choose_resident_keep_from(slots, 10, 100, 9) == 4, "an out-of-range lend region kept slots in RAM");
require(choose_resident_keep_from({}, 0, 0, 0) == 0, "an empty cache");
}
void test_resident_exchange() {
using namespace strata::core;
using namespace strata::core::detail;
// 2 layers x 3 experts; the GPU holds (0,1) and (1,2): the compact copy holds the other four
std::vector<uint64_t> offsets;
uint64_t bytes = 0;
std::string error;
require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error);
const std::vector<uint64_t> before = offsets;
// (1,0) moves into the GPU, (1,2) leaves it: (1,2) takes (1,0)'s bytes' place
require(exchange_cache_complement(offsets, 3, 5), "a valid exchange was refused");
require(offsets[5] == before[3] && offsets[3] == kNoCacheComplement, "the exchange did not move the place");
for (size_t i : {0u, 1u, 2u, 4u}) require(offsets[i] == before[i], "an exchange touched another expert");
// the copy's size and its set of places are unchanged
std::vector<uint64_t> a, b;
for (uint64_t o : before) if (o != kNoCacheComplement) a.push_back(o);
for (uint64_t o : offsets) if (o != kNoCacheComplement) b.push_back(o);
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
require(a == b, "an exchange changed the compact copy's places");
const std::vector<uint64_t> after = offsets;
require(!exchange_cache_complement(offsets, 3, 0), "an `in` the copy does not hold was accepted");
require(!exchange_cache_complement(offsets, 0, 2), "an `out` the copy holds already was accepted");
require(!exchange_cache_complement(offsets, 0, 0), "a self-exchange was accepted");
require(!exchange_cache_complement(offsets, 0, 6), "an out-of-range `out` was accepted");
require(offsets == after, "a refused exchange changed the offsets");
// and back: the copy is again what the plan makes for the original placement
require(exchange_cache_complement(offsets, 5, 3), "the reverse exchange was refused");
require(offsets == before, "exchanging back did not restore the plan");
}
void test_cgroup_memory_budget() {
using namespace strata::core::detail;
constexpr uint64_t GiB = 1ull << 30;
uint64_t bytes = 0;
CgroupMemoryStat clean_cache{40 * GiB, 32 * GiB, 0, 0, true};
require(cgroup_available_bytes(56 * GiB, clean_cache, bytes), "valid cgroup memory.stat was rejected");
require(bytes == 48 * GiB, "clean inactive file cache was not credited against the cgroup cap");
CgroupMemoryStat dirty_cache{40 * GiB, 32 * GiB, 4 * GiB, 2 * GiB, true};
require(cgroup_available_bytes(56 * GiB, dirty_cache, bytes), "valid dirty-cache counters were rejected");
require(bytes == 42 * GiB, "dirty/writeback pages were incorrectly counted as reclaimable");
CgroupMemoryStat oversized_inactive{10 * GiB, 20 * GiB, 0, 0, true};
require(cgroup_available_bytes(12 * GiB, oversized_inactive, bytes),
"valid oversized inactive-file counter was rejected");
require(bytes == 12 * GiB, "inactive-file accounting exceeded charged current usage");
const uint64_t max = std::numeric_limits<uint64_t>::max();
CgroupMemoryStat large_counters{max, max, max - 1, max, true};
require(cgroup_available_bytes(max, large_counters, bytes),
"large memory.stat counters were rejected");
require(bytes == 0, "dirty/writeback subtraction overflowed or escaped the usage cap");
CgroupMemoryStat usage_over_limit{60 * GiB, 0, 0, 0, true};
require(cgroup_available_bytes(56 * GiB, usage_over_limit, bytes),
"valid over-limit memory counters were rejected");
require(bytes == 0, "over-limit cgroup usage produced a positive budget");
CgroupMemoryStat missing_stat{};
bytes = 123;
require(!cgroup_available_bytes(56 * GiB, missing_stat, bytes) && bytes == 0,
"missing memory.stat counters did not fail closed");
}
// #633: the host RAM probe with fake /proc and cgroup trees: v2 (a limit, "max", a missing or malformed limit), v1
// (a limit, unlimited), and no cgroup line at all. Elsewhere than Linux it reads the machine's RAM.
void test_host_memory() {
using namespace strata::core::detail;
constexpr uint64_t GiB = 1ull << 30;
HostMemory m;
#if defined(__linux__)
TempDirectory t;
auto put = [&](const fs::path& rel, const std::string& text) {
fs::create_directories((t.path / rel).parent_path());
std::ofstream(t.path / rel) << text;
};
put("meminfo", "MemTotal: 134217728 kB\nMemAvailable: 104857600 kB\n"); // 100 GiB available
const std::string mi = (t.path / "meminfo").string(), cg = (t.path / "cgroup").string(),
root = (t.path / "fs").string();
auto probe = [&](const std::string& self) {
put("cgroup", self);
return host_available_memory(m, mi, cg, root);
};
// no cgroup line at all: MemAvailable alone (before #633: "cannot determine")
require(probe("") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "no cgroup: MemAvailable alone");
// v2, a 48 GiB limit with 16 GiB charged, 4 GiB of it clean cache
put("fs/cgroup.controllers", "memory\n");
put("fs/box/memory.max", std::to_string(48 * GiB) + "\n");
put("fs/box/memory.current", std::to_string(16 * GiB) + "\n");
put("fs/box/memory.stat", "inactive_file " + std::to_string(4 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n");
require(probe("0::/box\n") && m.available == 36 * GiB && m.cgroup_limit == 48 * GiB, "v2 limit");
put("fs/box/memory.max", "max\n");
require(probe("0::/box\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v2 max");
put("fs/box/memory.max", "48G\n");
require(!probe("0::/box\n"), "v2 malformed limit accepted");
fs::remove(t.path / "fs/box/memory.max");
require(!probe("0::/box\n"), "v2 group without memory.max accepted");
// v1: the memory controller's group (a hybrid line list), a 32 GiB limit with 10 GiB used
put("fs/memory/docker/abc/memory.limit_in_bytes", std::to_string(32 * GiB) + "\n");
put("fs/memory/docker/abc/memory.usage_in_bytes", std::to_string(10 * GiB) + "\n");
put("fs/memory/memory.limit_in_bytes", "9223372036854771712\n"); // the root: unlimited
put("fs/memory/memory.usage_in_bytes", std::to_string(50 * GiB) + "\n");
require(probe("12:cpu,cpuacct:/docker/abc\n4:memory:/docker/abc\n1:name=systemd:/docker/abc\n") &&
m.available == 22 * GiB && m.cgroup_limit == 32 * GiB, "v1 limit");
put("fs/memory/docker/abc/memory.limit_in_bytes", "9223372036854771712\n");
require(probe("4:memory:/docker/abc\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v1 unlimited");
// a v1 group not visible here (another namespace): MemAvailable alone
require(probe("4:memory:/elsewhere\n") && m.available == 100 * GiB, "v1 group not mounted");
#else
require(host_available_memory(m) && m.available > 0 && m.cgroup_limit == ~0ull, "this PC's RAM");
(void) GiB;
#endif
}
} // namespace
int main() {
try {
test_complement_plan();
test_resident_lend_region();
test_resident_exchange();
test_cgroup_memory_budget();
test_host_memory();
test_canonical_layout();
#if defined(STRATA_NATIVE_EXPERTS)
test_native_variable_layout();
#endif
std::cout << "file_expert_source_test: PASS\n";
return 0;
} catch (const std::exception& error) {
std::cerr << "file_expert_source_test: " << error.what() << '\n';
return 1;
}
}
-113
View File
@@ -1,113 +0,0 @@
// tests/core/gguf_fixture.hpp - synthetic GGUF v3 files for the loader tests (no gguf-py, no model, no GPU).
//
// A file is a header, metadata (strings and integers only), a tensor directory whose offsets are 32-byte aligned
// in the data section, and the tensors' payloads, each filled with a pattern the test can recognise.
#pragma once
#include "strata/artifact/gguf_reader.hpp"
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace fixture {
struct Kv {
std::string key;
uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32, 6 f32, 9 array (of u32)
std::string s;
uint64_t u = 0;
float f = 0.0f;
std::vector<uint32_t> a; ///< the elements of a u32 array
};
inline Kv str(const std::string& k, const std::string& v) { return Kv{k, 8, v, 0}; }
inline Kv u16(const std::string& k, uint64_t v) { return Kv{k, 2, {}, v}; }
inline Kv i32(const std::string& k, uint64_t v) { return Kv{k, 5, {}, v}; }
inline Kv u32(const std::string& k, uint64_t v) { return Kv{k, 4, {}, v}; }
inline Kv f32(const std::string& k, float v) { return Kv{k, 6, {}, 0, v}; }
inline Kv u32s(const std::string& k, const std::vector<uint32_t>& v) { return Kv{k, 9, {}, 0, 0.0f, v}; }
struct Tensor {
std::string name;
std::vector<uint64_t> shape; ///< GGUF order: dim 0 varies fastest
uint32_t type = 0;
uint8_t seed = 1; ///< payload byte i is (seed * 131 + i * 7 + i / 4093) & 0xff
};
inline uint8_t pattern(uint8_t seed, uint64_t i) { return (uint8_t) ((seed * 131u + i * 7u + i / 4093u) & 0xffu); }
/// The split keys llama.cpp's gguf-split writes (u16 split.no / split.count, i32 split.tensors.count).
inline std::vector<Kv> split_keys(uint64_t no, uint64_t count, uint64_t tensors) {
return {u16("split.no", no), u16("split.count", count), i32("split.tensors.count", tensors)};
}
struct Written {
uint64_t data_start = 0;
std::vector<uint64_t> offsets; ///< per tensor, from data_start
uint64_t size = 0;
};
/// Writes `path`; `cut` bytes are dropped from the end (a truncated download).
inline Written write(const std::filesystem::path& path, const std::vector<Kv>& kv, const std::vector<Tensor>& ts,
uint64_t cut = 0) {
std::vector<uint8_t> b;
auto put = [&](const void* p, size_t n) { b.insert(b.end(), (const uint8_t*) p, (const uint8_t*) p + n); };
auto put32 = [&](uint32_t v) { put(&v, 4); };
auto put64 = [&](uint64_t v) { put(&v, 8); };
auto puts = [&](const std::string& s) { put64(s.size()); put(s.data(), s.size()); };
put32(0x46554747u);
put32(3);
put64(ts.size());
put64(kv.size());
for (const auto& k : kv) {
puts(k.key);
put32(k.type);
if (k.type == 8) puts(k.s);
else if (k.type == 2) { const uint16_t v = (uint16_t) k.u; put(&v, 2); }
else if (k.type == 4 || k.type == 5) { const uint32_t v = (uint32_t) k.u; put(&v, 4); }
else if (k.type == 6) put(&k.f, 4);
else if (k.type == 9) { // an array: element type u32, count, elements
put32(4);
put64(k.a.size());
for (const uint32_t v : k.a) put32(v);
}
else throw std::runtime_error("fixture: unsupported metadata type");
}
Written w;
std::vector<uint64_t> bytes;
uint64_t at = 0;
for (const auto& t : ts) {
strata::TensorInfo info;
info.shape = t.shape;
info.type = t.type;
const uint64_t n = strata::tensor_payload_bytes(info);
if (n == 0) throw std::runtime_error("fixture: " + t.name + " has no whole-block byte count");
puts(t.name);
put32((uint32_t) t.shape.size());
for (uint64_t d : t.shape) put64(d);
put32(t.type);
put64(at);
w.offsets.push_back(at);
bytes.push_back(n);
at = (at + n + 31) / 32 * 32;
}
w.data_start = (b.size() + 31) / 32 * 32;
b.resize((size_t) w.data_start, 0);
for (size_t i = 0; i < ts.size(); ++i) {
b.resize((size_t) (w.data_start + w.offsets[i]), 0);
for (uint64_t j = 0; j < bytes[i]; ++j) b.push_back(pattern(ts[i].seed, j));
}
if (cut > b.size()) cut = b.size();
b.resize(b.size() - (size_t) cut);
w.size = b.size();
std::ofstream f(path, std::ios::binary | std::ios::trunc);
f.write((const char*) b.data(), (std::streamsize) b.size());
if (!f) throw std::runtime_error("fixture: cannot write " + path.string());
return w;
}
} // namespace fixture
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more