Compare commits
146
Commits
No files matched your search
+186
-8
@@ -231,6 +231,33 @@ 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 ----------------------------------------------------------
|
||||
@@ -242,6 +269,12 @@ 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.
|
||||
@@ -442,6 +475,11 @@ 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)
|
||||
@@ -456,6 +494,49 @@ 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)
|
||||
@@ -651,17 +732,50 @@ 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 (GPU,
|
||||
# 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,
|
||||
# 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_gpu_runtime_target})
|
||||
target_link_libraries(gdn_rec_parity PRIVATE strata_prefill ${_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)
|
||||
@@ -686,6 +800,20 @@ 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})
|
||||
@@ -763,6 +891,31 @@ 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)
|
||||
@@ -994,6 +1147,23 @@ 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)
|
||||
@@ -1049,10 +1219,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)
|
||||
# follows eddoursul/Strata 7706c1b), plus q6_k (Qwen3.6-35B-A3B UD-Q4_K_XL's layers 34, 38, 39)
|
||||
set(_strata_mmq_cuda_types ${_strata_mmq_types})
|
||||
if(STRATA_MMQ_KQUANTS)
|
||||
list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1)
|
||||
list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1 q6_k)
|
||||
endif()
|
||||
foreach(_t IN LISTS _strata_mmq_cuda_types)
|
||||
target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
|
||||
@@ -1151,17 +1321,25 @@ 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)
|
||||
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)
|
||||
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 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)
|
||||
# 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)
|
||||
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
|
||||
|
||||
@@ -1,7 +1,36 @@
|
||||
# UnbiasedStrata build. Needs CMake 3.24+, a C++20 compiler and the CUDA toolkit. Nothing is downloaded.
|
||||
BUILD_DIR ?= build
|
||||
# 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
|
||||
# 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 ?=
|
||||
ifeq ($(PASCAL),1)
|
||||
CUDA_ARCHS := 61
|
||||
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),)
|
||||
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
|
||||
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)
|
||||
|
||||
@@ -13,7 +42,7 @@ 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_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)"
|
||||
-DSTRATA_PORTABLE=ON -DSTRATA_MMQ_KQUANTS=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" $(SM60_FLAG) $(CMAKE_EXTRA)
|
||||
cmake --build $(BUILD_DIR) -j $(JOBS) --target unbiased-strata
|
||||
@echo "built: $(BUILD_DIR)/unbiased-strata"
|
||||
|
||||
@@ -45,3 +74,9 @@ 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)
|
||||
@@ -1,8 +1,10 @@
|
||||
# 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 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 (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.
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -10,11 +12,18 @@ needed to build or run it: rsync the source, run `make build`, start the binary.
|
||||
| --- | --- | --- |
|
||||
| Network access | no | no |
|
||||
| CMake 3.24+, C++20 compiler (tested: g++ 13.3) | yes | no |
|
||||
| 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 |
|
||||
| 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 |
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Build
|
||||
|
||||
@@ -24,19 +33,35 @@ 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 `86;89;120`.
|
||||
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.
|
||||
|
||||
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
|
||||
toolkit (CUDA 13 dropped sm_60/sm_70) and is outside the validated configuration above: no tensor cores, so
|
||||
expect the portable FP32 attention path and much lower throughput, and a card under 24 GB leans on the expert
|
||||
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); engine flags after `--` |
|
||||
| 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 `--`: `--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) |
|
||||
| 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 `temperature` > 0 |
|
||||
| Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off |
|
||||
| Tools | OpenAI format (`tools`, `tool_calls`) |
|
||||
@@ -56,7 +81,9 @@ 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 one supported model
|
||||
## The supported models
|
||||
|
||||
### Qwen3.8-Flash-Next
|
||||
|
||||
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),
|
||||
@@ -75,6 +102,66 @@ 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.
|
||||
@@ -88,6 +175,47 @@ 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.
|
||||
|
||||
@@ -107,19 +235,32 @@ 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 | 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) |
|
||||
| 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) |
|
||||
| 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 | one |
|
||||
| Configurations | several models, NVIDIA, AMD and Intel, Linux and Windows, multi-GPU | two models, one NVIDIA card (Pascal to RTX 50), Linux |
|
||||
|
||||
## Credits and licence
|
||||
|
||||
|
||||
+48
-1
@@ -20,7 +20,8 @@ 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` and applied in the submodule's working tree:
|
||||
`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:
|
||||
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
|
||||
@@ -73,3 +74,49 @@ 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`.)
|
||||
@@ -0,0 +1,39 @@
|
||||
# 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}")
|
||||
@@ -0,0 +1,28 @@
|
||||
# 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")
|
||||
@@ -0,0 +1,35 @@
|
||||
# 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}")
|
||||
@@ -0,0 +1,27 @@
|
||||
# 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.
@@ -127,6 +127,13 @@ Constraints across the ladder:
|
||||
|
||||
## 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
|
||||
@@ -230,6 +237,18 @@ Instruments, logged per run (the same three serve the engine later):
|
||||
- **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 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,313 @@
|
||||
# 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`).
|
||||
@@ -0,0 +1,198 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,166 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,214 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,202 @@
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,173 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,63 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,217 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,266 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,58 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,209 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,195 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,521 @@
|
||||
# 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.
|
||||
@@ -66,7 +66,94 @@ 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");
|
||||
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");
|
||||
"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");
|
||||
}
|
||||
+27
-3
@@ -18,6 +18,7 @@ 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;
|
||||
};
|
||||
|
||||
@@ -46,11 +47,19 @@ public:
|
||||
return out_ != nullptr;
|
||||
}
|
||||
|
||||
/// Reads the engine's start-up lines until it says READY. Loading the model takes minutes.
|
||||
bool wait_ready(std::string& err) {
|
||||
/// 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) {
|
||||
std::string line;
|
||||
while (read_line(line)) {
|
||||
if (line.rfind("READY", 0) == 0) return true;
|
||||
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("ERR", 0) == 0) { err = line; return false; }
|
||||
}
|
||||
err = "the engine exited before it was ready (its messages are above)";
|
||||
@@ -115,6 +124,21 @@ public:
|
||||
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");
|
||||
|
||||
@@ -10,6 +10,12 @@ 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");
|
||||
@@ -39,6 +45,13 @@ 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);
|
||||
|
||||
+286
-65
@@ -39,7 +39,25 @@ int strata_engine_main(int argc, char** argv);
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const kModelName = "qwen3.8-flash-next-iq3_xxs";
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -51,6 +69,11 @@ struct Options {
|
||||
int port = 8080;
|
||||
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
|
||||
std::vector<std::string> extra; // after `--`: passed to the engine as they are
|
||||
};
|
||||
|
||||
@@ -63,11 +86,23 @@ void usage() {
|
||||
" --mmproj PATH enable image input using this vision encoder (CPU)\n"
|
||||
" --vision-tokens N maximum tokens per image (default 1024)\n"
|
||||
" --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\n"
|
||||
"Serves POST /v1/chat/completions (OpenAI style, with streaming), GET /v1/models and GET /health.\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"
|
||||
"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");
|
||||
}
|
||||
|
||||
bool file_exists(const std::string& p) {
|
||||
@@ -125,12 +160,68 @@ 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 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;
|
||||
@@ -185,8 +276,36 @@ 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);
|
||||
@@ -232,16 +351,26 @@ struct Server {
|
||||
// (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();
|
||||
if (n + 1 + kEngineReserve > opt.ctx) {
|
||||
err = "the prompt is " + std::to_string(n) + " tokens, which does not fit the context of " +
|
||||
const long long room = opt.ctx - n - kEngineReserve;
|
||||
if (room < 1) {
|
||||
err = "the prompt is " + std::to_string(n) + " tokens, which leaves no room to generate in the context of " +
|
||||
std::to_string(opt.ctx);
|
||||
return false;
|
||||
}
|
||||
long long max_new = opt.ctx - n - kEngineReserve;
|
||||
long long max_new = room;
|
||||
for (const char* key : {"max_completion_tokens", "max_tokens"})
|
||||
if (body.contains(key) && body.at(key).is_number()) {
|
||||
const long long want = body.at(key).get<long long>();
|
||||
if (want >= 1) max_new = std::min(max_new, want);
|
||||
if (want >= 1) {
|
||||
if (want <= room) max_new = want;
|
||||
else if (opt.fit_max_tokens) max_new = room;
|
||||
else {
|
||||
err = "the request asks for " + std::to_string(want) + " tokens and the prompt is " +
|
||||
std::to_string(n) + ", which does not fit the context of " + std::to_string(opt.ctx) +
|
||||
" (--fit-max-tokens shortens the request to the room left)";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
p.max_new = max_new;
|
||||
@@ -275,8 +404,11 @@ struct Server {
|
||||
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 + " " : "");
|
||||
// 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;
|
||||
// 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")) {
|
||||
@@ -300,6 +432,8 @@ 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;
|
||||
}
|
||||
|
||||
@@ -317,11 +451,11 @@ 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, answer text, tool-call pieces); 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 (content and tool calls are published only once the message is complete, so a long answer
|
||||
/// is silent for minutes): 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
|
||||
/// `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.
|
||||
GenResult run(const Prepared& p, common_chat_msg& final_msg,
|
||||
const std::function<bool(const std::vector<common_chat_msg_diff>&)>& emit,
|
||||
@@ -330,57 +464,91 @@ struct Server {
|
||||
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;
|
||||
common_chat_msg msg;
|
||||
std::vector<std::string> call_ids;
|
||||
StreamParse parse;
|
||||
common_chat_msg& msg = parse.msg;
|
||||
bool client_ok = true;
|
||||
auto last_write = std::chrono::steady_clock::now();
|
||||
auto update = [&](bool partial) {
|
||||
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;
|
||||
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();
|
||||
}
|
||||
};
|
||||
GenResult r = engine.generate(p.header, p.ids, [&](llama_token id) {
|
||||
if (llama_vocab_is_eog(vocab, id)) return client_ok;
|
||||
// #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) {
|
||||
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);
|
||||
update(true);
|
||||
if (p.stream) update(true); // a whole response is parsed once, at the end
|
||||
}
|
||||
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;
|
||||
};
|
||||
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;
|
||||
}
|
||||
}
|
||||
return client_ok;
|
||||
});
|
||||
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;
|
||||
}
|
||||
text += pending;
|
||||
try {
|
||||
update(false);
|
||||
@@ -441,7 +609,7 @@ struct Server {
|
||||
out["id"] = id;
|
||||
out["object"] = "chat.completion";
|
||||
out["created"] = created;
|
||||
out["model"] = kModelName;
|
||||
out["model"] = g_model_name;
|
||||
out["choices"] = common_json::array();
|
||||
out["choices"].push_back(choice);
|
||||
out["usage"] = usage_json(r);
|
||||
@@ -462,7 +630,7 @@ struct Server {
|
||||
out["id"] = id;
|
||||
out["object"] = "chat.completion.chunk";
|
||||
out["created"] = created;
|
||||
out["model"] = kModelName;
|
||||
out["model"] = g_model_name;
|
||||
out["choices"] = common_json::array();
|
||||
out["choices"].push_back(choice);
|
||||
if (done) { out["usage"] = usage_json(*done); out["timings"] = timings_json(*done); }
|
||||
@@ -574,7 +742,13 @@ bool parse_args(int argc, char** argv, Options& o) {
|
||||
else if (a == "--host") o.host = next("--host");
|
||||
else if (a == "--port") o.port = std::atoi(next("--port").c_str());
|
||||
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 == "--") {
|
||||
for (++i; i < argc; ++i) {
|
||||
const std::string e = argv[i];
|
||||
@@ -591,6 +765,10 @@ 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;
|
||||
}
|
||||
return !o.model.empty() && !o.pack.empty() && !o.mtp.empty();
|
||||
}
|
||||
|
||||
@@ -602,19 +780,20 @@ 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) {
|
||||
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");
|
||||
if (at != std::string::npos) shard2.replace(at, 15, "-00002-of-00002");
|
||||
else shard2.clear();
|
||||
const std::string profile = o.pack + "/expert-profile.bin";
|
||||
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; }
|
||||
// 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; }
|
||||
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)) {
|
||||
@@ -622,9 +801,12 @@ 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, "--ple-gguf", shard2,
|
||||
"unbiased-strata", "--engine", "--serve", "--pack", o.pack, "--native", o.model,
|
||||
"--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), "--ple-io", "ram"};
|
||||
"--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)); }
|
||||
if (!o.mmproj.empty()) eargs.push_back("--vision");
|
||||
if (o.ctx > 8192) { eargs.push_back("--kv"); eargs.push_back("int8"); }
|
||||
if (o.threads <= 0) {
|
||||
@@ -660,23 +842,62 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
|
||||
std::fprintf(stderr, "unbiased-strata: loading the model (this takes a few minutes)...\n");
|
||||
if (!srv.engine.wait_ready(err)) {
|
||||
long long engine_ctx = 0;
|
||||
if (!srv.engine.wait_ready(err, &engine_ctx)) {
|
||||
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;
|
||||
res.set_content(srv.engine.alive() ? "{\"status\":\"ok\"}" : "{\"status\":\"error\"}", "application/json");
|
||||
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");
|
||||
});
|
||||
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"] = kModelName;
|
||||
m["id"] = g_model_name;
|
||||
m["object"] = "model";
|
||||
m["owned_by"] = "local";
|
||||
m["context_length"] = srv.opt.ctx;
|
||||
|
||||
+11
-1
@@ -74,7 +74,17 @@ 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);
|
||||
if (width_ != 2560) throw std::runtime_error("vision projector does not match Flash-Next's 2560 embedding width");
|
||||
// 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));
|
||||
max_tokens_ = max_tokens;
|
||||
auto cp = mtmd_context_params_default();
|
||||
cp.use_gpu = false; cp.print_timings = false; cp.warmup = false;
|
||||
|
||||
@@ -570,8 +570,12 @@ private:
|
||||
std::map<std::string, std::pair<size_t, const TensorInfo*>> index_;
|
||||
};
|
||||
|
||||
// ---- 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.
|
||||
// ---- 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.
|
||||
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
|
||||
@@ -581,26 +585,43 @@ 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;
|
||||
};
|
||||
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 == "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
|
||||
}
|
||||
return {}; // empty == ok
|
||||
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)";
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -80,6 +80,10 @@ 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.
|
||||
@@ -466,6 +470,8 @@ 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_; }
|
||||
@@ -609,6 +615,7 @@ 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;
|
||||
|
||||
@@ -277,6 +277,10 @@ 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();
|
||||
@@ -479,8 +483,35 @@ 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.
|
||||
|
||||
@@ -16,46 +16,88 @@
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/weights.hpp"
|
||||
#include "strata/kernels/gdn.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// 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.
|
||||
/// 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()`.
|
||||
struct ModelGeometry {
|
||||
ModelArch arch = ModelArch::Qwen4Exp;
|
||||
|
||||
int64_t n_embd = 2560;
|
||||
int64_t n_layers = 48;
|
||||
int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... 47
|
||||
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)
|
||||
|
||||
// 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
|
||||
// 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
|
||||
|
||||
// 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;
|
||||
// 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)
|
||||
|
||||
// gated residual, on every layer
|
||||
// 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.
|
||||
int64_t hc = 4;
|
||||
int64_t hc_lr = 320;
|
||||
|
||||
// MoE, on every layer
|
||||
int64_t n_expert = 512;
|
||||
int64_t n_ff = 640;
|
||||
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 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
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
// 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
|
||||
@@ -26,6 +26,7 @@
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -93,6 +94,37 @@ 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_; }
|
||||
@@ -103,6 +135,14 @@ 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);
|
||||
@@ -141,7 +181,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; };
|
||||
struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; int type = -1; };
|
||||
std::vector<Tensor> tensors_;
|
||||
uint8_t* dense_ = nullptr;
|
||||
uint8_t* experts_ = nullptr;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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
|
||||
@@ -42,6 +42,13 @@ 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);
|
||||
|
||||
@@ -130,6 +130,9 @@ 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:
|
||||
|
||||
@@ -74,7 +74,12 @@ 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).
|
||||
bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);
|
||||
/// `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);
|
||||
/// 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;
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
//
|
||||
// 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 * sigmoid(z)
|
||||
// y = rmsnorm(o) * gamma * act(z) (act = sigmoid for Flash-Next, SiLU for Qwen3.6: `GdnGate`, gdn.hpp)
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/gdn.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
@@ -28,8 +30,11 @@ 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, float* y, int h_k, int h_v,
|
||||
void* stream);
|
||||
const float* beta, const float* z, const float* gamma, float eps, GdnGate act, float* y,
|
||||
int h_k, int h_v, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -34,13 +34,26 @@
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// Geometry of one GDN layer. The real artifact: S = 128, h_k = 16, h_v = 48.
|
||||
/// 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.
|
||||
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
|
||||
@@ -87,11 +100,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 * sigmoid(z)`.
|
||||
/// The layer's closing norm: `y = rms_norm(o, eps) * ssm_norm * act(z)`, `act` per `GdnGate`.
|
||||
///
|
||||
/// Note SIGMOID, not SiLU - qwen3.5 used SiLU and this artifact does not, and `ref/gdn.py` says so outright.
|
||||
/// SIGMOID for Flash-Next (`ref/gdn.py` says so outright), SiLU for Qwen3.6 (`ref/qwen36.py`, qwen35moe.cpp:273).
|
||||
/// 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, void* stream);
|
||||
float eps, GdnGate act, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,6 +1,7 @@
|
||||
// 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).
|
||||
// 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).
|
||||
//
|
||||
// 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,4 +1,6 @@
|
||||
#pragma once
|
||||
#include "strata/kernels/gdn.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
@@ -28,10 +30,11 @@ 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*sigmoid(z). Gamma contains only
|
||||
// 128 floats and broadcasts across heads. Destination is disjoint from inputs.
|
||||
// [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.
|
||||
void native_gdn_out_norm(const float* output, const float* z, const float* gamma,
|
||||
float* destination, int64_t heads, int64_t cols,
|
||||
float epsilon, void* stream);
|
||||
float epsilon, GdnGate act, void* stream);
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -87,6 +87,7 @@
|
||||
// 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 {
|
||||
@@ -124,17 +125,36 @@ 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; }
|
||||
|
||||
/// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`.
|
||||
/// 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 `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
|
||||
@@ -157,7 +177,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
|
||||
kStepWidth = 3, ///< qsa_selection_width(n_kv, s): how many cells the selection returns (n_kv when dense)
|
||||
kStepCount = 4,
|
||||
};
|
||||
|
||||
@@ -281,6 +301,10 @@ 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);
|
||||
|
||||
|
||||
@@ -6,16 +6,27 @@
|
||||
// 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 (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
|
||||
// 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
|
||||
//
|
||||
// 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.
|
||||
// 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.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/qsa.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
@@ -32,15 +43,37 @@ struct QsaAttnPools {
|
||||
const int32_t* page_table = nullptr;
|
||||
};
|
||||
|
||||
/// Scratch floats for `cap` selected cells: partial accumulators, maxima and sums.
|
||||
/// 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.
|
||||
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], 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] 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.
|
||||
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
|
||||
@@ -14,6 +14,8 @@
|
||||
// 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 {
|
||||
@@ -31,9 +33,10 @@ 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`.
|
||||
/// *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`).
|
||||
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, float* y, int h_k, int h_v, int n_tok,
|
||||
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);
|
||||
/// 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).
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// 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
|
||||
@@ -5,6 +5,7 @@
|
||||
// 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"
|
||||
|
||||
@@ -37,26 +38,48 @@ 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);
|
||||
|
||||
// ---- 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 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);
|
||||
/// 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, 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_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_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, void* stream);
|
||||
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, const GdnGeom& g, void* stream);
|
||||
|
||||
// ---- MoE
|
||||
/// 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);
|
||||
/// 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);
|
||||
/// 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)
|
||||
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);
|
||||
/// 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);
|
||||
/// 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);
|
||||
@@ -65,9 +88,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_k w[t, k] * D[slot[t, k], :]
|
||||
/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_j w[t, j] * D[slot[t, j], :] over j < k, rows of n
|
||||
void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
|
||||
int64_t T, void* stream);
|
||||
int64_t T, int64_t n, int64_t k, void* stream);
|
||||
|
||||
// ---- QSA helpers
|
||||
/// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`).
|
||||
@@ -76,10 +99,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, 24, 512] (q | gate per head) -> q [T, 24, 256]
|
||||
void split_q(const float* q_full, float* q, int64_t T, 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);
|
||||
/// 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, void* stream);
|
||||
void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, int64_t n_head, 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.
|
||||
|
||||
@@ -19,11 +19,13 @@
|
||||
|
||||
namespace strata::prefill::fused {
|
||||
|
||||
/// One layer's native expert geometry (cpu::NativeFmt's fields the kernels read; n_embd 2560, n_ff 640).
|
||||
/// 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.
|
||||
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.
|
||||
|
||||
@@ -135,6 +135,17 @@ 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;
|
||||
|
||||
+7
-2
@@ -29,13 +29,18 @@ 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"}
|
||||
"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)}
|
||||
"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:
|
||||
|
||||
+683
@@ -0,0 +1,683 @@
|
||||
#!/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())
|
||||
@@ -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,7 +42,8 @@ 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.
|
||||
const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0;
|
||||
// (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;
|
||||
// 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.
|
||||
|
||||
@@ -61,6 +61,10 @@ 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)) ||
|
||||
@@ -106,8 +110,12 @@ 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);
|
||||
for (size_t i = 0; i < key.size(); ++i)
|
||||
if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry");
|
||||
// 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");
|
||||
}
|
||||
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)}) ||
|
||||
@@ -118,7 +126,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 = sizeof(int32_t);
|
||||
z.block_pos = g.has_indexer() ? sizeof(int32_t) : 0; // no indexer: no block position, no tail, no dead row
|
||||
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}) ||
|
||||
|
||||
@@ -223,8 +223,31 @@ 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;
|
||||
@@ -320,6 +343,7 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo, const std:
|
||||
return m.available > 0;
|
||||
#endif
|
||||
}
|
||||
} // namespace
|
||||
|
||||
} // namespace detail
|
||||
|
||||
@@ -1710,6 +1734,8 @@ 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,
|
||||
@@ -1826,6 +1852,8 @@ 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;
|
||||
@@ -2001,6 +2029,23 @@ 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;
|
||||
@@ -2143,11 +2188,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 * H, H, d.act_multi[(size_t) t]);
|
||||
act_quant_any(x_f + (size_t) t * W, (int) W, d.act_multi[(size_t) t]);
|
||||
else if (native)
|
||||
native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes);
|
||||
native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * W, d.nact_multi.data() + (size_t) t * kNativeActBytes);
|
||||
else
|
||||
act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
|
||||
act_quant_q8_1(x_f + (size_t) t * W, (int) W, d.act_multi[(size_t) t]);
|
||||
}
|
||||
}
|
||||
const auto c2 = std::chrono::steady_clock::now();
|
||||
@@ -2165,7 +2210,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 * H;
|
||||
float* row = out + (size_t) i * W;
|
||||
if (e < 0 || e >= d.n_expert) {
|
||||
d.failed = true;
|
||||
d.fail = "a routed expert id is out of range";
|
||||
@@ -2181,7 +2226,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) H * sizeof(float));
|
||||
std::memset(row, 0, (size_t) W * sizeof(float));
|
||||
continue;
|
||||
}
|
||||
++d.cache_refused;
|
||||
|
||||
+190
-22
@@ -1,6 +1,7 @@
|
||||
|
||||
// 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"
|
||||
@@ -314,15 +315,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 * sigmoid(z). SIGMOID, not SiLU.
|
||||
// ---- 7. z, then y = rms_norm(o) * ssm_norm * act(z). SIGMOID for Flash-Next, SiLU for Qwen3.6: `g.gdn_gate()`.
|
||||
// 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, 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);
|
||||
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);
|
||||
} 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
|
||||
@@ -473,17 +474,22 @@ 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(std::string& why) {
|
||||
// Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic.
|
||||
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.
|
||||
if (!native_bf16_projections) why = "the native BF16 projections are off";
|
||||
else if (!g_fused_gr) why = "the fused hyper-connection read is off";
|
||||
else if (g.hc > 1 && !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_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 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 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; }
|
||||
@@ -502,7 +508,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.
|
||||
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;}
|
||||
using strata::core::qsa_shapes; // the one builder (strata/core/qsa_shapes.hpp): dense = the three indexer widths zero
|
||||
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; }};
|
||||
@@ -524,7 +530,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 = max_cells / s.idx_block + 2;
|
||||
p.pooled_rows = strata::kernels::qsa_dense(s) ? 2 : max_cells / s.idx_block + 2; // dense: as the ring, no indexer
|
||||
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;
|
||||
@@ -552,6 +558,14 @@ 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; }
|
||||
@@ -584,6 +598,12 @@ 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");
|
||||
@@ -758,9 +778,13 @@ 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_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;
|
||||
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;
|
||||
// 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; 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;
|
||||
// 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;
|
||||
// attn
|
||||
n += (uint64_t) g.n_head * g.head_dim * 2;
|
||||
// attn16
|
||||
@@ -771,7 +795,8 @@ 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_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;}
|
||||
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;}
|
||||
// ================================ 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
|
||||
@@ -873,7 +898,10 @@ 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_width(kTopkMaxCells, s);
|
||||
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();
|
||||
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);
|
||||
@@ -888,16 +916,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 = !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; }
|
||||
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; }
|
||||
// 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 (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 (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; }
|
||||
// ---- 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) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
|
||||
if (!native_bf16_projections && has_idx) 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.
|
||||
//
|
||||
@@ -915,7 +943,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
|
||||
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
|
||||
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);
|
||||
// ---- 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
|
||||
@@ -940,7 +968,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); } { 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); } if (has_idx) { 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);
|
||||
@@ -959,12 +987,27 @@ 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);
|
||||
@@ -1001,6 +1044,7 @@ 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
|
||||
@@ -1087,6 +1131,20 @@ 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");
|
||||
@@ -1167,7 +1225,115 @@ 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
|
||||
@@ -1316,7 +1482,9 @@ 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) { 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) {
|
||||
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};
|
||||
// `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);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "strata/core/layout.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace strata::core {
|
||||
namespace {
|
||||
@@ -81,6 +82,12 @@ 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);
|
||||
@@ -96,6 +103,10 @@ 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},
|
||||
@@ -108,6 +119,11 @@ 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);
|
||||
|
||||
+403
-24
@@ -1,4 +1,5 @@
|
||||
// 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"
|
||||
@@ -10,6 +11,7 @@
|
||||
#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"
|
||||
@@ -68,15 +70,8 @@ bool mapped(size_t bytes, void** h, void** d) {
|
||||
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
// 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); }
|
||||
|
||||
// 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)
|
||||
@@ -87,6 +82,30 @@ strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) {
|
||||
#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
|
||||
@@ -146,6 +165,116 @@ 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) {
|
||||
@@ -170,6 +299,7 @@ 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;
|
||||
@@ -186,9 +316,13 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
|
||||
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
|
||||
vram_ += blob.size();
|
||||
}
|
||||
// ---- the 512 routed experts, one blob each
|
||||
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;
|
||||
{
|
||||
const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
|
||||
const uint64_t bytes = exp_bytes;
|
||||
// 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");
|
||||
@@ -197,7 +331,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 512 experts do not fit in VRAM"; return false; }
|
||||
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; }
|
||||
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);
|
||||
@@ -207,10 +341,12 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
|
||||
}
|
||||
vram_ += bytes;
|
||||
}
|
||||
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; }
|
||||
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; }
|
||||
}
|
||||
|
||||
// ---- the layer's own K/V (dense attention: no indexer state is read)
|
||||
const strata::kernels::QsaShapes s = shapes_of(g);
|
||||
@@ -267,7 +403,8 @@ 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) (NH * HD), 8));
|
||||
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)
|
||||
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);
|
||||
@@ -279,8 +416,10 @@ 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>(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));
|
||||
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)));
|
||||
x_bf16_ = b.take<uint16_t>(N);
|
||||
out_ids_ = b.take<int32_t>(T + 4);
|
||||
probs_ = b.take<float>(T + 4);
|
||||
@@ -302,11 +441,10 @@ 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, %.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);
|
||||
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);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -460,6 +598,7 @@ 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_;
|
||||
@@ -649,6 +788,246 @@ 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);
|
||||
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;
|
||||
|
||||
+8
-11
@@ -1,4 +1,5 @@
|
||||
// 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"
|
||||
@@ -47,8 +48,9 @@ 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() {
|
||||
return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float);
|
||||
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;
|
||||
}
|
||||
|
||||
uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) {
|
||||
@@ -68,7 +70,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(); // the PLE's NG_HIST normalized history rows
|
||||
n += ple_hist_bytes(g); // the PLE's NG_HIST normalized history rows (0 without a PLE)
|
||||
return align_up(n, SESSION_STATE_ALIGN) + 4096;
|
||||
}
|
||||
|
||||
@@ -123,7 +125,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 = (float*) take(ple_hist_bytes());
|
||||
s.ple_hist = ple_hist_bytes(g) ? (float*) take(ple_hist_bytes(g)) : nullptr;
|
||||
s.R = s.block.R;
|
||||
return used;
|
||||
}
|
||||
@@ -156,7 +158,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.
|
||||
cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(), cs);
|
||||
if (s.ple_hist != nullptr) cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(g), cs);
|
||||
s.ple_prev[0] = -1;
|
||||
s.ple_prev[1] = -1;
|
||||
s.ple_token = -1;
|
||||
@@ -175,12 +177,7 @@ 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) {
|
||||
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;
|
||||
const strata::kernels::QsaShapes sh = qsa_shapes(g); // the one builder (qsa_shapes.hpp): dense width = n_kv
|
||||
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);
|
||||
|
||||
+153
-43
@@ -1,4 +1,5 @@
|
||||
// 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)
|
||||
@@ -98,15 +99,8 @@ bool mapped(size_t bytes, void** h, void** d) {
|
||||
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
// 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); }
|
||||
|
||||
const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) {
|
||||
const WeightRef* r = v.get(suffix);
|
||||
@@ -125,6 +119,30 @@ 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) {
|
||||
@@ -329,13 +347,12 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
|
||||
return false;
|
||||
}
|
||||
std::string why;
|
||||
if (!layer_verify_compatible(why)) {
|
||||
if (!layer_verify_compatible(g, why)) {
|
||||
err = "verify: " + why + " (the verify window reproduces the default native decode path)";
|
||||
return false;
|
||||
}
|
||||
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";
|
||||
if (!verify_geometry_supported(g, ss.k, why)) {
|
||||
err = "verify: " + why;
|
||||
return false;
|
||||
}
|
||||
if (le_ < 0) le_ = g.n_layers;
|
||||
@@ -349,8 +366,9 @@ 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_width(strata::kernels::kTopkMaxCells, s);
|
||||
cap_ = strata::kernels::qsa_selection_cap(ss.qsa_states[ss.qsa_primary()].max_cells, s); // dense: max_cells
|
||||
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;
|
||||
@@ -417,7 +435,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);
|
||||
scores_ = b.take<float>(T * (uint64_t) max_blocks_); sel_ = b.take<int32_t>(T * (uint64_t) cap_);
|
||||
if (!dense) { 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);
|
||||
@@ -557,7 +575,23 @@ 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();
|
||||
auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
|
||||
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;
|
||||
};
|
||||
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) {
|
||||
@@ -622,7 +656,14 @@ 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 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
|
||||
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);
|
||||
@@ -631,8 +672,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)
|
||||
bool pending = l > 0 && !cvec().covers(l - 1);
|
||||
// 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);
|
||||
if (l == 1 && ple_on) {
|
||||
if (grp == 0) {
|
||||
if (all_resident_) wait_flag_ge(m_flag_, 1, cs);
|
||||
@@ -693,9 +734,16 @@ 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)));
|
||||
};
|
||||
gr_read_group(0, pending, inj2_, inj_);
|
||||
stamp(l, 1, grp);
|
||||
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;
|
||||
}
|
||||
stamp(l, 1, grp);
|
||||
try {
|
||||
if (!is_qsa_layer(g, l)) {
|
||||
// ======================= GDN =======================
|
||||
@@ -741,12 +789,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, y_ + (size_t) t * ZV,
|
||||
(int) HK, (int) HV, 1, nullptr, cs, 0);
|
||||
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);
|
||||
}
|
||||
} else
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
@@ -754,12 +802,18 @@ 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];
|
||||
const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err),
|
||||
// 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),
|
||||
*wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err),
|
||||
*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;
|
||||
*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;
|
||||
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;
|
||||
@@ -774,7 +828,8 @@ 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 (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 (!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);
|
||||
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);
|
||||
@@ -789,7 +844,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
|
||||
}
|
||||
stamp(l, 8, grp);
|
||||
if (batch_rec_) { // every slot's indexer tail, restored by its commit
|
||||
if (!has_idx) {}
|
||||
else 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);
|
||||
@@ -813,6 +869,7 @@ 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};
|
||||
@@ -831,9 +888,11 @@ 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;
|
||||
@@ -845,6 +904,7 @@ 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);
|
||||
@@ -852,6 +912,20 @@ 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];
|
||||
@@ -899,7 +973,15 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
return false;
|
||||
}
|
||||
stamp(l, 16, grp);
|
||||
gr_read_group(1, true, inj_, inj2_);
|
||||
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;
|
||||
}
|
||||
static const bool sh_stream_env = [] {
|
||||
const char* e = std::getenv("STRATA_SH_STREAM");
|
||||
return !e || e[0] != '0';
|
||||
@@ -998,7 +1080,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 && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
|
||||
const bool fuse_head_gr = fuse_head_gr_env && HC > 1 && (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;
|
||||
@@ -1091,7 +1173,15 @@ 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 (l == g.n_layers - 1) {
|
||||
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 (!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);
|
||||
@@ -1120,10 +1210,24 @@ 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 = 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) {
|
||||
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) {
|
||||
FusedGrArgs fa[kFusedGrMaxT];
|
||||
for (int t = 0; t < T; ++t) {
|
||||
FusedGrArgs& a = fa[t];
|
||||
@@ -1292,9 +1396,13 @@ 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, 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, g.gdn_gate(),
|
||||
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);
|
||||
@@ -1845,10 +1953,12 @@ 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, y_dummy_ + (size_t) t * ZV, (int) g.ssm_k_heads,
|
||||
(int) HV, 1, keep, cs_);
|
||||
(const float*) wnm->data, EPS, g.gdn_gate(), 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; }
|
||||
|
||||
@@ -230,12 +230,19 @@ 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, std::string& err) {
|
||||
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) {
|
||||
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;
|
||||
@@ -281,10 +288,11 @@ 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, H, FF, f, err)) return false;
|
||||
if (!native_fmt((int) gt, (int) dt, n_embd, n_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);
|
||||
" 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";
|
||||
return false;
|
||||
}
|
||||
if (ss >> go >> uo >> dox) { // v2 lines: the GGUF offsets
|
||||
|
||||
@@ -43,6 +43,11 @@ 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";
|
||||
|
||||
@@ -559,8 +559,12 @@ 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
|
||||
const int per = mode_ == 5 ? FF : H;
|
||||
// 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;
|
||||
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);
|
||||
@@ -696,16 +700,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 * FF;
|
||||
mrows_ = (int64_t) nb * f.n_ff; // the layer's widths (see run_phase mode 5 / 6), not FF / H
|
||||
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], 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], (int) f.n_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 * H;
|
||||
mrows_ = (int64_t) nb * f.n_embd;
|
||||
run_phase(6, mtasks_);
|
||||
const auto d = std::chrono::steady_clock::now();
|
||||
ms_multi_gu += std::chrono::duration<double, std::milli>(b - a).count();
|
||||
|
||||
@@ -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) {
|
||||
float* __restrict__ y, int h_k, int h_v, int silu) {
|
||||
__shared__ float sk[S], sq[S];
|
||||
__shared__ float red[RG][S];
|
||||
__shared__ float wsum[S * RG / 32];
|
||||
@@ -66,7 +66,9 @@ __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];
|
||||
y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,14 +150,15 @@ 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, float* y, int h_k, int h_v,
|
||||
void* stream) {
|
||||
const float* beta, const float* z, const float* gamma, float eps, GdnGate act, 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);
|
||||
gamma, eps, y, h_k, h_v,
|
||||
act == GdnGate::Silu ? 1 : 0);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e));
|
||||
|
||||
+11
-6
@@ -129,10 +129,11 @@ __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 * sigmoid(z), one warp per head, norm over that head's S values.
|
||||
/// 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))).
|
||||
__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) {
|
||||
float eps, int silu) {
|
||||
const int h = blockIdx.x;
|
||||
const float* po = o + (size_t) h * S;
|
||||
const float* pz = z + (size_t) h * S;
|
||||
@@ -144,8 +145,11 @@ __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)
|
||||
py[i] = po[i] * inv * ssm_norm[i] * sigmoid_f(pz[i]);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -233,9 +237,10 @@ 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, void* stream) {
|
||||
float eps, GdnGate act, 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);
|
||||
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);
|
||||
if (stream == nullptr) {
|
||||
const cudaError_t e = cudaDeviceSynchronize();
|
||||
if (e != cudaSuccess) {
|
||||
|
||||
@@ -309,8 +309,9 @@ __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.
|
||||
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2;
|
||||
// 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;
|
||||
|
||||
__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,
|
||||
@@ -415,6 +416,40 @@ __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
|
||||
@@ -513,6 +548,8 @@ 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;
|
||||
@@ -521,10 +558,13 @@ 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.
|
||||
#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)
|
||||
// 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)
|
||||
|
||||
__device__ __forceinline__ float warp_sum(float v) {
|
||||
#pragma unroll
|
||||
@@ -568,7 +608,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, 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, Q6_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;
|
||||
@@ -1588,6 +1628,23 @@ __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
|
||||
@@ -1654,6 +1711,7 @@ __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;
|
||||
@@ -1680,7 +1738,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 == 7 || t == 6 || t == 8;
|
||||
t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 8;
|
||||
}
|
||||
// values per block of the types the grouped expert kernels take (0 = none)
|
||||
int gu_qk(int t) {
|
||||
@@ -1791,6 +1849,7 @@ 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);
|
||||
|
||||
@@ -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) {
|
||||
const float* __restrict__ gamma, float* __restrict__ output, float epsilon, int silu) {
|
||||
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,9 +107,11 @@ __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.
|
||||
// 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))).
|
||||
const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]);
|
||||
output[offset + col] = weighted * sigmoid(z[offset + col]);
|
||||
const float zz = z[offset + col];
|
||||
output[offset + col] = weighted * (silu ? zz / (1.0f + expf(-zz)) : sigmoid(zz));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +186,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, void* stream) {
|
||||
float epsilon, GdnGate act, void* stream) {
|
||||
norm_geometry(heads, cols, epsilon, stream);
|
||||
const size_t bytes = size_t(heads) * S * sizeof(float);
|
||||
const Span writable{destination, bytes};
|
||||
@@ -193,7 +195,8 @@ 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);
|
||||
out_norm<<<unsigned(heads), 256, 0, static_cast<cudaStream_t>(stream)>>>(output, z, gamma, destination, epsilon,
|
||||
act == GdnGate::Silu ? 1 : 0);
|
||||
check_launch();
|
||||
}
|
||||
} // namespace strata::kernels
|
||||
+46
-26
@@ -88,29 +88,17 @@ 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) {
|
||||
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);
|
||||
char why[256];
|
||||
if (!qsa_shapes_valid(s, why, sizeof why)) {
|
||||
std::fprintf(stderr, "qsa: %s: %s\n", who, why);
|
||||
std::exit(1);
|
||||
}
|
||||
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);
|
||||
}
|
||||
/// 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);
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -607,7 +595,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(s, "qsa_index");
|
||||
validate_indexer(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
|
||||
@@ -621,7 +609,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(s, "topk_512");
|
||||
validate_indexer(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
|
||||
@@ -696,6 +684,38 @@ 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");
|
||||
@@ -722,7 +742,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(s, "indexer_key_append");
|
||||
validate_indexer(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)");
|
||||
@@ -740,7 +760,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(s, "qsa_index");
|
||||
validate_indexer(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.
|
||||
@@ -756,7 +776,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(s, "topk_512");
|
||||
validate_indexer(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",
|
||||
|
||||
+405
-149
@@ -9,15 +9,35 @@
|
||||
#include <cfloat>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
|
||||
namespace strata::kernels {
|
||||
namespace {
|
||||
|
||||
constexpr int HD = 256; // head_dim
|
||||
constexpr int G = 12; // query heads per KV head (24 / 2)
|
||||
constexpr int CHUNK = 64; // cells per block
|
||||
constexpr int CHUNK = 64; // cells per SUB-CHUNK: the unit of the score / softmax / value phases below
|
||||
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
|
||||
@@ -80,7 +100,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo
|
||||
} else load8_q4(p, value, row, d0, out);
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, int G>
|
||||
__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,
|
||||
@@ -89,94 +109,111 @@ __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;
|
||||
ids += (size_t) blockIdx.z * (size_t) cap;
|
||||
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;
|
||||
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads
|
||||
__shared__ __align__(16) float sq[G][HD]; // 12 KB at G 12: 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;
|
||||
const int c0 = chunk * CHUNK;
|
||||
const int n_here = min(CHUNK, n_ids - c0);
|
||||
// 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 slot = kvh * n_chunks + chunk;
|
||||
if (n_here <= 0) {
|
||||
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 < 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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
// 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.
|
||||
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 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;
|
||||
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;
|
||||
}
|
||||
__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) 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();
|
||||
// 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.
|
||||
#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]);
|
||||
}
|
||||
}
|
||||
__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];
|
||||
}
|
||||
@@ -237,21 +274,199 @@ __device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, i
|
||||
}
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, int G>
|
||||
__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)
|
||||
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;
|
||||
ids += (size_t) blockIdx.z * (size_t) cap;
|
||||
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;
|
||||
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads (dead once the scores are done)
|
||||
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__ 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
|
||||
@@ -273,7 +488,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float*
|
||||
if (t < CHUNK) {
|
||||
long long r = -1;
|
||||
if (t < n_here) {
|
||||
const int cell = ids[c0 + t];
|
||||
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.
|
||||
@@ -354,21 +569,25 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float*
|
||||
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.
|
||||
// values: thread t owns dimension t for all G heads.
|
||||
float acc[G];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
|
||||
// One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in
|
||||
// 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) {
|
||||
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]);
|
||||
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);
|
||||
@@ -390,8 +609,10 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float*
|
||||
#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,
|
||||
@@ -440,24 +661,21 @@ bool pre75_attn() {
|
||||
}
|
||||
return cc[dev] < 75;
|
||||
}
|
||||
#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)
|
||||
#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>)
|
||||
#else
|
||||
#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
|
||||
#define STRATA_ATTN_CHUNK(M, G) attn_chunk_kernel<M, G>
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
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));
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
// 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;
|
||||
@@ -465,71 +683,109 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
float* part_l = part_m + (size_t) n_chunks * s.n_head;
|
||||
const float scale = 1.0f / sqrtf((float) HD);
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
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);
|
||||
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)<<<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);
|
||||
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)<<<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);
|
||||
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)<<<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) {
|
||||
std::fprintf(stderr, "qsa_decode_attn_batch: %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
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);
|
||||
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 (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) {
|
||||
const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
|
||||
return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
|
||||
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);
|
||||
}
|
||||
|
||||
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) {
|
||||
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");
|
||||
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");
|
||||
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));
|
||||
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 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 cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "qsa_decode_attn: %s\n", cudaGetErrorString(e));
|
||||
std::fprintf(stderr, "qsa_identity_ids: %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,8 @@ namespace strata::kernels {
|
||||
namespace {
|
||||
|
||||
constexpr int HD = 256; // head_dim
|
||||
constexpr int G = 12; // query heads per KV head
|
||||
// `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.
|
||||
#ifndef D1_CH
|
||||
#define D1_CH 32
|
||||
#endif
|
||||
@@ -102,7 +103,7 @@ struct Smem {
|
||||
long long row[CH];
|
||||
};
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, int G>
|
||||
__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,
|
||||
@@ -114,7 +115,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;
|
||||
ids += (size_t) qi * cap;
|
||||
if (ids != nullptr) 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;
|
||||
@@ -149,7 +150,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[c0 + t];
|
||||
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t; // null ids: the identity (dense)
|
||||
const long long page = (long long) p.page_table[cell / page_size];
|
||||
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
}
|
||||
@@ -415,7 +416,8 @@ __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;
|
||||
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
|
||||
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);
|
||||
if (gid + 8 < G)
|
||||
*reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
|
||||
}
|
||||
@@ -460,6 +462,7 @@ __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,
|
||||
@@ -471,7 +474,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;
|
||||
ids += (size_t) qi * cap;
|
||||
if (ids != nullptr) 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;
|
||||
@@ -509,7 +512,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 ? __ldg(ids + c) : -1; };
|
||||
auto cell_of = [&](int c) -> int { return c < n ? (ids != nullptr ? __ldg(ids + c) : c) : -1; }; // null ids: identity
|
||||
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);
|
||||
@@ -669,12 +672,14 @@ __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;
|
||||
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
|
||||
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);
|
||||
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)
|
||||
@@ -683,7 +688,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, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
if (cudaFuncSetAttribute(prompt_attn_i8_kernel<G>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
@@ -693,8 +698,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<<<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,
|
||||
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,
|
||||
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
|
||||
}
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
@@ -705,7 +710,7 @@ bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, co
|
||||
return true;
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, int G>
|
||||
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
|
||||
@@ -714,7 +719,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>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE, G>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
@@ -724,8 +729,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><<<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,
|
||||
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,
|
||||
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
|
||||
}
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
@@ -789,7 +794,7 @@ struct Smem70 {
|
||||
long long row[CH];
|
||||
};
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, int G>
|
||||
__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,
|
||||
@@ -801,7 +806,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;
|
||||
ids += (size_t) qi * cap;
|
||||
if (ids != nullptr) 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
|
||||
@@ -842,7 +847,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[c0 + t];
|
||||
const int cell = ids != nullptr ? ids[c0 + t] : c0 + t; // null ids: the identity (dense)
|
||||
const long long page = (long long) p.page_table[cell / page_size];
|
||||
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
}
|
||||
@@ -1083,7 +1088,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
|
||||
}
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, int G>
|
||||
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] = {};
|
||||
@@ -1092,7 +1097,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>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE, G>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
@@ -1102,8 +1107,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><<<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,
|
||||
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,
|
||||
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
|
||||
}
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
@@ -1114,7 +1119,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>
|
||||
template <int KV_MODE, int G>
|
||||
bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*,
|
||||
int64_t, cudaStream_t) {
|
||||
return false;
|
||||
@@ -1169,6 +1174,7 @@ __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,
|
||||
@@ -1180,7 +1186,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;
|
||||
ids += (size_t) qi * cap;
|
||||
if (ids != nullptr) 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
|
||||
@@ -1230,7 +1236,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 = __ldg(ids + c0 + lane);
|
||||
const int cell = ids != nullptr ? __ldg(ids + c0 + lane) : c0 + lane; // null ids: the identity
|
||||
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);
|
||||
}
|
||||
@@ -1384,13 +1390,14 @@ 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<<<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,
|
||||
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,
|
||||
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
|
||||
}
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
@@ -1402,6 +1409,51 @@ 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,
|
||||
@@ -1434,46 +1486,14 @@ 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;
|
||||
}
|
||||
#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);
|
||||
// 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);
|
||||
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
|
||||
@@ -164,7 +164,8 @@ __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) {
|
||||
const int32_t* __restrict__ n_keep, int t_out_begin,
|
||||
int silu) {
|
||||
__shared__ float sk[S], sq[S];
|
||||
__shared__ float red[RG][S];
|
||||
__shared__ float wsum[S * RG / 32];
|
||||
@@ -224,7 +225,8 @@ __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];
|
||||
y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (n_keep != nullptr && n > 0) {
|
||||
@@ -471,7 +473,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, float* y, int h_k, int h_v, int n_tok,
|
||||
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) {
|
||||
if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 ||
|
||||
n_tok > kVerifyMaxT) {
|
||||
@@ -487,7 +489,8 @@ 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);
|
||||
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);
|
||||
}
|
||||
check("gdn_step_norm_multi");
|
||||
}
|
||||
|
||||
+330
-195
@@ -1,4 +1,5 @@
|
||||
// src/kernels/gdn_parity.cpp - P2.S2's test for the GDN recurrence, the conv and the two norms.
|
||||
// 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.
|
||||
//
|
||||
// `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
|
||||
@@ -15,10 +16,30 @@
|
||||
// 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>
|
||||
|
||||
@@ -32,6 +53,8 @@
|
||||
|
||||
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));
|
||||
@@ -40,11 +63,17 @@ 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.
|
||||
/// 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.
|
||||
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) {
|
||||
@@ -69,6 +98,19 @@ 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) {
|
||||
@@ -92,6 +134,241 @@ 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) {
|
||||
@@ -101,125 +378,19 @@ 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);
|
||||
int bad = 0;
|
||||
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");
|
||||
|
||||
// ================= 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);
|
||||
}
|
||||
// ================= 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;
|
||||
|
||||
// ================= 2. the conv =================
|
||||
{
|
||||
@@ -241,12 +412,6 @@ 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;
|
||||
@@ -273,29 +438,18 @@ 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;
|
||||
}
|
||||
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;
|
||||
std::printf("\n== the conv\n");
|
||||
observable("conv weight layout is observable", rel_l1(want, out_bad));
|
||||
}
|
||||
|
||||
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");
|
||||
float* d_cs = dev(cs, "cs");
|
||||
float* d_x = dev(x, "cx");
|
||||
float* d_w = dev(kW, "cw");
|
||||
float* d_o = nullptr;
|
||||
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);
|
||||
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; }
|
||||
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);
|
||||
cudaFree(d_cs); cudaFree(d_x); cudaFree(d_w); cudaFree(d_o);
|
||||
}
|
||||
|
||||
@@ -323,74 +477,55 @@ 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;
|
||||
}
|
||||
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;
|
||||
std::printf("\n== l2_norm\n");
|
||||
observable("eps on sum vs on mean is observable", rel_l1(x_ref, x_mean));
|
||||
|
||||
float* d_x = nullptr;
|
||||
check(cudaMalloc(&d_x, x.size() * 4), "lx");
|
||||
check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "lcx");
|
||||
float* d_x = dev(x, "lx");
|
||||
strata::kernels::gdn_l2_norm(d_x, rows, cols, eps, nullptr);
|
||||
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;
|
||||
within("l2_norm vs reference", rel_l1(x_ref, host(d_x, x.size(), "lcg")), 1e-6);
|
||||
cudaFree(d_x);
|
||||
}
|
||||
|
||||
// ================= 4. the closing norm =================
|
||||
// ================= 4. the closing norm on its own, both gates through both single-purpose kernels =================
|
||||
{
|
||||
const int S2 = 128, hv2 = 8;
|
||||
std::vector<float> o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) S2), y_ref((size_t) hv2 * S2);
|
||||
std::vector<float> o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) 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;
|
||||
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)]);
|
||||
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);
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -405,6 +405,7 @@ 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);
|
||||
|
||||
@@ -333,8 +333,18 @@ 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
|
||||
std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
|
||||
g_fail = 1;
|
||||
// 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;
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
k::fwht256_inplace_cuda(d_at4, QH, nullptr);
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways.
|
||||
//
|
||||
// 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 [--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 --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"
|
||||
@@ -26,6 +35,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -46,7 +56,26 @@ static double rel(const std::vector<float>& a, const std::vector<float>& b) {
|
||||
|
||||
namespace {
|
||||
constexpr int NT = 3, E = 7;
|
||||
constexpr int64_t H = 2560, FF = 640;
|
||||
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);
|
||||
}
|
||||
|
||||
// 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,
|
||||
@@ -303,9 +332,36 @@ 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);
|
||||
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);
|
||||
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)
|
||||
}
|
||||
{ // 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());
|
||||
@@ -367,10 +423,16 @@ 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);
|
||||
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");
|
||||
// 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");
|
||||
return failures + (ok ? 0 : 1);
|
||||
}
|
||||
|
||||
@@ -545,13 +607,22 @@ int main(int argc, char** argv) {
|
||||
int failures = 0;
|
||||
cudaStream_t s;
|
||||
cudaStreamCreate(&s);
|
||||
const std::string mode = argv[1];
|
||||
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);
|
||||
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 = 2; i < argc; ++i) {
|
||||
for (int i = ai + 1; 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));
|
||||
@@ -567,9 +638,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[1]));
|
||||
const strata::GgufModel model(strata::gguf_split_paths(argv[ai]));
|
||||
std::vector<int> layers;
|
||||
for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i]));
|
||||
for (int i = ai + 1; 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] = {};
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
// 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 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)
|
||||
//
|
||||
// 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),
|
||||
@@ -60,6 +62,7 @@ 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 "?";
|
||||
@@ -80,10 +83,11 @@ 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)
|
||||
const int e = (t == 12 || t == 13) ? 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; 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);
|
||||
const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));
|
||||
std::memcpy(&w[o], &h, 2);
|
||||
std::memcpy(&w[o + (t == 14 ? bs - 2 : 0)], &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));
|
||||
@@ -333,18 +337,64 @@ 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, 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
|
||||
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
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
// 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>
|
||||
@@ -116,51 +121,65 @@ 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
|
||||
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, 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);
|
||||
|
||||
// ---- 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);
|
||||
// ---- 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);
|
||||
|
||||
// ---- 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;
|
||||
// ---- 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;
|
||||
}
|
||||
}
|
||||
|
||||
std::printf("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n", bad, NT, NE,
|
||||
K);
|
||||
std::printf("\nrouter_top10: %d failures over 5 distributions x %d tokens at 512/10 and 256/8\n", bad, NT);
|
||||
if (bad) return 1;
|
||||
if (selftest) std::printf("router_top10_parity OK\n");
|
||||
return 0;
|
||||
|
||||
@@ -15,10 +15,13 @@
|
||||
// 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>
|
||||
|
||||
@@ -402,6 +405,194 @@ 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]`
|
||||
|
||||
+251
-43
@@ -1,23 +1,38 @@
|
||||
// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit and timed.
|
||||
// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit, against a reference, and timed.
|
||||
//
|
||||
// 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
|
||||
// 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
|
||||
// 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)
|
||||
// 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)
|
||||
// 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"
|
||||
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -27,9 +42,11 @@
|
||||
|
||||
namespace {
|
||||
|
||||
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 S = 128; // as kernels.cu: the head size (both models)
|
||||
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) {
|
||||
@@ -50,6 +67,7 @@ __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,
|
||||
@@ -146,11 +164,13 @@ __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, VPK = HV / HK; // tokens per staged block, value heads per key head
|
||||
constexpr int GDN_TB = 8; // tokens per staged block
|
||||
template <int HV, int HK, int C>
|
||||
__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];
|
||||
@@ -240,8 +260,10 @@ __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) {
|
||||
@@ -254,11 +276,12 @@ __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] * sigm(z[t * HV * S + head * S + col]);
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate<SILU>(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) {
|
||||
@@ -271,7 +294,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] * sigm(z[t * HV * S + head * S + col]);
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate<SILU>(z[t * HV * S + head * S + col]);
|
||||
y[at] = v;
|
||||
y16[at] = hf(v);
|
||||
}
|
||||
@@ -291,6 +314,7 @@ __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];
|
||||
@@ -388,6 +412,7 @@ 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;
|
||||
@@ -399,7 +424,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<<<dim3(2 * HK, (unsigned) T), S>>>(h, 1e-6f);
|
||||
l2_rows<C><<<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);
|
||||
@@ -412,15 +437,17 @@ struct Inputs {
|
||||
};
|
||||
|
||||
enum Rec { kBefore, kKeyHead, kRecCount };
|
||||
void run_rec(Rec v, float* state, const Inputs& in, float* oc, cudaStream_t s = 0) {
|
||||
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) {
|
||||
if (v == kBefore)
|
||||
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
|
||||
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);
|
||||
else
|
||||
gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
|
||||
gdn_rec_kh_kernel<HV, HK, C><<<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 in(T, seed);
|
||||
Inputs<HV, HK, C> 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];
|
||||
@@ -428,7 +455,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((Rec) v, state[v], in, oc[v]);
|
||||
run_rec<HV, HK, C>((Rec) v, state[v], in, oc[v]);
|
||||
}
|
||||
ck(cudaDeviceSynchronize(), "recurrence");
|
||||
int fails = 0;
|
||||
@@ -444,15 +471,16 @@ 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");
|
||||
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);
|
||||
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);
|
||||
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("T=%-6lld %s\n", (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)");
|
||||
std::printf("%d/%d/%d T=%-6lld %s\n", HV, HK, C, (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;
|
||||
@@ -463,8 +491,10 @@ 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) {
|
||||
Inputs in(T, 0xB3);
|
||||
constexpr bool SILU = HV == 32;
|
||||
Inputs<HV, HK, C> 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);
|
||||
@@ -487,7 +517,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(v, state, in, oc); });
|
||||
const float ms = timed([&] { run_rec<HV, HK, C>(v, state, in, oc); });
|
||||
if (i >= warm) t_rec[v].push_back(ms);
|
||||
}
|
||||
}
|
||||
@@ -495,22 +525,23 @@ 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<<<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 (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 (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 (48 value heads), medians of %d alternating runs:\n", (long long) T, rounds);
|
||||
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(" 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);
|
||||
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));
|
||||
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));
|
||||
cudaEventDestroy(e0);
|
||||
cudaEventDestroy(e1);
|
||||
cudaFree(state); cudaFree(oc); cudaFree(y16);
|
||||
@@ -523,15 +554,16 @@ 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, CB * RG, 0), "occupancy");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "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");
|
||||
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 in(T, 0xC7);
|
||||
Inputs<HV, HK, C> 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];
|
||||
@@ -559,9 +591,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<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
|
||||
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);
|
||||
else
|
||||
gdn_rec_kh_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
|
||||
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);
|
||||
cudaEventRecord(done[c], stream[c]);
|
||||
}
|
||||
for (int c = 1; c < n; ++c) cudaStreamWaitEvent(stream[0], done[c], 0);
|
||||
@@ -628,6 +660,7 @@ 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");
|
||||
@@ -642,13 +675,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), "attributes");
|
||||
ck(cudaFuncGetAttributes(&fa[kKeyHead], gdn_rec_kh_kernel), "attributes");
|
||||
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");
|
||||
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, CB * RG, 0), "occupancy");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "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");
|
||||
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);
|
||||
@@ -679,7 +712,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 in(T, 0xD5);
|
||||
Inputs<HV, HK, C> 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);
|
||||
@@ -783,7 +816,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(cs.v, state, in, oc, s_run);
|
||||
run_rec<HV, HK, C>(cs.v, state, in, oc, s_run);
|
||||
ck(cudaEventRecord(e1, s_run), "event");
|
||||
let_go(n);
|
||||
settle("fewer SMs");
|
||||
@@ -861,6 +894,165 @@ 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) {
|
||||
@@ -871,13 +1063,29 @@ 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(T, seed++);
|
||||
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++);
|
||||
if (do_bench) {
|
||||
std::printf("--bench: the prompt path's DeltaNet recurrence\n");
|
||||
bench(8192);
|
||||
bench(32768);
|
||||
bench<48, 16, 10240>(8192);
|
||||
bench<48, 16, 10240>(32768);
|
||||
bench<32, 16, 8192>(8192);
|
||||
bench<32, 16, 8192>(32768);
|
||||
scale(8192);
|
||||
fewer_sms(8192);
|
||||
}
|
||||
|
||||
+171
-65
@@ -15,8 +15,13 @@
|
||||
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, HK = 16, HV = 48, C = 10240;
|
||||
constexpr int S = 128;
|
||||
|
||||
__device__ __forceinline__ float warp_sum(float v) {
|
||||
#pragma unroll
|
||||
@@ -204,6 +209,11 @@ __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) {
|
||||
@@ -215,6 +225,7 @@ __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;
|
||||
@@ -233,6 +244,7 @@ __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;
|
||||
@@ -251,6 +263,7 @@ __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;
|
||||
@@ -261,8 +274,9 @@ __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 32 q/k heads, 128 threads
|
||||
// block (t, head) over the 2 * HK q/k heads, 128 threads
|
||||
const int64_t t = blockIdx.y;
|
||||
const int head = blockIdx.x;
|
||||
float* x = h + t * C + head * S;
|
||||
@@ -275,6 +289,7 @@ __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,
|
||||
@@ -321,7 +336,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 * sigm(z[t * HV * S + head * S + col]);
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * gdn_gate<SILU>(z[t * HV * S + head * S + col]);
|
||||
y[t * HV * S + head * S + col] = v;
|
||||
y16[t * HV * S + head * S + col] = hf(v);
|
||||
}
|
||||
@@ -335,6 +350,7 @@ __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,
|
||||
@@ -378,6 +394,7 @@ __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,
|
||||
@@ -475,11 +492,14 @@ __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, VPK = HV / HK; // tokens per staged block, value heads per key head
|
||||
constexpr int GDN_TB = 8; // tokens per staged block
|
||||
template <int HV, int HK, int C>
|
||||
__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];
|
||||
@@ -575,7 +595,8 @@ __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).
|
||||
// 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>
|
||||
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;
|
||||
@@ -586,7 +607,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, CB * RG, 0) ==
|
||||
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, gdn_rec_kh_kernel<HV, HK, C>, CB * RG, 0) ==
|
||||
cudaSuccess &&
|
||||
(int64_t) per_sm * sms >= (int64_t) HK * NCB;
|
||||
if (!yes) cudaGetLastError();
|
||||
@@ -597,6 +618,7 @@ 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) {
|
||||
@@ -609,14 +631,59 @@ __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] * sigm(z[t * HV * S + head * S + col]);
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * gdn_gate<SILU>(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) {
|
||||
int64_t T, int k) {
|
||||
const int64_t t = (int64_t) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
|
||||
if (t >= T) return;
|
||||
const int lane = threadIdx.x & 31;
|
||||
@@ -635,7 +702,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 < 10; ++rank) {
|
||||
for (int rank = 0; rank < k; ++rank) {
|
||||
float best = v[0];
|
||||
int ex = lane;
|
||||
#pragma unroll
|
||||
@@ -647,11 +714,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 * 10 + rank] = ex;
|
||||
if (lane == 0) ids[t * k + rank] = ex;
|
||||
if (rank == lane) selected = best;
|
||||
}
|
||||
selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f);
|
||||
if (lane < 10) wout[t * 10 + lane] = selected / selected_sum;
|
||||
if (lane < k) wout[t * k + 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>
|
||||
@@ -679,17 +746,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) {
|
||||
__global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t n, int64_t n_ff) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
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];
|
||||
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];
|
||||
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 * 640) return;
|
||||
if (i >= n) return;
|
||||
const float a = g[i];
|
||||
h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]);
|
||||
}
|
||||
@@ -701,15 +768,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) {
|
||||
const float* __restrict__ sg, float* __restrict__ bo, int64_t T, int64_t n, int k) {
|
||||
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;
|
||||
#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);
|
||||
for (int j = 0; j < k; ++j) s = fmaf(w[t * k + j], Dm[(int64_t) slot[t * k + j] * n + d], s);
|
||||
bo[i] = s + shared[i] * sigm(sg[t]);
|
||||
}
|
||||
|
||||
@@ -747,18 +814,19 @@ __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;
|
||||
}
|
||||
__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T) {
|
||||
// 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) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
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];
|
||||
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];
|
||||
}
|
||||
__global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16,
|
||||
int64_t T) {
|
||||
int64_t T, int64_t n_head) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
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]))));
|
||||
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]))));
|
||||
}
|
||||
|
||||
// one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is
|
||||
@@ -889,51 +957,88 @@ 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");
|
||||
}
|
||||
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);
|
||||
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);
|
||||
});
|
||||
check("gdn_gates");
|
||||
}
|
||||
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream) {
|
||||
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, const GdnGeom& g,
|
||||
void* stream) {
|
||||
static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr; // the old walk (A/B)
|
||||
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);
|
||||
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);
|
||||
});
|
||||
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, void* stream) {
|
||||
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, const GdnGeom& g, void* stream) {
|
||||
static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B)
|
||||
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; }();
|
||||
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 !defined(__HIPCC__)
|
||||
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);
|
||||
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);
|
||||
else
|
||||
#endif
|
||||
if (pipe) // the software-pipelined loads (same bits)
|
||||
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
|
||||
gdn_rec_cols_pipe_kernel<HV, HK, C><<<HV * NCB, dim3(CB, RG), 0, cs>>>(state, h, gate, beta, y, T);
|
||||
else
|
||||
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);
|
||||
}
|
||||
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);
|
||||
});
|
||||
check("gdn_recurrence");
|
||||
}
|
||||
void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {
|
||||
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);
|
||||
}
|
||||
if (n_expert == 512)
|
||||
route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);
|
||||
route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T, (int) k);
|
||||
else if (n_expert == 256)
|
||||
route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);
|
||||
route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T, (int) k);
|
||||
else
|
||||
strata::kernels::router_top10(logits, (int) T, (int) n_expert, 10, ids, weights, stream);
|
||||
strata::kernels::router_top10(logits, (int) T, (int) n_expert, (int) k, 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");
|
||||
@@ -942,13 +1047,14 @@ 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, void* stream) {
|
||||
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, int64_t n_ff, void* stream) {
|
||||
if (n <= 0) return;
|
||||
swiglu_il_kernel<<<blocks_for(n * 640), 256, 0, (cudaStream_t) stream>>>(gu, h16, n);
|
||||
swiglu_il_kernel<<<blocks_for(n * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h16, n, n_ff);
|
||||
check("swiglu_interleaved");
|
||||
}
|
||||
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);
|
||||
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);
|
||||
check("swiglu_pair");
|
||||
}
|
||||
namespace {
|
||||
@@ -982,8 +1088,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, void* stream) {
|
||||
moe_combine_kernel<<<blocks_for(T * N), 256, 0, (cudaStream_t) stream>>>(Dm, slot, w, shared, sg, bo, T);
|
||||
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);
|
||||
check("moe_combine");
|
||||
}
|
||||
void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) {
|
||||
@@ -1012,12 +1118,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, void* stream) {
|
||||
split_q_kernel<<<blocks_for(T * 24 * 256), 256, 0, (cudaStream_t) stream>>>(q_full, q, T);
|
||||
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);
|
||||
check("split_q");
|
||||
}
|
||||
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);
|
||||
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);
|
||||
check("gate_attn");
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,8 @@ 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)
|
||||
constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and of down (n_ff)
|
||||
// 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.
|
||||
|
||||
// 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,
|
||||
@@ -294,9 +295,11 @@ 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;
|
||||
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)
|
||||
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 BS = block_bytes(WT);
|
||||
constexpr bool K16 = per16(WT);
|
||||
extern __shared__ __align__(16) uint8_t smem[];
|
||||
@@ -349,7 +352,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 < GU_ROWS_K / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));
|
||||
if (dec && sb < n_embd / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));
|
||||
};
|
||||
if (GU) {
|
||||
#pragma unroll
|
||||
@@ -481,7 +484,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) * (10 * AB) + (blk >> 1) * AB;
|
||||
uint8_t* o = out + (size_t) (row0 + r) * (H_BLOCKS * 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);
|
||||
@@ -498,7 +501,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) * 2560 + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q];
|
||||
if (r < nrows) dm[(size_t) (row0 + r) * n_embd + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -620,8 +623,13 @@ 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);
|
||||
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);
|
||||
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);
|
||||
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;
|
||||
|
||||
@@ -116,6 +116,7 @@ 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:
|
||||
@@ -201,6 +202,7 @@ 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);
|
||||
|
||||
+413
-138
@@ -1,4 +1,5 @@
|
||||
// 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"
|
||||
@@ -87,8 +88,35 @@ namespace {
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
constexpr float EPS = 1e-6f;
|
||||
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;
|
||||
// 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;
|
||||
// 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())
|
||||
@@ -233,13 +261,25 @@ 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) { ok = false; return 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;
|
||||
}
|
||||
T* p = (T*) (base + used);
|
||||
used += bytes;
|
||||
return p;
|
||||
}
|
||||
void* p = nullptr;
|
||||
if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return 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;
|
||||
}
|
||||
owned->push_back(p);
|
||||
used += bytes;
|
||||
return (T*) p;
|
||||
@@ -394,7 +434,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 / 16 + 2;
|
||||
static constexpr int kGrpEv = NE_MAX / 16 + 2; // sized for the largest pack; a smaller one uses fewer
|
||||
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;
|
||||
@@ -443,7 +483,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 + NE / 16 + 2) + 64;
|
||||
static constexpr size_t kHostBounds = 2 * (NE_MAX + NE_MAX / 16 + 2) + 64;
|
||||
int64_t back_at = 0, back_rows = 0;
|
||||
std::vector<int32_t> bounds_host;
|
||||
std::vector<void*> owned;
|
||||
@@ -478,6 +518,7 @@ 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;
|
||||
@@ -572,6 +613,7 @@ 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;
|
||||
@@ -637,22 +679,40 @@ 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) {
|
||||
uint64_t gdn_set_bytes(size_t T, const Geom& G) {
|
||||
const int64_t C = G.c, ZV = G.zv, HV = G.hv;
|
||||
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 strata::kernels::QsaShapes& s, const Geom& G) {
|
||||
Alloc a; a.count_only = true; bool ok = true;
|
||||
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>(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>((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).
|
||||
@@ -677,12 +737,15 @@ 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;
|
||||
// #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; }
|
||||
// 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; }
|
||||
p.layer[(size_t) l] = 1;
|
||||
p.any = true;
|
||||
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));
|
||||
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));
|
||||
}
|
||||
return p;
|
||||
}();
|
||||
@@ -700,25 +763,27 @@ 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, 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)};
|
||||
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)};
|
||||
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 * 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),
|
||||
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),
|
||||
std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)),
|
||||
mmq::q8_bytes((int64_t) (ts * K), 640)};
|
||||
mmq::q8_bytes((int64_t) (ts * K), FF)};
|
||||
}
|
||||
uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
|
||||
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;
|
||||
const MmqPlan& mp = mmq_plan();
|
||||
const MoeBufs mb = moe_bufs(T, n_expert, fused);
|
||||
const MoeBufs mb = moe_bufs(T, G, fused);
|
||||
Alloc a; a.count_only = true; bool ok = true;
|
||||
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<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<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 * 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.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.any) {
|
||||
a.take<uint8_t>(mb.xq, ok);
|
||||
a.take<float>(mb.h, ok);
|
||||
@@ -734,8 +799,38 @@ 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_;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
cudaGetDevice(&m.device);
|
||||
if (stage_le_ < 0) stage_le_ = g.n_layers;
|
||||
@@ -813,7 +908,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_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table
|
||||
if (ss.qsa_alloc > 0 && 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;
|
||||
@@ -848,28 +943,30 @@ 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_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.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.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 (bf16x2_hc()) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, 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()) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);
|
||||
m.steps_dev = o.take<int32_t>(T * strata::kernels::kStepCount, 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;
|
||||
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;
|
||||
const strata::kernels::QsaShapes s = shapes_of(g);
|
||||
m.cap = selection_cap(ss, s);
|
||||
m.max_blocks = primary_cells(ss) / 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, 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)});
|
||||
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)});
|
||||
uint8_t* base = o.take<uint8_t>((size_t) region, ok);
|
||||
m.region = base;
|
||||
m.region_bytes = region;
|
||||
@@ -880,22 +977,24 @@ 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 * 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.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.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 * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
|
||||
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.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 * 640, ok) : nullptr;
|
||||
m.Hh = mp.fallback ? c.take<uint16_t>(T * K * G.ff, ok) : nullptr;
|
||||
m.Dm = c.take<float>(T * K * N, 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.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.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);
|
||||
@@ -904,11 +1003,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>(1280 * 2560, ok); m.dq_d[i] = o.take<uint16_t>(2560 * 640, ok); }
|
||||
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); }
|
||||
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 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok);
|
||||
m.bounds_dev = o.take<int32_t>((size_t) (2 * (G.ne + G.ne / 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
|
||||
@@ -921,8 +1020,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 = o.take<float>(T * N, ok);
|
||||
m.ple_norm = o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok);
|
||||
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;
|
||||
take_stage(o, ss, s, m.stage, ok);
|
||||
m.T = (int64_t) T;
|
||||
return ok;
|
||||
@@ -965,13 +1064,140 @@ 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;
|
||||
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;
|
||||
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");
|
||||
@@ -993,9 +1219,6 @@ 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);
|
||||
@@ -1026,15 +1249,12 @@ 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();
|
||||
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 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>();
|
||||
@@ -1202,6 +1422,7 @@ 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
|
||||
@@ -1254,6 +1475,8 @@ 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));
|
||||
@@ -1291,9 +1514,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, 640));
|
||||
pp->GU_g = (float*) take((size_t) Gr * 1280 * 4);
|
||||
pp->H_g = (float*) take((size_t) Gr * 640 * 4);
|
||||
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->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;
|
||||
@@ -1317,9 +1540,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, 640));
|
||||
pp->GU = (float*) take((size_t) R * 1280 * 4);
|
||||
pp->H = (float*) take((size_t) R * 640 * 4);
|
||||
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->Dm = (float*) take((size_t) R * N * 4);
|
||||
}
|
||||
const int64_t Rt = pp->cap_rows;
|
||||
@@ -1358,6 +1581,9 @@ 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;
|
||||
@@ -1369,26 +1595,25 @@ 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.
|
||||
if (ring_bytes_on()) {
|
||||
// The plain block (hc 1) has none of the hyper-connection's buffers.
|
||||
if (ring_bytes_on() || !gr) {
|
||||
f(T * N); f(T * D);
|
||||
if (gr_unfused()) f(T * D);
|
||||
f(T * HC);
|
||||
if (gr && gr_unfused()) f(T * D);
|
||||
if (gr) f(T * HC);
|
||||
} else { // STRATA_RING_BYTES=0: 0.1.39's count
|
||||
f(T * N); f(T * D); f(T * D);
|
||||
}
|
||||
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 (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); }
|
||||
if (bf16x2()) o.take<uint16_t>(T * N, ok);
|
||||
o.take<int32_t>(T * strata::kernels::kStepCount, 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); }
|
||||
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); }
|
||||
if (mmq_plan().any) {
|
||||
const MmqPlan& mp = mmq_plan();
|
||||
o.take<int32_t>(T * K, ok);
|
||||
@@ -1397,8 +1622,10 @@ 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);
|
||||
f(T * N);
|
||||
f((size_t) strata::kernels::NG_HC_DIM);
|
||||
if (g.has_ple) {
|
||||
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
|
||||
@@ -1548,14 +1775,16 @@ 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
|
||||
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 strata::kernels::QsaShapes s = shapes_of(g);
|
||||
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]};
|
||||
@@ -1676,7 +1905,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs);
|
||||
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);
|
||||
}
|
||||
// ---- 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)
|
||||
@@ -1716,6 +1948,7 @@ 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);
|
||||
@@ -1973,7 +2206,20 @@ 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",
|
||||
@@ -1992,6 +2238,7 @@ 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 =======================
|
||||
@@ -2009,32 +2256,39 @@ 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, m.cs);
|
||||
gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs);
|
||||
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);
|
||||
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, m.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);
|
||||
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),
|
||||
*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;
|
||||
*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;
|
||||
}
|
||||
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 (!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);
|
||||
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);
|
||||
// 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;
|
||||
@@ -2083,10 +2337,18 @@ 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, 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);
|
||||
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) {
|
||||
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:
|
||||
@@ -2211,6 +2473,7 @@ 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);
|
||||
@@ -2223,13 +2486,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 * ZV, pools, m.sel_ids + t0 * m.cap,
|
||||
strata::kernels::qsa_decode_attn_batch(m.q + t0 * G.av, pools, m.sel_ids ? m.sel_ids + t0 * m.cap : nullptr,
|
||||
m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,
|
||||
s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);
|
||||
s, m.attn_scratch, m.attn + t0 * G.av, nb, m.cs);
|
||||
}
|
||||
if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);
|
||||
if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * G.nh, m.cs);
|
||||
pt.mark(kPfQsa, cs);
|
||||
gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs);
|
||||
gate_attn(m.attn, m.Qf, m.attn_h, T, G.nh, 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 {
|
||||
@@ -2242,11 +2505,12 @@ 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, m.cs);
|
||||
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
|
||||
// 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, m.cs);
|
||||
swiglu_pair(m.sgate, m.sup, m.sh_h, T, G.ffs, 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);
|
||||
@@ -2312,7 +2576,8 @@ 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};
|
||||
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};
|
||||
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 {
|
||||
@@ -2408,8 +2673,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, 1280, N) : 0;
|
||||
const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;
|
||||
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;
|
||||
pt.mark(kPfGather, cs);
|
||||
if (use_mmq) {
|
||||
// step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
|
||||
@@ -2532,16 +2797,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 = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
|
||||
gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; 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 = 1280;
|
||||
gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = G.ff2;
|
||||
P.run_ctx->run(gu, 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);
|
||||
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);
|
||||
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 = 640; dn.expert_bytes = mmq_db;
|
||||
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; 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;
|
||||
@@ -2593,14 +2858,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 = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
|
||||
gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; 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 = 1280;
|
||||
gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = G.ff2;
|
||||
P.run_ctx->run(gu, 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::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::Product dn;
|
||||
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
|
||||
dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; 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;
|
||||
@@ -2761,15 +3026,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 = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
|
||||
gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = G.ff2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
|
||||
gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
|
||||
gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
|
||||
gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = G.ff2;
|
||||
m.mmq_ctx->run(gu, m.cs);
|
||||
mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
|
||||
mmq::swiglu(m.GU + r0 * G.ff2, m.H + r0 * G.ff, nr, G.ff, !lay.native, m.cs);
|
||||
pt.mark(kPfGemmD, cs);
|
||||
mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs);
|
||||
mmq::quantize(m.H + r0 * G.ff, nullptr, m.Hq, mmq_dt, G.ff, G.ff, nr, m.cs);
|
||||
mmq::Product dn;
|
||||
dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
|
||||
dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = G.ff; 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;
|
||||
@@ -2789,10 +3054,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 * 1280, ne, 1280, N);
|
||||
swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.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);
|
||||
pt.mark(kPfGemmD, cs);
|
||||
m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640);
|
||||
m.gemm.f16(m.Hh + o0 * G.ff, m.dq_d[q], m.Dm + o0 * N, ne, N, G.ff);
|
||||
return true;
|
||||
};
|
||||
if (!stream_all) {
|
||||
@@ -2860,7 +3125,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, m.cs);
|
||||
moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, N, K, 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);
|
||||
@@ -2872,9 +3137,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 * 1280), bdm = bad(m.Dm, T * K * N),
|
||||
const int64_t bgu = fused_l ? 0 : bad(m.GU, T * K * G.ff2), 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 * 640) : -1;
|
||||
const int64_t bh = m.H && !fused_l ? bad(m.H, T * K * G.ff) : -1;
|
||||
static int64_t reported = -1;
|
||||
if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) {
|
||||
reported = stats_.chunks;
|
||||
@@ -2885,6 +3150,14 @@ 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)
|
||||
@@ -2904,8 +3177,10 @@ 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
|
||||
|
||||
+517
-52
@@ -27,6 +27,8 @@
|
||||
#include "strata/core/peer_experts.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/core/model_geometry.hpp"
|
||||
#include "strata/plan/vram_plan.hpp"
|
||||
#include "strata/core/session.hpp"
|
||||
#include "strata/core/weights.hpp"
|
||||
#include "strata/kernels/cpu/expert.hpp"
|
||||
@@ -116,11 +118,31 @@ bool under_wddm() {
|
||||
#endif
|
||||
}
|
||||
|
||||
// --vram-cap MIB (Qwen3.6 port, step 2; Maya's STRATA_GLM_VRAM_GB idea): the engine limits its own VRAM to a smaller
|
||||
// card's, so the 1080 Ti emulates the 6 and 8 GB rungs and a 48 GB card the 12, 16 and 32 GB ones. Two halves: every
|
||||
// free figure the planners read is clamped to `cap - used` here (so the expert cache is sized as the smaller card
|
||||
// would size it), and a blocker of `total - cap` is allocated at start (main, before the weight arena), so the driver
|
||||
// is under the pressure the real card would be under. 0 = no cap.
|
||||
int64_t g_vram_cap_bytes = 0;
|
||||
uint64_t g_vram_blocker_bytes = 0; // the blocker's own allocation, which `used` below must not count twice
|
||||
cudaError_t vram_info(size_t* free_b, size_t* total_b) {
|
||||
const cudaError_t e = cudaMemGetInfo(free_b, total_b);
|
||||
if (e == cudaSuccess && g_vram_cap_bytes > 0 && *total_b > 0) {
|
||||
// this process AND every other one, minus the blocker: the blocker already took `total - cap` out of
|
||||
// `free`, so counting it in `used` as well subtracted it twice (room went negative at --vram-cap 5722)
|
||||
const uint64_t all = *total_b > *free_b ? *total_b - *free_b : 0;
|
||||
const uint64_t used = all > g_vram_blocker_bytes ? all - g_vram_blocker_bytes : 0;
|
||||
const uint64_t room = (uint64_t) g_vram_cap_bytes > used ? (uint64_t) g_vram_cap_bytes - used : 0;
|
||||
if (*free_b > room) *free_b = (size_t) room;
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
// #620 #486: " (N MiB of M MiB VRAM free on this GPU)" for an allocation's failure message (clears the error first)
|
||||
std::string vram_free_note() {
|
||||
(void) cudaGetLastError();
|
||||
size_t free_b = 0, total_b = 0;
|
||||
if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) {
|
||||
if (vram_info(&free_b, &total_b) != cudaSuccess) {
|
||||
(void) cudaGetLastError();
|
||||
return {};
|
||||
}
|
||||
@@ -423,6 +445,10 @@ struct Options {
|
||||
/// and the KV state, minus this reserve for the graphs, the hit scratch and the head.
|
||||
int vram_reserve_mib = 700;
|
||||
bool vram_reserve_given = false; ///< --vram-reserve-mib on the command line (#496: no smaller automatic reserve)
|
||||
/// Qwen3.6 port, step 2 (docs/QWEN36-35B-A3B.md 4.2 item 4): --vram-cap MIB limits this engine's VRAM to a smaller
|
||||
/// card's (the free figures clamped, a blocker allocated); --ram-cap GIB bounds the RAM tier and the pinned arena.
|
||||
int64_t vram_cap_mib = 0;
|
||||
double ram_cap_gib = 0.0;
|
||||
/// #533 (opt-in): the expert cache in physical segments (CUDA virtual memory management), so the serve loop's
|
||||
/// `VRAM <reserve_mib>` command can give part of it back to other programs and take it again. Off: one cudaMalloc.
|
||||
bool vram_elastic = false;
|
||||
@@ -462,6 +488,11 @@ struct Options {
|
||||
int batch_groups = 1;
|
||||
std::string spec_oracle;
|
||||
int spec_corrupt = 0;
|
||||
/// Qwen3.6 step 4 (docs/qwen36-port/step4-runner.md): with --spec-oracle, every window row is committed and the
|
||||
/// next window starts from the oracle's own token, so the engine is held to a reference continuation (llama.cpp's
|
||||
/// greedy text) position by position; `produced` keeps the engine's picks and --dump-logits writes one row per
|
||||
/// position. Without it the oracle only drafts.
|
||||
bool teacher_force = false;
|
||||
/// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it.
|
||||
std::string mtp;
|
||||
int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell)
|
||||
@@ -617,6 +648,10 @@ void usage() {
|
||||
" --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n"
|
||||
" --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n"
|
||||
" --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n"
|
||||
" --vram-cap MIB emulate a smaller card: this engine uses at most MIB of VRAM (the free figures it\n"
|
||||
" plans from are clamped and a blocker holds the rest), so a 1080 Ti can be run\n"
|
||||
" as a 6 GB card (5722) or an A6000 as a 16 GB one (15258)\n"
|
||||
" --ram-cap GIB bound the RAM expert tier (--resident-*) and the pinned arena to GIB\n"
|
||||
" --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n"
|
||||
" default 512), so the command `VRAM <reserve_mib>` (the server's POST /v1/vram) can\n"
|
||||
" give VRAM back to other programs between requests and take it back later\n"
|
||||
@@ -633,6 +668,9 @@ void usage() {
|
||||
" --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n"
|
||||
" when it pays (default 3; 0 = MTP only)\n"
|
||||
" --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n"
|
||||
" --teacher-force with --spec-oracle FILE: hold the engine to that continuation (every window row\n"
|
||||
" committed, the next window from the oracle's token); --dump-logits then writes\n"
|
||||
" one row per position, and `produced` is what the engine would have picked\n"
|
||||
" --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n"
|
||||
" format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n"
|
||||
" --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n"
|
||||
@@ -748,6 +786,7 @@ struct Drive {
|
||||
/// needs no locking. `d.layers` is the CURRENT layer on entry (the adapter increments it as it walks the
|
||||
/// blob), which is why the layer index comes from there rather than from a counter of our own.
|
||||
std::FILE* routing = nullptr;
|
||||
int32_t n_layers = 48; ///< the trace's layer bound, from the model's geometry (48 was Flash-Next's literal)
|
||||
};
|
||||
|
||||
void drive_pool(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, int64_t k,
|
||||
@@ -768,8 +807,9 @@ void drive_pool(void* user, const float* x_f, const int32_t* ids, const float* w
|
||||
// unaffected - it is a per-layer split, and shifting every layer by one preserves both metrics - but
|
||||
// anything keyed on the layer index, which is exactly what a cache profile is, would have been wrong.
|
||||
const int32_t layer_idx = (int32_t) (t->d.layers - 1);
|
||||
if (layer_idx < 0 || layer_idx >= 48) {
|
||||
std::fprintf(stderr, "strata generate: the routing trace saw layer %d, outside 0..47\n", layer_idx);
|
||||
if (layer_idx < 0 || layer_idx >= t->n_layers) {
|
||||
std::fprintf(stderr, "strata generate: the routing trace saw layer %d, outside 0..%d\n", layer_idx,
|
||||
t->n_layers - 1);
|
||||
return;
|
||||
}
|
||||
const int32_t rec[2] = {layer_idx, (int32_t) k};
|
||||
@@ -792,7 +832,7 @@ void drive_pool_multi(void* user, const float* x_f, const int32_t* ids, int64_t
|
||||
// one record per token. The multi dispatch fuses the router weights into the kernel and does not surface
|
||||
// them, so records carry unit weights: tools/make_profile.py ranks pairs by routed frequency, which is the
|
||||
// signal that matters; a one-shot --dump-routing run records true weights if a weighted ranking is wanted.
|
||||
if (t->routing != nullptr && layer >= 0 && layer < 48) {
|
||||
if (t->routing != nullptr && layer >= 0 && layer < t->n_layers) {
|
||||
for (int64_t tok = 0; tok < n_tok; ++tok) {
|
||||
const int32_t rec[2] = {(int32_t) layer, (int32_t) k};
|
||||
std::fwrite(rec, sizeof rec, 1, t->routing);
|
||||
@@ -1019,7 +1059,7 @@ void mem_mark(const char* where) {
|
||||
static const bool on = std::getenv("STRATA_TRACE") != nullptr;
|
||||
if (!on) return;
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where);
|
||||
}
|
||||
|
||||
@@ -1389,6 +1429,14 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--expert-cache-remote-placement")
|
||||
o.expert_cache_remote_placement = next("--expert-cache-remote-placement");
|
||||
else if (a == "--vram-reserve-mib") { o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); o.vram_reserve_given = true; }
|
||||
else if (a == "--vram-cap") {
|
||||
o.vram_cap_mib = std::atoll(next("--vram-cap"));
|
||||
if (o.vram_cap_mib <= 0) { std::fprintf(stderr, "strata generate: --vram-cap needs MiB > 0\n"); return 2; }
|
||||
}
|
||||
else if (a == "--ram-cap") {
|
||||
o.ram_cap_gib = std::atof(next("--ram-cap"));
|
||||
if (!(o.ram_cap_gib > 0.0)) { std::fprintf(stderr, "strata generate: --ram-cap needs GiB > 0\n"); return 2; }
|
||||
}
|
||||
else if (a == "--prefill") {
|
||||
const std::string v = next("--prefill");
|
||||
o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0;
|
||||
@@ -1411,6 +1459,7 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--trim-stage-weights") o.trim_stage_weights = true;
|
||||
else if (a == "--batch-groups") o.batch_groups = std::atoi(next("--batch-groups"));
|
||||
else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle");
|
||||
else if (a == "--teacher-force") o.teacher_force = true;
|
||||
else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt"));
|
||||
else if (a == "--mtp") o.mtp = next("--mtp");
|
||||
else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));
|
||||
@@ -1808,7 +1857,24 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what());
|
||||
return 2;
|
||||
}
|
||||
if (o.no_ple || o.ple_gguf.empty()) {
|
||||
// Qwen3.6 port, step 2 (docs/QWEN36-35B-A3B.md 3.9): the kernels always ran without a PLE (`block_layer_pre`
|
||||
// applies it only when a table is ready); the CLI did not. A model whose architecture has no per-layer token
|
||||
// embedding (qwen35moe) starts without --ple-gguf, with no PLE kernels selected and no PLE session state.
|
||||
bool model_has_ple = true;
|
||||
{
|
||||
strata::core::ModelGeometry mg;
|
||||
std::string gerr;
|
||||
if (strata::core::read_model_geometry(o.native_shards.front(), mg, gerr)) model_has_ple = mg.has_ple;
|
||||
// an unreadable geometry is reported below, where the file is read for every field
|
||||
}
|
||||
if (!model_has_ple) {
|
||||
if (!o.ple_gguf.empty()) {
|
||||
std::fprintf(stderr, "strata generate: --ple-gguf %s: this model (%s) has no per-layer token embedding; "
|
||||
"the flag does not apply to it\n", o.ple_gguf.c_str(), o.native_preset.c_str());
|
||||
return 2;
|
||||
}
|
||||
o.no_ple = true;
|
||||
} else if (o.no_ple || o.ple_gguf.empty()) {
|
||||
std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too), and no "
|
||||
"shard of the model holds per_layer_token_embd.weight\n");
|
||||
return 2;
|
||||
@@ -1816,8 +1882,9 @@ int main(int argc, char** argv) {
|
||||
o.stream_token = true;
|
||||
o.gr_native_mmvf = true;
|
||||
o.native_bf16 = o.native_bf16_extra = true;
|
||||
o.native_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true;
|
||||
o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true;
|
||||
o.native_moe_combine = o.native_gdn = o.native_router = true;
|
||||
o.native_qsa = o.native_qsa_indexer = o.native_rope = true;
|
||||
o.native_ple_key = o.native_ple_postops = model_has_ple;
|
||||
if (o.native_head_gguf.empty()) o.native_head_gguf = o.native_preset;
|
||||
if (o.native_dense_gguf.empty()) {
|
||||
// every shard of the model (<name>-0000N-of-0000M.gguf beside --native), then the PLE shard: a split
|
||||
@@ -1829,7 +1896,7 @@ int main(int argc, char** argv) {
|
||||
strata::GgufFile pg(o.ple_gguf);
|
||||
if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple";
|
||||
} catch (const std::exception&) {}
|
||||
if (!ple_only &&
|
||||
if (!ple_only && !o.ple_gguf.empty() &&
|
||||
std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end())
|
||||
o.native_dense_gguf.push_back(o.ple_gguf);
|
||||
}
|
||||
@@ -1840,6 +1907,17 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "strata generate: --logits-stride > 1 requires --max-new 1 and --dump-logits\n");
|
||||
return 2;
|
||||
}
|
||||
if (o.teacher_force && (o.spec_oracle.empty() || o.serve)) {
|
||||
std::fprintf(stderr, "strata generate: --teacher-force needs --spec-oracle FILE (the continuation to hold the "
|
||||
"engine to) and is not a --serve mode\n");
|
||||
return 2;
|
||||
}
|
||||
if (o.teacher_force && !o.mtp.empty()) {
|
||||
// the window's rows after the first would be the drafter's guesses, and teacher forcing commits every row:
|
||||
// the state then holds tokens the oracle never had (seen as 70 of 400 top-1 on a run that is 394 without)
|
||||
std::fprintf(stderr, "strata generate: --teacher-force takes its window rows from --spec-oracle; drop --mtp\n");
|
||||
return 2;
|
||||
}
|
||||
if (o.no_ple && !o.ple_gguf.empty()) {
|
||||
std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n");
|
||||
return 2;
|
||||
@@ -2002,15 +2080,253 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "--native-head-gguf requires --stream-token\n");
|
||||
return 2;
|
||||
}
|
||||
// THE GEOMETRY, FROM THE MODEL FILE, BEFORE ANYTHING IS SIZED BY IT (Qwen3.6 port, step 2; docs/QWEN36-35B-A3B.md
|
||||
// 3.8). With --native the file is the authority on every field (strata/core/model_geometry.hpp reads the
|
||||
// `<arch>.*` keys of the metadata shard; a pruned GSQ-RCO Coder's 256 experts, Qwen3.6's 2048 x 40 x 256 x top-8);
|
||||
// without it the canonical Flash-Next defaults stand, as they always did for the Q2_0 pack. `K` is the router's
|
||||
// k from the same place. Until this step only `expert_count` and `expert_used_count` were read, and after the
|
||||
// expert layout below had already been checked against the defaults (geometry-inventory.md rows 7 to 10).
|
||||
strata::core::ModelGeometry g;
|
||||
if (!o.native_preset.empty()) {
|
||||
if (!strata::core::read_model_geometry(o.native_shards.front(), g, err)) {
|
||||
std::fprintf(stderr, "strata generate: reading the model's geometry from %s: %s\n",
|
||||
o.native_preset.c_str(), err.c_str());
|
||||
return 1;
|
||||
}
|
||||
if (g.arch != strata::core::ModelArch::Qwen4Exp)
|
||||
std::fprintf(stderr, "strata generate: model geometry (%s, from the file's metadata):\n%s",
|
||||
o.native_preset.c_str(), strata::core::model_geometry_text(g).c_str());
|
||||
// KV streaming is a lever only for selected attention: with no indexer every cell is read every token
|
||||
// (qsa_state_init refuses as the backstop; this names it before any weight moves)
|
||||
if (o.kv_resident > 0 && !strata::core::qsa_kv_streaming_applies(g, err)) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
// the fused tensor layouts llama.cpp accepts and this engine refuses by name (no shipped file uses them)
|
||||
try {
|
||||
const strata::GgufModel model(o.native_shards);
|
||||
if (!strata::core::check_model_tensor_forms(model, g, err)) {
|
||||
std::fprintf(stderr, "strata generate: %s: %s\n", o.native_preset.c_str(), err.c_str());
|
||||
return 1;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
int64_t K = g.n_expert_used;
|
||||
// Plan v0.3 P6: where the experts live. A native pack (tools/iq_pack.py: the IQ2_XS / IQ3_XXS files) keeps
|
||||
// every quantized tensor in its GGUF form, so it needs --native (the dense projections, head and embedding
|
||||
// come from the model file) and runs its experts in verify windows only (--spec).
|
||||
{
|
||||
const strata::core::ModelGeometry g0;
|
||||
if (!strata::kernels::cpu::expert_layout_load(o.pack, g0.n_layers, g0.n_expert, err)) {
|
||||
if (!strata::kernels::cpu::expert_layout_load(o.pack, g.n_layers, g.n_expert, g.n_embd, g.n_ff, err)) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
const bool native_pack = strata::kernels::cpu::expert_layout().native;
|
||||
// --vram-cap: the blocker, allocated before anything else of this engine is, so every later figure (and the
|
||||
// driver's own pressure) is the smaller card's. `vram_info` clamps the free figures from here on.
|
||||
if (o.vram_cap_mib > 0) {
|
||||
size_t free_b = 0, total_b = 0;
|
||||
if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) {
|
||||
std::fprintf(stderr, "strata generate: --vram-cap: cudaMemGetInfo failed: %s\n", cudaGetErrorString(cudaGetLastError()));
|
||||
return 1;
|
||||
}
|
||||
const uint64_t cap = (uint64_t) o.vram_cap_mib << 20;
|
||||
const uint64_t used = total_b - free_b;
|
||||
if (cap >= total_b) {
|
||||
std::fprintf(stderr, "strata generate: --vram-cap %lld MiB is not below this card's %llu MiB: no cap\n",
|
||||
(long long) o.vram_cap_mib, (unsigned long long) (total_b >> 20));
|
||||
} else {
|
||||
void* blocker = nullptr;
|
||||
const uint64_t hold = total_b - cap; // what a card of `cap` would not have
|
||||
if (hold > free_b || cudaMalloc(&blocker, (size_t) hold) != cudaSuccess) {
|
||||
(void) cudaGetLastError();
|
||||
std::fprintf(stderr, "strata generate: --vram-cap %lld MiB: cannot hold back %llu MiB of this card's %llu "
|
||||
"(%llu MiB free, %llu used by other programs)\n", (long long) o.vram_cap_mib,
|
||||
(unsigned long long) (hold >> 20), (unsigned long long) (total_b >> 20),
|
||||
(unsigned long long) (free_b >> 20), (unsigned long long) (used >> 20));
|
||||
return 1;
|
||||
}
|
||||
g_vram_cap_bytes = (int64_t) cap;
|
||||
g_vram_blocker_bytes = hold;
|
||||
size_t f2 = 0, t2 = 0;
|
||||
vram_info(&f2, &t2);
|
||||
// what a card of `cap` would show free with the same other programs on it; the driver may round the
|
||||
// blocker up by a few MiB, so the figure is a bound, not an identity
|
||||
const uint64_t expect = cap > used ? cap - used : 0;
|
||||
std::fprintf(stderr, "strata generate: --vram-cap %lld MiB: %llu MiB of this %llu MiB card held back; %llu MiB "
|
||||
"free to this engine (the other %llu MiB were in use before it started; a %llu MiB card "
|
||||
"would show %llu)\n",
|
||||
(long long) o.vram_cap_mib, (unsigned long long) (hold >> 20), (unsigned long long) (total_b >> 20),
|
||||
(unsigned long long) (f2 >> 20), (unsigned long long) (used >> 20), (unsigned long long) (cap >> 20),
|
||||
(unsigned long long) (expect >> 20));
|
||||
if (f2 > expect || expect - f2 > (64ull << 20)) {
|
||||
std::fprintf(stderr, "strata generate: --vram-cap: the free figure after the blocker is %llu MiB, not the "
|
||||
"%llu MiB a card of the cap would have: the clamp is wrong\n",
|
||||
(unsigned long long) (f2 >> 20), (unsigned long long) (expect >> 20));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// --ram-cap: the RAM tier (--resident-*) and the pinned arena see at most this much host memory
|
||||
if (o.ram_cap_gib > 0.0) {
|
||||
const uint64_t cap = (uint64_t) (o.ram_cap_gib * 1073741824.0);
|
||||
strata::core::detail::set_host_ram_cap(cap);
|
||||
// only an explicit --resident-budget-gib above the cap is clamped: setting a budget for the auto path would
|
||||
// flip pin_cache_complement into explicit-budget mode (no lending, the file tier unbuffered, the budget
|
||||
// warning on every run); the auto path is already bounded by the host_available_memory clamp above
|
||||
if (o.resident_budget > cap) o.resident_budget = cap;
|
||||
std::fprintf(stderr, "strata generate: --ram-cap %.2f GiB: the RAM expert tier and the pinned arena are bounded "
|
||||
"to it (the page cache is not: cap it with the machine or a cgroup)\n", o.ram_cap_gib);
|
||||
}
|
||||
// ---- THE QWEN3.6 VRAM PLAN (Phase 2 step 2 of docs/PLAN-qwen36-35b-a3b.md; the plan itself is docs/QWEN36-35B-A3B.md
|
||||
// 4.2). The geometry is read, the pack's layout is checked against it, and the plan is made from this card and
|
||||
// this file's census and printed; a plan that does not fit stops the start here, before any weight moves. Until
|
||||
// step 4 (docs/qwen36-port/step4-runner.md) the start stopped here unconditionally (`qwen35moe_not_yet`, the
|
||||
// step-2 gate); the loads that follow are the order pack_load_check.cpp proved on both cards, plus `check_all`
|
||||
// after the native projections.
|
||||
if (g.arch == strata::core::ModelArch::Qwen35Moe) {
|
||||
strata::plan::VramPlanInput in;
|
||||
try {
|
||||
const strata::GgufModel model(o.native_shards);
|
||||
uint64_t weights = 0, experts = 0, draft = 0;
|
||||
int64_t n_exp = 0;
|
||||
for (size_t i = 0; i < model.size(); ++i)
|
||||
for (const strata::TensorInfo& t : model.shard(i).tensors()) {
|
||||
const uint64_t b = strata::tensor_payload_bytes(t);
|
||||
if (t.name == "token_embd.weight") continue; // mapped host memory, not the GPU
|
||||
int64_t blk = -1;
|
||||
if (t.name.rfind("blk.", 0) == 0) blk = std::atoll(t.name.c_str() + 4);
|
||||
if (blk >= g.n_layers) { draft += b; continue; } // the nextn block: the drafter's
|
||||
if (t.name.find("_exps.weight") != std::string::npos) { experts += b; ++n_exp; continue; }
|
||||
weights += b;
|
||||
}
|
||||
in.weights_bytes = weights;
|
||||
// the drafter (step4-drafter.md section 7), only when one is asked for: the draft block's weights in VRAM
|
||||
// (its dense and experts; the plain file has no block and the pack then comes from the -MTP file's blk.40:
|
||||
// 464 MiB of experts, 40 of dense), its K/V over the WHOLE context in the --kv format (counted per token
|
||||
// below), the draft head over the pack's draft vocabulary (or the whole head) at the file's head row bytes
|
||||
// plus 8 x n_vocab logits, and the identity ids T x cells x 4
|
||||
if (!o.mtp.empty()) {
|
||||
in.drafter_bytes = draft ? draft : (504ull << 20);
|
||||
int64_t n_dvocab = g.n_vocab;
|
||||
uint64_t head_row = 0;
|
||||
for (size_t i = 0; i < model.size(); ++i)
|
||||
for (const strata::TensorInfo& t : model.shard(i).tensors())
|
||||
if (t.name == "output.weight" && t.shape.size() > 1 && t.shape[1] > 0) {
|
||||
n_dvocab = (int64_t) t.shape[1];
|
||||
head_row = strata::tensor_payload_bytes(t) / (uint64_t) t.shape[1];
|
||||
}
|
||||
const int64_t n_vocab_file = n_dvocab;
|
||||
std::error_code ec;
|
||||
const auto dv = std::filesystem::file_size(o.mtp + "/draft_vocab.bin", ec);
|
||||
// With a vocabulary subset the drafter gathers its own head (n_dvocab rows); without one it scores
|
||||
// with the target's head and allocates no copy (mtp.cpp: dhead_ stays null), so only the logits count
|
||||
const bool subset = !ec && dv >= 4;
|
||||
if (subset) n_dvocab = (int64_t) (dv / 4);
|
||||
in.drafter_head_bytes = (subset ? (uint64_t) n_dvocab * head_row : 0) + (uint64_t) 8 * (uint64_t) n_vocab_file * 4;
|
||||
in.drafter_ids_bytes_per_token = (uint64_t) std::max(o.spec, 1) * 4;
|
||||
}
|
||||
in.n_experts = g.n_layers * g.n_expert;
|
||||
const auto& lay = strata::kernels::cpu::expert_layout();
|
||||
in.mean_blob = lay.native && lay.total > 0 ? lay.total / (uint64_t) in.n_experts
|
||||
: (experts > 0 ? experts / (uint64_t) in.n_experts : 0);
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "strata generate: %s: %s\n", o.native_preset.c_str(), e.what());
|
||||
return 1;
|
||||
}
|
||||
// KV per token over the attention layers, in the format asked for (dense attention keeps every cell in VRAM)
|
||||
const double kv_elem = o.kv == "q4_0" ? 18.0 / 32.0 : o.kv == "int8" ? 1.0 + 2.0 / 64.0 : o.kv == "k8v4" ? 816.0 / 1024.0 : 2.0;
|
||||
in.kv_bytes_per_token = (uint64_t) (g.n_qsa_layers() * 2 * g.n_head_kv * g.head_dim * kv_elem);
|
||||
// the drafter's one attention layer, the same format, the whole context (no ring without --kv-resident)
|
||||
// (under --kv k8v4 the drafter keeps plain INT8 K/V, mtp.cpp: charged as such, not as the hybrid's bytes)
|
||||
const double drafter_kv_elem = o.kv == "k8v4" ? 1.0 + 2.0 / 64.0 : kv_elem;
|
||||
if (!o.mtp.empty()) in.drafter_kv_bytes_per_token = (uint64_t) (2 * g.n_head_kv * g.head_dim * drafter_kv_elem);
|
||||
// the session: one RoPE table (max_cells x n_rot/2 x 2 floats), the GDN state, ~36 MiB of scratch
|
||||
in.session_bytes = (uint64_t) o.max_context * (uint64_t) g.n_rot * 4 +
|
||||
(uint64_t) g.n_gdn_layers() * ((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)) * 4 +
|
||||
(36ull << 20);
|
||||
// cudaMemGetInfo's free figure is read after this process's context exists, so the driver's share is
|
||||
// already out of it: 0 here. The planner's unit test puts the study's 300 MiB in, because its budgets are
|
||||
// the cards' sizes (table 4.1), not a free figure.
|
||||
in.cuda_context_bytes = 0;
|
||||
in.reserve_bytes = (uint64_t) (o.vram_reserve_given ? o.vram_reserve_mib : 300) << 20; // kSmallReserveMib
|
||||
const bool borrow = !o.no_prefill_borrow && !o.expert_profile.empty();
|
||||
in.prompt_bytes = (o.prefill_chunk > 0 && !borrow) ? ((uint64_t) (160 + (o.prefill_chunk * 680) / 1024) << 20) : 0;
|
||||
in.context = o.max_context;
|
||||
in.context_floor = std::min<int64_t>(131072, o.max_context);
|
||||
{
|
||||
size_t free_b = 0, total_b = 0;
|
||||
if (vram_info(&free_b, &total_b) != cudaSuccess) { (void) cudaGetLastError(); free_b = 0; }
|
||||
in.budget_bytes = free_b;
|
||||
}
|
||||
{
|
||||
strata::core::detail::HostMemory hm;
|
||||
in.ram_available_bytes = strata::core::detail::host_available_memory(hm) ? hm.available : 0;
|
||||
// the RAM tier's headroom: --resident-experts' 4 GiB (the study's), unless the resident mode set its own
|
||||
in.ram_headroom_bytes = o.resident_cpu_experts ? o.resident_headroom : (4ull << 30);
|
||||
}
|
||||
if (o.native_preset.find("IQ3") == std::string::npos) in.smaller_file = "Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf";
|
||||
const strata::plan::VramPlan plan = strata::plan::make_vram_plan(in);
|
||||
std::fprintf(stderr, "strata generate: VRAM plan for %s on this card (kv %s, %s):\n%s", o.native_preset.c_str(),
|
||||
o.kv.c_str(), borrow ? "prefill borrows cache slots" : "prefill has its own buffers",
|
||||
strata::plan::vram_plan_text(in, plan, " ").c_str());
|
||||
if (!plan.fits) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", plan.refusal.c_str());
|
||||
return 2;
|
||||
}
|
||||
if (plan.lowered) { // the plan's context is the one everything below allocates for, not the request's
|
||||
std::fprintf(stderr, "strata generate: the context is lowered from %lld to %lld tokens by the VRAM plan above\n",
|
||||
(long long) o.max_context, (long long) plan.context);
|
||||
o.max_context = plan.context;
|
||||
}
|
||||
// The RAM tier. The resident arena pins every expert in RAM; when the host cannot hold that (the plan's
|
||||
// 12 GiB rung: --ram-cap, a cgroup limit, or simply less RAM than the file), the experts stay mapped from the
|
||||
// file and the hottest ones by profile rank are copied into RAM (the --resident-experts mode), which is what
|
||||
// the plan's "expert copies in RAM" line already assumed. Chosen here, before anything keys on the mode;
|
||||
// an explicit --mmap-experts / --resident-experts is left alone.
|
||||
if (!o.mmap_experts && o.shared_expert_arena.empty() && o.peer_device < 1 && !o.remote_expert_opt) {
|
||||
// (an explicit shared arena keeps its own pages; the multi-GPU helpers' residency rules were validated at
|
||||
// option time and are not revisited here)
|
||||
const auto& lay2 = strata::kernels::cpu::expert_layout();
|
||||
strata::core::detail::HostMemory hm;
|
||||
if (lay2.native && lay2.total > 0 && strata::core::detail::host_available_memory(hm)) {
|
||||
const uint64_t need = lay2.total + (uint64_t) lay2.max_blob;
|
||||
if (hm.cgroup_limit < need || hm.available < need) {
|
||||
const double gib = 1073741824.0;
|
||||
std::fprintf(stderr, "strata generate: RAM tier: the resident expert arena needs %.2f GiB but the host "
|
||||
"allows %.2f GiB (%s): the experts stay mapped from the file and the hottest are copied "
|
||||
"into RAM by profile rank (as --resident-experts)\n",
|
||||
(double) need / gib, (double) std::min(hm.cgroup_limit, hm.available) / gib,
|
||||
hm.cgroup_limit < need ? "the memory limit" : "available RAM");
|
||||
o.mmap_experts = true;
|
||||
if (!o.expert_profile.empty()) {
|
||||
o.resident_cpu_experts = o.resident_pin = o.resident_soft = true;
|
||||
o.resident_headroom = 4ull << 30;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((o.peer_device >= 1 || o.remote_expert_opt) && g.n_embd != (int64_t) strata::kernels::cpu::H) {
|
||||
std::fprintf(stderr, "strata generate: the multi-GPU expert helpers (--peer-device, --remote-expert-opt) are "
|
||||
"compiled for the canonical %d-wide expert and are not available for this model (n_embd %lld)\n",
|
||||
(int) strata::kernels::cpu::H, (long long) g.n_embd);
|
||||
return 2;
|
||||
}
|
||||
// a native pack decodes in verify windows only (plan v0.3 P6), and this model has no MTP drafter wired yet
|
||||
// (docs/qwen36-port/step4-runner.md: the drafter is `--mtp DIR`, qwen36-step4-drafter): without one the
|
||||
// windows hold one token each and `--spec` is only the verifier's capacity, so a run that asked for none
|
||||
// gets the smallest window the verifier takes instead of the native pack's refusal below
|
||||
if (o.mtp.empty() && o.spec < 2 && !o.serve) {
|
||||
std::fprintf(stderr, "strata generate: no drafter (--mtp): the decode windows hold one token each; --spec %d "
|
||||
"becomes 2 (the verifier's smallest window)\n", o.spec);
|
||||
o.spec = 2;
|
||||
}
|
||||
}
|
||||
{
|
||||
// Every layer's formats must have GPU expert kernels and a prompt-path dequantizer, checked here, before
|
||||
// anything is allocated: an unsupported down type used to exit from inside the first verify window, and
|
||||
// an unsupported dequant type left the prompt path's fp16 buffer unwritten.
|
||||
@@ -2026,7 +2342,6 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool native_pack = strata::kernels::cpu::expert_layout().native;
|
||||
// STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's
|
||||
// pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs,
|
||||
// and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory").
|
||||
@@ -2070,8 +2385,6 @@ int main(int argc, char** argv) {
|
||||
"(multi-token for the i-quant gate/up rows)\n",
|
||||
!strata::kernels::cpu::cpu_avx2_ok() ? "ggml-cpu vec_dot (no AVX2: the older-CPU build)"
|
||||
: std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");
|
||||
strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below
|
||||
int64_t K = 10;
|
||||
// THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken,
|
||||
// and `session_init` below builds the rope table from it and captures the kernels reading its constants
|
||||
// (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats
|
||||
@@ -2084,16 +2397,15 @@ int main(int argc, char** argv) {
|
||||
std::string gguf_rope_type;
|
||||
double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0;
|
||||
if (!o.native_preset.empty()) {
|
||||
// a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file
|
||||
// is the authority on its own MoE shape - everything else in the geometry is unchanged
|
||||
// the MoE shape and the rest of the geometry were read above (`g`, `K`); the rope keys are under the
|
||||
// same architecture prefix (qwen4exp. or qwen35moe.)
|
||||
try {
|
||||
strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard
|
||||
if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u;
|
||||
if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u;
|
||||
if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num();
|
||||
if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s;
|
||||
if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num();
|
||||
if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length"))
|
||||
const std::string pre = std::string(strata::core::model_arch_name(g.arch)) + ".";
|
||||
if (const strata::MetaValue* v = model_gguf.get(pre + "rope.freq_base")) gguf_rope_base = v->num();
|
||||
if (const strata::MetaValue* v = model_gguf.get(pre + "rope.scaling.type")) gguf_rope_type = v->s;
|
||||
if (const strata::MetaValue* v = model_gguf.get(pre + "rope.scaling.factor")) gguf_rope_factor = v->num();
|
||||
if (const strata::MetaValue* v = model_gguf.get(pre + "rope.scaling.original_context_length"))
|
||||
gguf_rope_orig_ctx = v->num();
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n",
|
||||
@@ -2181,9 +2493,8 @@ int main(int argc, char** argv) {
|
||||
"and --prefill CHUNK\n", o.pack.c_str());
|
||||
return 2;
|
||||
}
|
||||
const strata::core::ModelGeometry g0;
|
||||
if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector<std::string>{o.embd_gguf}, g0.n_embd,
|
||||
248320, err)) {
|
||||
if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector<std::string>{o.embd_gguf}, g.n_embd,
|
||||
g.n_vocab, err)) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
@@ -2258,7 +2569,7 @@ int main(int argc, char** argv) {
|
||||
// missing is held by something else: say how much was free
|
||||
cudaGetLastError();
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
std::fprintf(stderr, "strata generate: cudaMalloc(%llu) for the weight arena failed (%s): %llu MiB of %llu "
|
||||
"MiB VRAM free on this GPU. The arena is allocated first, before the KV and expert "
|
||||
"caches: another program (or an engine that is still exiting) holds the rest - "
|
||||
@@ -2278,13 +2589,29 @@ int main(int argc, char** argv) {
|
||||
|
||||
strata::core::NativeDense native_dense;
|
||||
if (!o.native_dense_gguf.empty()) {
|
||||
if (!native_dense.load(o.native_dense_gguf, wt, err, o.native_ple_key)) {
|
||||
// bounded to the trunk: a -MTP file's draft block (blk.40 of Qwen3.6, `nextn_predict_layers`) carries the
|
||||
// same projection names, is not in the trunk's pack (tools/iq_pack.py leaves it to the drafter's), and would
|
||||
// otherwise be "absent from canonical table"; no Flash-Next file has a block past its trunk
|
||||
if (!native_dense.load(o.native_dense_gguf, wt, err, o.native_ple_key, 0, g.n_layers)) {
|
||||
std::fprintf(stderr, "strata generate: native dense projections: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights\n",
|
||||
native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0));
|
||||
}
|
||||
// Qwen3.6 (step 4, docs/qwen36-port/step4-pack.md section 6): every layer's names, shapes and engine forms as the
|
||||
// kernels require them (src/core/layout.cpp), now that the arena and the native projections are in place - a
|
||||
// pack that is missing a row, or carries it in the wrong form, is refused here by name instead of inside the
|
||||
// first window. The whole trunk only: a layer split loads other stages' layers elsewhere.
|
||||
if (g.arch == strata::core::ModelArch::Qwen35Moe && !stage_trim) {
|
||||
if (!strata::core::check_all(wt, g, err)) {
|
||||
std::fprintf(stderr, "strata generate: %s: %s\n", o.pack.c_str(), err.c_str());
|
||||
return 1;
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: check_all: %lld layers (%lld attention, %lld GDN): every weight the "
|
||||
"kernels read is present in its form\n", (long long) g.n_layers,
|
||||
(long long) g.n_qsa_layers(), (long long) g.n_gdn_layers());
|
||||
}
|
||||
|
||||
strata::kernels::gr_set_fp32_activations(o.gr_fp32_activations);
|
||||
strata::kernels::gr_set_native_mmvf(o.gr_native_mmvf);
|
||||
@@ -2537,7 +2864,7 @@ int main(int argc, char** argv) {
|
||||
for (const auto& pr : prof)
|
||||
pairs_bytes += native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob;
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers);
|
||||
const int64_t held_back = session + (((int64_t) o.vram_reserve_mib + 1000 + 96) << 20); // + drafter/head, windows
|
||||
const int64_t room = (int64_t) fb - held_back;
|
||||
@@ -2598,7 +2925,7 @@ int main(int argc, char** argv) {
|
||||
!st.wt.load(o.pack, arena_s, pool_s, err, skip_s.empty() ? nullptr : &skip_s)) {
|
||||
cudaGetLastError();
|
||||
size_t free_b = 0, total_b = 0; // #486: what that card had free
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
std::fprintf(stderr, "strata generate: layer split, CUDA%d weights: %s (%llu MiB needed, %llu MiB of %llu "
|
||||
"MiB free on that card)\n", st.dev,
|
||||
err.empty() ? "the weight arena does not fit" : err.c_str(),
|
||||
@@ -2647,7 +2974,7 @@ int main(int argc, char** argv) {
|
||||
"%.2f\n", st.dev, bw, bursts.c_str(), st.pcie_frac);
|
||||
}
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session "
|
||||
"follows the split search)\n", st.dev, (double) fb / 1073741824.0);
|
||||
}
|
||||
@@ -2752,7 +3079,7 @@ int main(int argc, char** argv) {
|
||||
auto stage_room = [&](int dev, bool later, bool drafter, bool search = false) -> int64_t {
|
||||
const strata::core::OnDevice on(dev);
|
||||
size_t fb = 0, tb = 0;
|
||||
if (const cudaError_t e = cudaMemGetInfo(&fb, &tb); e != cudaSuccess)
|
||||
if (const cudaError_t e = vram_info(&fb, &tb); e != cudaSuccess)
|
||||
std::fprintf(stderr, "strata generate: layer split: CUDA%d free memory: %s\n", dev < 0 ? 0 : dev,
|
||||
cudaGetErrorString(e));
|
||||
const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib;
|
||||
@@ -2933,7 +3260,7 @@ int main(int argc, char** argv) {
|
||||
return 1;
|
||||
}
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights, session [%lld, %lld)%s; "
|
||||
"%.2f GiB free\n", st.dev, (long long) st.lb, (long long) st.le,
|
||||
last ? " and the head" : "", (double) fb / 1073741824.0);
|
||||
@@ -2980,7 +3307,7 @@ int main(int argc, char** argv) {
|
||||
cudaGetLastError();
|
||||
if (buf != nullptr) cudaFree(buf);
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
std::fprintf(stderr, "strata generate: WARNING: --batch %d: slot %d's session does not fit on CUDA%d "
|
||||
"(%.2f GiB each, %.2f GiB free); %d slot%s\n", o.batch, b, dev,
|
||||
(double) bytes / 1073741824.0, (double) fb / 1073741824.0, b, b == 1 ? "" : "s");
|
||||
@@ -2992,7 +3319,7 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
cudaDeviceSynchronize();
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
std::fprintf(stderr, "strata generate: --batch: %d slot sessions on CUDA%d (%.2f GiB each); %.2f GiB free\n",
|
||||
(int) bslot_ss[k].size(), dev, (double) bytes / 1073741824.0, (double) fb / 1073741824.0);
|
||||
}
|
||||
@@ -3021,9 +3348,12 @@ int main(int argc, char** argv) {
|
||||
o.mtp.clear();
|
||||
}
|
||||
if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
|
||||
// the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
|
||||
// so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
|
||||
static const strata::core::ModelGeometry draft_geometry{};
|
||||
// Flash-Next: the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
|
||||
// so it always sees the canonical geometry. Qwen3.6 (qwen35moe): the drafter is the -MTP file's nextn block
|
||||
// and its geometry FOLLOWS THE TARGET (docs/QWEN36-35B-A3B.md 3.10; the pack records what it was cut for and
|
||||
// MtpDrafter::load refuses a mismatch by name). `static` because MtpDrafter keeps a reference.
|
||||
static const strata::core::ModelGeometry draft_geometry =
|
||||
g.arch == strata::core::ModelArch::Qwen35Moe ? g : strata::core::ModelGeometry{};
|
||||
// with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device
|
||||
const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1);
|
||||
if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; }
|
||||
@@ -3165,7 +3495,11 @@ int main(int argc, char** argv) {
|
||||
// such limit, so there the whole arena is pinned (#253). STRATA_ARENA_PIN_GIB overrides both ways.
|
||||
const int pin_env = strata::core::arena_pin_cap_gib(); // -1 unset, -2 "auto" (#243, Windows sliced pin)
|
||||
const bool pin_wddm_cap = pin_env < 0 && (o.expert_cache_remote[0] > 0 || multi_gpu) && under_wddm();
|
||||
const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0;
|
||||
uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0;
|
||||
if (o.ram_cap_gib > 0.0) { // --ram-cap: the pinned arena is bounded too (0 = everything, so a cap replaces it)
|
||||
const uint64_t cap = (uint64_t) (o.ram_cap_gib * 1073741824.0);
|
||||
pin_limit = pin_limit == 0 ? cap : std::min(pin_limit, cap);
|
||||
}
|
||||
if (pin_env >= 0)
|
||||
std::fprintf(stderr, "strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n", pin_env,
|
||||
pin_env == 0 ? "the whole expert arena is pinned" : "the expert arena's pinning is capped");
|
||||
@@ -3218,7 +3552,7 @@ int main(int argc, char** argv) {
|
||||
bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits
|
||||
if (o.expert_cache < 0) {
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here -
|
||||
// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.
|
||||
// (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is
|
||||
@@ -3291,7 +3625,7 @@ int main(int argc, char** argv) {
|
||||
// fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends
|
||||
// slots instead and `prefill_mib` is 0, so only the reserve is checked)
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
|
||||
const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;
|
||||
const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0);
|
||||
@@ -3311,7 +3645,7 @@ int main(int argc, char** argv) {
|
||||
std::vector<int64_t> sized_slots;
|
||||
if (native_pack && o.expert_cache > 0 && !profile.empty() && !o.expert_cache_per_layer) {
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
const auto& lay = strata::kernels::cpu::expert_layout();
|
||||
const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted
|
||||
uint64_t used = 0;
|
||||
@@ -3415,7 +3749,7 @@ int main(int argc, char** argv) {
|
||||
cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes());
|
||||
cudaDeviceSynchronize();
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
const int64_t want = (int64_t) o.vram_reserve_mib << 20;
|
||||
if ((int64_t) free_b >= want - (64ll << 20)) break;
|
||||
// short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB
|
||||
@@ -3517,7 +3851,7 @@ int main(int argc, char** argv) {
|
||||
const strata::core::OnDevice on(st.dev);
|
||||
{
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
std::fprintf(stderr, "strata generate: layer split, CUDA%d: %.2f GiB free of %.2f, room for experts %.2f GiB\n",
|
||||
st.dev, (double) fb / 1073741824.0, (double) tb / 1073741824.0, (double) room / 1073741824.0);
|
||||
}
|
||||
@@ -3673,6 +4007,7 @@ int main(int argc, char** argv) {
|
||||
|
||||
if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
|
||||
Drive drive;
|
||||
drive.n_layers = (int32_t) g.n_layers;
|
||||
for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
|
||||
drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r];
|
||||
drive.d.peer = peer.valid() ? &peer : nullptr;
|
||||
@@ -4847,7 +5182,7 @@ int main(int argc, char** argv) {
|
||||
for (PfPart& p : pf_parts) {
|
||||
const strata::core::OnDevice on(p.dev);
|
||||
size_t fb = 0, tb = 0;
|
||||
if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; }
|
||||
if (vram_info(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; }
|
||||
const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk);
|
||||
if ((uint64_t) fb >= need + (3ull << 29)) {
|
||||
std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of "
|
||||
@@ -4935,7 +5270,7 @@ int main(int argc, char** argv) {
|
||||
const int dev = i == 0 ? -1 : stages[i - 1]->dev;
|
||||
const strata::core::OnDevice on(dev);
|
||||
size_t fb = 0, tb = 0;
|
||||
cudaMemGetInfo(&fb, &tb);
|
||||
vram_info(&fb, &tb);
|
||||
const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c);
|
||||
if (need + kHeadroom > (int64_t) fb) {
|
||||
dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb;
|
||||
@@ -5667,7 +6002,7 @@ int main(int argc, char** argv) {
|
||||
// what is left once everything is allocated: under WDDM a GPU filled to the brim does not fail, it pages -
|
||||
// and a page-in while the verify graph spins on a host flag stalls the request for good
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
// below ~256 MiB a later allocation (a first-used window's buffers, the desktop, another program) can make
|
||||
// the driver page GPU memory, and a verify graph spinning on a host flag then never finishes
|
||||
const int64_t free_mib = (int64_t) (free_b >> 20);
|
||||
@@ -5689,7 +6024,7 @@ int main(int argc, char** argv) {
|
||||
// what the server's Monitor tab shows (servers before 0.1.8 skip unknown lines until READY)
|
||||
{
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
// "Experts in VRAM" is every tier, not one card's. This used to report `xcache` alone, so a layer split
|
||||
// showed CUDA0's cache as if it were the whole GPU's: a 4-GPU 256K run read 3327 experts when the four
|
||||
// cards held 13320, and the Monitor tab was wrong by 4x for every multi-GPU config. The tiers are
|
||||
@@ -5794,6 +6129,33 @@ int main(int argc, char** argv) {
|
||||
p.first = (int32_t) std::max<int64_t>(0, live - part_slots(p, c));
|
||||
p.first_now = -1; // laid out again at the next loan
|
||||
};
|
||||
// The tier census and the per-token counters, one JSON line: VRAM slots (and how many hold an expert), RAM copies,
|
||||
// experts mapped from the file; then the counters since start: tokens served, VRAM hits (`cache_hits`), RAM-copy
|
||||
// reads, file reads, warm hints (`FileExpertSource::warm`), and the process's major page faults from
|
||||
// /proc/self/stat (the disk-read proxy: a page-cache miss on a mapped expert is not otherwise observable).
|
||||
const uint64_t faults0 = mem_sample().faults;
|
||||
int64_t served_tokens = 0;
|
||||
auto tier_stats = [&]() -> std::string {
|
||||
const int64_t total = g.n_layers * g.n_expert;
|
||||
const int64_t vram_slots = xcache.slots(), vram_held = xcache.resident();
|
||||
const int64_t ram_copies = src.complement_count();
|
||||
const int64_t mapped = std::max<int64_t>(total - vram_held - ram_copies, 0);
|
||||
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
|
||||
char buf[768];
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"STATS {\"experts\":%lld,\"vram_slots\":%lld,\"vram_held\":%lld,\"ram_copies\":%lld,\"mapped\":%lld,"
|
||||
"\"mean_blob\":%llu,\"tokens\":%lld,\"vram_hits\":%lld,\"lookups\":%lld,\"ram_reads\":%lld,"
|
||||
"\"file_reads\":%lld,\"file_mb\":%.1f,\"warm_hints\":%lld,\"major_faults\":%llu,\"max_context\":%lld}",
|
||||
(long long) total, (long long) vram_slots, (long long) vram_held, (long long) ram_copies,
|
||||
(long long) mapped, (unsigned long long) (lay.native && total > 0 ? lay.total / (uint64_t) total : lay.max_blob),
|
||||
(long long) served_tokens, (long long) drive.d.cache_hits,
|
||||
(long long) (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused),
|
||||
(long long) src.ram_reads(), (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6,
|
||||
(long long) src.warmed(), (unsigned long long) (mem_sample().faults - faults0),
|
||||
(long long) o.max_context);
|
||||
return buf;
|
||||
};
|
||||
std::fprintf(stderr, "strata serve: tiers at start: %s\n", tier_stats().c_str() + 6);
|
||||
auto vram_command = [&](const std::string& cmd, std::string& e) -> bool {
|
||||
// `VRAM` alone: the reserve the engine started with (--vram-reserve-mib)
|
||||
char* end = nullptr;
|
||||
@@ -5819,7 +6181,7 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
const auto t0 = Clock::now();
|
||||
size_t free_b = 0, total_b = 0;
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
const int64_t want_free = (int64_t) reserve << 20, mapped = xcache.mapped_bytes();
|
||||
const int64_t before = xcache.slots();
|
||||
// what stays at least: the prompt path's smallest loan (256 tokens) and the 128 slots it must leave
|
||||
@@ -5875,7 +6237,7 @@ int main(int argc, char** argv) {
|
||||
res_upload();
|
||||
}
|
||||
relend();
|
||||
cudaMemGetInfo(&free_b, &total_b);
|
||||
vram_info(&free_b, &total_b);
|
||||
std::fprintf(stderr, "strata serve: VRAM %lld MiB kept free: the expert cache %lld -> %lld of %lld slots "
|
||||
"(%.2f of %.2f GiB), %lld MiB free now, prompt chunk %lld, in %.0f ms%s\n",
|
||||
reserve, (long long) before, (long long) xcache.slots(), (long long) xcache.full_slots(),
|
||||
@@ -6213,6 +6575,11 @@ int main(int argc, char** argv) {
|
||||
continue;
|
||||
}
|
||||
if (line.rfind("BYIELD", 0) == 0) continue; // for a prompt read that has ended meanwhile
|
||||
if (line.rfind("STATS", 0) == 0) { // the tiers and their counters (Qwen3.6 step 2; the server's /health)
|
||||
std::printf("%s\n", tier_stats().c_str());
|
||||
std::fflush(stdout);
|
||||
continue;
|
||||
}
|
||||
if (line.rfind("VRAM", 0) == 0) { // #533 (above): between requests, not a request
|
||||
std::string verr;
|
||||
if (batch_on()) verr = "VRAM: not while batch slots are decoding";
|
||||
@@ -7148,6 +7515,52 @@ int main(int argc, char** argv) {
|
||||
int a = 0;
|
||||
while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
|
||||
if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
|
||||
// Diagnostics, STRATA_SERVE_LOGIT_TRACE=FILE: one line per emitted token with the head's five
|
||||
// largest logits, the window's shape and the experts it missed, so two runs of one request can
|
||||
// be compared where they part (docs/qwen36-port/step5-serve.md, "The same greedy request").
|
||||
// With STRATA_SERVE_LOGIT_DUMP=PREFIX too, every emitted token's whole row goes to
|
||||
// PREFIX.<request>.f32 (raw F32, tools/qwen36_compare_logits.py --no-engine-header): 1 MB a token.
|
||||
// The window's result is not touched.
|
||||
static FILE* const logit_trace = [] {
|
||||
const char* f = std::getenv("STRATA_SERVE_LOGIT_TRACE");
|
||||
return f != nullptr && *f != '\0' ? std::fopen(f, "a") : nullptr;
|
||||
}();
|
||||
if (logit_trace != nullptr) {
|
||||
static std::vector<float> row;
|
||||
static int64_t tr_miss = 0, tr_pcie = 0, tr_hits = 0, tr_req = -1;
|
||||
if (first_window) ++tr_req;
|
||||
static FILE* dumpf = nullptr;
|
||||
row.resize((size_t) ver.vocab());
|
||||
if (first_window) {
|
||||
if (dumpf != nullptr) std::fclose(dumpf);
|
||||
const char* pre = std::getenv("STRATA_SERVE_LOGIT_DUMP");
|
||||
dumpf = pre != nullptr && *pre != '\0'
|
||||
? std::fopen((std::string(pre) + "." + std::to_string(tr_req) + ".f32").c_str(), "wb") : nullptr;
|
||||
}
|
||||
for (int i = 0; i <= a && produced_n + i < max_new; ++i) {
|
||||
if (!ver.copy_logits(i, row.data())) break;
|
||||
if (dumpf != nullptr) std::fwrite(row.data(), sizeof(float), row.size(), dumpf);
|
||||
int top[5];
|
||||
for (int k = 0; k < 5; ++k) {
|
||||
int best = -1;
|
||||
for (int v = 0; v < (int) row.size(); ++v) {
|
||||
bool taken = false;
|
||||
for (int q = 0; q < k; ++q) taken = taken || top[q] == v;
|
||||
if (!taken && (best < 0 || row[(size_t) v] > row[(size_t) best])) best = v;
|
||||
}
|
||||
top[k] = best;
|
||||
}
|
||||
std::fprintf(logit_trace, "L %lld %lld %d row %d of T %d%s miss %lld pcie %lld hits %lld top",
|
||||
(long long) tr_req, (long long) (produced_n + i), (int) outv[(size_t) i], i, T,
|
||||
from_sfx ? " sfx" : "", (long long) (drive.d.multi_misses - tr_miss),
|
||||
(long long) (drive.d.pcie_experts - tr_pcie), (long long) (drive.d.cache_hits - tr_hits));
|
||||
for (int k = 0; k < 5; ++k) std::fprintf(logit_trace, " %d:%.6f", top[k], (double) row[(size_t) top[k]]);
|
||||
std::fputc('\n', logit_trace);
|
||||
}
|
||||
tr_miss = drive.d.multi_misses; tr_pcie = drive.d.pcie_experts; tr_hits = drive.d.cache_hits;
|
||||
std::fflush(logit_trace);
|
||||
if (dumpf != nullptr) std::fflush(dumpf);
|
||||
}
|
||||
const Clock::time_point tw1 = Clock::now();
|
||||
std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate)
|
||||
bool adapt_ok = true;
|
||||
@@ -7358,6 +7771,7 @@ int main(int argc, char** argv) {
|
||||
// [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed;
|
||||
// not in [lookups])
|
||||
if (yielded_at >= 0) std::printf("YIELDED %d %lld\n", yielded_slot, (long long) yielded_at);
|
||||
served_tokens += produced_n;
|
||||
std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld\n",
|
||||
(long long) produced_n,
|
||||
(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,
|
||||
@@ -7830,6 +8244,11 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "strata generate: cannot read --spec-oracle %s\n", o.spec_oracle.c_str());
|
||||
return 2;
|
||||
}
|
||||
if (o.teacher_force && (int64_t) oracle.size() < o.max_new) {
|
||||
std::fprintf(stderr, "strata generate: --teacher-force: the oracle holds %zu tokens, so --max-new %lld "
|
||||
"becomes %zu\n", oracle.size(), (long long) o.max_new, oracle.size());
|
||||
o.max_new = (int64_t) oracle.size();
|
||||
}
|
||||
}
|
||||
if (thits.d_res == nullptr) {
|
||||
std::fprintf(stderr, "strata generate: --spec needs the device residency table (--expert-profile, "
|
||||
@@ -8002,6 +8421,7 @@ int main(int argc, char** argv) {
|
||||
std::vector<int32_t> window((size_t) o.spec), outv((size_t) o.spec);
|
||||
std::vector<int64_t> accepted_hist((size_t) o.spec, 0);
|
||||
int64_t rounds = 0, drafts_total = 0, drafts_ok = 0, corrupt_counter = 0;
|
||||
int64_t forced_rows = 0, forced_agree = 0; // --teacher-force: positions compared, picks equal to the oracle's
|
||||
const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec;
|
||||
if (use_mtp && S_mtp < o.spec) mtp.set_max_drafts(S_mtp - 1);
|
||||
strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096);
|
||||
@@ -8022,9 +8442,14 @@ int main(int argc, char** argv) {
|
||||
while (T < S_mtp && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T;
|
||||
}
|
||||
if (first_window) T = 1;
|
||||
// no draft source (no drafter, no oracle): one token per window - a window padded with token 0 would
|
||||
// verify a draft nobody made (Qwen3.6 step 4: the drafter-off path, docs/qwen36-port/step4-runner.md)
|
||||
if (!use_mtp && oracle.empty()) T = 1;
|
||||
// teacher forcing: the window never runs past the oracle's last token
|
||||
if (o.teacher_force) T = (int) std::min<int64_t>(T, o.max_new - (int64_t) produced.size());
|
||||
bool from_sfx = false;
|
||||
int sfx_match = 0;
|
||||
if (o.suffix_draft > 0 && !first_window) {
|
||||
if (o.suffix_draft > 0 && !first_window && !o.teacher_force) {
|
||||
const int k = sfx.propose(o.spec - 1, sbuf.data());
|
||||
sfx_match = sfx.last_match();
|
||||
if (k > 0 && (!use_mtp || sbuf[0] == drafts[0])) {
|
||||
@@ -8065,6 +8490,38 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
int a = 0;
|
||||
while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
|
||||
if (o.teacher_force) {
|
||||
// row i's pick against the oracle's token at that position (oracle[j] is the j-th generated token;
|
||||
// `produced` holds j0 of them, so row i of this window predicts oracle[j0 + i]); every row commits
|
||||
for (int i = 0; i < T; ++i) {
|
||||
const size_t j = produced.size() + (size_t) i;
|
||||
if (j < oracle.size() && (int64_t) outv[(size_t) i] == oracle[j]) ++forced_agree;
|
||||
if (j < oracle.size()) ++forced_rows;
|
||||
}
|
||||
a = T - 1;
|
||||
}
|
||||
if (dump != nullptr) {
|
||||
// one row of head logits per emitted position (the accepted rows are the greedy path's positions;
|
||||
// under teacher forcing every row): a native pack writes nothing before this loop, so its header
|
||||
// promises exactly --max-new rows; the token path's header (written with its first row) already counts
|
||||
// these positions
|
||||
if (!hdr_written) {
|
||||
hdr[1] = (int32_t) o.max_new;
|
||||
if (std::fwrite(hdr, sizeof hdr, 1, dump) != 1) {
|
||||
std::fprintf(stderr, "strata generate: cannot write logits header\n");
|
||||
return 1;
|
||||
}
|
||||
hdr_written = true;
|
||||
}
|
||||
for (int i = 0; i <= a && (int64_t) produced.size() + i < o.max_new; ++i) {
|
||||
if (!ver.copy_logits(i, logits.data()) ||
|
||||
std::fwrite(logits.data(), sizeof(float), (size_t) n_vocab, dump) != (size_t) n_vocab) {
|
||||
std::fprintf(stderr, "strata generate: cannot write the window's logits at position %lld\n",
|
||||
(long long) (p + i));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (first_window) {
|
||||
first_window = false;
|
||||
ttft_ms = std::chrono::duration<double, std::milli>(Clock::now() - t_start).count();
|
||||
@@ -8099,7 +8556,8 @@ int main(int argc, char** argv) {
|
||||
for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) {
|
||||
produced.push_back(outv[(size_t) i]);
|
||||
if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);
|
||||
eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
|
||||
eos = !o.teacher_force && o.stop_eos &&
|
||||
std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
|
||||
}
|
||||
if (eos) {
|
||||
if (adapt_thr.joinable()) adapt_thr.join();
|
||||
@@ -8114,7 +8572,10 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
x = outv[(size_t) a];
|
||||
// the next window's first token: the engine's own pick, or under teacher forcing the oracle's token at
|
||||
// that position (the T rows just committed hold oracle[j0 - 1 .. j0 + T - 2]; the next is oracle[j0 + T - 1])
|
||||
x = o.teacher_force && !produced.empty() && produced.size() - 1 < oracle.size()
|
||||
? (int32_t) oracle[produced.size() - 1] : outv[(size_t) a];
|
||||
p += a + 1;
|
||||
const double round_ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
||||
total_ms += round_ms;
|
||||
@@ -8132,6 +8593,10 @@ int main(int argc, char** argv) {
|
||||
"speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total,
|
||||
drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0,
|
||||
rounds > 0 ? (double) (drafts_ok + rounds) / (double) rounds : 0.0);
|
||||
if (o.teacher_force)
|
||||
std::printf("%-24s top-1 agreement %lld of %lld positions (%.4f) with %s\n", "teacher-forced",
|
||||
(long long) forced_agree, (long long) forced_rows,
|
||||
forced_rows > 0 ? (double) forced_agree / (double) forced_rows : 0.0, o.spec_oracle.c_str());
|
||||
if (o.spec_min_p > 0.0) {
|
||||
std::printf("%-24s", "window sizes");
|
||||
for (size_t i = 1; i < window_hist.size(); ++i) std::printf(" T%zu:%lld", i, (long long) window_hist[i]);
|
||||
|
||||
@@ -53,9 +53,12 @@ struct TempDir {
|
||||
|
||||
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, std::string& err) {
|
||||
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, err);
|
||||
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
|
||||
@@ -105,6 +108,56 @@ void real_packs(const fs::path& data) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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) +
|
||||
@@ -329,9 +382,12 @@ void arena() {
|
||||
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 && std::string(argv[1]) == "--real") {
|
||||
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;
|
||||
if (!load(argv[2], 48, 512, err)) { std::printf("layout refused: %s\n", err.c_str()); return 1; }
|
||||
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;
|
||||
@@ -348,6 +404,7 @@ int main(int argc, char** argv) {
|
||||
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);
|
||||
|
||||
@@ -74,6 +74,18 @@ int main() {
|
||||
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;
|
||||
|
||||
@@ -89,7 +89,7 @@ void test_canonical_layout() {
|
||||
TempDirectory dir;
|
||||
|
||||
std::string err;
|
||||
const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, 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'}});
|
||||
@@ -153,7 +153,7 @@ void test_native_variable_layout() {
|
||||
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, err);
|
||||
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);
|
||||
|
||||
@@ -18,14 +18,18 @@ namespace fixture {
|
||||
|
||||
struct Kv {
|
||||
std::string key;
|
||||
uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32
|
||||
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;
|
||||
@@ -65,6 +69,12 @@ inline Written write(const std::filesystem::path& path, const std::vector<Kv>& k
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
// tests/core/model_geometry_test.cpp - `ModelGeometry` from a model file's own metadata (no model, no GPU).
|
||||
//
|
||||
// model_geometry_test <dir> the synthetic qwen35moe GGUFs tools/qwen36_synth_gguf.py wrote into <dir>
|
||||
// (CMake's qwen36_synth_fixtures test): every field of the toy geometry, the
|
||||
// nextn block subtracted from the layer count, the fused forms refused by name
|
||||
// model_geometry_test --real FILE a real file: prints the geometry and, for Qwen3.6-35B-A3B, asserts the values
|
||||
// of docs/qwen36-port/gguf-metadata.md
|
||||
//
|
||||
// The negative cases: a `qwen4exp` file read with Flash-Next's `hc = 4` and PLE, an unknown architecture refused
|
||||
// with its name, a file whose `ssm.inner_size` contradicts its head counts, and the two fused tensor layouts.
|
||||
#include "gguf_fixture.hpp"
|
||||
|
||||
#include "strata/core/model_geometry.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using strata::core::ModelArch;
|
||||
using strata::core::ModelGeometry;
|
||||
|
||||
namespace {
|
||||
int g_fail = 0;
|
||||
void check(bool ok, const std::string& what) {
|
||||
std::printf(" %-96s %s\n", what.c_str(), ok ? "ok" : "FAIL");
|
||||
if (!ok) ++g_fail;
|
||||
}
|
||||
|
||||
struct TempDir {
|
||||
fs::path path;
|
||||
TempDir() {
|
||||
path = fs::temp_directory_path() /
|
||||
("strata-model-geometry-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);
|
||||
}
|
||||
};
|
||||
|
||||
bool read(const std::string& path, ModelGeometry& g, std::string& err) {
|
||||
return strata::core::read_model_geometry(path, g, err);
|
||||
}
|
||||
|
||||
bool forms_ok(const std::string& path, const ModelGeometry& g, std::string& err) {
|
||||
const strata::GgufModel m = strata::GgufModel::open(path);
|
||||
return strata::core::check_model_tensor_forms(m, g, err);
|
||||
}
|
||||
|
||||
// ---- the toy geometry tools/qwen36_synth_gguf.py writes by default (its docstring)
|
||||
void toy(const fs::path& dir) {
|
||||
ModelGeometry g;
|
||||
std::string err;
|
||||
const std::string plain = (dir / "toy.gguf").string();
|
||||
const bool ok = read(plain, g, err);
|
||||
check(ok, "toy.gguf reads" + (ok ? std::string() : ": " + err));
|
||||
if (!ok) return;
|
||||
check(g.arch == ModelArch::Qwen35Moe, "arch qwen35moe");
|
||||
check(g.n_embd == 64, "n_embd 64 (embedding_length)");
|
||||
check(g.n_vocab == 128, "n_vocab 128 (output.weight / token_embd.weight rows, the 128 tokens)");
|
||||
check(g.n_layers == 4 && g.nextn_layers == 1, "n_layers 4 = block_count 5 - nextn_predict_layers 1");
|
||||
check(g.qsa_interval == 4 && g.n_qsa_layers() == 1 && g.n_gdn_layers() == 3,
|
||||
"full_attention_interval 4: layers 0,1,2 GDN, layer 3 attention");
|
||||
check(strata::core::is_qsa_layer(g, 3) && !strata::core::is_qsa_layer(g, 2), "is_qsa_layer: (il+1) % 4 == 0");
|
||||
check(g.ssm_state_size == 16 && g.ssm_k_heads == 4 && g.ssm_v_heads == 8 && g.ssm_d_conv == 4,
|
||||
"ssm.state_size 16, group_count 4 (k-heads), time_step_rank 8 (v-heads), conv_kernel 4");
|
||||
check(g.ssm_value_dim == 128 && g.ssm_conv_channels == 2 * 4 * 16 + 128,
|
||||
"derived: value dim 8*16 = 128 (= ssm.inner_size), conv channels 2*4*16 + 128 = 256");
|
||||
check(g.n_head == 2 && g.n_head_kv == 1 && g.head_dim == 32, "attention.head_count 2, head_count_kv 1, key_length 32");
|
||||
check(g.n_rot == 8 && g.rope_sections[0] == 2 && g.rope_sections[1] == 1 && g.rope_sections[2] == 1 &&
|
||||
g.rope_sections[3] == 0,
|
||||
"rope.dimension_count 8 (0.25 * 32), dimension_sections [2,1,1,0]");
|
||||
check(std::fabs(g.rope_base - 10000.0) < 1e-6, "rope.freq_base 1e4 (the toy's; the real model is 1e7)");
|
||||
check(std::fabs(g.rms_eps - 1e-6) < 1e-12, "attention.layer_norm_rms_epsilon 1e-6");
|
||||
check(g.n_expert == 8 && g.n_expert_used == 2, "expert_count 8, expert_used_count 2");
|
||||
check(g.n_ff == 32 && g.n_ff_shexp == 32, "expert_feed_forward_length 32, expert_shared_feed_forward_length 32");
|
||||
check(g.hc == 1 && g.hc_dim() == g.n_embd, "hc 1 (no hyper-connections): hc_dim == n_embd");
|
||||
check(!g.has_ple && !g.has_indexer() && g.idx_q_heads == 0, "no PLE, no indexer");
|
||||
check(forms_ok(plain, g, err), "no fused tensor form: " + err);
|
||||
|
||||
const std::string nonextn = (dir / "toy-nonextn.gguf").string();
|
||||
ModelGeometry g2;
|
||||
check(read(nonextn, g2, err) && g2.n_layers == 4 && g2.nextn_layers == 0,
|
||||
"toy-nonextn.gguf: block_count 4, no nextn_predict_layers key -> 4 trunk layers, 0 draft blocks");
|
||||
check(forms_ok(nonextn, g2, err), "toy-nonextn.gguf: no fused tensor form");
|
||||
|
||||
const std::string fgu = (dir / "toy-fused-gate-up.gguf").string();
|
||||
ModelGeometry g3;
|
||||
check(read(fgu, g3, err), "toy-fused-gate-up.gguf: the metadata reads (the refusal is by tensor name)");
|
||||
const bool fgu_refused = !forms_ok(fgu, g3, err);
|
||||
check(fgu_refused && err.find("blk.0.ffn_gate_up_exps.weight") == 0,
|
||||
"toy-fused-gate-up.gguf: refused by name: " + err.substr(0, 60));
|
||||
|
||||
const std::string fqkv = (dir / "toy-fused-qkv.gguf").string();
|
||||
ModelGeometry g4;
|
||||
check(read(fqkv, g4, err), "toy-fused-qkv.gguf: the metadata reads");
|
||||
const bool fqkv_refused = !forms_ok(fqkv, g4, err);
|
||||
check(fqkv_refused && err.find("blk.3.attn_qkv.weight") == 0,
|
||||
"toy-fused-qkv.gguf: attn_qkv in the attention layer refused by name (blk.3), the GDN layers' attn_qkv "
|
||||
"accepted: " + err.substr(0, 40));
|
||||
}
|
||||
|
||||
// ---- Flash-Next's file (the six guard keys, as gguf_fixture writes them): the defaults stay, hc 4, PLE
|
||||
void qwen4exp() {
|
||||
TempDir d;
|
||||
const fs::path p = d.path / "flash.gguf";
|
||||
fixture::write(p, {fixture::str("general.architecture", "qwen4exp"), fixture::u32("qwen4exp.block_count", 48),
|
||||
fixture::u32("qwen4exp.embedding_length", 2560), fixture::u32("qwen4exp.expert_count", 512),
|
||||
fixture::u32("qwen4exp.expert_used_count", 10), fixture::u32("qwen4exp.attention.head_count", 24),
|
||||
fixture::u32("qwen4exp.attention.head_count_kv", 2)},
|
||||
{});
|
||||
ModelGeometry g;
|
||||
std::string err;
|
||||
const bool ok = read(p.string(), g, err);
|
||||
check(ok, "a qwen4exp file reads" + (ok ? std::string() : ": " + err));
|
||||
check(g.arch == ModelArch::Qwen4Exp && g.hc == 4 && g.hc_lr == 320 && g.has_ple && g.has_indexer(),
|
||||
"qwen4exp: hc 4, hc_lr 320, PLE and the indexer");
|
||||
check(g.n_layers == 48 && g.n_embd == 2560 && g.n_expert == 512 && g.n_expert_used == 10 && g.n_head == 24,
|
||||
"qwen4exp: the six keys");
|
||||
check(g.ssm_v_heads == 48 && g.ssm_conv_channels == 10240 && g.ssm_value_dim == 6144 && g.n_ff == 640,
|
||||
"qwen4exp: the GDN and expert widths keep Flash-Next's defaults when the file has no key for them");
|
||||
check(strata::check_architecture(strata::GgufFile(p.string())).empty(), "qwen4exp passes the architecture guard");
|
||||
|
||||
// the real Flash-Next key set (the Q2 file's metadata: ssm.*, key_length, the interval, the expert widths, the
|
||||
// rope keys): the reader's optional reads and its four refusals run on the working model's values and must land
|
||||
// on the defaults field by field - this is the one path that could refuse the model the engine already serves
|
||||
const fs::path full = d.path / "flash-full.gguf";
|
||||
// (block_count 48 with no draft block: the guard's qwen4exp branch wants the literal 48, as it always did)
|
||||
fixture::write(full, {fixture::str("general.architecture", "qwen4exp"), fixture::u32("qwen4exp.block_count", 48),
|
||||
fixture::u32("qwen4exp.embedding_length", 2560),
|
||||
fixture::u32("qwen4exp.expert_count", 512), fixture::u32("qwen4exp.expert_used_count", 10),
|
||||
fixture::u32("qwen4exp.attention.head_count", 24), fixture::u32("qwen4exp.attention.head_count_kv", 2),
|
||||
fixture::u32("qwen4exp.attention.key_length", 256), fixture::u32("qwen4exp.full_attention_interval", 4),
|
||||
fixture::u32("qwen4exp.ssm.conv_kernel", 4), fixture::u32("qwen4exp.ssm.state_size", 128),
|
||||
fixture::u32("qwen4exp.ssm.group_count", 16), fixture::u32("qwen4exp.ssm.time_step_rank", 48),
|
||||
fixture::u32("qwen4exp.ssm.inner_size", 6144), fixture::u32("qwen4exp.expert_feed_forward_length", 640),
|
||||
fixture::u32("qwen4exp.expert_shared_feed_forward_length", 640),
|
||||
fixture::u32("qwen4exp.rope.dimension_count", 64), fixture::u32s("qwen4exp.rope.dimension_sections", {11, 11, 10, 0}),
|
||||
fixture::f32("qwen4exp.rope.freq_base", 10000000.0f),
|
||||
fixture::f32("qwen4exp.attention.layer_norm_rms_epsilon", 1e-6f)},
|
||||
{});
|
||||
ModelGeometry gf;
|
||||
const bool okf = read(full.string(), gf, err);
|
||||
check(okf, "a qwen4exp file with the full key set reads" + (okf ? std::string() : ": " + err));
|
||||
const ModelGeometry def; // the struct's defaults are Flash-Next's
|
||||
check(gf.arch == def.arch && gf.n_embd == def.n_embd && gf.n_layers == def.n_layers && gf.nextn_layers == 0 &&
|
||||
gf.qsa_interval == def.qsa_interval && gf.n_vocab == def.n_vocab,
|
||||
"full key set: n_embd, 48 trunk layers, the interval, n_vocab equal the defaults");
|
||||
check(gf.ssm_state_size == def.ssm_state_size && gf.ssm_k_heads == def.ssm_k_heads && gf.ssm_v_heads == def.ssm_v_heads &&
|
||||
gf.ssm_d_conv == def.ssm_d_conv && gf.ssm_conv_channels == def.ssm_conv_channels &&
|
||||
gf.ssm_value_dim == def.ssm_value_dim,
|
||||
"full key set: the GDN fields and the derived conv channels / value dim equal the defaults");
|
||||
check(gf.n_head == def.n_head && gf.n_head_kv == def.n_head_kv && gf.head_dim == def.head_dim && gf.n_rot == def.n_rot &&
|
||||
gf.rope_sections[0] == 11 && gf.rope_sections[1] == 11 && gf.rope_sections[2] == 10 && gf.rope_sections[3] == 0 &&
|
||||
gf.rope_base == def.rope_base && std::fabs(gf.rms_eps - def.rms_eps) < 1e-12,
|
||||
"full key set: the attention and rope fields equal the defaults");
|
||||
check(gf.idx_q_heads == def.idx_q_heads && gf.idx_key_dim == def.idx_key_dim && gf.hc == def.hc && gf.hc_lr == def.hc_lr &&
|
||||
gf.n_expert == def.n_expert && gf.n_expert_used == def.n_expert_used && gf.n_ff == def.n_ff &&
|
||||
gf.n_ff_shexp == def.n_ff_shexp && gf.has_ple == def.has_ple && gf.has_indexer(),
|
||||
"full key set: the indexer, hc, the MoE widths and the PLE equal the defaults");
|
||||
const std::string guard_full = strata::check_architecture(strata::GgufFile(full.string()));
|
||||
check(guard_full.empty(), "the full-key file passes the guard" + (guard_full.empty() ? std::string() : ": " + guard_full));
|
||||
|
||||
// the guard and the reader refuse an unknown architecture by its name
|
||||
const fs::path q = d.path / "other.gguf";
|
||||
fixture::write(q, {fixture::str("general.architecture", "llama"), fixture::u32("llama.block_count", 32)}, {});
|
||||
const std::string guard = strata::check_architecture(strata::GgufFile(q.string()));
|
||||
check(guard.find("'llama'") != std::string::npos, "guard: 'llama' refused by name: " + guard);
|
||||
check(!read(q.string(), g, err) && err.find("'llama'") != std::string::npos, "reader: 'llama' refused by name");
|
||||
|
||||
// the vocabulary is read from the tensors; two statements of it that disagree are refused naming both
|
||||
const fs::path vq = d.path / "vocab.gguf";
|
||||
fixture::write(vq, {fixture::str("general.architecture", "qwen4exp"), fixture::u32("qwen4exp.block_count", 48),
|
||||
fixture::u32("qwen4exp.embedding_length", 2560), fixture::u32("qwen4exp.expert_count", 512),
|
||||
fixture::u32("qwen4exp.expert_used_count", 10), fixture::u32("qwen4exp.attention.head_count", 24),
|
||||
fixture::u32("qwen4exp.attention.head_count_kv", 2)},
|
||||
{fixture::Tensor{"output.weight", {64, 100}, 0, 1}, fixture::Tensor{"token_embd.weight", {64, 128}, 0, 2}});
|
||||
ModelGeometry gv;
|
||||
check(!read(vq.string(), gv, err) && err.find("output.weight says 100 tokens but token_embd.weight says 128") != std::string::npos,
|
||||
"output.weight 100 rows against token_embd.weight 128: refused naming both: " + err.substr(0, 70));
|
||||
const fs::path vo = d.path / "vocab-ok.gguf";
|
||||
fixture::write(vo, {fixture::str("general.architecture", "qwen4exp"), fixture::u32("qwen4exp.block_count", 48),
|
||||
fixture::u32("qwen4exp.embedding_length", 2560), fixture::u32("qwen4exp.expert_count", 512),
|
||||
fixture::u32("qwen4exp.expert_used_count", 10), fixture::u32("qwen4exp.attention.head_count", 24),
|
||||
fixture::u32("qwen4exp.attention.head_count_kv", 2)},
|
||||
{fixture::Tensor{"output.weight", {64, 100}, 0, 1}});
|
||||
check(read(vo.string(), gv, err) && gv.n_vocab == 100, "output.weight alone sets n_vocab 100");
|
||||
|
||||
// a qwen35moe file with a key llama.cpp's loader requires missing: the guard names it
|
||||
const fs::path r = d.path / "short.gguf";
|
||||
fixture::write(r, {fixture::str("general.architecture", "qwen35moe"), fixture::u32("qwen35moe.block_count", 40)}, {});
|
||||
const std::string g2 = strata::check_architecture(strata::GgufFile(r.string()));
|
||||
check(g2.find("missing qwen35moe.embedding_length") == 0, "guard: a short qwen35moe file: " + g2);
|
||||
|
||||
// a qwen35moe file whose ssm.inner_size contradicts state_size * time_step_rank
|
||||
const fs::path t = d.path / "inner.gguf";
|
||||
fixture::write(t, {fixture::str("general.architecture", "qwen35moe"), fixture::u32("qwen35moe.block_count", 4),
|
||||
fixture::u32("qwen35moe.embedding_length", 64), fixture::u32("qwen35moe.expert_count", 8),
|
||||
fixture::u32("qwen35moe.expert_used_count", 2), fixture::u32("qwen35moe.attention.head_count", 2),
|
||||
fixture::u32("qwen35moe.attention.head_count_kv", 1), fixture::u32("qwen35moe.attention.key_length", 32),
|
||||
fixture::u32("qwen35moe.full_attention_interval", 4), fixture::u32("qwen35moe.ssm.conv_kernel", 4),
|
||||
fixture::u32("qwen35moe.ssm.state_size", 16), fixture::u32("qwen35moe.ssm.group_count", 4),
|
||||
fixture::u32("qwen35moe.ssm.time_step_rank", 8), fixture::u32("qwen35moe.ssm.inner_size", 100),
|
||||
fixture::u32("qwen35moe.expert_feed_forward_length", 32)},
|
||||
{});
|
||||
check(!read(t.string(), g, err) && err.find("ssm.inner_size is 100") != std::string::npos,
|
||||
"reader: ssm.inner_size 100 against 16 * 8 refused: " + err);
|
||||
}
|
||||
|
||||
int real(const std::string& path) {
|
||||
ModelGeometry g;
|
||||
std::string err;
|
||||
if (!read(path, g, err)) {
|
||||
std::printf(" refused: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
std::printf("%s", strata::core::model_geometry_text(g).c_str());
|
||||
try {
|
||||
const std::string guard = strata::check_architecture(strata::GgufFile(path));
|
||||
std::printf(" architecture guard: %s\n", guard.empty() ? "passes" : guard.c_str());
|
||||
} catch (const std::exception& e) {
|
||||
std::printf(" architecture guard: %s\n", e.what());
|
||||
}
|
||||
try {
|
||||
if (!forms_ok(path, g, err)) std::printf(" tensor forms: %s\n", err.c_str());
|
||||
else std::printf(" tensor forms: separate experts, separate attention projections\n");
|
||||
} catch (const std::exception& e) {
|
||||
std::printf(" tensor forms: %s\n", e.what());
|
||||
}
|
||||
if (g.arch == ModelArch::Qwen35Moe && g.n_embd == 2048) {
|
||||
// Qwen3.6-35B-A3B exactly (docs/qwen36-port/gguf-metadata.md, metadata table)
|
||||
check(g.n_layers == 40 && (g.nextn_layers == 0 || g.nextn_layers == 1), "40 trunk layers (41 blocks in the MTP files)");
|
||||
check(g.n_qsa_layers() == 10 && g.n_gdn_layers() == 30, "10 attention layers (3, 7, ..., 39), 30 GDN");
|
||||
check(g.ssm_state_size == 128 && g.ssm_k_heads == 16 && g.ssm_v_heads == 32 && g.ssm_d_conv == 4,
|
||||
"GDN: state 128, 16 k-heads, 32 v-heads, conv 4");
|
||||
check(g.ssm_conv_channels == 8192 && g.ssm_value_dim == 4096, "conv channels 8192 = 2*2048 + 4096, value dim 4096");
|
||||
check(g.n_head == 16 && g.n_head_kv == 2 && g.head_dim == 256, "attention 16 heads / 2 KV / 256");
|
||||
check(g.n_rot == 64 && g.rope_sections[0] == 11 && g.rope_sections[1] == 11 && g.rope_sections[2] == 10 &&
|
||||
g.rope_sections[3] == 0 && std::fabs(g.rope_base - 1e7) < 1.0,
|
||||
"rope 64 of 256, sections [11, 11, 10, 0], base 1e7");
|
||||
check(g.n_expert == 256 && g.n_expert_used == 8 && g.n_ff == 512 && g.n_ff_shexp == 512,
|
||||
"256 experts x top-8, ff 512, shared ff 512");
|
||||
check(g.hc == 1 && !g.has_ple && !g.has_indexer(), "plain residual, no PLE, no indexer");
|
||||
check(std::fabs(g.rms_eps - 1e-6) < 1e-9, "rms eps 1e-6");
|
||||
check(g.n_vocab == 248320, "n_vocab 248320 (output.weight's rows, the tokenizer's list)");
|
||||
}
|
||||
if (g.arch == ModelArch::Qwen35Moe) std::printf(" gate: %s\n", strata::core::qwen35moe_not_yet(g).c_str());
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc == 3 && std::string(argv[1]) == "--real") return real(argv[2]);
|
||||
if (argc != 2) {
|
||||
std::printf("usage: model_geometry_test <dir of tools/qwen36_synth_gguf.py fixtures> | --real FILE.gguf\n");
|
||||
return 2;
|
||||
}
|
||||
if (fs::exists(fs::path(argv[1]) / "SKIP")) { // the fixture step found no numpy / gguf-py
|
||||
std::printf("model_geometry_test: the synthetic fixtures were not written (python3 with numpy and gguf-py "
|
||||
"is needed) - skipped\n");
|
||||
return 3;
|
||||
}
|
||||
std::printf("model_geometry_test\n");
|
||||
toy(argv[1]);
|
||||
qwen4exp();
|
||||
std::printf("%s\n", g_fail ? "FAILED" : "all passed");
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// tests/core/pack_load_check.cpp - a native pack loaded the way `strata generate --native SHARD1 --pack DIR` loads it,
|
||||
// up to the point where the first token would run, and every dense weight the step-3 code reads accounted for.
|
||||
//
|
||||
// pack_load_check --native FILE.gguf --pack DIR (or STRATA_QWEN36_GGUF / STRATA_QWEN36_PACK; neither: exit 77)
|
||||
//
|
||||
// Why a separate binary (Qwen3.6 port, step 4, docs/qwen36-port/step4-pack.md): `generate.cpp` stops a qwen35moe
|
||||
// start at the step-2 gate, which fires BEFORE the arena, the native projections, the head and the embedding are
|
||||
// loaded, so a run through the gate proves nothing about the pack. This does what the lines after the gate do, in
|
||||
// their order, with the same classes and the same skip set, then `check_all` (the per-layer shape and form check the
|
||||
// kernels rely on, which generate.cpp does not call itself), and prints what each site will read: the name, the
|
||||
// engine form (WeightKind), the bytes, and for a natively served projection its ggml type. Exit 0 when every load
|
||||
// and every check passes, 1 with the first refusal on stderr, 77 without a CUDA device or a model.
|
||||
//
|
||||
// What it is NOT: it runs no kernel. The first Qwen3.6 token through this pack is the gate-lifting agent's.
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
#include "strata/artifact/gguf_split.hpp"
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/core/model_geometry.hpp"
|
||||
#include "strata/core/native_dense.hpp"
|
||||
#include "strata/core/native_head.hpp"
|
||||
#include "strata/core/weights.hpp"
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using strata::core::ModelGeometry;
|
||||
using strata::core::WeightKind;
|
||||
using strata::core::WeightRef;
|
||||
using strata::core::WeightTable;
|
||||
|
||||
namespace {
|
||||
|
||||
double now_ms() {
|
||||
using namespace std::chrono;
|
||||
return duration<double, std::milli>(steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
int fail(const std::string& what, const std::string& err) {
|
||||
std::fprintf(stderr, "pack_load_check: %s: %s\n", what.c_str(), err.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char* kind_name(WeightKind k) {
|
||||
switch (k) {
|
||||
case WeightKind::Verbatim: return "verbatim";
|
||||
case WeightKind::Bf16InF32: return "bf16";
|
||||
case WeightKind::F32: return "f32";
|
||||
case WeightKind::F16InF32: return "f16";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/// One weight as a site reads it: `name kind bytes [native TYPE]`, or `MISSING`.
|
||||
std::string describe(const WeightTable& wt, const std::string& name) {
|
||||
const WeightRef* r = wt.find(name);
|
||||
if (!r) return name + " MISSING";
|
||||
char buf[256];
|
||||
if (r->native_data) {
|
||||
std::snprintf(buf, sizeof buf, "%s native %s [%lld x %lld]", name.c_str(),
|
||||
strata::ggml_type_name((uint32_t) r->native_type), (long long) r->ne0, (long long) r->ne1);
|
||||
} else {
|
||||
std::snprintf(buf, sizeof buf, "%s %s %llu B (%lld elems)%s", name.c_str(), kind_name(r->kind),
|
||||
(unsigned long long) r->bytes, (long long) r->elements, r->resident ? "" : " NOT RESIDENT");
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::string gguf, pack;
|
||||
for (int i = 1; i + 1 < argc; ++i) {
|
||||
if (std::strcmp(argv[i], "--native") == 0) gguf = argv[++i];
|
||||
else if (std::strcmp(argv[i], "--pack") == 0) pack = argv[++i];
|
||||
}
|
||||
if (gguf.empty() && std::getenv("STRATA_QWEN36_GGUF")) gguf = std::getenv("STRATA_QWEN36_GGUF");
|
||||
if (pack.empty() && std::getenv("STRATA_QWEN36_PACK")) pack = std::getenv("STRATA_QWEN36_PACK");
|
||||
if (gguf.empty() || pack.empty()) {
|
||||
std::fprintf(stderr, "pack_load_check: no --native FILE / --pack DIR (nor STRATA_QWEN36_GGUF / STRATA_QWEN36_PACK): "
|
||||
"skipped\n");
|
||||
return 77;
|
||||
}
|
||||
int devices = 0;
|
||||
if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
|
||||
std::fprintf(stderr, "pack_load_check: no CUDA device: skipped\n");
|
||||
return 77;
|
||||
}
|
||||
std::string err;
|
||||
|
||||
// ---- 1. the geometry from the file, the fused forms refused, as generate.cpp:2071-2095
|
||||
ModelGeometry g;
|
||||
if (!strata::core::read_model_geometry(gguf, g, err)) return fail("read_model_geometry", err);
|
||||
std::printf("geometry (%s):\n%s", gguf.c_str(), strata::core::model_geometry_text(g).c_str());
|
||||
std::vector<std::string> shards;
|
||||
try {
|
||||
shards = strata::gguf_split_paths(gguf);
|
||||
const strata::GgufModel model(shards);
|
||||
if (!strata::core::check_model_tensor_forms(model, g, err)) return fail("check_model_tensor_forms", err);
|
||||
} catch (const std::exception& e) {
|
||||
return fail("opening the shards", e.what());
|
||||
}
|
||||
|
||||
// ---- 2. the expert table against the geometry (generate.cpp:2102)
|
||||
if (!strata::kernels::cpu::expert_layout_load(pack, g.n_layers, g.n_expert, g.n_embd, g.n_ff, err))
|
||||
return fail("expert_layout_load", err);
|
||||
const auto& lay = strata::kernels::cpu::expert_layout();
|
||||
if (!lay.native) return fail("expert layout", pack + " has no native_experts.txt (not a native pack)");
|
||||
std::printf("native_experts.txt: v%d, %lld layers x %lld experts, %llu B of experts, largest blob %zu B\n",
|
||||
lay.version, (long long) lay.fmt.size(), (long long) lay.n_expert, (unsigned long long) lay.total,
|
||||
lay.max_blob);
|
||||
if ((int64_t) lay.fmt.size() != g.n_layers)
|
||||
return fail("expert layout", "the table has " + std::to_string(lay.fmt.size()) + " layers, the geometry " +
|
||||
std::to_string(g.n_layers));
|
||||
|
||||
// ---- 3. the skip set and the arena (generate.cpp:2433-2516): natively served names are not loaded in
|
||||
// canonical form; the head and the embedding come from the GGUF
|
||||
std::set<std::string> skip;
|
||||
if (!strata::core::NativeDense::served_names(shards, false, skip, err)) return fail("served_names", err);
|
||||
skip.insert("output.weight");
|
||||
skip.insert("token_embd.weight");
|
||||
uint64_t pool = 0;
|
||||
if (!WeightTable::pool_bytes(pack, pool, err, &skip)) return fail("pool_bytes", err);
|
||||
void* arena = nullptr;
|
||||
if (cudaMalloc(&arena, pool) != cudaSuccess) return fail("cudaMalloc", "arena of " + std::to_string(pool) + " B");
|
||||
WeightTable wt;
|
||||
double t0 = now_ms();
|
||||
if (!wt.load(pack, arena, pool, err, &skip)) return fail("WeightTable::load", err);
|
||||
std::printf("dense.bin: %zu index rows, %llu B arena (%.1f MiB), %zu rows skipped as natively served, "
|
||||
"read %.0f ms + upload %.0f ms\n", wt.report().tensors, (unsigned long long) pool, pool / 1048576.0,
|
||||
skip.size(), wt.report().read_ms, wt.report().upload_ms);
|
||||
|
||||
// ---- 4. the native projections, bounded to the trunk (the draft block of a -MTP file is the drafter's)
|
||||
strata::core::NativeDense dense;
|
||||
t0 = now_ms();
|
||||
if (!dense.load(shards, wt, err, false, 0, g.n_layers)) return fail("NativeDense::load", err);
|
||||
std::printf("native projections: %zu matrices, %llu B (%.1f MiB) in VRAM, %.0f ms\n", dense.tensor_count(),
|
||||
(unsigned long long) dense.weight_bytes(), dense.weight_bytes() / 1048576.0, now_ms() - t0);
|
||||
|
||||
// ---- 5. every layer's shapes and forms, as the kernels require them (src/core/layout.cpp)
|
||||
if (!strata::core::check_all(wt, g, err)) return fail("check_all", err);
|
||||
std::printf("check_all: %lld layers (%lld attention, %lld GDN): every name, shape and engine form the kernels "
|
||||
"require\n", (long long) g.n_layers, (long long) g.n_qsa_layers(), (long long) g.n_gdn_layers());
|
||||
|
||||
// ---- 6. the head and the embedding from the GGUF (generate.cpp:3277-3283, :2424); the vocabulary is
|
||||
// output.weight's ne1, as generate.cpp takes it (ModelGeometry::n_vocab is the Flash-Next default)
|
||||
const WeightRef* wo = wt.find("output.weight");
|
||||
const WeightRef* wn = wt.find("output_norm.weight");
|
||||
if (!wo) return fail("output.weight", "missing from the index");
|
||||
if (!wn || wn->kind != WeightKind::F32 || wn->elements != g.n_embd)
|
||||
return fail("output_norm.weight", wn ? "wrong form or size" : "missing");
|
||||
const int64_t n_vocab = wo->ne1;
|
||||
strata::core::NativeHead head;
|
||||
t0 = now_ms();
|
||||
if (!head.load(shards, g.n_embd, n_vocab, err)) return fail("NativeHead::load", err);
|
||||
std::printf("native head: output.weight %s, %llu B, n_vocab %lld, %.0f ms\n",
|
||||
strata::ggml_type_name((uint32_t) head.type()), (unsigned long long) head.weight_bytes(),
|
||||
(long long) n_vocab, now_ms() - t0);
|
||||
strata::core::NativeEmbed embed;
|
||||
t0 = now_ms();
|
||||
if (!embed.load(shards, g.n_embd, n_vocab, err)) return fail("NativeEmbed::load", err);
|
||||
std::printf("native embedding: token_embd.weight %s, %llu B mapped, %.0f ms\n",
|
||||
strata::ggml_type_name((uint32_t) embed.type()), (unsigned long long) embed.bytes(), now_ms() - t0);
|
||||
|
||||
// ---- 7. the expert profile, when the pack ships one
|
||||
const std::string profile = pack + "/expert-profile.bin";
|
||||
if (std::filesystem::exists(profile)) {
|
||||
std::vector<std::pair<int32_t, int32_t>> ranked;
|
||||
int64_t slots = 0;
|
||||
if (!strata::core::read_expert_profile(profile, g.n_layers, g.n_expert, ranked, slots, err))
|
||||
return fail("read_expert_profile", err);
|
||||
std::printf("expert-profile.bin: %zu ranked pairs of %lld x %lld, %lld slots\n", ranked.size(),
|
||||
(long long) g.n_layers, (long long) g.n_expert, (long long) slots);
|
||||
} else {
|
||||
std::printf("expert-profile.bin: none in the pack\n");
|
||||
}
|
||||
|
||||
// ---- 8. what each site reads, per layer family: the names from layout.cpp's tables and the mixers' own
|
||||
// lookups (layer.cpp gdn_layer / qsa_layer / moe_route / moe_shared, verify.cpp, prefill.cpp)
|
||||
const char* gdn[] = {"attn_norm.weight", "post_attention_norm.weight", "attn_qkv.weight", "attn_gate.weight",
|
||||
"ssm_out.weight", "ssm_conv1d.weight", "ssm_alpha.weight", "ssm_beta.weight", "ssm_a",
|
||||
"ssm_dt.bias", "ssm_norm.weight", "ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight",
|
||||
"ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight"};
|
||||
const char* attn[] = {"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"};
|
||||
int missing = 0;
|
||||
for (int64_t l = 0; l < g.n_layers; ++l) {
|
||||
const strata::core::LayerView v(wt, l);
|
||||
const bool qsa = strata::core::is_qsa_layer(g, l);
|
||||
const bool show = l == 0 || l == g.qsa_interval - 1; // one GDN and one attention layer in full
|
||||
if (show) std::printf("layer %lld (%s):\n", (long long) l, qsa ? "attention" : "GDN");
|
||||
const char* const* names = qsa ? attn : gdn;
|
||||
const size_t n = qsa ? sizeof attn / sizeof *attn : sizeof gdn / sizeof *gdn;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const std::string d = describe(wt, v.name(names[i]));
|
||||
if (d.find(" MISSING") != std::string::npos || d.find("NOT RESIDENT") != std::string::npos) {
|
||||
++missing;
|
||||
std::printf(" %s\n", d.c_str());
|
||||
} else if (show) {
|
||||
std::printf(" %s\n", d.c_str());
|
||||
}
|
||||
}
|
||||
// the draft block's names must not have leaked into the trunk's table
|
||||
if (wt.find("blk." + std::to_string(g.n_layers) + ".attn_norm.weight") != nullptr) {
|
||||
std::printf(" blk.%lld (a draft block) is in the index: the pack is not trunk-only\n", (long long) g.n_layers);
|
||||
++missing;
|
||||
}
|
||||
}
|
||||
std::printf("output_norm.weight: %s\n", describe(wt, "output_norm.weight").c_str());
|
||||
std::printf("output.weight: index row %lld x %lld, served by the native head\n", (long long) wo->ne0, (long long) wo->ne1);
|
||||
if (missing) return fail("site reads", std::to_string(missing) + " weight(s) missing or not resident (above)");
|
||||
std::printf("pack_load_check: %s against %s: OK\n", pack.c_str(), gguf.c_str());
|
||||
cudaFree(arena);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// The expert pool's native-pack path (run_split_multi_native: gate/up rows, the intermediate's quantization, down
|
||||
// rows, each split across the workers) must use the LAYER'S widths, NativeFmt::n_ff and n_embd, not the canonical
|
||||
// Q2_0 pack's FF / H (640 / 2560). Qwen3.6-35B-A3B's experts are 2048 x 512: with FF / H the down phase wrote 512
|
||||
// rows past every output row and the first verify window with a CPU-computed expert miss decoded to token 0.
|
||||
//
|
||||
// Three Q8_0 experts at 2048 x 512, four tokens; the pool's rows against the same kernels called directly, and a
|
||||
// guard after every output row that must stay untouched.
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
#include "strata/kernels/cpu/pool.hpp"
|
||||
#include "ggml.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace strata::kernels::cpu;
|
||||
|
||||
namespace {
|
||||
int g_fail = 0;
|
||||
void check(bool ok, const std::string& what) {
|
||||
std::printf(" %-90s %s\n", what.c_str(), ok ? "ok" : "FAIL");
|
||||
if (!ok) ++g_fail;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const int64_t n_embd = 2048, n_ff = 512; // Qwen3.6-35B-A3B's expert geometry
|
||||
const int kType = (int) GGML_TYPE_Q8_0;
|
||||
NativeFmt f;
|
||||
std::string err;
|
||||
if (!native_fmt(kType, kType, n_embd, n_ff, f, err)) { std::printf("native_fmt: %s\n", err.c_str()); return 1; }
|
||||
check(f.n_embd == n_embd && f.n_ff == n_ff, "the format carries the layer's widths 2048 x 512");
|
||||
check(n_embd < H && n_ff < FF, "the layer is narrower than the canonical FF / H, so the old row counts overran");
|
||||
NativeFmt wide;
|
||||
const bool wide_ok = native_fmt(kType, kType, H + 64, n_ff, wide, err);
|
||||
check(!wide_ok, "a layer wider than the pool's buffers is refused: " + err);
|
||||
|
||||
const int E = 3, T = 4;
|
||||
std::mt19937 rng(7);
|
||||
std::normal_distribution<float> nd(0.f, 0.5f);
|
||||
std::vector<std::vector<uint8_t>> blobs((size_t) E);
|
||||
std::vector<float> row((size_t) std::max(n_embd, n_ff));
|
||||
for (int e = 0; e < E; ++e) {
|
||||
auto& b = blobs[(size_t) e];
|
||||
b.assign(f.bytes, 0);
|
||||
for (int part = 0; part < 3; ++part) { // gate, up: n_ff rows of n_embd; down: n_embd rows of n_ff
|
||||
const int64_t rows = part < 2 ? n_ff : n_embd, cols = part < 2 ? n_embd : n_ff;
|
||||
std::vector<float> m((size_t) (rows * cols));
|
||||
for (float& v : m) v = nd(rng);
|
||||
uint8_t* dst = b.data() + (part == 0 ? 0 : part == 1 ? f.up_off : f.down_off);
|
||||
ggml_quantize_chunk((ggml_type) kType, m.data(), dst, 0, rows, cols, nullptr);
|
||||
}
|
||||
}
|
||||
std::vector<std::vector<float>> x((size_t) T, std::vector<float>((size_t) n_embd));
|
||||
std::vector<std::vector<uint8_t>> act((size_t) T, std::vector<uint8_t>(kNativeActBytes));
|
||||
for (int t = 0; t < T; ++t) {
|
||||
for (float& v : x[(size_t) t]) v = nd(rng);
|
||||
native_quant_act(f, x[(size_t) t].data(), act[(size_t) t].data());
|
||||
}
|
||||
// token -> expert: tokens 0,1 on expert 0; token 2 on expert 1; token 3 on expert 2 (then 1 again: two experts)
|
||||
const int routes[][2] = {{0, 0}, {1, 0}, {2, 1}, {3, 2}, {3, 1}};
|
||||
const int R = 5;
|
||||
|
||||
// the reference: the kernels directly, one expert at a time, over exactly the layer's rows
|
||||
std::vector<std::vector<float>> ref((size_t) R, std::vector<float>((size_t) n_embd));
|
||||
for (int e = 0; e < E; ++e) {
|
||||
const void* nact[MAXT] = {};
|
||||
float* ffp[MAXT] = {};
|
||||
const void* hq[MAXT] = {};
|
||||
float* out[MAXT] = {};
|
||||
std::vector<std::vector<float>> ff;
|
||||
std::vector<std::vector<uint8_t>> h;
|
||||
int nt = 0;
|
||||
for (int r = 0; r < R; ++r)
|
||||
if (routes[r][1] == e) {
|
||||
ff.emplace_back((size_t) n_ff);
|
||||
h.emplace_back(kNativeHBytes);
|
||||
++nt;
|
||||
}
|
||||
int i = 0;
|
||||
for (int r = 0; r < R; ++r)
|
||||
if (routes[r][1] == e) {
|
||||
nact[i] = act[(size_t) routes[r][0]].data();
|
||||
ffp[i] = ff[(size_t) i].data();
|
||||
hq[i] = h[(size_t) i].data();
|
||||
out[i] = ref[(size_t) r].data();
|
||||
++i;
|
||||
}
|
||||
native_gu_rows(f, blobs[(size_t) e].data(), nact, nt, ffp, 0, (int) n_ff);
|
||||
for (int k = 0; k < nt; ++k) native_quant_h(f, ffp[k], h[(size_t) k].data());
|
||||
native_down_rows(f, blobs[(size_t) e].data(), hq, nt, out, 0, (int) n_embd);
|
||||
}
|
||||
|
||||
// the pool: every output row followed by a guard of H floats (the old overrun was H - n_embd rows)
|
||||
const int64_t guard = H, pitch = n_embd + guard;
|
||||
const float sentinel = 1234.5f;
|
||||
std::vector<float> outbuf((size_t) (R * pitch), sentinel);
|
||||
ExpertJobMulti jobs[E];
|
||||
for (int e = 0; e < E; ++e) jobs[e].blob = blobs[(size_t) e].data();
|
||||
for (int r = 0; r < R; ++r) {
|
||||
ExpertJobMulti& j = jobs[routes[r][1]];
|
||||
j.nact[j.nt] = act[(size_t) routes[r][0]].data();
|
||||
j.out[j.nt] = outbuf.data() + (size_t) r * pitch;
|
||||
++j.nt;
|
||||
}
|
||||
ExpertPool pool(2, false, true);
|
||||
pool.run_split_multi_native(f, jobs, E);
|
||||
|
||||
double worst = 0;
|
||||
bool guards = true;
|
||||
for (int r = 0; r < R; ++r) {
|
||||
const float* got = outbuf.data() + (size_t) r * pitch;
|
||||
for (int64_t i = 0; i < n_embd; ++i)
|
||||
worst = std::max(worst, (double) std::fabs(got[i] - ref[(size_t) r][(size_t) i]));
|
||||
for (int64_t i = n_embd; i < pitch; ++i)
|
||||
if (got[i] != sentinel) { guards = false; break; }
|
||||
}
|
||||
check(guards, "no output row's guard was written (the down phase stopped at n_embd rows)");
|
||||
check(worst <= 1e-5, "the pool's rows equal the kernels' direct rows (worst abs diff " + std::to_string(worst) + ")");
|
||||
std::printf("%s: %d failure(s)\n", g_fail == 0 ? "PASS" : "FAIL", g_fail);
|
||||
return g_fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
// tests/core/vram_plan_test.cpp - the VRAM planner's arithmetic against docs/QWEN36-35B-A3B.md table 4.3 (no GPU).
|
||||
//
|
||||
// The inputs are the study's fixed set (table 4.1: weights 2,038 / 1,597 MiB, drafter ~520, KV 1,440 MiB at
|
||||
// 262,144 as q4_0 over 10 attention layers = 5,760 B per token, session ~164, CUDA context ~300, the 300 MiB small
|
||||
// reserve, prompt buffers 1,904 / 1,878 MiB when prefill does not borrow) and the census of the two files
|
||||
// (tests/data/native_experts/qwen36-*.txt: 19,635,634,176 and 11,108,614,144 B over 40 x 256 experts, the "1.829 /
|
||||
// 1.035 MiB mean blob"). Each ladder row is checked two ways: exactly against the derivation
|
||||
// floor((budget - fixed) / blob), and within the table's rounding (its values are rounded to tens) of the number
|
||||
// the study printed. Then the rule's other branches: the context lowered toward 131,072 when the request does
|
||||
// not fit, the refusal below the floor naming the IQ3 file, the RAM tier at the replay's 9.5 GB, and the disk
|
||||
// tier that remains on the 1080 Ti.
|
||||
#include "strata/plan/vram_plan.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
using strata::plan::VramPlan;
|
||||
using strata::plan::VramPlanInput;
|
||||
|
||||
namespace {
|
||||
int g_fail = 0;
|
||||
void check(bool ok, const std::string& what) {
|
||||
std::printf(" %-100s %s\n", what.c_str(), ok ? "ok" : "FAIL");
|
||||
if (!ok) ++g_fail;
|
||||
}
|
||||
constexpr uint64_t MiB = 1u << 20;
|
||||
constexpr int64_t kExperts = 40 * 256;
|
||||
constexpr uint64_t kQ4Total = 19635634176ull, kIq3Total = 11108614144ull; // the two files' expert bytes (census)
|
||||
constexpr uint64_t kQ4Blob = kQ4Total / kExperts, kIq3Blob = kIq3Total / kExperts;
|
||||
constexpr uint64_t kKvPerToken = 5760; // q4_0 K and V, 2 KV heads x 256, 10 layers: 1,440 MiB at 262,144
|
||||
|
||||
VramPlanInput arm(bool q4, bool borrow, uint64_t budget_mib) {
|
||||
VramPlanInput in;
|
||||
in.budget_bytes = budget_mib * MiB;
|
||||
in.weights_bytes = (q4 ? 2038 : 1597) * MiB;
|
||||
in.drafter_bytes = 520 * MiB;
|
||||
in.kv_bytes_per_token = kKvPerToken;
|
||||
in.session_bytes = 164 * MiB;
|
||||
in.cuda_context_bytes = 300 * MiB;
|
||||
in.reserve_bytes = 300 * MiB;
|
||||
in.prompt_bytes = borrow ? 0 : (q4 ? 1904 : 1878) * MiB;
|
||||
in.context = 262144;
|
||||
in.context_floor = 131072;
|
||||
in.n_experts = kExperts;
|
||||
in.mean_blob = q4 ? kQ4Blob : kIq3Blob;
|
||||
in.ram_available_bytes = 0;
|
||||
in.smaller_file = "Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf";
|
||||
return in;
|
||||
}
|
||||
|
||||
/// The derivation the table was made by: floor((budget - fixed) / blob), capped at every expert; -1 = no fit.
|
||||
int64_t derive(const VramPlanInput& in) {
|
||||
const uint64_t fixed = strata::plan::vram_plan_fixed(in, in.context);
|
||||
if (fixed > in.budget_bytes) return -1;
|
||||
const int64_t s = (int64_t) ((in.budget_bytes - fixed) / in.mean_blob);
|
||||
return s < in.n_experts ? s : in.n_experts;
|
||||
}
|
||||
|
||||
struct Row { const char* label; uint64_t budget_mib; int64_t q4_noborrow, q4_borrow, iq3_borrow; };
|
||||
constexpr int64_t ALL = kExperts, NOFIT = -1;
|
||||
// table 4.3's "derived" columns (the study's rounding: to tens; "all" is every expert)
|
||||
const Row rows[] = {
|
||||
{"6 GB (5,722 MiB)", 5722, NOFIT, 525, 1350},
|
||||
{"8 GB (7,629 MiB)", 7629, 525, 1570, 3200},
|
||||
{"11 GB decimal (10,490 MiB)", 10490, 2090, 3130, 5960},
|
||||
{"1080 Ti (11,264 MiB)", 11264, 2510, 3550, 6700},
|
||||
{"12 GB (11,444 MiB)", 11444, 2610, 3650, 6880},
|
||||
{"16 GB (15,258 MiB)", 15258, 4700, 5740, ALL},
|
||||
{"24 GB (24,576 MiB)", 24576, 9790, ALL, ALL},
|
||||
{"32 GB (30,517 MiB)", 30517, ALL, ALL, ALL},
|
||||
};
|
||||
|
||||
void ladder() {
|
||||
for (const Row& r : rows) {
|
||||
struct Col { const char* name; bool q4, borrow; int64_t table; } cols[] = {
|
||||
{"Q4 no borrow", true, false, r.q4_noborrow},
|
||||
{"Q4 borrow", true, true, r.q4_borrow},
|
||||
{"IQ3 borrow", false, true, r.iq3_borrow},
|
||||
};
|
||||
for (const Col& c : cols) {
|
||||
const VramPlanInput in = arm(c.q4, c.borrow, r.budget_mib);
|
||||
const VramPlan p = strata::plan::make_vram_plan(in);
|
||||
const int64_t d = derive(in);
|
||||
char what[256];
|
||||
if (c.table == NOFIT) {
|
||||
// the fixed set does not fit at 262,144; nor at the floor (6 GB at Q4 without borrowing)
|
||||
std::snprintf(what, sizeof what, "%s, %s: does not fit at 262,144 nor at 131,072 (table: 0)", r.label, c.name);
|
||||
check(!p.fits && d == NOFIT && p.refusal.find("Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf") != std::string::npos &&
|
||||
p.refusal.find("131072") != std::string::npos,
|
||||
what);
|
||||
continue;
|
||||
}
|
||||
const int64_t got = p.vram_slots;
|
||||
const int64_t diff = got > c.table ? got - c.table : c.table - got;
|
||||
std::snprintf(what, sizeof what, "%s, %s: %lld slots (derivation %lld, table %s%lld)", r.label, c.name,
|
||||
(long long) got, (long long) d, c.table == ALL ? "all = " : "~", (long long) c.table);
|
||||
// exact against the derivation; the printed table rounds to tens (one cell, the 1080 Ti at IQ3, to the
|
||||
// hundred: 6,711 printed as ~6,700), so the figure it printed is within 15 of the slot count
|
||||
check(p.fits && !p.lowered && p.context == 262144 && got == d && diff <= 15, what);
|
||||
if (c.table == ALL) {
|
||||
std::snprintf(what, sizeof what, "%s, %s: every expert resident, spare %llu MiB", r.label, c.name,
|
||||
(unsigned long long) (p.spare_bytes >> 20));
|
||||
check(p.vram_slots == kExperts && p.mapped == 0 && p.spare_bytes == (in.budget_bytes - p.fixed_bytes) - kExperts * in.mean_blob, what);
|
||||
}
|
||||
}
|
||||
}
|
||||
// the 24 GB Q4-borrow row's spare: the table says ~1,090 MiB
|
||||
const VramPlan p24 = strata::plan::make_vram_plan(arm(true, true, 24576));
|
||||
check(p24.spare_bytes / MiB >= 1080 && p24.spare_bytes / MiB <= 1095,
|
||||
"24 GB, Q4 borrow: ~1,090 MiB spare (" + std::to_string(p24.spare_bytes / MiB) + ")");
|
||||
}
|
||||
|
||||
// Qwen3.6 step 4 (step4-drafter.md section 7): the drafter's term is its weights, its K/V over the WHOLE context in
|
||||
// the --kv format, the draft head subset with the logits, and the identity ids; the step-2 line (weights + 16 MiB)
|
||||
// undercounted it. The per-token part lowers with the context.
|
||||
void drafter() {
|
||||
VramPlanInput in = arm(true, true, 24576);
|
||||
in.drafter_bytes = 506 * MiB;
|
||||
in.drafter_kv_bytes_per_token = 2 * 2 * 256 * 2; // fp16 K and V, 2 KV heads x 256: 1,024 B per cell
|
||||
in.drafter_head_bytes = 106299ull * 2176 + 8ull * 248320 * 4; // the Q8_0 head's subset (221 MiB) + logits
|
||||
in.drafter_ids_bytes_per_token = 4 * 4; // --spec 4
|
||||
const uint64_t drafter = strata::plan::vram_plan_drafter(in, 262144);
|
||||
check(drafter / MiB >= 506 + 512 + 221 + 7 + 4 && drafter / MiB <= 506 + 512 + 229 + 4 + 2,
|
||||
"24 GB, Q4 borrow, --mtp at 262,144 fp16: the drafter is weights 506 + K/V 512 + head 221 + logits 7.6 + ids 4 MiB (" +
|
||||
std::to_string(drafter / MiB) + ")");
|
||||
const VramPlan p = strata::plan::make_vram_plan(in);
|
||||
const VramPlan p0 = strata::plan::make_vram_plan(arm(true, true, 24576));
|
||||
check(p.fits && p.fixed_bytes == p0.fixed_bytes - 520 * MiB + drafter && p.vram_slots == derive(in),
|
||||
"the fixed set grows by the drafter's whole share and the slots derive from it (" + std::to_string(p.vram_slots) +
|
||||
" vs " + std::to_string(p0.vram_slots) + " at the step-2 line)");
|
||||
// the lowering counts the drafter's per-token K/V and ids: a budget that holds the fixed set at 0 tokens plus
|
||||
// exactly 200,000 tokens' worth of per-token bytes lowers to 196,608 (the step), not to what the trunk's KV alone
|
||||
// would give
|
||||
VramPlanInput low = in;
|
||||
low.budget_bytes = strata::plan::vram_plan_fixed(in, 0) + strata::plan::vram_plan_per_token(in) * 200000;
|
||||
const VramPlan pl = strata::plan::make_vram_plan(low);
|
||||
check(pl.fits && pl.lowered && pl.context == 196608,
|
||||
"a budget 200,000 tokens of trunk KV + drafter K/V + ids above the fixed set lowers to 196,608 (" +
|
||||
std::to_string(pl.context) + ")");
|
||||
VramPlanInput none = arm(true, true, 24576);
|
||||
none.drafter_bytes = 0;
|
||||
check(strata::plan::vram_plan_text(none, strata::plan::make_vram_plan(none)).find("(no --mtp)") != std::string::npos,
|
||||
"without --mtp the plan says so and counts no drafter");
|
||||
}
|
||||
|
||||
void tiers() {
|
||||
// the RAM tier at the replay's 9.5 GB usable (section 4.3: Q4 ~4,950 experts, IQ3 ~8,760), the 1080 Ti's VRAM
|
||||
// slots, and the disk tier that remains at Q4 (~1,740 with borrowing, ~2,780 without)
|
||||
VramPlanInput q4 = arm(true, true, 11264);
|
||||
q4.ram_available_bytes = 9500000000ull; // 9.5 GB decimal, as the replay
|
||||
q4.ram_headroom_bytes = 0;
|
||||
const VramPlan p = strata::plan::make_vram_plan(q4);
|
||||
check(p.ram_copies >= 4940 && p.ram_copies <= 4960, "1080 Ti, Q4 borrow, 9.5 GB RAM: ~4,950 RAM copies (" + std::to_string(p.ram_copies) + ")");
|
||||
check(p.mapped >= 1730 && p.mapped <= 1750 && p.vram_slots + p.ram_copies + p.mapped == kExperts,
|
||||
"1080 Ti, Q4 borrow: ~1,740 experts stay on disk (" + std::to_string(p.mapped) + "), the three tiers sum to 10,240");
|
||||
VramPlanInput q4n = arm(true, false, 11264);
|
||||
q4n.ram_available_bytes = 9500000000ull;
|
||||
const VramPlan pn = strata::plan::make_vram_plan(q4n);
|
||||
check(pn.mapped >= 2770 && pn.mapped <= 2790, "1080 Ti, Q4 no borrow: ~2,780 on disk (" + std::to_string(pn.mapped) + ")");
|
||||
VramPlanInput iq3 = arm(false, true, 11264);
|
||||
iq3.ram_available_bytes = 9500000000ull;
|
||||
const VramPlan pi = strata::plan::make_vram_plan(iq3);
|
||||
check(pi.mapped == 0 && pi.ram_copies == kExperts - pi.vram_slots && pi.ram_copies < 8760,
|
||||
"1080 Ti, IQ3: no disk tier (RAM would hold ~8,760, " + std::to_string(kExperts - pi.vram_slots) + " are needed)");
|
||||
// the headroom comes off the RAM before anything is placed
|
||||
VramPlanInput h = arm(true, true, 11264);
|
||||
h.ram_available_bytes = 12ull << 30;
|
||||
h.ram_headroom_bytes = 4ull << 30;
|
||||
const VramPlan ph = strata::plan::make_vram_plan(h);
|
||||
check(ph.ram_copies == (int64_t) ((8ull << 30) / kQ4Blob), "12 GiB available minus 4 GiB headroom: the tier is sized from 8 GiB");
|
||||
}
|
||||
|
||||
void lowering() {
|
||||
// Q4 without borrowing on a card between the floor and the request: the context is lowered, a multiple of 4,096,
|
||||
// never below 131,072, and the plan says so
|
||||
const VramPlanInput in = arm(true, false, 6400);
|
||||
const VramPlan p = strata::plan::make_vram_plan(in);
|
||||
const uint64_t without_kv = strata::plan::vram_plan_fixed(in, 0);
|
||||
const int64_t expect = (int64_t) (((6400 * MiB - without_kv) / kKvPerToken) / 4096 * 4096);
|
||||
check(p.fits && p.lowered && p.context == expect && p.context >= 131072 && p.context < 262144 && p.context % 4096 == 0,
|
||||
"Q4 no borrow at 6,400 MiB: context lowered to " + std::to_string(p.context) + " (a multiple of 4,096 at or above the floor)");
|
||||
check(strata::plan::vram_plan_fixed(in, p.context) <= in.budget_bytes &&
|
||||
strata::plan::vram_plan_fixed(in, p.context + 4096) > in.budget_bytes,
|
||||
"the lowered context is the largest step that fits");
|
||||
const std::string text = strata::plan::vram_plan_text(in, p);
|
||||
check(text.find("LOWERED") != std::string::npos && text.find("131072") != std::string::npos, "the log says LOWERED and names the floor");
|
||||
// IQ3 without borrowing on 6 GB: the floor fits (6,200 - 720 = 5,480 MiB), 262,144 does not
|
||||
const VramPlanInput i6 = arm(false, false, 5722);
|
||||
const VramPlan p6 = strata::plan::make_vram_plan(i6);
|
||||
check(p6.fits && p6.lowered && p6.context >= 131072 && p6.vram_slots > 0 && p6.vram_slots == (int64_t) ((5722 * MiB - strata::plan::vram_plan_fixed(i6, p6.context)) / kIq3Blob),
|
||||
"IQ3 no borrow on 6 GB: lowered to " + std::to_string(p6.context) + " with " + std::to_string(p6.vram_slots) + " slots");
|
||||
// the refusal: the floor itself does not fit, the numbers and the smaller file are in the message, nothing is chosen
|
||||
const VramPlanInput r = arm(true, false, 5722);
|
||||
const VramPlan pr = strata::plan::make_vram_plan(r);
|
||||
check(!pr.fits && pr.vram_slots == 0 && pr.context_needed_bytes_short > 0 &&
|
||||
pr.refusal.find("MiB short even at the floor") != std::string::npos &&
|
||||
pr.refusal.find("Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf") != std::string::npos &&
|
||||
pr.refusal.find("expert profile") != std::string::npos,
|
||||
"Q4 no borrow on 6 GB: refused with the shortfall at the floor, the IQ3 file and the borrowing hint");
|
||||
const std::string rt = strata::plan::vram_plan_text(r, pr);
|
||||
check(rt.find("REFUSED") != std::string::npos, "the log says REFUSED");
|
||||
// --vram-cap below the fixed set: the same refusal (the engine clamps the budget; the rule does the rest)
|
||||
const VramPlanInput cap = arm(true, true, 4000);
|
||||
check(!strata::plan::make_vram_plan(cap).fits, "a 4,000 MiB budget (a --vram-cap below the fixed set) refuses");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc == 4 && std::string(argv[1]) == "--at") {
|
||||
// vram_plan_test --at <q4|iq3> <budget MiB>: print the plan for one budget (prefill borrowing)
|
||||
const VramPlanInput in = arm(std::string(argv[2]) == "q4", true, (uint64_t) std::atoll(argv[3]));
|
||||
std::printf("%s", strata::plan::vram_plan_text(in, strata::plan::make_vram_plan(in)).c_str());
|
||||
return 0;
|
||||
}
|
||||
std::printf("vram_plan_test (docs/QWEN36-35B-A3B.md table 4.3)\n");
|
||||
ladder();
|
||||
drafter();
|
||||
tiers();
|
||||
lowering();
|
||||
std::printf(g_fail ? "vram_plan_test: %d FAILED\n" : "vram_plan_test: all passed\n", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -38,7 +38,10 @@ namespace {
|
||||
namespace mmq = strata::prefill::mmq;
|
||||
namespace fused = strata::prefill::fused;
|
||||
|
||||
constexpr int N = 2560, FF = 640, K = 10, GROUP = 16;
|
||||
// the geometry under test: Flash-Next's 2560 / 640 top-10, then Qwen3.6's 2048 / 512 top-8 (the reference part runs
|
||||
// both; the timings keep the pack they were measured on)
|
||||
int N = 2560, FF = 640, K = 10;
|
||||
constexpr int GROUP = 16;
|
||||
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
|
||||
@@ -70,7 +73,7 @@ struct Geo {
|
||||
fused::NativeGeom native(const Pair& p) const {
|
||||
fused::NativeGeom g;
|
||||
g.gu_type = (int) p.gu; g.d_type = (int) p.d; g.gu_row = gu_row; g.d_row = d_row; g.up_off = up_off;
|
||||
g.down_off = down_off;
|
||||
g.down_off = down_off; g.n_embd = N; g.n_ff = FF;
|
||||
return g;
|
||||
}
|
||||
};
|
||||
@@ -160,9 +163,9 @@ Routing sort_rows(const std::vector<int32_t>& ids, int E) {
|
||||
struct MmqBufs {
|
||||
Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d;
|
||||
MmqBufs(const Pair& p, int64_t rows, int E)
|
||||
: xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 1280 * 4), h((size_t) rows * FF * 4),
|
||||
: xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 2 * FF * 4), h((size_t) rows * FF * 4),
|
||||
hq(mmq::q8_bytes(rows, FF)), dm((size_t) rows * N * 4), ident((size_t) rows * 4),
|
||||
bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), grp_gu(GROUP * mmq::matrix_bytes(p.gu, 1280, N) + 4096),
|
||||
bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), grp_gu(GROUP * mmq::matrix_bytes(p.gu, 2 * FF, N) + 4096),
|
||||
grp_d(GROUP * mmq::matrix_bytes(p.d, N, FF) + 4096) {}
|
||||
};
|
||||
// `direct`: no gathers - the products read the blobs where they are (they must lie at a fixed stride, every expert
|
||||
@@ -170,7 +173,7 @@ struct MmqBufs {
|
||||
void run_mmq(const Pair& p, const Geo& geo, mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev,
|
||||
const int32_t* src_dev, const std::vector<const uint8_t*>& blob, int64_t rows, cudaStream_t s,
|
||||
bool direct = false, size_t stride = 0) {
|
||||
const size_t gub = mmq::matrix_bytes(p.gu, 1280, N), db = mmq::matrix_bytes(p.d, N, FF);
|
||||
const size_t gub = mmq::matrix_bytes(p.gu, 2 * FF, N), db = mmq::matrix_bytes(p.d, N, FF);
|
||||
const int E = (int) r.cnt.size();
|
||||
std::vector<int32_t> order;
|
||||
for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e);
|
||||
@@ -202,12 +205,12 @@ void run_mmq(const Pair& p, const Geo& geo, mmq::Context& ctx, MmqBufs& b, const
|
||||
}
|
||||
const uint8_t* b0 = blob[(size_t) order[j0]];
|
||||
mmq::Product gu;
|
||||
gu.w = direct ? (const void*) b0 : b.grp_gu.p; gu.type = (int) p.gu; gu.w_rows = 1280; gu.w_cols = N;
|
||||
gu.w = direct ? (const void*) b0 : b.grp_gu.p; gu.type = (int) p.gu; gu.w_rows = 2 * FF; gu.w_cols = N;
|
||||
gu.expert_bytes = direct ? stride : gub;
|
||||
gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as<int32_t>() + j0; gu.ids = b.ident.as<int32_t>();
|
||||
gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = 1280;
|
||||
gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = 2 * FF;
|
||||
ctx.run(gu, s);
|
||||
mmq::swiglu(b.gu.as<float>() + r0 * 1280, b.h.as<float>() + r0 * FF, nr, FF, false, s);
|
||||
mmq::swiglu(b.gu.as<float>() + r0 * 2 * FF, b.h.as<float>() + r0 * FF, nr, FF, false, s);
|
||||
mmq::quantize(b.h.as<float>() + r0 * FF, nullptr, b.hq.p, (int) p.d, FF, FF, nr, s);
|
||||
mmq::Product dn;
|
||||
dn.w = direct ? (const void*) (b0 + geo.down_off) : b.grp_d.p; dn.type = (int) p.d; dn.w_rows = N; dn.w_cols = FF;
|
||||
@@ -610,12 +613,18 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
cudaStream_t s = nullptr;
|
||||
ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
|
||||
for (const Pair& p : pairs) {
|
||||
if (only && std::string(p.name).find(only) == std::string::npos) continue;
|
||||
if (!fused::native_supported((int) p.gu, (int) p.d))
|
||||
throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels");
|
||||
if (ref) reference_part(p, s);
|
||||
struct Geom { int n, ff, k; const char* model; };
|
||||
for (const Geom& gm : {Geom{2560, 640, 10, "Flash-Next"}, Geom{2048, 512, 8, "Qwen3.6"}}) {
|
||||
N = gm.n; FF = gm.ff; K = gm.k;
|
||||
std::printf("== %s geometry: n_embd %d, n_ff %d, top-%d\n", gm.model, N, FF, K);
|
||||
for (const Pair& p : pairs) {
|
||||
if (only && std::string(p.name).find(only) == std::string::npos) continue;
|
||||
if (!fused::native_supported((int) p.gu, (int) p.d))
|
||||
throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels");
|
||||
if (ref) reference_part(p, s);
|
||||
}
|
||||
}
|
||||
N = 2560; FF = 640; K = 10;
|
||||
if (timing) {
|
||||
// the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's
|
||||
for (const Pair& p : {pairs[0], pairs[1], pairs[4], pairs[3]}) {
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// reference quantizers, against a double-precision product of ggml's dequantized weights. MMQ rounds the activations
|
||||
// to q8_1 by design, so this is a screen for layout, stride, expert-bound and row-id errors (the bounds of
|
||||
// tests/hip/prefill_mmq_parity.cpp), not a bit-exactness test. Several experts per product, permuted rows, an
|
||||
// all-zero row; the formats the build does not cover (Q6_K) must say so.
|
||||
// all-zero row. Qwen3.6-35B-A3B's UD-Q4_K_XL adds Q5_K and Q6_K down projections at its 2048 x 512; a format the
|
||||
// build does not cover (Q3_K) must say so.
|
||||
#include "strata/prefill/moe_mmq.hpp"
|
||||
|
||||
#include "ggml.h"
|
||||
@@ -14,6 +15,8 @@
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
@@ -37,6 +40,7 @@ struct Dev {
|
||||
std::vector<uint8_t> make_matrix(ggml_type t, int64_t rows, int64_t cols, int expert, int trial) {
|
||||
const auto* tr = ggml_get_type_traits(t);
|
||||
if (tr == nullptr || tr->from_float_ref == nullptr) throw std::runtime_error("no reference quantizer");
|
||||
ggml_quantize_init(t); // the i-quant quantizers' lookup tables (a probe of IQ3_XXS faulted without it)
|
||||
const size_t rb = ggml_row_size(t, cols);
|
||||
std::vector<uint8_t> out((size_t) rows * rb);
|
||||
std::vector<float> row((size_t) cols);
|
||||
@@ -94,6 +98,10 @@ void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, i
|
||||
ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "bounds");
|
||||
ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
|
||||
ck(cudaMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * 4), "sentinel");
|
||||
// the copies and the sentinel memset above run on the legacy default stream, which does not order itself before
|
||||
// the non-blocking stream `s`: without this the memset could land after the product's writes (every row then
|
||||
// reads as unwritten, seen on the second product of a run at 2048 x 512 on an RTX 4090)
|
||||
ck(cudaDeviceSynchronize(), "inputs");
|
||||
mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, dxq.p, (int) t, cols, cols, rows, s);
|
||||
mmq::Product p;
|
||||
p.w = dw.p; p.type = (int) t; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = eb; p.n = n;
|
||||
@@ -122,8 +130,26 @@ void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, i
|
||||
}
|
||||
}
|
||||
double err2 = 0, ref2 = 0, max_abs = 0, zero_max = 0;
|
||||
{ // which rows went wrong, and whether they were never written (the 0xff sentinel) or computed non-finite
|
||||
size_t unwritten = 0, nonfinite = 0;
|
||||
std::string rows_bad;
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
size_t u = 0, nf = 0;
|
||||
for (int64_t o = 0; o < out_rows; ++o) {
|
||||
const float v = got[(size_t) r * (size_t) out_rows + (size_t) o];
|
||||
uint32_t bits;
|
||||
std::memcpy(&bits, &v, 4);
|
||||
if (bits == 0xffffffffu) ++u;
|
||||
else if (!std::isfinite(v)) ++nf;
|
||||
}
|
||||
unwritten += u; nonfinite += nf;
|
||||
if (u || nf) rows_bad += " row " + std::to_string(r) + " (" + std::to_string(u) + " unwritten, " + std::to_string(nf) + " non-finite)";
|
||||
}
|
||||
if (unwritten || nonfinite)
|
||||
throw std::runtime_error(std::string(name) + ": " + std::to_string(unwritten) + " values unwritten, " +
|
||||
std::to_string(nonfinite) + " non-finite:" + rows_bad);
|
||||
}
|
||||
for (size_t i = 0; i < got.size(); ++i) {
|
||||
if (!std::isfinite(got[i])) throw std::runtime_error(std::string(name) + ": unwritten or non-finite output");
|
||||
const double d = (double) got[i] - ref[i];
|
||||
err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, std::fabs(d));
|
||||
}
|
||||
@@ -139,12 +165,25 @@ void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, i
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; }
|
||||
if (mmq::supported(GGML_TYPE_Q6_K)) throw std::runtime_error("Q6_K should not be covered");
|
||||
if (mmq::supported(GGML_TYPE_Q3_K)) throw std::runtime_error("Q3_K should not be covered");
|
||||
cudaStream_t s = nullptr;
|
||||
ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
|
||||
if (argc > 1) { // probes: each argument one product TYPE,OUT_ROWS,COLS[,TRIAL] (ggml type id), one context
|
||||
mmq::Context ctx;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
int t = 0, trial = 0;
|
||||
long long rows = 0, cols = 0;
|
||||
if (std::sscanf(argv[i], "%d,%lld,%lld,%d", &t, &rows, &cols, &trial) < 3) throw std::runtime_error("probe: TYPE,ROWS,COLS[,TRIAL]");
|
||||
std::printf("probe %s %lld x %lld trial %d (fits %d)\n", ggml_type_name((ggml_type) t), rows, cols, trial,
|
||||
(int) mmq::fits(t, rows));
|
||||
product(ctx, s, argv[i], (ggml_type) t, rows, cols, {1, 3, 3}, trial);
|
||||
}
|
||||
std::printf("probes passed\n");
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
mmq::Context ctx;
|
||||
const std::vector<std::vector<int>> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}};
|
||||
@@ -155,6 +194,8 @@ int main() {
|
||||
product(ctx, s, ("Q5_K gate/up" + tag).c_str(), GGML_TYPE_Q5_K, 1280, 2560, counts, trial + 5);
|
||||
product(ctx, s, ("Q5_1 down" + tag).c_str(), GGML_TYPE_Q5_1, 2560, 640, counts, trial + 9);
|
||||
product(ctx, s, ("Q8_0 down" + tag).c_str(), GGML_TYPE_Q8_0, 2560, 640, counts, trial + 13);
|
||||
product(ctx, s, ("Q5_K down 2048x512" + tag).c_str(), GGML_TYPE_Q5_K, 2048, 512, counts, trial + 17);
|
||||
product(ctx, s, ("Q6_K down 2048x512" + tag).c_str(), GGML_TYPE_Q6_K, 2048, 512, counts, trial + 21);
|
||||
++trial;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
// prefill_qwen36_test - the prompt path (src/prefill) at Qwen3.6's geometry against the oracle's dumps
|
||||
// (docs/qwen36-port/step3-prefill.md; the fixtures from tests/python/qwen36_prefill_fixture.py).
|
||||
//
|
||||
// prefill_qwen36_test <fixture dir> gdn3|full4 [--chunk N] [--no-force]
|
||||
//
|
||||
// The synthetic model of the fixture (2048 wide, GDN 16 / 32 heads of 128, attention 16 / 2 heads of 256, 16 experts
|
||||
// top-8 of 512; Q8_0 projections and experts, BF16-exact routers) is run through Prefill::run twice, as one chunk of
|
||||
// 40 tokens and in chunks of 7 (the oracle's base_c7 case), and every seam the layer loop exposes (Prefill::on_seam,
|
||||
// llama.cpp's names) is held to the oracle's dump of the same 40 tokens with the layer's input TEACHER-FORCED to
|
||||
// the oracle's l_out of the layer before (oracle-crosscheck.md, "Tolerance policy", item 2: per layer, not
|
||||
// accumulated), so each seam's error is that layer's own; --no-force reports the accumulated error too. The router's
|
||||
// top-k must be the oracle's exactly (the F32 fixture has no near ties). Negative controls: the oracle's dumps with
|
||||
// one reading flipped to its rival (the sigmoid GDN gate, the interleaved head pairing, the unnormalised router
|
||||
// weights, the attention gate skipped) must sit more than 5 % relative L1 from what the engine computes, else the
|
||||
// harness could not tell the readings apart. Geometry refusals: Prefill::init with top-10 on this 16-expert file,
|
||||
// and with a GDN geometry the kernels are not built for.
|
||||
//
|
||||
// Exit 0 pass, 1 fail, 77 skip (no CUDA device, or <fixture dir>/SKIP: the fixture script found no numpy / gguf-py).
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
#include "strata/core/expert_source.hpp"
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/core/model_geometry.hpp"
|
||||
#include "strata/core/session.hpp"
|
||||
#include "strata/core/weights.hpp"
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
#include "strata/prefill/prefill.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
namespace core = strata::core;
|
||||
|
||||
[[noreturn]] void die(const std::string& what) {
|
||||
std::fprintf(stderr, "prefill_qwen36_test: %s\n", what.c_str());
|
||||
std::exit(1);
|
||||
}
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) die(std::string(what) + ": " + cudaGetErrorString(e));
|
||||
}
|
||||
template <typename T> T* dalloc(size_t n) {
|
||||
void* p = nullptr;
|
||||
ck(cudaMalloc(&p, n * sizeof(T) + 256), "cudaMalloc");
|
||||
return (T*) p;
|
||||
}
|
||||
template <typename T> T* upload(const void* host, size_t bytes) {
|
||||
T* d = dalloc<uint8_t>(bytes) ? (T*) nullptr : nullptr;
|
||||
(void) d;
|
||||
void* p = nullptr;
|
||||
ck(cudaMalloc(&p, bytes + 256), "cudaMalloc");
|
||||
ck(cudaMemcpy(p, host, bytes, cudaMemcpyHostToDevice), "upload");
|
||||
return (T*) p;
|
||||
}
|
||||
bool ends_with(const std::string& s, const char* suf) {
|
||||
const size_t n = std::strlen(suf);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
|
||||
}
|
||||
uint16_t bf16_of(float f) { // round to nearest even (the values are BF16-exact already: the rounding is the identity)
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, 4);
|
||||
u += 0x7fffu + ((u >> 16) & 1u);
|
||||
return (uint16_t) (u >> 16);
|
||||
}
|
||||
std::vector<float> read_f32(const std::string& path, bool required = true) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in) {
|
||||
if (required) die("cannot read " + path);
|
||||
return {};
|
||||
}
|
||||
in.seekg(0, std::ios::end);
|
||||
const std::streamoff n = in.tellg();
|
||||
in.seekg(0);
|
||||
std::vector<float> v((size_t) n / 4);
|
||||
in.read((char*) v.data(), (std::streamsize) (v.size() * 4));
|
||||
return v;
|
||||
}
|
||||
// the L1 sums of ||a - b|| and ||b|| over n values, NaN-safe (a NaN anywhere makes the numerator infinite)
|
||||
void l1_sums(const float* a, const float* b, size_t n, double& num, double& den) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) { num = INFINITY; return; }
|
||||
num += std::fabs((double) a[i] - b[i]);
|
||||
den += std::fabs((double) b[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// the Q8_0 expert blobs of the fixture, [gate rows | up rows | down rows] as tools/iq_pack.py lays them out, in host
|
||||
// memory (not pinned: the prompt path's stager copies them)
|
||||
struct HostExperts : core::ExpertSource {
|
||||
std::vector<std::vector<uint8_t>> blobs; // [layer * n_expert + e]
|
||||
int64_t n_expert = 0;
|
||||
const uint8_t* blob(int64_t layer, int64_t expert) override { return blobs[(size_t) (layer * n_expert + expert)].data(); }
|
||||
};
|
||||
|
||||
struct Fixture {
|
||||
strata::GgufFile gguf;
|
||||
core::ModelGeometry g;
|
||||
core::WeightTable wt;
|
||||
std::vector<void*> owned;
|
||||
HostExperts experts;
|
||||
std::vector<float> embd; // [n_vocab][n_embd]
|
||||
explicit Fixture(const std::string& path) : gguf(path) {
|
||||
std::string err;
|
||||
if (!core::read_model_geometry(gguf, g, err)) {
|
||||
// gdn3 (three DeltaNet layers, no attention layer) is a file the geometry reader refuses by design
|
||||
// (block_count must be a multiple of full_attention_interval, as every shipped file's is): its geometry
|
||||
// is full4's with the layer count of its own header, which is what the oracle ran it as
|
||||
const std::string alt = path.substr(0, path.rfind('/') + 1) + "full4.gguf";
|
||||
std::string err2;
|
||||
strata::GgufFile full(alt);
|
||||
if (!core::read_model_geometry(full, g, err2)) die("geometry: " + err + "; and " + alt + ": " + err2);
|
||||
auto it = gguf.metadata().find("qwen35moe.block_count");
|
||||
if (it == gguf.metadata().end()) die("geometry: " + err);
|
||||
g.n_layers = (int64_t) it->second.u;
|
||||
std::printf("geometry from %s (%s), %lld layers from the header\n", alt.c_str(), err.c_str(), (long long) g.n_layers);
|
||||
}
|
||||
if (g.arch != core::ModelArch::Qwen35Moe) die("the fixture is not a qwen35moe file");
|
||||
std::printf("fixture %s: %lld layers, n_embd %lld, GDN %lld/%lld heads, conv %lld, attention %lld/%lld x %lld, "
|
||||
"%lld experts top-%lld of %lld, hc %lld\n", path.c_str(), (long long) g.n_layers, (long long) g.n_embd,
|
||||
(long long) g.ssm_k_heads, (long long) g.ssm_v_heads, (long long) g.ssm_conv_channels, (long long) g.n_head,
|
||||
(long long) g.n_head_kv, (long long) g.head_dim, (long long) g.n_expert, (long long) g.n_expert_used,
|
||||
(long long) g.n_ff, (long long) g.hc);
|
||||
experts.n_expert = g.n_expert;
|
||||
experts.blobs.resize((size_t) (g.n_layers * g.n_expert));
|
||||
std::map<std::string, const strata::TensorInfo*> exp_t;
|
||||
for (const auto& t : gguf.tensors()) {
|
||||
const uint64_t bytes = strata::tensor_payload_bytes(t);
|
||||
if (bytes == 0) die("tensor " + t.name + ": unknown payload size");
|
||||
const uint8_t* src = gguf.tensor_data(t);
|
||||
if (ends_with(t.name, "_exps.weight")) { exp_t[t.name] = &t; continue; } // the experts: blobs below
|
||||
if (t.name == "token_embd.weight") {
|
||||
if (t.type != 0) die("token_embd is not F32");
|
||||
embd.assign((const float*) src, (const float*) src + t.elements());
|
||||
continue;
|
||||
}
|
||||
core::WeightRef r;
|
||||
r.ne0 = (int64_t) t.shape[0];
|
||||
r.ne1 = t.shape.size() > 1 ? (int64_t) t.shape[1] : 1;
|
||||
r.elements = (int64_t) t.elements();
|
||||
r.bytes = bytes;
|
||||
if (t.type == 8) { // Q8_0: served natively (Gemm::native dequantizes the blocks)
|
||||
r.native_data = upload<uint8_t>(src, bytes);
|
||||
r.native_type = 8;
|
||||
r.resident = false;
|
||||
owned.push_back((void*) r.native_data);
|
||||
} else if (t.type != 0) {
|
||||
die("tensor " + t.name + " has type " + std::to_string(t.type) + " (the fixture uses F32 and Q8_0)");
|
||||
} else if (ends_with(t.name, "ffn_gate_inp.weight") || ends_with(t.name, "ssm_alpha.weight") ||
|
||||
ends_with(t.name, "ssm_beta.weight") || ends_with(t.name, "ffn_gate_inp_shexp.weight")) {
|
||||
// the engine's BF16 form of the F32 tensor (exact: the fixture rounded the values to BF16)
|
||||
std::vector<uint16_t> h((size_t) r.elements);
|
||||
const float* f = (const float*) src;
|
||||
for (size_t i = 0; i < h.size(); ++i) {
|
||||
h[i] = bf16_of(f[i]);
|
||||
uint32_t back = (uint32_t) h[i] << 16;
|
||||
float fb;
|
||||
std::memcpy(&fb, &back, 4);
|
||||
if (fb != f[i]) die("tensor " + t.name + " is not BF16-exact at " + std::to_string(i));
|
||||
}
|
||||
r.kind = core::WeightKind::Bf16InF32;
|
||||
r.data = upload<uint8_t>(h.data(), h.size() * 2);
|
||||
r.bytes = h.size() * 2;
|
||||
owned.push_back((void*) r.data);
|
||||
} else {
|
||||
r.kind = core::WeightKind::F32;
|
||||
r.data = upload<uint8_t>(src, bytes);
|
||||
owned.push_back((void*) r.data);
|
||||
}
|
||||
wt.set(t.name, r);
|
||||
}
|
||||
// the expert blobs: [gate | up | down] rows of expert e from the three [E, rows, cols] Q8_0 tensors
|
||||
for (int64_t l = 0; l < g.n_layers; ++l) {
|
||||
const std::string p = "blk." + std::to_string(l) + ".";
|
||||
const strata::TensorInfo* gt = exp_t.count(p + "ffn_gate_exps.weight") ? exp_t[p + "ffn_gate_exps.weight"] : nullptr;
|
||||
const strata::TensorInfo* ut = exp_t.count(p + "ffn_up_exps.weight") ? exp_t[p + "ffn_up_exps.weight"] : nullptr;
|
||||
const strata::TensorInfo* dt = exp_t.count(p + "ffn_down_exps.weight") ? exp_t[p + "ffn_down_exps.weight"] : nullptr;
|
||||
if (!gt || !ut || !dt) die("layer " + std::to_string(l) + ": expert tensors missing");
|
||||
if (gt->type != 8 || ut->type != 8 || dt->type != 8) die("the experts are not Q8_0");
|
||||
const size_t gu_row = (size_t) g.n_embd / 32 * 34, d_row = (size_t) g.n_ff / 32 * 34;
|
||||
const size_t gu_mat = gu_row * (size_t) g.n_ff, d_mat = d_row * (size_t) g.n_embd;
|
||||
if (strata::tensor_payload_bytes(*gt) != gu_mat * g.n_expert || strata::tensor_payload_bytes(*dt) != d_mat * g.n_expert)
|
||||
die("expert tensor sizes do not match the geometry");
|
||||
for (int64_t e = 0; e < g.n_expert; ++e) {
|
||||
std::vector<uint8_t>& b = experts.blobs[(size_t) (l * g.n_expert + e)];
|
||||
b.resize(2 * gu_mat + d_mat);
|
||||
std::memcpy(b.data(), gguf.tensor_data(*gt) + e * gu_mat, gu_mat);
|
||||
std::memcpy(b.data() + gu_mat, gguf.tensor_data(*ut) + e * gu_mat, gu_mat);
|
||||
std::memcpy(b.data() + 2 * gu_mat, gguf.tensor_data(*dt) + e * d_mat, d_mat);
|
||||
}
|
||||
}
|
||||
}
|
||||
~Fixture() { for (void* p : owned) cudaFree(p); }
|
||||
// the pack's native_experts.txt for these blobs (v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off)
|
||||
void write_layout(const std::string& dir) const {
|
||||
const size_t gu_row = (size_t) g.n_embd / 32 * 34, d_row = (size_t) g.n_ff / 32 * 34;
|
||||
const size_t gu_mat = gu_row * (size_t) g.n_ff, d_mat = d_row * (size_t) g.n_embd, blob = 2 * gu_mat + d_mat;
|
||||
std::ofstream out(dir + "/native_experts.txt");
|
||||
out << "# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert "
|
||||
<< g.n_expert << ", total " << blob * (size_t) g.n_layers * (size_t) g.n_expert << "; the harness's in-memory blobs)\n";
|
||||
for (int64_t l = 0; l < g.n_layers; ++l)
|
||||
out << l << " 8 8 " << (size_t) l * g.n_expert * blob << " " << blob << " 0 " << gu_mat << " " << 2 * gu_mat << "\n";
|
||||
}
|
||||
};
|
||||
|
||||
// one named seam's relative L1 over the whole sequence (the sums over its chunks), per layer
|
||||
struct Stat {
|
||||
double num = 0.0, den = 0.0;
|
||||
int64_t rows = 0;
|
||||
bool seen = false;
|
||||
double rel() const { return den > 0.0 ? num / den : (num > 0.0 ? INFINITY : 0.0); }
|
||||
};
|
||||
|
||||
struct Run {
|
||||
const Fixture& fx;
|
||||
const std::string dumps; // the oracle's faithful dumps
|
||||
bool force = true;
|
||||
int64_t T_total = 0;
|
||||
std::map<std::string, Stat> stats; // "<seam>-<layer>"
|
||||
std::vector<std::string> topk_flips;
|
||||
int topk_bad = 0;
|
||||
static constexpr double kTieGap = 2e-3; // a swap is a near tie when the oracle's probabilities are this close
|
||||
std::vector<float> scratch;
|
||||
std::map<std::string, std::vector<float>> cache;
|
||||
const std::vector<float>& dump(const std::string& stem) {
|
||||
auto it = cache.find(stem);
|
||||
if (it == cache.end()) it = cache.emplace(stem, read_f32(dumps + "/" + stem + ".f32")).first;
|
||||
return it->second;
|
||||
}
|
||||
bool on_seam(const char* seam, int64_t layer, float* dev, int64_t rows, int64_t cols, int64_t p0, std::string& err) {
|
||||
const std::string s(seam);
|
||||
ck(cudaDeviceSynchronize(), "on_seam sync");
|
||||
scratch.resize((size_t) (rows * cols));
|
||||
ck(cudaMemcpy(scratch.data(), dev, scratch.size() * 4, cudaMemcpyDeviceToHost), "on_seam copy");
|
||||
if (s == "l_in") {
|
||||
if (layer == 0) return true; // the embedding rows: the oracle's own, fed through embd_rows
|
||||
const std::vector<float>& prev = dump("l_out-" + std::to_string(layer - 1));
|
||||
if (force) { // teacher forcing: this layer starts from the oracle's output of the layer before
|
||||
if (prev.size() != (size_t) (T_total * cols)) { err = "l_out dump size"; return false; }
|
||||
ck(cudaMemcpy(dev, prev.data() + (size_t) p0 * cols, scratch.size() * 4, cudaMemcpyHostToDevice), "force");
|
||||
// the prompt path's stream is non-blocking: a pageable H2D copy may still be in flight when its next
|
||||
// kernel starts, so wait for it here
|
||||
ck(cudaDeviceSynchronize(), "force sync");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (s == "ffn_moe_topk") {
|
||||
// int32 ids [rows, k] against the oracle's float ids. The prompt path's router multiplies BF16-rounded
|
||||
// activations (the decode path's is FP32), so a pair of experts whose oracle probabilities are within
|
||||
// ~1e-3 can swap ranks; such a near tie is reported and allowed (the gap in the oracle's own softmax must
|
||||
// be below kTieGap), any other disagreement is a failure (oracle-crosscheck.md: exact top-k on the F32
|
||||
// fixture; the prompt path is the one engine path that is not F32 at the router).
|
||||
const std::vector<float>& o = dump("ffn_moe_topk-" + std::to_string(layer));
|
||||
const std::vector<float>& probs = dump("ffn_moe_probs-" + std::to_string(layer));
|
||||
const int64_t E = (int64_t) probs.size() / T_total;
|
||||
const int32_t* ids = (const int32_t*) scratch.data();
|
||||
for (int64_t t = 0; t < rows; ++t) {
|
||||
const float* pr = probs.data() + (size_t) (p0 + t) * E;
|
||||
for (int64_t j = 0; j < cols; ++j) {
|
||||
const int32_t e = ids[t * cols + j], oe = (int32_t) o[(size_t) ((p0 + t) * cols + j)];
|
||||
if (e == oe) continue;
|
||||
const double gap = std::fabs((double) pr[e] - pr[oe]);
|
||||
char line[200];
|
||||
std::snprintf(line, sizeof line, "layer %lld pos %lld rank %lld: engine %d, oracle %d, oracle probability gap %.2e%s",
|
||||
(long long) layer, (long long) (p0 + t), (long long) j, e, oe, gap, gap < kTieGap ? " (near tie)" : " *** NOT A TIE ***");
|
||||
topk_flips.push_back(line);
|
||||
if (gap >= kTieGap) ++topk_bad;
|
||||
}
|
||||
}
|
||||
Stat& st = stats["ffn_moe_topk-" + std::to_string(layer)];
|
||||
st.seen = true; st.rows += rows;
|
||||
return true;
|
||||
}
|
||||
const std::vector<float>& o = dump(s + "-" + std::to_string(layer));
|
||||
if (o.size() != (size_t) (T_total * cols)) { err = s + " dump size " + std::to_string(o.size()); return false; }
|
||||
Stat& st = stats[s + "-" + std::to_string(layer)];
|
||||
l1_sums(scratch.data(), o.data() + (size_t) p0 * cols, scratch.size(), st.num, st.den);
|
||||
st.rows += rows; st.seen = true;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// the engine's seams on one run, against the dumps in `run.dumps`
|
||||
bool run_prefill(const Fixture& fx, core::SessionState& ss, int64_t chunk, Run& run, const std::vector<int64_t>& tokens,
|
||||
std::string& err, cudaStream_t cs) {
|
||||
strata::prefill::Prefill pf;
|
||||
if (!pf.init(fx.wt, fx.g, ss, const_cast<HostExperts*>(&fx.experts), nullptr, nullptr, chunk, cs, err)) return false;
|
||||
std::vector<const float*> rows(tokens.size());
|
||||
for (size_t i = 0; i < tokens.size(); ++i) rows[i] = fx.embd.data() + (size_t) tokens[i] * fx.g.n_embd;
|
||||
pf.embd_rows = rows.data();
|
||||
run.T_total = (int64_t) tokens.size();
|
||||
pf.on_seam = [&run](const char* seam, int64_t layer, float* dev, int64_t r, int64_t c, int64_t p0, std::string& e) {
|
||||
return run.on_seam(seam, layer, dev, r, c, p0, e);
|
||||
};
|
||||
core::session_zero(ss, fx.g, nullptr, cs);
|
||||
ck(cudaStreamSynchronize(cs), "zero");
|
||||
return pf.run(tokens.data(), (int64_t) tokens.size(), 0, err);
|
||||
}
|
||||
|
||||
const char* const kFloatSeams[] = {"attn_norm", "linear_attn_out", "attn_output", "attn_post_norm", "ffn_out", "l_out"};
|
||||
double gate_for(const std::string& seam, bool forced) {
|
||||
// against the F32 oracle: the plain-block norms are FP32 (summation order only); the mixers run FP16 GEMMs over
|
||||
// FP16-dequantized Q8_0 weights (2^-11 per operand) and the experts the int8 MMQ products (q8_1 activations,
|
||||
// q8_1 H): oracle-crosscheck.md's "Tolerance policy" puts a 2x margin on the F32 column for an FP32 engine path;
|
||||
// these gates are what the 4090 measured (step3-prefill.md) with a 4x margin, and the negatives sit at 0.1 to 1.3
|
||||
if (seam == "attn_norm") return 1e-4;
|
||||
if (seam == "attn_post_norm") return 2e-3; // the norm of R + the mixer's output: the mixer's own error passes through
|
||||
if (seam == "linear_attn_out" || seam == "attn_output") return 1e-2;
|
||||
if (seam == "ffn_out") return 2e-2;
|
||||
return forced ? 1e-2 : 5e-2; // l_out (accumulated without forcing)
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 3) {
|
||||
std::fprintf(stderr, "usage: prefill_qwen36_test <fixture dir> gdn3|full4 [--chunk N] [--no-force]\n");
|
||||
return 2;
|
||||
}
|
||||
const std::string dir = argv[1], kase = argv[2];
|
||||
int64_t chunk_override = 0;
|
||||
bool force = true;
|
||||
for (int i = 3; i < argc; ++i) {
|
||||
if (std::strcmp(argv[i], "--chunk") == 0 && i + 1 < argc) chunk_override = std::atoll(argv[++i]);
|
||||
else if (std::strcmp(argv[i], "--no-force") == 0) force = false;
|
||||
}
|
||||
if (std::ifstream skip(dir + "/SKIP"); skip) {
|
||||
std::string why;
|
||||
std::getline(skip, why);
|
||||
std::printf("prefill_qwen36_test: the fixtures were not generated (%s/SKIP: %s): skip\n", dir.c_str(), why.c_str());
|
||||
return 77;
|
||||
}
|
||||
int ndev = 0;
|
||||
if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev < 1) {
|
||||
std::printf("prefill_qwen36_test: no CUDA device (skip)\n");
|
||||
return 77;
|
||||
}
|
||||
cudaDeviceProp p{};
|
||||
ck(cudaGetDeviceProperties(&p, 0), "device");
|
||||
std::printf("prefill_qwen36_test on %s (sm_%d%d), case %s\n", p.name, p.major, p.minor, kase.c_str());
|
||||
Fixture fx(dir + "/" + kase + ".gguf");
|
||||
const std::string dumps = dir + "/" + kase;
|
||||
std::string err;
|
||||
// the pack layout (process-wide) for these blobs
|
||||
fx.write_layout(dir);
|
||||
if (!strata::kernels::cpu::expert_layout_load(dir, fx.g.n_layers, fx.g.n_expert, fx.g.n_embd, fx.g.n_ff, err))
|
||||
die("expert layout: " + err);
|
||||
// the session: 64 cells is plenty for 40 tokens
|
||||
const int64_t max_cells = 64;
|
||||
core::SessionState ss;
|
||||
const uint64_t sbytes = core::session_bytes(fx.g, max_cells, fx.g.n_expert_used);
|
||||
void* sbase = nullptr;
|
||||
ck(cudaMalloc(&sbase, sbytes), "session");
|
||||
if (core::session_init(fx.g, max_cells, fx.g.n_expert_used, sbase, ss) == 0) die("session_init failed");
|
||||
ss.k = fx.g.n_expert_used;
|
||||
cudaStream_t cs = nullptr;
|
||||
ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream");
|
||||
const std::string text = "the quick brown fox jumps over the lazy "; // 40 tokens, the fixture script's
|
||||
std::vector<int64_t> tokens;
|
||||
for (char c : text) tokens.push_back((int64_t) (unsigned char) c);
|
||||
int fails = 0;
|
||||
|
||||
// ---- the geometry refusals
|
||||
{
|
||||
strata::prefill::Prefill pf;
|
||||
core::SessionState bad = ss;
|
||||
bad.k = 10; // top-10 routing on a top-8 file of 16 experts
|
||||
std::string e;
|
||||
const bool refused = !pf.init(fx.wt, fx.g, bad, &fx.experts, nullptr, nullptr, 40, cs, e);
|
||||
std::printf("refusal: top-10 on the top-8 file: %s (%s)\n", refused ? "refused" : "*** ACCEPTED ***", e.c_str());
|
||||
fails += !refused;
|
||||
core::ModelGeometry g2 = fx.g;
|
||||
g2.ssm_k_heads = 8; g2.derive(); // 4 value heads per key head (32 / 8 / 6144): no kernels are built for it
|
||||
strata::prefill::Prefill pf2;
|
||||
core::SessionState s2 = ss;
|
||||
const bool refused2 = !pf2.init(fx.wt, g2, s2, &fx.experts, nullptr, nullptr, 40, cs, e);
|
||||
const bool by_name = e.find("no GDN kernels") != std::string::npos;
|
||||
std::printf("refusal: 32 value heads / 8 key heads / 6144 conv channels: %s (%s)\n",
|
||||
refused2 && by_name ? "refused by name" : refused2 ? "*** refused for another reason ***" : "*** ACCEPTED ***", e.c_str());
|
||||
fails += !(refused2 && by_name);
|
||||
}
|
||||
|
||||
// ---- the runs: one chunk of 40, chunks of 7 (the oracle's base_c7), each seam against the faithful dumps
|
||||
const int64_t chunks[] = {chunk_override > 0 ? chunk_override : 40, chunk_override > 0 ? chunk_override : 7};
|
||||
for (int ci = 0; ci < (chunk_override > 0 ? 1 : 2); ++ci) {
|
||||
Run run{fx, dumps + "/o", force};
|
||||
if (!run_prefill(fx, ss, chunks[ci], run, tokens, err, cs)) die("run (chunk " + std::to_string(chunks[ci]) + "): " + err);
|
||||
std::printf("chunk %lld (%s):\n", (long long) chunks[ci], force ? "teacher-forced layer inputs" : "accumulated");
|
||||
for (int64_t l = 0; l < fx.g.n_layers; ++l) {
|
||||
for (const char* seam : kFloatSeams) {
|
||||
const std::string key = std::string(seam) + "-" + std::to_string(l);
|
||||
auto it = run.stats.find(key);
|
||||
if (it == run.stats.end() || !it->second.seen) continue;
|
||||
const double gate = gate_for(seam, force), e = it->second.rel();
|
||||
const bool pass = e <= gate;
|
||||
std::printf(" %-20s %.3e (gate %.0e) %s\n", key.c_str(), e, gate, pass ? "ok" : "*** FAIL ***");
|
||||
fails += !pass;
|
||||
}
|
||||
const std::string tk = "ffn_moe_topk-" + std::to_string(l);
|
||||
if (run.stats.count(tk) && run.stats[tk].seen) std::printf(" %-20s compared over %lld rows\n", tk.c_str(), (long long) run.stats[tk].rows);
|
||||
}
|
||||
if (!run.topk_flips.empty()) {
|
||||
std::printf(" top-k: %zu disagreements with the oracle, %d of them not a near tie%s\n", run.topk_flips.size(), run.topk_bad,
|
||||
run.topk_bad ? " *** FAIL ***" : "");
|
||||
for (size_t i = 0; i < run.topk_flips.size() && i < 12; ++i) std::printf(" %s\n", run.topk_flips[i].c_str());
|
||||
fails += run.topk_bad > 0;
|
||||
} else {
|
||||
std::printf(" top-k: identical to the oracle's at every position and rank\n");
|
||||
}
|
||||
// the rows the chunked run compared must be the whole sequence for every seam it saw
|
||||
for (const auto& [k, st] : run.stats)
|
||||
if (st.seen && st.rows != (int64_t) tokens.size()) {
|
||||
std::printf(" *** %s compared %lld of %zu rows\n", k.c_str(), (long long) st.rows, tokens.size());
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the negative controls: the engine (forced from the faithful dumps) against the rival readings' dumps
|
||||
struct Neg { const char* dir; const char* seam; int64_t layer; };
|
||||
const Neg negs[] = {{"neg_gate", "linear_attn_out", 0}, {"neg_pair", "linear_attn_out", 0}, {"neg_norm", "ffn_out", 0},
|
||||
{"neg_attngate", "attn_output", 3}};
|
||||
std::printf("negative controls (the engine against the oracle's rival readings; each must exceed 5%%):\n");
|
||||
for (const Neg& ng : negs) {
|
||||
if (ng.layer >= fx.g.n_layers) continue;
|
||||
Run run{fx, dumps + "/o", true};
|
||||
// the forced inputs come from the faithful dumps; only the compared seam reads the rival's
|
||||
const std::string rival = dumps + "/" + ng.dir + "/" + ng.seam + "-" + std::to_string(ng.layer) + ".f32";
|
||||
run.cache[std::string(ng.seam) + "-" + std::to_string(ng.layer)] = read_f32(rival);
|
||||
std::string e;
|
||||
if (!run_prefill(fx, ss, 40, run, tokens, e, cs)) die("negative run: " + e);
|
||||
const double d = run.stats[std::string(ng.seam) + "-" + std::to_string(ng.layer)].rel();
|
||||
const bool seen = d > 0.05;
|
||||
std::printf(" %-13s %s-%lld: %.3f relative L1 %s\n", ng.dir, ng.seam, (long long) ng.layer, d, seen ? "yes" : "*** NO ***");
|
||||
fails += !seen;
|
||||
}
|
||||
|
||||
// ---- the same against the oracle's --act-quant q8 dumps (the activations rounded to Q8 before each quantized
|
||||
// matmul as ggml does; closer to the int8 MMQ experts), for the record
|
||||
if (force) {
|
||||
Run run{fx, dumps + "/o_q8", true};
|
||||
std::string e;
|
||||
const bool ok = run_prefill(fx, ss, 40, run, tokens, e, cs);
|
||||
if (!ok) die("q8 run: " + e);
|
||||
std::printf("against the Q8 oracle (forced inputs from its own l_out), one chunk of 40:\n");
|
||||
for (int64_t l = 0; l < fx.g.n_layers; ++l)
|
||||
for (const char* seam : {"linear_attn_out", "attn_output", "ffn_out", "l_out"}) {
|
||||
const std::string key = std::string(seam) + "-" + std::to_string(l);
|
||||
if (run.stats.count(key) && run.stats[key].seen) std::printf(" %-20s %.3e\n", key.c_str(), run.stats[key].rel());
|
||||
}
|
||||
}
|
||||
// ---- the accumulated error, for the record (no forcing)
|
||||
if (force) {
|
||||
Run run{fx, dumps + "/o", false};
|
||||
std::string e;
|
||||
if (!run_prefill(fx, ss, 40, run, tokens, e, cs)) die("unforced run: " + e);
|
||||
std::printf("accumulated (no forcing), one chunk of 40:\n");
|
||||
for (int64_t l = 0; l < fx.g.n_layers; ++l) {
|
||||
const std::string key = "l_out-" + std::to_string(l);
|
||||
if (run.stats.count(key) && run.stats[key].seen) std::printf(" %-20s %.3e\n", key.c_str(), run.stats[key].rel());
|
||||
}
|
||||
}
|
||||
|
||||
core::session_release(ss);
|
||||
cudaFree(sbase);
|
||||
cudaStreamDestroy(cs);
|
||||
if (fails) {
|
||||
std::printf("prefill_qwen36_test (%s): %d failures\n", kase.c_str(), fails);
|
||||
return 1;
|
||||
}
|
||||
std::printf("prefill_qwen36_test (%s): pass\n", kase.c_str());
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
// tests/cuda/qwen36_block_test.cpp - the plain block (hc = 1, Qwen3.6) composed by the engine, held to the oracle.
|
||||
//
|
||||
// qwen36_block_test <synth dir> <dump dir>
|
||||
//
|
||||
// <synth dir> holds tools/qwen36_synth_gguf.py's toy.gguf (CMake's qwen36_synth_fixtures); <dump dir> the oracle's
|
||||
// cb()-named dumps of that file on 8 tokens (cmake/qwen36_block_fixtures.cmake runs ref/qwen36.py). Maya's layer
|
||||
// composition shape (docs/QWEN36-35B-A3B.md section 6, step 3, fourth bullet), for every layer of the fixture
|
||||
// (0-2 GDN + MoE, 3 attention + MoE) and the head:
|
||||
//
|
||||
// 1. the single-token path THROUGH THE ENGINE'S OWN FUNCTIONS on a WeightTable loaded from a pack the test writes
|
||||
// (the F32 norms, the BF16 router, the BF16 shared-expert gate): `block_layer_pre` stage 0 (`attn_norm-N`), the
|
||||
// residual add (`attn_residual-N`), `block_layer_pre` half 2 (`attn_post_norm-N`, the router's `ffn_moe_topk-N`
|
||||
// and `ffn_moe_weights_norm-N`), `block_layer_post` (`ffn_out-N`, `l_out-N`), `lm_head_mix` (`result_norm`) and
|
||||
// the logits (`result_output`, the engine's normed vector through a host F32 projection of `output.weight`);
|
||||
// 2. the verify window's row arithmetic: the T = 8 row calls (`plain_norm_rows`, `plain_residual_rows`,
|
||||
// `native_moe_combine_multi`) bitwise the one-row calls per row, and the 8-token sequence carried through the
|
||||
// four layers against `attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `ffn_out-N`, `l_out-N`, `h_nextn`
|
||||
// per position;
|
||||
// 3. the negative cases (upstream-tooling.md section 3): the GR read at hc = 1 with identity bottleneck weights
|
||||
// is NOT the plain norm (> 5 % relative L1), the post-attention norm skipped (and unweighted) is not the normed
|
||||
// activation, top-10 on the 8-expert file is refused by name, a missing norm is refused by name.
|
||||
//
|
||||
// THE MIXERS AND THE EXPERTS ARE TEACHER-FORCED from the dumps (`linear_attn_out-N`, `attn_output-N`, the per-expert
|
||||
// `ffn_moe_down-N`, `ffn_shexp_gated-N`): the fixture's projections are F32 and the engine has no F32 projection
|
||||
// kernel (the GDN and attention mixers are the sibling step-3 branches', the quantized pack is step 4's), so the
|
||||
// block's own seams are asserted here and the mixer seams are REPORTED (the engine's own error on the attempt).
|
||||
//
|
||||
// Tolerances (relative L2, ||engine - oracle|| / ||oracle||): the norms 1e-6 (`rsqrtf` is 2 ulp, the oracle's own
|
||||
// numpy-vs-numpy figure of 5e-8 in oracle-crosscheck.md is below one CUDA ulp), the adds and the MoE composition
|
||||
// 1e-6 (F32 with FMA against numpy's sequential adds), the logits 1e-5 (a 64-long F32 dot product), the router's
|
||||
// renormalised weights 1e-2 reported (the engine's router weight is BF16 by contract; the picks must be identical).
|
||||
// Exit 77 without a CUDA device or when the fixtures were not written (no numpy), 1 on a failure.
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/core/model_geometry.hpp"
|
||||
#include "strata/core/verify.hpp"
|
||||
#include "strata/core/weights.hpp"
|
||||
#include "strata/kernels/gr.hpp"
|
||||
#include "strata/kernels/native_gdn.hpp"
|
||||
#include "strata/kernels/native_moe.hpp"
|
||||
#include "strata/kernels/verify_kernels.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using strata::core::BlockBuffers;
|
||||
using strata::core::ModelGeometry;
|
||||
using strata::core::MoEBuffers;
|
||||
using strata::core::WeightTable;
|
||||
|
||||
namespace {
|
||||
int g_fail = 0;
|
||||
void check(bool ok, const std::string& what) {
|
||||
std::printf(" %-104s %s\n", what.c_str(), ok ? "ok" : "FAIL");
|
||||
if (!ok) ++g_fail;
|
||||
}
|
||||
std::string fmt(double v) { char b[32]; std::snprintf(b, sizeof b, "%.2e", v); return b; }
|
||||
#define CUDA_OK(call) do { const cudaError_t e_ = (call); if (e_ != cudaSuccess) { std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, cudaGetErrorString(e_)); std::exit(1); } } while (0)
|
||||
|
||||
struct TempDir {
|
||||
fs::path path;
|
||||
TempDir() {
|
||||
path = fs::temp_directory_path() /
|
||||
("strata-qwen36-block-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); }
|
||||
};
|
||||
|
||||
// ---- the oracle's dumps: <stem>.f32 in C order of the numpy array, shapes from manifest.txt (`stem kind ne0,ne1,..`)
|
||||
struct Dumps {
|
||||
fs::path dir;
|
||||
std::map<std::string, std::vector<int64_t>> ne; // GGUF order: ne[0] fastest
|
||||
bool open(const fs::path& d) {
|
||||
dir = d;
|
||||
std::ifstream m(d / "manifest.txt");
|
||||
if (!m) return false;
|
||||
std::string line;
|
||||
while (std::getline(m, line)) {
|
||||
std::istringstream is(line);
|
||||
std::string stem, kind, dims;
|
||||
if (!(is >> stem >> kind >> dims)) continue;
|
||||
std::vector<int64_t> v;
|
||||
std::istringstream ds(dims);
|
||||
std::string tok;
|
||||
while (std::getline(ds, tok, ',')) v.push_back(std::stoll(tok));
|
||||
ne[stem] = v;
|
||||
}
|
||||
return !ne.empty();
|
||||
}
|
||||
bool has(const std::string& stem) const { return ne.count(stem) != 0; }
|
||||
template <class T> std::vector<T> read(const std::string& stem) const {
|
||||
std::ifstream f(dir / (stem + ".f32"), std::ios::binary);
|
||||
if (!f) { std::fprintf(stderr, "qwen36_block_test: missing dump %s\n", stem.c_str()); std::exit(1); }
|
||||
f.seekg(0, std::ios::end);
|
||||
const std::streamoff n = f.tellg();
|
||||
f.seekg(0);
|
||||
std::vector<T> v((size_t) n / sizeof(T));
|
||||
f.read((char*) v.data(), n);
|
||||
return v;
|
||||
}
|
||||
std::vector<float> f(const std::string& stem) const { return read<float>(stem); }
|
||||
/// the "i32" dumps (`ffn_moe_topk-N`) are written as float32 like every other (the oracle's Dump casts to F32)
|
||||
std::vector<int32_t> i(const std::string& stem) const {
|
||||
const std::vector<float> v = read<float>(stem);
|
||||
std::vector<int32_t> r(v.size());
|
||||
for (size_t k = 0; k < v.size(); ++k) r[k] = (int32_t) std::lround(v[k]);
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
// ---- metrics (NaN-safe: a non-finite value is a failure, not a small number)
|
||||
double rel_l2(const float* a, const float* b, size_t n) {
|
||||
double d = 0, m = 0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) return INFINITY;
|
||||
d += (double) (a[i] - b[i]) * (a[i] - b[i]);
|
||||
m += (double) b[i] * b[i];
|
||||
}
|
||||
return m > 0 ? std::sqrt(d / m) : (d > 0 ? INFINITY : 0.0);
|
||||
}
|
||||
double rel_l1(const float* a, const float* b, size_t n) {
|
||||
double d = 0, m = 0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (!std::isfinite(a[i]) || !std::isfinite(b[i])) return INFINITY;
|
||||
d += std::fabs((double) a[i] - b[i]);
|
||||
m += std::fabs((double) b[i]);
|
||||
}
|
||||
return m > 0 ? d / m : (d > 0 ? INFINITY : 0.0);
|
||||
}
|
||||
|
||||
// ---- device helpers
|
||||
float* dev(size_t n) { float* p = nullptr; CUDA_OK(cudaMalloc(&p, n * 4 + 256)); CUDA_OK(cudaMemset(p, 0, n * 4 + 256)); return p; }
|
||||
void up(float* d, const float* h, size_t n) { CUDA_OK(cudaMemcpy(d, h, n * 4, cudaMemcpyHostToDevice)); }
|
||||
std::vector<float> down(const float* d, size_t n) { std::vector<float> v(n); CUDA_OK(cudaMemcpy(v.data(), d, n * 4, cudaMemcpyDeviceToHost)); return v; }
|
||||
std::vector<int32_t> down_i(const int32_t* d, size_t n) { std::vector<int32_t> v(n); CUDA_OK(cudaMemcpy(v.data(), d, n * 4, cudaMemcpyDeviceToHost)); return v; }
|
||||
|
||||
uint16_t bf16_rne(float f) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, 4);
|
||||
u += 0x7fffu + ((u >> 16) & 1u);
|
||||
return (uint16_t) (u >> 16);
|
||||
}
|
||||
|
||||
// ---- the pack the test writes: the tensors the plain block and the router read, in the engine's forms
|
||||
// (index row: 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; kind 2 = F32, kind 4 = raw BF16)
|
||||
struct PackRow { std::string name; int kind; std::vector<uint8_t> bytes; int64_t ne0, ne1; };
|
||||
void write_pack(const fs::path& dir, const std::vector<PackRow>& rows) {
|
||||
fs::create_directories(dir);
|
||||
std::vector<uint8_t> blob;
|
||||
std::string idx;
|
||||
uint64_t at = 0;
|
||||
for (const PackRow& r : rows) {
|
||||
at = (at + 255) & ~255ull;
|
||||
blob.resize(at + r.bytes.size());
|
||||
std::memcpy(blob.data() + at, r.bytes.data(), r.bytes.size());
|
||||
idx += r.name + " 0 " + std::to_string(r.kind) + " " + std::to_string(at) + " " + std::to_string(r.bytes.size()) +
|
||||
" " + std::to_string(at) + " " + std::to_string(r.bytes.size()) + " " + std::to_string(r.ne0) + " " +
|
||||
std::to_string(r.ne1) + " 0 0 1 0 0 0 0 0 0 0\n";
|
||||
at += r.bytes.size();
|
||||
}
|
||||
at = (at + 255) & ~255ull;
|
||||
std::ofstream(dir / "index.txt", std::ios::binary)
|
||||
<< "# align 256 pool " << at << " tensors " << rows.size() << "\n" << idx;
|
||||
std::ofstream(dir / "dense.bin", std::ios::binary).write((const char*) blob.data(), (std::streamsize) blob.size());
|
||||
}
|
||||
PackRow f32_row(const std::string& name, const float* p, int64_t ne0, int64_t ne1) {
|
||||
PackRow r{name, 2, {}, ne0, ne1};
|
||||
r.bytes.resize((size_t) ne0 * (ne1 > 0 ? ne1 : 1) * 4);
|
||||
std::memcpy(r.bytes.data(), p, r.bytes.size());
|
||||
return r;
|
||||
}
|
||||
PackRow bf16_row(const std::string& name, const float* p, int64_t ne0, int64_t ne1) {
|
||||
PackRow r{name, 4, {}, ne0, ne1};
|
||||
const size_t n = (size_t) ne0 * (ne1 > 0 ? ne1 : 1);
|
||||
r.bytes.resize(n * 2);
|
||||
for (size_t i = 0; i < n; ++i) { const uint16_t h = bf16_rne(p[i]); std::memcpy(r.bytes.data() + 2 * i, &h, 2); }
|
||||
return r;
|
||||
}
|
||||
|
||||
const float* tensor_f32(const strata::GgufFile& f, const std::string& name) {
|
||||
const strata::TensorInfo* t = f.find(name);
|
||||
if (t == nullptr || t->type != 0) { std::fprintf(stderr, "qwen36_block_test: %s is not an F32 tensor of the fixture\n", name.c_str()); std::exit(1); }
|
||||
return (const float*) f.tensor_data(*t);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 3) { std::fprintf(stderr, "usage: qwen36_block_test <synth dir> <dump dir>\n"); return 2; }
|
||||
int devices = 0;
|
||||
if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
|
||||
std::printf("qwen36_block_test: no CUDA device, skipped\n");
|
||||
return 77;
|
||||
}
|
||||
const fs::path synth = argv[1], dumpdir = argv[2];
|
||||
if (fs::exists(synth / "SKIP") || fs::exists(dumpdir / "SKIP") || !fs::exists(dumpdir / "manifest.txt")) {
|
||||
std::printf("qwen36_block_test: the fixtures were not written (no numpy / gguf-py), skipped\n");
|
||||
return 77;
|
||||
}
|
||||
const std::string gguf = (synth / "toy.gguf").string();
|
||||
ModelGeometry g;
|
||||
std::string err;
|
||||
if (!strata::core::read_model_geometry(gguf, g, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 1; }
|
||||
Dumps d;
|
||||
if (!d.open(dumpdir)) { std::fprintf(stderr, "qwen36_block_test: cannot read %s/manifest.txt\n", argv[2]); return 1; }
|
||||
const strata::GgufFile file(gguf);
|
||||
const int64_t N = g.n_embd, K = g.n_expert_used, L = g.n_layers, E = g.n_expert;
|
||||
// the vocabulary from the head tensor itself: `read_model_geometry` leaves `n_vocab` at its default (the engine
|
||||
// takes it from `output.weight`'s ne1 as well, verify.cpp)
|
||||
const strata::TensorInfo* wo_info = file.find("output.weight");
|
||||
if (wo_info == nullptr || wo_info->shape.size() != 2) { std::fprintf(stderr, "qwen36_block_test: no 2-D output.weight\n"); return 1; }
|
||||
const int64_t V = (int64_t) wo_info->shape[1];
|
||||
const std::vector<float> x0 = d.f("model.input_embed");
|
||||
const int T = (int) (x0.size() / (size_t) N);
|
||||
std::printf("qwen36_block_test: %s (hc %lld, n_embd %lld, %lld layers, %lld experts top-%lld, eps %g), %d tokens\n",
|
||||
gguf.c_str(), (long long) g.hc, (long long) N, (long long) L, (long long) E, (long long) K, g.rms_eps, T);
|
||||
check(g.hc == 1 && g.arch == strata::core::ModelArch::Qwen35Moe, "the fixture is qwen35moe at hc = 1");
|
||||
check(T >= 2 && T <= strata::kernels::kVerifyMaxT, "the dump holds a verify window's worth of tokens (2..8)");
|
||||
const float eps = (float) g.rms_eps;
|
||||
cudaStream_t cs = nullptr;
|
||||
CUDA_OK(cudaStreamCreate(&cs));
|
||||
|
||||
// ---- the pack: per layer the two norms (F32) and the router (BF16, the engine's contract), plus the shared
|
||||
// expert's scalar gate (BF16) and the head norm; the mixer and expert projections are NOT in it (see the header)
|
||||
TempDir tmp;
|
||||
std::vector<PackRow> rows;
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const std::string p = "blk." + std::to_string(l) + ".";
|
||||
rows.push_back(f32_row(p + "attn_norm.weight", tensor_f32(file, p + "attn_norm.weight"), N, 0));
|
||||
rows.push_back(f32_row(p + "post_attention_norm.weight", tensor_f32(file, p + "post_attention_norm.weight"), N, 0));
|
||||
rows.push_back(bf16_row(p + "ffn_gate_inp.weight", tensor_f32(file, p + "ffn_gate_inp.weight"), N, E));
|
||||
rows.push_back(bf16_row(p + "ffn_gate_inp_shexp.weight", tensor_f32(file, p + "ffn_gate_inp_shexp.weight"), N, 0));
|
||||
}
|
||||
rows.push_back(f32_row("output_norm.weight", tensor_f32(file, "output_norm.weight"), N, 0));
|
||||
write_pack(tmp.path / "pack", rows);
|
||||
uint64_t pool = 0;
|
||||
if (!WeightTable::pool_bytes((tmp.path / "pack").string(), pool, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 1; }
|
||||
void* arena = nullptr;
|
||||
CUDA_OK(cudaMalloc(&arena, pool));
|
||||
WeightTable wt;
|
||||
if (!wt.load((tmp.path / "pack").string(), arena, pool, err)) { std::fprintf(stderr, "pack load: %s\n", err.c_str()); return 1; }
|
||||
check(wt.find("blk.0.attn_norm.weight") != nullptr && wt.find("blk.0.attn_norm.weight")->kind == strata::core::WeightKind::F32,
|
||||
"the pack loads: blk.0.attn_norm.weight is F32");
|
||||
|
||||
// ---- the engine's buffers, as a session carves them
|
||||
void* block_arena = nullptr;
|
||||
CUDA_OK(cudaMalloc(&block_arena, strata::core::block_buffers_bytes(g)));
|
||||
BlockBuffers bb;
|
||||
strata::core::block_buffers_init(g, block_arena, bb);
|
||||
void* moe_arena = nullptr;
|
||||
CUDA_OK(cudaMalloc(&moe_arena, strata::core::moe_buffers_bytes(g, K)));
|
||||
MoEBuffers mb;
|
||||
strata::core::moe_buffers_init(g, K, moe_arena, mb);
|
||||
float* parts = dev((size_t) K * N);
|
||||
strata::core::GdnBuffers gb; // empty: the mixers are not run (reported), see the header
|
||||
strata::core::QsaState qst;
|
||||
strata::core::QsaBuffers qb;
|
||||
strata::core::layer_set_native_bf16(true); // the decode configuration the verify window reproduces
|
||||
|
||||
auto sync = [&] { CUDA_OK(cudaStreamSynchronize(cs)); };
|
||||
const char* mixer_seam[2] = {"linear_attn_out", "attn_output"};
|
||||
|
||||
// ================================ 1. the single-token path through the engine ================================
|
||||
std::printf("1. the single-token path: block_layer_pre / block_layer_post / lm_head_mix per layer and token\n");
|
||||
double worst_norm = 0, worst_post = 0, worst_res = 0, worst_ffn = 0, worst_lout = 0, worst_w = 0;
|
||||
int flips = 0;
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const std::string sl = "-" + std::to_string(l);
|
||||
const std::vector<float> x_in = l == 0 ? x0 : d.f("l_out-" + std::to_string(l - 1));
|
||||
const std::vector<float> an = d.f("attn_norm" + sl), mix = d.f(std::string(mixer_seam[strata::core::is_qsa_layer(g, l)]) + sl),
|
||||
res = d.f("attn_residual" + sl), pn = d.f("attn_post_norm" + sl),
|
||||
wn = d.f("ffn_moe_weights_norm" + sl), downs = d.f("ffn_moe_down" + sl),
|
||||
shg = d.f("ffn_shexp_gated" + sl), ffn = d.f("ffn_out" + sl), lo = d.f("l_out" + sl);
|
||||
const std::vector<int32_t> topk = d.i("ffn_moe_topk" + sl);
|
||||
for (int t = 0; t < T; ++t) {
|
||||
// stage 0: x = rms_norm(R) * attn_norm
|
||||
up(bb.R, x_in.data() + (size_t) t * N, (size_t) N);
|
||||
if (!strata::core::block_layer_pre(wt, g, l, t, 0, gb, qst, qb, mb, K, bb, cs, err, nullptr, nullptr, 0, 1)) {
|
||||
check(false, "block_layer_pre stage 0: " + err); continue;
|
||||
}
|
||||
sync();
|
||||
worst_norm = std::max(worst_norm, rel_l2(down(bb.mixed, (size_t) N).data(), an.data() + (size_t) t * N, (size_t) N));
|
||||
// the residual add with the mixer's output teacher-forced
|
||||
up(bb.block_out, mix.data() + (size_t) t * N, (size_t) N);
|
||||
strata::core::plain_residual_rows(bb.R, bb.block_out, N, 1, cs);
|
||||
sync();
|
||||
worst_res = std::max(worst_res, rel_l2(down(bb.R, (size_t) N).data(), res.data() + (size_t) t * N, (size_t) N));
|
||||
// half 2: x = rms_norm(R) * post_attention_norm, then the router (no shared expert: its weights are not here)
|
||||
up(bb.R, res.data() + (size_t) t * N, (size_t) N);
|
||||
strata::core::layer_set_shared_early(false);
|
||||
if (!strata::core::block_layer_pre(wt, g, l, t, 0, gb, qst, qb, mb, K, bb, cs, err, nullptr, nullptr, 2, 0)) {
|
||||
check(false, "block_layer_pre half 2: " + err); continue;
|
||||
}
|
||||
sync();
|
||||
worst_post = std::max(worst_post, rel_l2(down(bb.mixed, (size_t) N).data(), pn.data() + (size_t) t * N, (size_t) N));
|
||||
const std::vector<int32_t> ids = down_i(mb.ids, (size_t) K);
|
||||
for (int64_t j = 0; j < K; ++j) flips += ids[(size_t) j] != topk[(size_t) t * K + j];
|
||||
worst_w = std::max(worst_w, rel_l2(down(mb.weights, (size_t) K).data(), wn.data() + (size_t) t * K, (size_t) K));
|
||||
// post: combine the oracle's per-expert outputs with its renormalised weights and shared expert, R += out
|
||||
up(mb.weights, wn.data() + (size_t) t * K, (size_t) K);
|
||||
up(mb.shared, shg.data() + (size_t) t * N, (size_t) N);
|
||||
up(parts, downs.data() + (size_t) t * K * N, (size_t) K * N);
|
||||
strata::core::layer_set_shared_early(true);
|
||||
if (!strata::core::block_layer_post(wt, g, l, K, mb, bb, parts, cs, err)) { check(false, "block_layer_post: " + err); continue; }
|
||||
sync();
|
||||
worst_ffn = std::max(worst_ffn, rel_l2(down(bb.block_out, (size_t) N).data(), ffn.data() + (size_t) t * N, (size_t) N));
|
||||
worst_lout = std::max(worst_lout, rel_l2(down(bb.R, (size_t) N).data(), lo.data() + (size_t) t * N, (size_t) N));
|
||||
}
|
||||
// the mixer: reported, not asserted (the attempt's own error says why)
|
||||
up(bb.R, x_in.data(), (size_t) N);
|
||||
const bool ran = strata::core::block_layer_pre(wt, g, l, 0, 0, gb, qst, qb, mb, K, bb, cs, err, nullptr, nullptr, 0, 2);
|
||||
sync();
|
||||
std::printf(" layer %lld mixer seam %s: %s\n", (long long) l, mixer_seam[strata::core::is_qsa_layer(g, l)],
|
||||
ran ? ("ran: " + fmt(rel_l2(down(bb.block_out, (size_t) N).data(), mix.data(), (size_t) N)) + " relative L2 (reported)").c_str()
|
||||
: ("not run (" + err + ")").c_str());
|
||||
}
|
||||
check(worst_norm <= 1e-6, "attn_norm-N, all layers and tokens: " + fmt(worst_norm) + " relative L2 (tolerance 1e-6)");
|
||||
check(worst_res <= 1e-6, "attn_residual-N (mixer out forced): " + fmt(worst_res) + " (1e-6)");
|
||||
check(worst_post <= 1e-6, "attn_post_norm-N through block_layer_pre half 2: " + fmt(worst_post) + " (1e-6)");
|
||||
check(flips == 0, "ffn_moe_topk-N: the engine's BF16 router picks the oracle's experts (" + std::to_string(flips) + " of " +
|
||||
std::to_string(L * T * K) + " slots differ)");
|
||||
std::printf(" ffn_moe_weights_norm-N from the BF16 router: %s relative L2 (reported; the contract rounds the weight)\n", fmt(worst_w).c_str());
|
||||
check(worst_w <= 1e-2, "ffn_moe_weights_norm-N within 1e-2 of the F32 oracle");
|
||||
check(worst_ffn <= 1e-6, "ffn_out-N through block_layer_post (experts forced): " + fmt(worst_ffn) + " (1e-6)");
|
||||
check(worst_lout <= 1e-6, "l_out-N through block_layer_post: " + fmt(worst_lout) + " (1e-6)");
|
||||
|
||||
// the head: result_norm through lm_head_mix, the logits through a host projection of the engine's vector
|
||||
{
|
||||
const std::vector<float> lo = d.f("l_out-" + std::to_string(L - 1)), rn = d.f("result_norm"), ro = d.f("result_output");
|
||||
up(bb.R, lo.data() + (size_t) (T - 1) * N, (size_t) N);
|
||||
if (!strata::core::lm_head_mix(wt, g, bb, cs, err)) check(false, "lm_head_mix: " + err);
|
||||
sync();
|
||||
const std::vector<float> h = down(bb.mixed, (size_t) N);
|
||||
const double e_rn = rel_l2(h.data(), rn.data(), (size_t) N);
|
||||
check(e_rn <= 1e-6, "result_norm through lm_head_mix (output_norm): " + fmt(e_rn) + " (1e-6)");
|
||||
const float* wo = tensor_f32(file, "output.weight"); // ne [n_embd, n_vocab]: row v contiguous
|
||||
std::vector<float> logits((size_t) V);
|
||||
for (int64_t v = 0; v < V; ++v) {
|
||||
double acc = 0;
|
||||
for (int64_t i = 0; i < N; ++i) acc += (double) h[(size_t) i] * wo[(size_t) v * N + i];
|
||||
logits[(size_t) v] = (float) acc;
|
||||
}
|
||||
const double e_ro = rel_l2(logits.data(), ro.data(), (size_t) V);
|
||||
check(e_ro <= 1e-5, "result_output (engine's result_norm x output.weight on the host): " + fmt(e_ro) + " (1e-5)");
|
||||
}
|
||||
|
||||
// ================================ 2. the verify window's row arithmetic ================================
|
||||
std::printf("2. the verify window: the T-row calls bitwise the one-row calls, the 8-token sequence per position\n");
|
||||
{
|
||||
float* R = dev((size_t) T * N);
|
||||
float* mixed = dev((size_t) T * N);
|
||||
float* one = dev((size_t) N);
|
||||
float* bo = dev((size_t) T * N);
|
||||
float* partsT = dev((size_t) T * K * N);
|
||||
float* wT = dev((size_t) T * K);
|
||||
float* shT = dev((size_t) T * N);
|
||||
float* boT = dev((size_t) T * N);
|
||||
bool bit_norm = true, bit_add = true, bit_comb = true;
|
||||
double w_norm = 0, w_res = 0, w_post = 0, w_ffn = 0, w_lout = 0;
|
||||
up(R, x0.data(), (size_t) T * N); // the window's R, carried through the layers from the embeddings
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const std::string sl = "-" + std::to_string(l), p = "blk." + std::to_string(l) + ".";
|
||||
const float* wp_attn = (const float*) wt.find(p + "attn_norm.weight")->data;
|
||||
const float* wp_post = (const float*) wt.find(p + "post_attention_norm.weight")->data;
|
||||
const std::vector<float> an = d.f("attn_norm" + sl), mix = d.f(std::string(mixer_seam[strata::core::is_qsa_layer(g, l)]) + sl),
|
||||
res = d.f("attn_residual" + sl), pn = d.f("attn_post_norm" + sl),
|
||||
wn = d.f("ffn_moe_weights_norm" + sl), downs = d.f("ffn_moe_down" + sl),
|
||||
shg = d.f("ffn_shexp_gated" + sl), ffn = d.f("ffn_out" + sl), lo = d.f("l_out" + sl);
|
||||
const std::vector<float> R_in = down(R, (size_t) T * N);
|
||||
// the T-row norm against T one-row norms, bitwise, and against the oracle
|
||||
strata::core::plain_norm_rows(R, wp_attn, mixed, N, eps, T, cs);
|
||||
sync();
|
||||
std::vector<float> mT = down(mixed, (size_t) T * N);
|
||||
for (int t = 0; t < T; ++t) {
|
||||
strata::core::plain_norm_rows(R + (size_t) t * N, wp_attn, one, N, eps, 1, cs);
|
||||
sync();
|
||||
const std::vector<float> m1 = down(one, (size_t) N);
|
||||
bit_norm = bit_norm && std::memcmp(m1.data(), mT.data() + (size_t) t * N, (size_t) N * 4) == 0;
|
||||
}
|
||||
w_norm = std::max(w_norm, rel_l2(mT.data(), an.data(), (size_t) T * N));
|
||||
// R += mixer out (forced), T rows at once against one row at a time
|
||||
up(bo, mix.data(), (size_t) T * N);
|
||||
strata::core::plain_residual_rows(R, bo, N, T, cs);
|
||||
sync();
|
||||
const std::vector<float> rT = down(R, (size_t) T * N);
|
||||
for (int t = 0; t < T; ++t) {
|
||||
up(one, R_in.data() + (size_t) t * N, (size_t) N);
|
||||
strata::core::plain_residual_rows(one, bo + (size_t) t * N, N, 1, cs);
|
||||
sync();
|
||||
const std::vector<float> r1 = down(one, (size_t) N);
|
||||
bit_add = bit_add && std::memcmp(r1.data(), rT.data() + (size_t) t * N, (size_t) N * 4) == 0;
|
||||
}
|
||||
w_res = std::max(w_res, rel_l2(rT.data(), res.data(), (size_t) T * N));
|
||||
strata::core::plain_norm_rows(R, wp_post, mixed, N, eps, T, cs);
|
||||
sync();
|
||||
w_post = std::max(w_post, rel_l2(down(mixed, (size_t) T * N).data(), pn.data(), (size_t) T * N));
|
||||
// the combine over T rows (the window's launch) against the one-row combine, and the oracle
|
||||
up(partsT, downs.data(), (size_t) T * K * N);
|
||||
up(wT, wn.data(), (size_t) T * K);
|
||||
up(shT, shg.data(), (size_t) T * N);
|
||||
strata::kernels::native_moe_combine_multi(partsT, wT, shT, boT, N, K, T, cs);
|
||||
sync();
|
||||
const std::vector<float> cT = down(boT, (size_t) T * N);
|
||||
for (int t = 0; t < T; ++t) {
|
||||
strata::kernels::native_moe_combine(partsT + (size_t) t * K * N, wT + (size_t) t * K, shT + (size_t) t * N, one, N, K, cs);
|
||||
sync();
|
||||
const std::vector<float> c1 = down(one, (size_t) N);
|
||||
bit_comb = bit_comb && std::memcmp(c1.data(), cT.data() + (size_t) t * N, (size_t) N * 4) == 0;
|
||||
}
|
||||
w_ffn = std::max(w_ffn, rel_l2(cT.data(), ffn.data(), (size_t) T * N));
|
||||
strata::core::plain_residual_rows(R, boT, N, T, cs);
|
||||
sync();
|
||||
const double e_l = rel_l2(down(R, (size_t) T * N).data(), lo.data(), (size_t) T * N);
|
||||
w_lout = std::max(w_lout, e_l);
|
||||
std::printf(" layer %lld: l_out%s over %d positions %s relative L2 (R carried from the embeddings)\n",
|
||||
(long long) l, sl.c_str(), T, fmt(e_l).c_str());
|
||||
}
|
||||
check(bit_norm, "plain_norm_rows over T rows is bitwise the one-row call, every row and layer");
|
||||
check(bit_add, "plain_residual_rows over T rows is bitwise the one-row call");
|
||||
check(bit_comb, "native_moe_combine_multi over T rows is bitwise native_moe_combine per row");
|
||||
check(w_norm <= 1e-6, "window attn_norm-N, all positions: " + fmt(w_norm) + " (1e-6)");
|
||||
check(w_res <= 1e-6, "window attn_residual-N: " + fmt(w_res) + " (1e-6)");
|
||||
check(w_post <= 1e-6, "window attn_post_norm-N: " + fmt(w_post) + " (1e-6)");
|
||||
check(w_ffn <= 1e-6, "window ffn_out-N: " + fmt(w_ffn) + " (1e-6)");
|
||||
check(w_lout <= 1e-6, "window l_out-N per position, R carried through the layers: " + fmt(w_lout) + " (1e-6)");
|
||||
// the head over the window's rows: h_nextn is every token's output-normed state, result_norm the last one's
|
||||
const std::vector<float> hn = d.f("h_nextn"), rn = d.f("result_norm");
|
||||
strata::core::plain_norm_rows(R, (const float*) wt.find("output_norm.weight")->data, mixed, N, eps, T, cs);
|
||||
sync();
|
||||
const std::vector<float> hT = down(mixed, (size_t) T * N);
|
||||
const double e_h = rel_l2(hT.data(), hn.data(), (size_t) T * N);
|
||||
const double e_r = rel_l2(hT.data() + (size_t) (T - 1) * N, rn.data(), (size_t) N);
|
||||
check(e_h <= 1e-6, "window h_nextn (output_norm over the T rows): " + fmt(e_h) + " (1e-6)");
|
||||
check(e_r <= 1e-6, "window result_norm (row T-1): " + fmt(e_r) + " (1e-6)");
|
||||
for (float* p : {R, mixed, one, bo, partsT, wT, shT, boT}) cudaFree(p);
|
||||
}
|
||||
|
||||
// ================================ 3. the negative cases ================================
|
||||
std::printf("3. negative cases (each wrong reading must differ from the oracle by > 5%% relative L1)\n");
|
||||
{
|
||||
// the GR read at hc = 1 with identity bottleneck weights: NOT the plain norm. `gr_read`'s norm weight is
|
||||
// stored as (1 + w) and its bottleneck gates the normed stream with a sigmoid, so one stream through the
|
||||
// hyper-connection kernels is a different function - the reason the plain block is a second path.
|
||||
using strata::kernels::GrShapes;
|
||||
const GrShapes gs{N, 1, N}; // hc_lr = n_embd, so the down / up projections can be identities
|
||||
strata::kernels::GrWorkspace ws;
|
||||
const size_t wb = strata::kernels::gr_workspace_bytes(gs);
|
||||
void* wsm = nullptr;
|
||||
CUDA_OK(cudaMalloc(&wsm, wb));
|
||||
strata::kernels::gr_workspace_init(gs, wsm, ws);
|
||||
std::vector<uint16_t> ident((size_t) N * N, 0);
|
||||
for (int64_t i = 0; i < N; ++i) ident[(size_t) i * N + i] = bf16_rne(1.0f);
|
||||
uint16_t* d_ident = nullptr;
|
||||
CUDA_OK(cudaMalloc(&d_ident, ident.size() * 2));
|
||||
CUDA_OK(cudaMemcpy(d_ident, ident.data(), ident.size() * 2, cudaMemcpyHostToDevice));
|
||||
const std::vector<float> an = d.f("attn_norm-0");
|
||||
up(bb.R, x0.data(), (size_t) N);
|
||||
strata::kernels::gr_read(bb.R, (const float*) wt.find("blk.0.attn_norm.weight")->data, d_ident, d_ident, nullptr,
|
||||
eps, gs, ws, bb.mixed, bb.inject, cs);
|
||||
sync();
|
||||
const double e_gr = rel_l1(down(bb.mixed, (size_t) N).data(), an.data(), (size_t) N);
|
||||
check(e_gr > 0.05, "the GR read at hc = 1 with identity bottleneck weights is not attn_norm-0: " + fmt(e_gr) + " relative L1");
|
||||
cudaFree(wsm);
|
||||
cudaFree(d_ident);
|
||||
// the post-attention norm skipped: the residual itself fed to the MoE; and the norm without its weight
|
||||
const std::vector<float> res = d.f("attn_residual-0"), pn = d.f("attn_post_norm-0");
|
||||
const double e_skip = rel_l1(res.data(), pn.data(), (size_t) T * N);
|
||||
check(e_skip > 0.05, "post_attention_norm skipped (attn_residual-0 as the MoE input): " + fmt(e_skip) + " relative L1");
|
||||
std::vector<float> ones((size_t) N, 1.0f);
|
||||
float* d_ones = dev((size_t) N);
|
||||
up(d_ones, ones.data(), (size_t) N);
|
||||
float* rT = dev((size_t) T * N);
|
||||
float* mT = dev((size_t) T * N);
|
||||
up(rT, res.data(), (size_t) T * N);
|
||||
strata::core::plain_norm_rows(rT, d_ones, mT, N, eps, T, cs);
|
||||
sync();
|
||||
const double e_unw = rel_l1(down(mT, (size_t) T * N).data(), pn.data(), (size_t) T * N);
|
||||
check(e_unw > 0.05, "post_attention_norm without its weight: " + fmt(e_unw) + " relative L1");
|
||||
cudaFree(d_ones); cudaFree(rT); cudaFree(mT);
|
||||
// k = 10 on the 8-expert file: refused by name; the file's own k accepted. The fixture's GDN state is 16, which
|
||||
// the T-token GDN kernels (state 128) refuse on their own, so the k checks run on the geometry at state 128.
|
||||
std::string why;
|
||||
const bool r16 = strata::core::verify_geometry_supported(g, K, why);
|
||||
check(!r16 && why.find("state 128") != std::string::npos,
|
||||
"verify_geometry_supported refuses the fixture's GDN state 16 by name: " + why);
|
||||
ModelGeometry g128 = g;
|
||||
g128.ssm_state_size = 128;
|
||||
g128.derive();
|
||||
why.clear();
|
||||
const bool r10 = strata::core::verify_geometry_supported(g128, 10, why);
|
||||
check(!r10 && why.find("top-10") != std::string::npos && why.find("top-" + std::to_string(K)) != std::string::npos,
|
||||
"verify_geometry_supported refuses k = 10 on the file's top-" + std::to_string(K) + ": " + why);
|
||||
why.clear();
|
||||
const bool rk = strata::core::verify_geometry_supported(g128, K, why);
|
||||
check(rk, "verify_geometry_supported accepts the file's k " + std::to_string(K) + (rk ? "" : ": " + why));
|
||||
why.clear();
|
||||
check(!strata::core::verify_geometry_supported(g128, 0, why), "verify_geometry_supported refuses k = 0");
|
||||
// the plain block refuses a layer whose norm is not in the pack, naming it
|
||||
err.clear();
|
||||
const bool missing = strata::core::block_layer_pre(wt, g, L, 0, 0, gb, qst, qb, mb, K, bb, cs, err, nullptr, nullptr, 0, 1);
|
||||
check(!missing && err.find("blk." + std::to_string(L) + ".attn_norm.weight") != std::string::npos,
|
||||
"a missing attn_norm is refused by name: " + err);
|
||||
// the verify compatibility at hc = 1 does not demand the fused GR read or the indexer
|
||||
strata::core::layer_set_fused_gr(false);
|
||||
strata::kernels::native_gdn_set_enabled(true); // the default decode path's GDN kernels (generate.cpp turns them on)
|
||||
why.clear();
|
||||
const bool compat = strata::core::layer_verify_compatible(g, why);
|
||||
check(compat, "layer_verify_compatible at hc = 1 without the fused GR read: " + (compat ? std::string("ok") : why));
|
||||
ModelGeometry fn; // Flash-Next's defaults: the fused read is still required there
|
||||
check(!strata::core::layer_verify_compatible(fn, why) && why.find("hyper-connection") != std::string::npos,
|
||||
"layer_verify_compatible at hc = 4 still requires the fused GR read: " + why);
|
||||
}
|
||||
|
||||
cudaFree(parts); cudaFree(moe_arena); cudaFree(block_arena); cudaFree(arena);
|
||||
cudaStreamDestroy(cs);
|
||||
std::printf(g_fail ? "qwen36_block_test: %d FAILED\n" : "qwen36_block_test: all passed\n", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user